log
2026-07-11 2fa3e25841826aa4e8f95d988024f16149793368
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
#!/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="与 --skip-if-current 同时使用时仍强制刷新(兼容旧命令)",
    )
    parser.add_argument(
        "--skip-if-current",
        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 market_date_coverage(df, date, expected_stock_count=None):
    """Return stock count and coverage for one market date."""
    normalized_dates = pd.to_datetime(df["date"], errors="coerce").dt.normalize()
    date = pd.Timestamp(date).normalize()
    actual = int(df.loc[normalized_dates == date, "stock_code"].astype(str).nunique())
    expected = int(
        expected_stock_count
        if expected_stock_count is not None
        else df["stock_code"].astype(str).nunique()
    )
    coverage = actual / expected if expected > 0 else 0.0
    return expected, actual, coverage
 
 
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}"
    )
    before_expected, before_actual, before_coverage = market_date_coverage(
        existing,
        latest_before,
    )
    logger.info(
        f"本地最新日覆盖: {before_actual}/{before_expected} "
        f"({before_coverage:.2%})"
    )
    if latest_before >= expected_date and args.skip_if_current and not args.force:
        logger.info("本地行情已是最新,无需发起网络请求")
        logger.info("✅ 增量数据更新完成(无新增)")
        return 0
    if latest_before >= expected_date:
        logger.info("日期已是最新,仍按默认策略刷新并覆盖最近行情窗口")
 
    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
 
    latest_expected_count, latest_actual_count, latest_coverage = (
        market_date_coverage(
            merged,
            latest_after,
            expected_stock_count=max(
                expected_stock_count,
                int(merged["stock_code"].astype(str).nunique()),
            ),
        )
    )
 
    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"),
        "latest_date_stock_count": latest_actual_count,
        "latest_date_expected_stock_count": latest_expected_count,
        "latest_date_coverage_ratio": latest_coverage,
        "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"✓ 最新日覆盖: {latest_actual_count}/{latest_expected_count} "
        f"({latest_coverage:.2%})"
    )
    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())