From e565b77640285d6c433c9edf82505157733314ca Mon Sep 17 00:00:00 2001
From: log
Date: Sat, 11 Jul 2026 08:06:38 +0800
Subject: [PATCH] feat: add safe incremental stock updates

---
 scripts/update_stock_data.py            |  331 +++++++++++++++++++++++++++
 openclaw-skill/a-stock-advisor/SKILL.md |   56 +++-
 tests/test_incremental_update.py        |  161 +++++++++++++
 tests/test_a_stock_manager.py           |   29 ++
 scripts/reset_stock_data.py             |   90 +++++++
 a_stock_manager.py                      |   50 ++-
 6 files changed, 683 insertions(+), 34 deletions(-)

diff --git a/a_stock_manager.py b/a_stock_manager.py
index 59cc850..b6ac6e5 100644
--- a/a_stock_manager.py
+++ b/a_stock_manager.py
@@ -346,41 +346,48 @@
     print("  • 支持多种数据源:AKShare、BaoStock、腾讯行情")
     print("  • 自动计算技术因子指标")
     print("  • 自动运行增强因子系统")
-    print("  • 支持增量更新")
+    print("  • 默认增量更新,全量重建需显式选择")
+    print("  • 重置数据会先移动到备份目录,不直接永久删除")
     
     print("\n选择数据更新方式:")
-    print("1. 使用真实数据源(AKShare/BaoStock)⭐推荐")
-    print("2. 使用本地模拟数据(仅测试用)")
-    print("3. 从AKShare在线获取(需要网络)")
-    print("4. 仅重新计算因子(不更新数据)⭐新增")
+    print("1. 增量更新全部A股 ⭐推荐")
+    print("2. 全量重建全部A股(耗时较长)")
+    print("3. 快速增量更新500只(连通性测试)")
+    print("4. 仅重新计算因子(不更新数据)")
     print("5. 仅补充北交所历史数据")
+    print("6. 安全重置本地数据(自动备份)")
+    print("7. 使用本地模拟数据(仅测试用)")
     print("0. 返回")
     
-    choice = input("\n请选择 (0-5): ").strip()
+    choice = input("\n请选择 (0-7): ").strip()
     
     if choice == '1':
-        result = fetch_real_data()
+        result = run_script(
+            'update_stock_data.py',
+            "增量更新全部A股",
+        )
         if result:
             print_info("数据更新完成,正在运行增强因子系统...")
             run_enhanced_factor_system()
         return result
     elif choice == '2':
-        result = run_script('data_update_v3.py', "使用本地模拟数据")
+        result = run_script(
+            'update_stock_data.py',
+            "全量重建全部A股",
+            args=['--full', '--n-stocks', 'all', '--days', '730'],
+        )
         if result:
-            print_info("数据更新完成,正在运行增强因子系统...")
+            print_info("全量重建完成,正在运行增强因子系统...")
             run_enhanced_factor_system()
         return result
     elif choice == '3':
-        args, stock_count_desc = prompt_stock_count_args()
-        if args is None:
-            return False
         result = run_script(
-            'data_update_v2.py',
-            f"从AKShare在线获取数据({stock_count_desc})",
-            args=args,
+            'update_stock_data.py',
+            "快速增量更新500只",
+            args=['--n-stocks', '500', '--force'],
         )
         if result:
-            print_info("数据更新完成,正在运行增强因子系统...")
+            print_info("快速增量更新完成,正在运行增强因子系统...")
             run_enhanced_factor_system()
         return result
     elif choice == '4':
@@ -395,6 +402,17 @@
             print_info("北交所数据补充完成,正在运行增强因子系统...")
             run_enhanced_factor_system()
         return result
+    elif choice == '6':
+        return run_script(
+            'reset_stock_data.py',
+            "安全重置本地行情、因子和选股数据",
+        )
+    elif choice == '7':
+        result = run_script('data_update_v3.py', "使用本地模拟数据")
+        if result:
+            print_info("模拟数据生成完成,正在运行增强因子系统...")
+            run_enhanced_factor_system()
+        return result
 
 def fetch_real_data():
     """获取真实数据"""
