From 048ea1585b4e1b89ef1f547844869ef9a74accd8 Mon Sep 17 00:00:00 2001
From: log
Date: Thu, 09 Jul 2026 18:36:34 +0800
Subject: [PATCH] fix: abort akshare history after repeated failures

---
 scripts/data_update_v2.py    |   27 +++++++++++++++++++++++----
 tests/test_data_update_v2.py |   29 +++++++++++++++++++++++++++++
 2 files changed, 52 insertions(+), 4 deletions(-)

diff --git a/scripts/data_update_v2.py b/scripts/data_update_v2.py
index efc3f8d..d612cc6 100755
--- a/scripts/data_update_v2.py
+++ b/scripts/data_update_v2.py
@@ -79,7 +79,11 @@
         return fallback_stock_pool()
 
 
-def fetch_real_stock_data_from_akshare_only(n_stocks=500, days=365):
+def fetch_real_stock_data_from_akshare_only(
+    n_stocks=500,
+    days=365,
+    max_consecutive_failures=10,
+):
     """从AKShare获取真实股票历史数据"""
     logger.info("="*60)
     logger.info("从AKShare获取真实A股数据")
@@ -102,12 +106,14 @@
         
         stock_list = stock_list.head(n_stocks)
         
-        for idx, row in stock_list.iterrows():
+        consecutive_failures = 0
+
+        for position, (_, row) in enumerate(stock_list.iterrows(), start=1):
             stock_code = row['代码']
             stock_name = row['名称']
             
             try:
-                logger.info(f"  [{idx+1}/{len(stock_list)}] 获取 {stock_name}({stock_code})...")
+                logger.info(f"  [{position}/{len(stock_list)}] 获取 {stock_name}({stock_code})...")
                 
                 df = ak.stock_zh_a_hist(
                     symbol=stock_code,
@@ -127,14 +133,27 @@
                     df['date'] = pd.to_datetime(df['date'])
                     
                     df = calculate_technical_factors(df)
-                    
+
                     all_data.append(df)
+                    consecutive_failures = 0
                     logger.info(f"    ✓ 获取 {len(df)} 条记录")
                 else:
                     logger.warning(f"    ⚠️ 无数据")
                     
             except Exception as e:
+                consecutive_failures += 1
                 logger.warning(f"    ⚠️ 获取失败: {e}")
+                if (
+                    max_consecutive_failures
+                    and consecutive_failures >= max_consecutive_failures
+                ):
+                    logger.error(
+                        f"❌ AKShare历史行情连续失败 {consecutive_failures} 次,"
+                        "提前停止并切换备用数据源"
+                    )
+                    if not all_data:
+                        return None
+                    break
                 continue
         
         if all_data:
diff --git a/tests/test_data_update_v2.py b/tests/test_data_update_v2.py
index 31df51a..4e02a65 100644
--- a/tests/test_data_update_v2.py
+++ b/tests/test_data_update_v2.py
@@ -107,6 +107,35 @@
             ],
         )
 
+    def test_akshare_history_failures_abort_before_full_stock_pool(self):
+        class FakeAkShare:
+            def __init__(self):
+                self.history_calls = 0
+
+            def stock_info_a_code_name(self):
+                return pd.DataFrame(
+                    [
+                        {"code": f"{index:06d}", "name": f"测试{index}"}
+                        for index in range(1, 21)
+                    ]
+                )
+
+            def stock_zh_a_hist(self, **kwargs):
+                self.history_calls += 1
+                raise ConnectionError(
+                    "Remote end closed connection without response"
+                )
+
+        fake_ak = FakeAkShare()
+
+        with patch.dict(sys.modules, {"akshare": fake_ak}):
+            result = data_update_v2.fetch_real_stock_data_from_akshare_only(
+                n_stocks=20, days=10, max_consecutive_failures=3
+            )
+
+        self.assertIsNone(result)
+        self.assertEqual(fake_ak.history_calls, 3)
+
     def test_convert_baostock_history_matches_existing_schema(self):
         raw = pd.DataFrame(
             [

--
Gitblit v1.8.0