Spaces:
Paused
Paused
superxuu commited on
Commit ·
2065db8
1
Parent(s): daa231d
fix: Add retry logic for AkShare to maximize data completeness (turnover rate)
Browse files- backend/scripts/sync_data.py +44 -40
backend/scripts/sync_data.py
CHANGED
|
@@ -110,15 +110,16 @@ def get_stock_list() -> pd.DataFrame:
|
|
| 110 |
def get_target_daily(code: str, start_date: str, market: str) -> Optional[pd.DataFrame]:
|
| 111 |
"""
|
| 112 |
获取单只标的的日线数据(支持增量时间)
|
|
|
|
| 113 |
"""
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
fetch_start = start_date.replace('-', '')
|
| 117 |
-
|
| 118 |
-
df = None
|
| 119 |
-
|
| 120 |
-
# 1. 尝试 AkShare
|
| 121 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
if market in ['ETF', 'LOF']:
|
| 123 |
df = ak.fund_etf_hist_sina(symbol=f"sh{code}" if code.startswith('5') else f"sz{code}")
|
| 124 |
if df is not None and not df.empty:
|
|
@@ -150,44 +151,47 @@ def get_target_daily(code: str, start_date: str, market: str) -> Optional[pd.Dat
|
|
| 150 |
'涨跌幅': 'pct_chg', '换手率': 'turnover_rate'
|
| 151 |
})
|
| 152 |
df['trade_date'] = pd.to_datetime(df['trade_date'])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
except Exception as e:
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
# 转换代码格式逻辑优化
|
| 159 |
-
if code == '000300': # 沪深300特例
|
| 160 |
-
yf_code = "000300.SS"
|
| 161 |
-
elif code.startswith(('8', '4', '920')):
|
| 162 |
-
yf_code = f"{code}.BJ" # 北交所
|
| 163 |
-
elif code.startswith(('6', '9', '5', '11')):
|
| 164 |
-
yf_code = f"{code}.SS" # 沪市
|
| 165 |
else:
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
ticker = yf.Ticker(yf_code)
|
| 169 |
-
days_diff = (datetime.now() - pd.to_datetime(start_date)).days + 5
|
| 170 |
-
df_yf = ticker.history(period=f"{days_diff}d", interval="1d", auto_adjust=True)
|
| 171 |
-
|
| 172 |
-
if df_yf is not None and not df_yf.empty:
|
| 173 |
-
df_yf = df_yf.reset_index()
|
| 174 |
-
df_yf = df_yf.rename(columns={'Date': 'trade_date', 'Open': 'open', 'High': 'high', 'Low': 'low', 'Close': 'close', 'Volume': 'volume'})
|
| 175 |
-
df_yf['trade_date'] = pd.to_datetime(df_yf['trade_date']).dt.tz_localize(None)
|
| 176 |
-
df_yf = df_yf[df_yf['trade_date'] >= pd.to_datetime(start_date)]
|
| 177 |
-
df_yf['amount'] = df_yf['close'] * df_yf['volume']
|
| 178 |
-
df_yf['pct_chg'] = df_yf['close'].pct_change() * 100
|
| 179 |
-
df_yf['turnover_rate'] = 0
|
| 180 |
-
df = df_yf
|
| 181 |
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 187 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 188 |
except Exception as e:
|
| 189 |
-
logger.
|
| 190 |
-
|
|
|
|
| 191 |
|
| 192 |
|
| 193 |
def get_index_daily(code: str, years: int = YEARS_OF_DATA) -> Optional[pd.DataFrame]:
|
|
|
|
| 110 |
def get_target_daily(code: str, start_date: str, market: str) -> Optional[pd.DataFrame]:
|
| 111 |
"""
|
| 112 |
获取单只标的的日线数据(支持增量时间)
|
| 113 |
+
优先使用 AkShare (带重试),最后才考虑 Yahoo Finance
|
| 114 |
"""
|
| 115 |
+
max_retries = 3
|
| 116 |
+
for attempt in range(max_retries):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
try:
|
| 118 |
+
end_date = datetime.now().strftime('%Y%m%d')
|
| 119 |
+
fetch_start = start_date.replace('-', '')
|
| 120 |
+
df = None
|
| 121 |
+
|
| 122 |
+
# 尝试 AkShare
|
| 123 |
if market in ['ETF', 'LOF']:
|
| 124 |
df = ak.fund_etf_hist_sina(symbol=f"sh{code}" if code.startswith('5') else f"sz{code}")
|
| 125 |
if df is not None and not df.empty:
|
|
|
|
| 151 |
'涨跌幅': 'pct_chg', '换手率': 'turnover_rate'
|
| 152 |
})
|
| 153 |
df['trade_date'] = pd.to_datetime(df['trade_date'])
|
| 154 |
+
|
| 155 |
+
if df is not None and not df.empty:
|
| 156 |
+
df['code'] = code
|
| 157 |
+
cols = ['code', 'trade_date', 'open', 'high', 'low', 'close', 'volume', 'amount', 'pct_chg', 'turnover_rate']
|
| 158 |
+
return df[[c for c in cols if c in df.columns]]
|
| 159 |
+
|
| 160 |
except Exception as e:
|
| 161 |
+
if attempt < max_retries - 1:
|
| 162 |
+
logger.warning(f"AkShare attempt {attempt+1} failed for {code}, retrying...")
|
| 163 |
+
time.sleep(1)
|
| 164 |
+
continue
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 165 |
else:
|
| 166 |
+
logger.warning(f"AkShare failed after {max_retries} attempts for {code}, trying Yahoo Finance: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
|
| 168 |
+
# 2. 尝试 Yahoo Finance (作为最后的兜底)
|
| 169 |
+
try:
|
| 170 |
+
# 转换代码格式
|
| 171 |
+
if code == '000300': yf_code = "000300.SS"
|
| 172 |
+
elif code.startswith(('8', '4', '920')): yf_code = f"{code}.BJ"
|
| 173 |
+
elif code.startswith(('6', '9', '5', '11')): yf_code = f"{code}.SS"
|
| 174 |
+
else: yf_code = f"{code}.SZ"
|
| 175 |
+
|
| 176 |
+
ticker = yf.Ticker(yf_code)
|
| 177 |
+
days_diff = (datetime.now() - pd.to_datetime(start_date)).days + 5
|
| 178 |
+
df_yf = ticker.history(period=f"{days_diff}d", interval="1d", auto_adjust=True)
|
| 179 |
|
| 180 |
+
if df_yf is not None and not df_yf.empty:
|
| 181 |
+
df_yf = df_yf.reset_index()
|
| 182 |
+
df_yf = df_yf.rename(columns={'Date': 'trade_date', 'Open': 'open', 'High': 'high', 'Low': 'low', 'Close': 'close', 'Volume': 'volume'})
|
| 183 |
+
df_yf['trade_date'] = pd.to_datetime(df_yf['trade_date']).dt.tz_localize(None)
|
| 184 |
+
df_yf = df_yf[df_yf['trade_date'] >= pd.to_datetime(start_date)]
|
| 185 |
+
df_yf['amount'] = df_yf['close'] * df_yf['volume']
|
| 186 |
+
df_yf['pct_chg'] = df_yf['close'].pct_change() * 100
|
| 187 |
+
df_yf['turnover_rate'] = 0
|
| 188 |
+
df_yf['code'] = code
|
| 189 |
+
cols = ['code', 'trade_date', 'open', 'high', 'low', 'close', 'volume', 'amount', 'pct_chg', 'turnover_rate']
|
| 190 |
+
return df_yf[[c for c in cols if c in df_yf.columns]]
|
| 191 |
except Exception as e:
|
| 192 |
+
logger.error(f"Yahoo Finance also failed for {code}: {e}")
|
| 193 |
+
|
| 194 |
+
return None
|
| 195 |
|
| 196 |
|
| 197 |
def get_index_daily(code: str, years: int = YEARS_OF_DATA) -> Optional[pd.DataFrame]:
|