diff --git a/openclaw-skill/a-stock-advisor/SKILL.md b/openclaw-skill/a-stock-advisor/SKILL.md
index 37c56c8..38653a3 100644
--- a/openclaw-skill/a-stock-advisor/SKILL.md
+++ b/openclaw-skill/a-stock-advisor/SKILL.md
@@ -1,7 +1,7 @@
 ---
 name: a-stock-advisor
 description: 操作本地 A 股量化项目,执行行情数据更新、北交所补数、数据质量检查、因子分析、每日选股、报告读取、日志诊断、回测和模拟交易。用户提到 A 股、股票同步、AKShare、BaoStock、腾讯行情、因子 IC/IR、选股结果、每日主控、回测、模拟盘或量化报告时使用。不得执行真实券商委托或资金操作。
-metadata: {"version":"2026.7.10.2"}
+metadata: {"version":"2026.7.11.1"}
 ---
 
 # A股量化助手
@@ -49,11 +49,13 @@
 
 | 用户意图 | 必须执行 |
 |---|---|
-| “更新A股数据”“同步股票数据”“获取最新行情” | `{PYTHON} scripts/data_update_v2.py --n-stocks all --days 730` |
-| “快速更新500只” | `{PYTHON} scripts/data_update_v2.py --n-stocks 500 --days 730` |
+| “更新A股数据”“同步股票数据”“获取最新行情” | `{PYTHON} scripts/update_stock_data.py` |
+| “全量更新”“全量重建数据” | `{PYTHON} scripts/update_stock_data.py --full --n-stocks all --days 730` |
+| “快速更新500只” | `{PYTHON} scripts/update_stock_data.py --n-stocks 500 --force` |
 | “只更新北交所” | `{PYTHON} scripts/data_update_v2.py --bse-only --days 730` |
 | “运行每日选股” | `{PYTHON} scripts/daily_master.py` |
-| “更新数据后运行每日选股” | 先执行全量 `data_update_v2.py`,成功后再执行不带参数的 `daily_master.py` |
+| “更新数据后运行每日选股” | 先执行增量 `update_stock_data.py`,成功后再执行不带参数的 `daily_master.py` |
+| “重置/清空股票数据” | 先向用户解释将自动备份并要求明确确认;确认后执行 `{PYTHON} scripts/reset_stock_data.py --yes` |
 
 处理数据更新请求时禁止调用:
 
@@ -62,9 +64,9 @@
 - `a_stock_manager.py` 的交互菜单
 - 直接调用 AKShare、BaoStock 或腾讯接口的临时代码
 
-`scripts/data_update_v2.py` 是唯一的数据更新入口。它内部使用经过项目优化的多数据源流程:AKShare 获取股票列表和首选行情,连续失败后自动切换 BaoStock 获取沪深历史行情,并使用腾讯行情补充北交所及新旧代码映射。
+`scripts/update_stock_data.py` 是默认数据更新入口:存在正式数据时执行增量合并,不存在时自动执行全量初始化。`scripts/data_update_v2.py` 是底层全量和专项修复引擎。两者都复用经过项目优化的多数据源流程:AKShare 获取股票列表和首选行情,失败或覆盖不足时自动切换 BaoStock 获取沪深历史行情,并使用腾讯行情补充北交所及新旧代码映射。
 
-执行前必须向用户显示即将运行的完整命令。若实际命令不包含 `scripts/data_update_v2.py`,立即停止并纠正路由。
+执行前必须向用户显示即将运行的完整命令。普通更新若实际命令不是 `scripts/update_stock_data.py`,立即停止并纠正路由。
 
 ## 工作原则
 
@@ -88,21 +90,29 @@
 
 向用户报告:创建时间、行情日期范围、股票数、记录数、数据源、最近一次任务是否完成。不要直接打印整个 pickle 文件。
 
-### 更新股票行情
+### 增量更新股票行情
 
-用户只说“更新A股数据”而没有指定数量时,默认更新全部 A 股,直接运行:
+用户只说“更新A股数据”而没有指定数量时,默认更新全部 A 股的增量行情,直接运行:
 
 ```text
-{PYTHON} scripts/data_update_v2.py --n-stocks all --days 730
+{PYTHON} scripts/update_stock_data.py
 ```
 
-用户指定股票数量或历史天数时,将 `all` 和 `730` 替换为用户给定值。小范围连通性测试使用:
+增量模式会读取本地最近完整交易日,保留重叠窗口,并按 `股票代码 + 日期` 替换去重。若本地数据已经覆盖最近预期交易日,则不发起网络请求。若正式数据文件不存在,会自动执行首次全量初始化。
+
+用户指定股票数量时使用 `--n-stocks`。小范围连通性测试使用:
 
 ```text
-{PYTHON} scripts/data_update_v2.py --n-stocks 10 --days 30
+{PYTHON} scripts/update_stock_data.py --n-stocks 10 --force
 ```
 
