fix: reconnect baostock after network drop
| | |
| | | import pickle |
| | | import json |
| | | import argparse |
| | | import time |
| | | |
| | | os.makedirs('logs', exist_ok=True) |
| | | |
| | |
| | | return converted[columns] |
| | | |
| | | |
| | | def fetch_real_stock_data_from_baostock(n_stocks=500, days=365, stock_list=None): |
| | | def reconnect_baostock(bs): |
| | | """BaoStock长时间运行后可能断开连接,重登后可继续请求。""" |
| | | try: |
| | | bs.logout() |
| | | except Exception as e: |
| | | logger.warning(f"⚠️ BaoStock重连前登出失败: {e}") |
| | | |
| | | login_result = bs.login() |
| | | if getattr(login_result, 'error_code', '0') != '0': |
| | | logger.error(f"❌ BaoStock重新登录失败: {login_result.error_msg}") |
| | | return None |
| | | logger.info("✓ BaoStock已重新登录") |
| | | return login_result |
| | | |
| | | |
| | | def fetch_real_stock_data_from_baostock( |
| | | n_stocks=500, |
| | | days=365, |
| | | stock_list=None, |
| | | max_retries=2, |
| | | retry_delay=1, |
| | | ): |
| | | """从BaoStock获取真实股票历史数据,作为东方财富/AKShare不可用时的备用源。""" |
| | | logger.info("="*60) |
| | | logger.info("从BaoStock获取真实A股数据") |
| | |
| | | stock_code = normalize_baostock_code(bs_code) |
| | | stock_name = row['code_name'] |
| | | |
| | | try: |
| | | logger.info(f" [{position}/{len(stock_list)}] 获取 {stock_name}({stock_code})...") |
| | | result = bs.query_history_k_data_plus( |
| | | bs_code, |
| | | fields, |
| | | start_date=start_date, |
| | | end_date=end_date, |
| | | frequency="d", |
| | | adjustflag="2" |
| | | ) |
| | | for attempt in range(max_retries + 1): |
| | | if attempt > 0: |
| | | logger.info(f" ↻ 重试 {attempt}/{max_retries}: {stock_name}({stock_code})") |
| | | |
| | | if getattr(result, 'error_code', '0') != '0': |
| | | logger.warning(f" ⚠️ 获取失败: {result.error_msg}") |
| | | continue |
| | | try: |
| | | logger.info(f" [{position}/{len(stock_list)}] 获取 {stock_name}({stock_code})...") |
| | | result = bs.query_history_k_data_plus( |
| | | bs_code, |
| | | fields, |
| | | start_date=start_date, |
| | | end_date=end_date, |
| | | frequency="d", |
| | | adjustflag="2" |
| | | ) |
| | | |
| | | df = convert_baostock_history( |
| | | baostock_result_to_dataframe(result), |
| | | stock_code, |
| | | stock_name |
| | | ) |
| | | if df is not None and len(df) > 0: |
| | | df = calculate_technical_factors(df) |
| | | all_data.append(df) |
| | | logger.info(f" ✓ 获取 {len(df)} 条记录") |
| | | else: |
| | | logger.warning(" ⚠️ 无数据") |
| | | if getattr(result, 'error_code', '0') != '0': |
| | | logger.warning(f" ⚠️ 获取失败: {result.error_msg}") |
| | | break |
| | | |
| | | except Exception as e: |
| | | logger.warning(f" ⚠️ 获取失败: {e}") |
| | | continue |
| | | df = convert_baostock_history( |
| | | baostock_result_to_dataframe(result), |
| | | stock_code, |
| | | stock_name |
| | | ) |
| | | if df is not None and len(df) > 0: |
| | | df = calculate_technical_factors(df) |
| | | all_data.append(df) |
| | | logger.info(f" ✓ 获取 {len(df)} 条记录") |
| | | else: |
| | | logger.warning(" ⚠️ 无数据") |
| | | break |
| | | |
| | | except Exception as e: |
| | | logger.warning(f" ⚠️ 获取失败: {e}") |
| | | if attempt >= max_retries: |
| | | break |
| | | |
| | | if retry_delay: |
| | | time.sleep(retry_delay) |
| | | |
| | | login_result = reconnect_baostock(bs) |
| | | if login_result is None: |
| | | break |
| | | |
| | | if all_data: |
| | | combined = pd.concat(all_data, ignore_index=True) |
| | |
| | | self.logged_out = False |
| | | self.stock_basic_calls = 0 |
| | | self.history_codes = [] |
| | | self.login_calls = 0 |
| | | |
| | | def login(self): |
| | | self.login_calls += 1 |
| | | return type("LoginResult", (), {"error_code": "0", "error_msg": "success"})() |
| | | |
| | | def logout(self): |
| | |
| | | self.assertIn("ma5", result.columns) |
| | | self.assertTrue(fake_bs.logged_out) |
| | | |
| | | def test_fetch_baostock_relogs_in_and_retries_after_network_error(self): |
| | | class FlakyBaoStock(FakeBaoStock): |
| | | def __init__(self): |
| | | super().__init__() |
| | | self.fail_once = True |
| | | |
| | | def query_history_k_data_plus( |
| | | self, code, fields, start_date, end_date, frequency, adjustflag |
| | | ): |
| | | self.history_codes.append(code) |
| | | if self.fail_once: |
| | | self.fail_once = False |
| | | raise OSError("网络接收错误。") |
| | | return FakeBaoStockResult( |
| | | pd.DataFrame( |
| | | [ |
| | | { |
| | | "date": "2026-07-08", |
| | | "code": code, |
| | | "open": "1500.0", |
| | | "high": "1510.0", |
| | | "low": "1495.0", |
| | | "close": "1508.0", |
| | | "preclose": "1490.0", |
| | | "volume": "10000", |
| | | "amount": "15080000", |
| | | "turn": "0.12", |
| | | "pctChg": "1.20", |
| | | } |
| | | ] |
| | | ) |
| | | ) |
| | | |
| | | fake_bs = FlakyBaoStock() |
| | | stock_list = pd.DataFrame([{"代码": "600519", "名称": "贵州茅台"}]) |
| | | |
| | | with patch.dict(sys.modules, {"baostock": fake_bs}): |
| | | result = data_update_v2.fetch_real_stock_data_from_baostock( |
| | | n_stocks=1, |
| | | days=10, |
| | | stock_list=stock_list, |
| | | max_retries=1, |
| | | retry_delay=0, |
| | | ) |
| | | |
| | | self.assertIsNotNone(result) |
| | | self.assertEqual(fake_bs.history_codes, ["sh.600519", "sh.600519"]) |
| | | self.assertEqual(fake_bs.login_calls, 2) |
| | | self.assertEqual(result["stock_code"].unique().tolist(), ["600519"]) |
| | | |
| | | def test_baostock_result_to_dataframe_uses_iterator_api(self): |
| | | raw = pd.DataFrame([{"code": "sh.600519", "code_name": "贵州茅台"}]) |
| | | |