fix: timeout stalled baostock requests
| | |
| | | import json |
| | | import argparse |
| | | import time |
| | | import socket |
| | | |
| | | os.makedirs('logs', exist_ok=True) |
| | | |
| | |
| | | max_retries=3, |
| | | retry_delay=1, |
| | | request_delay=0.1, |
| | | socket_timeout=30, |
| | | ): |
| | | """从BaoStock获取真实股票历史数据,作为东方财富/AKShare不可用时的备用源。""" |
| | | logger.info("="*60) |
| | |
| | | all_data = [] |
| | | |
| | | login_result = None |
| | | previous_socket_timeout = socket.getdefaulttimeout() |
| | | try: |
| | | if socket_timeout: |
| | | socket.setdefaulttimeout(socket_timeout) |
| | | logger.info(f"✓ BaoStock网络超时设置为 {socket_timeout} 秒") |
| | | |
| | | login_result = bs.login() |
| | | if getattr(login_result, 'error_code', '0') != '0': |
| | | logger.error(f"❌ BaoStock登录失败: {login_result.error_msg}") |
| | |
| | | bs.logout() |
| | | except Exception as e: |
| | | logger.warning(f"⚠️ BaoStock登出失败: {e}") |
| | | socket.setdefaulttimeout(previous_socket_timeout) |
| | | |
| | | |
| | | def calculate_technical_factors(df): |
| | |
| | | self.assertEqual(fake_bs.login_calls, 2) |
| | | self.assertEqual(result["stock_code"].unique().tolist(), ["600519"]) |
| | | |
| | | def test_fetch_baostock_sets_and_restores_socket_timeout(self): |
| | | fake_bs = FakeBaoStock() |
| | | stock_list = pd.DataFrame([{"代码": "600519", "名称": "贵州茅台"}]) |
| | | |
| | | with patch.dict(sys.modules, {"baostock": fake_bs}): |
| | | with patch.object(data_update_v2.socket, "getdefaulttimeout", return_value=None): |
| | | with patch.object(data_update_v2.socket, "setdefaulttimeout") as set_timeout: |
| | | result = data_update_v2.fetch_real_stock_data_from_baostock( |
| | | n_stocks=1, |
| | | days=10, |
| | | stock_list=stock_list, |
| | | socket_timeout=12, |
| | | request_delay=0, |
| | | ) |
| | | |
| | | self.assertIsNotNone(result) |
| | | self.assertEqual(set_timeout.call_args_list[0].args, (12,)) |
| | | self.assertEqual(set_timeout.call_args_list[-1].args, (None,)) |
| | | |
| | | def test_baostock_result_to_dataframe_uses_iterator_api(self): |
| | | raw = pd.DataFrame([{"code": "sh.600519", "code_name": "贵州茅台"}]) |
| | | |