-注意:小范围测试会写入正式数据文件。除非用户明确允许,不要用小范围测试替换已经存在的全量数据。
+增量小范围测试只合并相应股票,不会把其他股票从正式文件删除。
+
+用户明确要求全量重建时才运行:
+
+```text
+{PYTHON} scripts/update_stock_data.py --full --n-stocks all --days 730
+```
 
 运行期间通过 `logs/data_update_v3.log` 判断进度。只有当日志超过 5 分钟没有新增、进程也没有网络或 CPU 活动时,才提示可能停滞。
 
@@ -115,15 +125,15 @@
 
 正确流程的日志必须依次包含以下关键标记:
 
-1. `数据更新任务开始 - 使用真实数据源`
-2. `更新范围: 全部A股`,或用户明确指定的数量
-3. `获取A股股票列表`
+1. `数据更新任务开始 - 默认增量模式`
+2. `本地完整交易日` 和 `预期最新交易日`
+3. 数据已最新时出现 `增量数据更新完成(无新增)`;否则继续获取股票列表
 4. AKShare 成功,或者出现切换备用数据源的说明
 5. BaoStock 沪深历史行情进度(发生降级时)
 6. 腾讯北交所历史行情进度(切换备用源且存在北交所股票时)
-7. `数据更新任务完成`
+7. `增量数据更新完成`
 
-如果日志出现 `执行完整数据管道` 或只显示固定 `500` 只,而用户没有要求快速更新,说明走错入口;停止该任务并改用上面的强制命令。
+如果普通更新日志出现 `更新模式: 全量重建`,但用户没有明确要求全量,说明走错入口;停止该任务并改用默认增量命令。
 
 ### 仅补充北交所行情
 
@@ -143,7 +153,17 @@
 {PYTHON} scripts/daily_master.py
 ```
 
-用户要求“更新数据后选股”时,不使用 `--run-pipeline`。先运行优化后的 `data_update_v2.py --n-stocks all --days 730`,确认成功后再运行不带参数的 `daily_master.py`。
+用户要求“更新数据后选股”时,不使用 `--run-pipeline`。先运行默认增量入口 `update_stock_data.py`,确认成功后再运行不带参数的 `daily_master.py`。
+
+### 安全重置数据
+
+只有用户明确要求重置或清空数据时才允许执行。先说明行情、增强因子和选股结果会从正式位置移走,并要求用户明确确认。确认后运行:
+
+```text
+{PYTHON} scripts/reset_stock_data.py --yes
+```
+
+该命令不会永久删除文件,而会移动到 `data/backups/stock_data_时间戳/`。完成后,下一次普通更新会自动执行全量初始化。不得自行删除备份目录。
 
 完成后读取并总结:
 
diff --git a/scripts/reset_stock_data.py b/scripts/reset_stock_data.py
new file mode 100644
index 0000000..c4968e6
--- /dev/null
+++ b/scripts/reset_stock_data.py
@@ -0,0 +1,90 @@
+#!/usr/bin/env python3
+"""Safely reset generated stock data by moving it into a timestamped backup."""
+
+import argparse
+import json
+import shutil
+import sys
+from datetime import datetime
+from pathlib import Path
+
+
+PROJECT_ROOT = Path(__file__).resolve().parents[1]
+DATA_DIR = PROJECT_ROOT / "data"
+BACKUP_ROOT = DATA_DIR / "backups"
+RESET_FILES = (
+    "akshare_real_data_fixed.pkl",
+    "akshare_real_data_fixed_metadata.json",
+    "enhanced_factors.pkl",
+    "selection_result.json",
+)
+
+
+def parse_args(argv=None):
+    parser = argparse.ArgumentParser(
+        description="安全重置行情和派生结果;原文件会移动到 data/backups"
+    )
+    parser.add_argument(
+        "--yes",
+        action="store_true",
+        help="确认执行;仅用于用户已经明确确认的自动化场景",
+    )
+    return parser.parse_args(argv)
+
+
+def safe_reset_data(data_dir=DATA_DIR, backup_root=BACKUP_ROOT, now=None):
+    data_dir = Path(data_dir)
+    backup_root = Path(backup_root)
+    candidates = [data_dir / name for name in RESET_FILES]
+    existing = [path for path in candidates if path.exists()]
+    if not existing:
+        return None, []
+
+    timestamp = (now or datetime.now()).strftime("%Y%m%d_%H%M%S")
+    backup_dir = backup_root / f"stock_data_{timestamp}"
+    backup_dir.mkdir(parents=True, exist_ok=False)
+
+    moved = []
+    try:
+        for source in existing:
+            destination = backup_dir / source.name
+            shutil.move(str(source), str(destination))
+            moved.append(destination)
+        manifest = {
+            "created_at": (now or datetime.now()).isoformat(),
+            "files": [path.name for path in moved],
+        }
+        with (backup_dir / "manifest.json").open("w", encoding="utf-8") as handle:
+            json.dump(manifest, handle, ensure_ascii=False, indent=2)
+    except Exception:
+        for destination in reversed(moved):
+            if destination.exists():
+                shutil.move(str(destination), str(data_dir / destination.name))
+        raise
+
+    return backup_dir, moved
+
+
+def main(argv=None):
+    args = parse_args(argv)
+    if not args.yes:
+        print("此操作会重置正式行情、增强因子和选股结果。")
+        print("原文件不会永久删除,而会移动到 data/backups。")
+        confirmation = input("请输入 RESET 确认: ").strip()
+        if confirmation != "RESET":
+            print("已取消。")
+            return 1
+
+    backup_dir, moved = safe_reset_data()
+    if not moved:
+        print("没有找到需要重置的数据文件。")
+        return 0
+
+    print(f"已安全重置 {len(moved)} 个文件。")
+    print(f"备份目录: {backup_dir}")
+    print("下次运行 update_stock_data.py 将自动执行全量初始化。")
+    return 0
+
+
+if __name__ == "__main__":
+    sys.exit(main())
diff --git a/scripts/update_stock_data.py b/scripts/update_stock_data.py
new file mode 100644
index 0000000..f7ebd2a
--- /dev/null
+++ b/scripts/update_stock_data.py
@@ -0,0 +1,331 @@
+#!/usr/bin/env python3
+"""A-share data update dispatcher: incremental by default, full on request."""
+
+import argparse
+import json
+import os
+import pickle
+import sys
+from datetime import datetime
+from pathlib import Path
+
+import numpy as np
+import pandas as pd
+
+
+PROJECT_ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(PROJECT_ROOT))
+os.chdir(PROJECT_ROOT)
+
+from scripts import data_update_v2 as data_source
+
+
+logger = data_source.logger
+DATA_FILE = PROJECT_ROOT / "data" / "akshare_real_data_fixed.pkl"
+METADATA_FILE = PROJECT_ROOT / "data" / "akshare_real_data_fixed_metadata.json"
+DEFAULT_CONTEXT_DAYS = 70
+DEFAULT_OVERLAP_DAYS = 7
+DEFAULT_FULL_DAYS = 730
+DEFAULT_MIN_COVERAGE = 0.90
+
+
+def parse_args(argv=None):
+    parser = argparse.ArgumentParser(
+        description="更新A股行情;默认增量,使用 --full 执行全量重建"
+    )
+    parser.add_argument(
+        "--full",
+        action="store_true",
+        help="忽略现有数据并执行全量重建",
+    )
+    parser.add_argument(
+        "--n-stocks",
+        default="all",
+        type=data_source.parse_n_stocks,
+        help="股票数量,正整数或 all;默认 all",
+    )
+    parser.add_argument(
+        "--days",
+        default=DEFAULT_FULL_DAYS,
+        type=int,
+        help=f"全量重建历史天数;默认 {DEFAULT_FULL_DAYS}",
+    )
+    parser.add_argument(
+        "--context-days",
+        default=DEFAULT_CONTEXT_DAYS,
+        type=int,
+        help=f"增量下载的最小技术指标上下文;默认 {DEFAULT_CONTEXT_DAYS}",
+    )
+    parser.add_argument(
+        "--overlap-days",
+        default=DEFAULT_OVERLAP_DAYS,
+        type=int,
+        help=f"增量合并重叠窗口;默认 {DEFAULT_OVERLAP_DAYS}",
+    )
+    parser.add_argument(
+        "--min-coverage",
+        default=DEFAULT_MIN_COVERAGE,
+        type=float,
+        help=(
+            "允许写入的最低股票覆盖率;默认 "
+            f"{DEFAULT_MIN_COVERAGE:.0%}"
+        ).replace("%", "%%"),
+    )
+    parser.add_argument(
+        "--force",
+        action="store_true",
+        help="即使数据已覆盖最近预期交易日,也强制执行增量请求",
+    )
+    return parser.parse_args(argv)
+
+
+def latest_complete_market_date(df, coverage_ratio=0.8):
+    """Return the latest date whose stock coverage is broadly complete."""
+    if df is None or len(df) == 0:
+        return None
+    if not {"date", "stock_code"}.issubset(df.columns):
+        return None
+
+    dates = pd.to_datetime(df["date"], errors="coerce").dt.normalize()
+    valid = df.loc[dates.notna(), ["stock_code"]].copy()
+    valid["_date"] = dates[dates.notna()].values
+    counts = valid.groupby("_date")["stock_code"].nunique().sort_index()
+    if counts.empty:
+        return None
+
+    minimum_count = max(1, int(np.ceil(counts.max() * coverage_ratio)))
+    complete = counts[counts >= minimum_count]
+    selected = complete.index.max() if not complete.empty else counts.index.max()
+    return pd.Timestamp(selected).normalize()
+
+
+def latest_expected_business_date(now=None, market_close_hour=16):
+    """Approximate the latest completed trading day without an exchange calendar."""
+    current = pd.Timestamp(now or datetime.now())
+    day = current.normalize()
+    if day.weekday() < 5 and current.hour >= market_close_hour:
+        return day
+
+    end = day - pd.Timedelta(days=1) if day.weekday() < 5 else day
+    return pd.bdate_range(end=end, periods=1)[0].normalize()
+
+
+def prepare_incremental_rows(existing, fetched, replace_start):
+    """Keep only overlap/new rows while retaining context for newly listed stocks."""
+    existing_codes = set(existing["stock_code"].astype(str).str.zfill(6))
+    updates = fetched.copy()
+    updates["stock_code"] = updates["stock_code"].astype(str).str.zfill(6)
+    updates["date"] = pd.to_datetime(updates["date"], errors="coerce")
+    updates = updates.dropna(subset=["date", "stock_code"])
+
+    is_new_stock = ~updates["stock_code"].isin(existing_codes)
+    updates = updates[is_new_stock | (updates["date"] >= replace_start)].copy()
+    return updates.drop_duplicates(["stock_code", "date"], keep="last")
+
+
+def merge_incremental_data(existing, fetched, replace_start):
+    """Replace matching stock/date keys and append genuinely new observations."""
+    current = existing
+    if not pd.api.types.is_datetime64_any_dtype(current["date"]):
+        current = current.copy()
+        current["date"] = pd.to_datetime(current["date"], errors="coerce")
+    if not pd.api.types.is_string_dtype(current["stock_code"]):
+        if current is existing:
+            current = current.copy()
+        current["stock_code"] = current["stock_code"].astype(str).str.zfill(6)
+    updates = prepare_incremental_rows(current, fetched, replace_start)
+    if len(updates) == 0:
+        return current, 0, 0
+
+    update_index = pd.MultiIndex.from_frame(updates[["stock_code", "date"]])
+    current_index = pd.MultiIndex.from_frame(current[["stock_code", "date"]])
+    retained = current.loc[~current_index.isin(update_index)]
+    merged = pd.concat([retained, updates], ignore_index=True, sort=False)
+
+    new_rows = max(0, len(merged) - len(current))
+    replaced_rows = len(updates) - new_rows
+    return merged, int(new_rows), int(replaced_rows)
+
+
+def calculate_download_coverage(existing, fetched, requested_stock_count=None):
+    """Calculate coverage independently of optional data-source metadata."""
+    expected = int(
+        requested_stock_count
+        if requested_stock_count is not None
+        else existing["stock_code"].astype(str).nunique()
+    )
+    actual = int(fetched["stock_code"].astype(str).nunique())
+    calculated = actual / expected if expected > 0 else 0.0
+    reported = fetched.attrs.get("coverage_ratio")
+    coverage = (
+        min(calculated, float(reported))
+        if reported is not None
+        else calculated
+    )
+    return expected, actual, coverage
+
+
+def write_pickle_atomic(df, destination):
+    destination = Path(destination)
+    destination.parent.mkdir(parents=True, exist_ok=True)
+    temporary = destination.with_suffix(destination.suffix + ".tmp")
+    try:
+        with temporary.open("wb") as handle:
+            pickle.dump(df, handle, protocol=pickle.HIGHEST_PROTOCOL)
+        os.replace(temporary, destination)
+    finally:
+        if temporary.exists():
+            temporary.unlink()
+
+
+def write_json_atomic(payload, destination):
+    destination = Path(destination)
+    destination.parent.mkdir(parents=True, exist_ok=True)
+    temporary = destination.with_suffix(destination.suffix + ".tmp")
+    try:
+        with temporary.open("w", encoding="utf-8") as handle:
+            json.dump(payload, handle, ensure_ascii=False, indent=2)
+        os.replace(temporary, destination)
+    finally:
+        if temporary.exists():
+            temporary.unlink()
+
+
+def run_full_update(args):
+    count = "all" if args.n_stocks is None else str(args.n_stocks)
+    logger.info("更新模式: 全量重建")
+    return data_source.main([
+        "--n-stocks",
+        count,
+        "--days",
+        str(args.days),
+    ])
+
+
+def run_incremental_update(args):
+    if not DATA_FILE.exists():
+        logger.warning("未找到本地正式数据,自动执行首次全量初始化")
+        return run_full_update(args)
+
+    logger.info("=" * 60)
+    logger.info("数据更新任务开始 - 默认增量模式")
+    logger.info("=" * 60)
+    with DATA_FILE.open("rb") as handle:
+        existing = pickle.load(handle)
+
+    latest_before = latest_complete_market_date(existing)
+    if latest_before is None:
+        logger.error("无法识别本地完整交易日,请使用 --full 重建数据")
+        return 1
+
+    expected_date = latest_expected_business_date()
+    logger.info(
+        f"本地完整交易日: {latest_before:%Y-%m-%d}; "
+        f"预期最新交易日: {expected_date:%Y-%m-%d}"
+    )
+    if latest_before >= expected_date and not args.force:
+        logger.info("本地行情已是最新,无需发起网络请求")
+        logger.info("✅ 增量数据更新完成(无新增)")
+        return 0
+
+    stale_days = max(0, (expected_date - latest_before).days)
+    fetch_days = max(args.context_days, stale_days + args.overlap_days)
+    count_desc = "全部A股" if args.n_stocks is None else f"{args.n_stocks}只股票"
+    logger.info(
+        f"增量请求范围: {count_desc}; 上下文天数: {fetch_days}; "
+        f"重叠天数: {args.overlap_days}"
+    )
+
+    fetched = data_source.fetch_real_stock_data_from_akshare(
+        n_stocks=args.n_stocks,
+        days=fetch_days,
+    )
+    if fetched is None or len(fetched) == 0:
+        logger.error("增量数据源未返回有效行情,保留原文件不变")
+        return 1
+
+    expected_stock_count, actual_stock_count, coverage = (
+        calculate_download_coverage(
+            existing,
+            fetched,
+            requested_stock_count=args.n_stocks,
+        )
+    )
+    if coverage is not None and coverage < args.min_coverage:
+        logger.error(
+            f"增量股票覆盖率 {actual_stock_count}/{expected_stock_count} "
+            f"({coverage:.2%}) 低于最低要求 "
+            f"{args.min_coverage:.0%},保留原文件不变"
+        )
+        return 1
+
+    replace_start = latest_before - pd.Timedelta(days=args.overlap_days)
+    merged, new_rows, replaced_rows = merge_incremental_data(
+        existing,
+        fetched,
+        replace_start,
+    )
+    latest_after = latest_complete_market_date(merged)
+    if latest_after is None or latest_after < latest_before:
+        logger.error("合并后完整交易日倒退,拒绝写入并保留原文件")
+        return 1
+
+    merged.attrs.update(getattr(existing, "attrs", {}))
+    merged.attrs.update({
+        "source": f"incremental_{fetched.attrs.get('source', 'multi_source')}",
+        "update_mode": "incremental",
+        "factors_need_refresh": True,
+        "coverage_ratio": coverage,
+    })
+
+    logger.info(
+        f"增量合并: 下载 {len(fetched)} 条,新增 {new_rows} 条,"
+        f"替换 {replaced_rows} 条"
+    )
+    logger.info("正在原子写入正式数据文件...")
+    write_pickle_atomic(merged, DATA_FILE)
+
+    metadata = {
+        "create_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
+        "source": merged.attrs["source"],
+        "update_mode": "incremental",
+        "description": "AKShare/BaoStock/腾讯行情增量合并数据",
+        "requested_stock_count": (
+            "all" if args.n_stocks is None else int(args.n_stocks)
+        ),
+        "context_days": int(fetch_days),
+        "overlap_days": int(args.overlap_days),
+        "previous_complete_date": latest_before.strftime("%Y-%m-%d"),
+        "latest_complete_date": latest_after.strftime("%Y-%m-%d"),
+        "stock_count": int(merged["stock_code"].nunique()),
+        "total_records": int(len(merged)),
+        "downloaded_records": int(len(fetched)),
+        "new_records": new_rows,
+        "replaced_records": replaced_rows,
+        "coverage_ratio": coverage,
+        "expected_stock_count": expected_stock_count,
+        "downloaded_stock_count": actual_stock_count,
+        "factors_need_refresh": True,
+        "date_range": f"{merged['date'].min()} to {merged['date'].max()}",
+    }
+    write_json_atomic(metadata, METADATA_FILE)
+
+    logger.info(f"✓ 最新完整交易日: {latest_after:%Y-%m-%d}")
+    logger.info(f"✓ 股票数量: {merged['stock_code'].nunique()}")
+    logger.info(f"✓ 总记录数: {len(merged)}")
+    logger.info("✅ 增量数据更新完成")
+    return 0
+
+
+def main(argv=None):
+    args = parse_args(argv)
+    for name in ("days", "context_days", "overlap_days"):
+        if getattr(args, name) <= 0:
+            raise SystemExit(f"--{name.replace('_', '-')} 必须为正整数")
+    if not 0 < args.min_coverage <= 1:
+        raise SystemExit("--min-coverage 必须在 0 和 1 之间")
+    return run_full_update(args) if args.full else run_incremental_update(args)
+
+
+if __name__ == "__main__":
+    sys.exit(main())
diff --git a/tests/test_a_stock_manager.py b/tests/test_a_stock_manager.py
index 05a2415..f5674bc 100644
--- a/tests/test_a_stock_manager.py
+++ b/tests/test_a_stock_manager.py
@@ -60,6 +60,35 @@
         self.assertEqual(args, ["--n-stocks", "all"])
         self.assertIn("全量", description)
 
+    def test_data_update_defaults_to_incremental_dispatcher(self):
+        with patch("builtins.input", return_value="1"), patch.object(
+            a_stock_manager, "run_script", return_value=True
+        ) as run, patch.object(
+            a_stock_manager, "run_enhanced_factor_system", return_value=True
+        ):
+            result = a_stock_manager.data_update()
+
+        self.assertTrue(result)
+        run.assert_called_once_with(
+            "update_stock_data.py",
+            "增量更新全部A股",
+        )
+
+    def test_data_update_full_rebuild_is_explicit(self):
+        with patch("builtins.input", return_value="2"), patch.object(
+            a_stock_manager, "run_script", return_value=True
+        ) as run, patch.object(
+            a_stock_manager, "run_enhanced_factor_system", return_value=True
+        ):
+            result = a_stock_manager.data_update()
+
+        self.assertTrue(result)
+        run.assert_called_once_with(
+            "update_stock_data.py",
+            "全量重建全部A股",
+            args=["--full", "--n-stocks", "all", "--days", "730"],
+        )
+
 
 if __name__ == "__main__":
     unittest.main()
diff --git a/tests/test_incremental_update.py b/tests/test_incremental_update.py
new file mode 100644
index 0000000..b0c8853
--- /dev/null
+++ b/tests/test_incremental_update.py
@@ -0,0 +1,161 @@
+import importlib
+import pickle
+import sys
+import tempfile
+import unittest
+from datetime import datetime
+from pathlib import Path
+from unittest.mock import patch
+
+import pandas as pd
+
+
+PROJECT_ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(PROJECT_ROOT))
+
+incremental = importlib.import_module("scripts.update_stock_data")
+reset_data = importlib.import_module("scripts.reset_stock_data")
+
+
+class IncrementalUpdateTests(unittest.TestCase):
+    def test_default_mode_is_full_universe_incremental(self):
+        args = incremental.parse_args([])
+
+        self.assertFalse(args.full)
+        self.assertIsNone(args.n_stocks)
+        self.assertEqual(args.context_days, 70)
+        self.assertEqual(args.overlap_days, 7)
+
+    def test_latest_complete_date_ignores_partial_newer_market(self):
+        rows = []
+        for code in ["600001", "000001", "300001", "688001"]:
+            rows.append({"date": "2026-07-09", "stock_code": code})
+        rows.append({"date": "2026-07-10", "stock_code": "920001"})
+
+        result = incremental.latest_complete_market_date(pd.DataFrame(rows))
+
+        self.assertEqual(result, pd.Timestamp("2026-07-09"))
+
+    def test_expected_business_date_handles_weekend_and_preclose(self):
+        self.assertEqual(
+            incremental.latest_expected_business_date(
+                datetime(2026, 7, 11, 12, 0)
+            ),
+            pd.Timestamp("2026-07-10"),
+        )
+        self.assertEqual(
+            incremental.latest_expected_business_date(
+                datetime(2026, 7, 13, 10, 0)
+            ),
+            pd.Timestamp("2026-07-10"),
+        )
+
+    def test_merge_replaces_duplicate_keys_and_keeps_new_stock_context(self):
+        existing = pd.DataFrame([
+            {
+                "date": "2026-07-08",
+                "stock_code": "600001",
+                "close": 10.0,
+                "final_score": 0.8,
+            },
+            {
+                "date": "2026-07-09",
+                "stock_code": "600001",
+                "close": 10.5,
+                "final_score": 0.9,
+            },
+        ])
+        fetched = pd.DataFrame([
+            {"date": "2026-07-01", "stock_code": "600001", "close": 9.0},
+            {"date": "2026-07-09", "stock_code": "600001", "close": 10.6},
+            {"date": "2026-07-10", "stock_code": "600001", "close": 10.8},
+            {"date": "2026-06-01", "stock_code": "920001", "close": 20.0},
+            {"date": "2026-07-10", "stock_code": "920001", "close": 21.0},
+        ])
+
+        result, new_rows, replaced_rows = incremental.merge_incremental_data(
+            existing,
+            fetched,
+            pd.Timestamp("2026-07-03"),
+        )
+
+        self.assertEqual(len(result), 5)
+        self.assertEqual(new_rows, 3)
+        self.assertEqual(replaced_rows, 1)
+        replaced = result[
+            (result["stock_code"] == "600001")
+            & (result["date"] == pd.Timestamp("2026-07-09"))
+        ]
+        self.assertEqual(replaced["close"].tolist(), [10.6])
+        self.assertIn(pd.Timestamp("2026-06-01"), set(result["date"]))
+        self.assertNotIn(pd.Timestamp("2026-07-01"), set(result["date"]))
+
+    def test_coverage_uses_existing_universe_when_upstream_has_no_metadata(self):
+        existing = pd.DataFrame({
+            "stock_code": [f"{index:06d}" for index in range(100)]
+        })
+        fetched = pd.DataFrame({
+            "stock_code": [f"{index:06d}" for index in range(20)]
+        })
+
+        expected, actual, coverage = incremental.calculate_download_coverage(
+            existing,
+            fetched,
+        )
+
+        self.assertEqual(expected, 100)
+        self.assertEqual(actual, 20)
+        self.assertEqual(coverage, 0.2)
+
+    def test_up_to_date_file_skips_network_fetch(self):
+        data = pd.DataFrame([
+            {"date": "2026-07-10", "stock_code": "600001", "close": 10.0},
+            {"date": "2026-07-10", "stock_code": "000001", "close": 11.0},
+        ])
+        with tempfile.TemporaryDirectory() as temp_dir:
+            data_file = Path(temp_dir) / "stock.pkl"
+            with data_file.open("wb") as handle:
+                pickle.dump(data, handle)
+
+            args = incremental.parse_args([])
+            with patch.object(incremental, "DATA_FILE", data_file), patch.object(
+                incremental,
+                "latest_expected_business_date",
+                return_value=pd.Timestamp("2026-07-10"),
+            ), patch.object(
+                incremental.data_source,
+                "fetch_real_stock_data_from_akshare",
+            ) as fetch:
+                result = incremental.run_incremental_update(args)
+
+        self.assertEqual(result, 0)
+        fetch.assert_not_called()
+
+
+class SafeResetTests(unittest.TestCase):
+    def test_reset_moves_generated_files_to_timestamped_backup(self):
+        with tempfile.TemporaryDirectory() as temp_dir:
+            data_dir = Path(temp_dir) / "data"
+            backup_root = data_dir / "backups"
+            data_dir.mkdir()
+            source = data_dir / "akshare_real_data_fixed.pkl"
+            source.write_bytes(b"stock-data")
+
+            backup_dir, moved = reset_data.safe_reset_data(
+                data_dir=data_dir,
+                backup_root=backup_root,
+                now=datetime(2026, 7, 11, 9, 30),
+            )
+
+            self.assertFalse(source.exists())
+            self.assertEqual(
+                backup_dir.name,
+                "stock_data_20260711_093000",
+            )
+            self.assertEqual([path.name for path in moved], [source.name])
+            self.assertEqual((backup_dir / source.name).read_bytes(), b"stock-data")
+            self.assertTrue((backup_dir / "manifest.json").exists())
+
+
+if __name__ == "__main__":
+    unittest.main()

--
Gitblit v1.8.0