程序员量化交易实战 33:汇总模拟盘运行历史

程序员量化交易实战 33:汇总模拟盘运行历史

第 32 篇把每日运行结果写成了 JSON 归档。

单日归档解决了“当天发生了什么”。第 33 篇要回答另一个问题:最近一段时间,这个模拟盘系统是否稳定。

历史摘要看什么

现在先不做复杂报表,只统计四个最基础的指标:

字段含义
report_count归档报告数量
latest_trade_date最新交易日
latest_status最新健康状态
blocker_count历史阻断次数
notification_success_rate通知成功率

这些指标足够支撑一个很实际的判断:如果最近十天有三天 blocker,问题不在策略,而在运行链路。

摘要对象

第 33 章新增app/run_history.py

@dataclass(frozen=True) class RunHistorySummary: report_count: int latest_trade_date: str latest_status: str blocker_count: int notification_success_rate: float

这不是策略收益统计,而是运行质量统计。

从归档目录读取

实现逻辑很直接:读取目录下所有*-paper-report.json,按文件名排序,然后统计。

reports = [] for path in sorted(Path(directory).glob("*-paper-report.json")): reports.append(read_archived_report(path))

空目录也要有明确返回,不能抛异常。

if not reports: return RunHistorySummary(0, "", "missing", 0, 0.0)

对模拟盘来说,missing是一个有用状态。它告诉上层:不是系统健康,而是还没有历史。

通知成功率

通知成功率按归档报告里的健康信息统计。

notification_count = sum( 1 for item in reports if item["health"].get("notification_accepted") )

最后保留 6 位小数:

notification_success_rate=round(notification_count / len(reports), 6)

这里没有引入 pandas,也没有做图。运行历史摘要应该足够轻,可以在命令行、接口、日报里随手调用。

当前联动运行结果

paper-ops-check会先写入一条前一日 blocker 归档,再写入当天 ok 归档,然后从归档目录汇总历史:

uv run python -m scripts.chapter_examples paper-ops-check

这次历史摘要里,report_count=2blocker_count=1,通知成功率是50%。这不是收益统计,而是运行质量统计。等真实调度接入以后,这类摘要可以快速回答“最近是策略表现不好,还是系统经常没跑稳”。

测试历史统计

测试先复用第 32 章的归档函数造两天数据:

uv run pytest tests/test_run_history.py

关键断言:

assert summary.report_count == 2 assert summary.latest_trade_date == "2026-01-29" assert summary.latest_status == "blocker" assert summary.blocker_count == 1 assert summary.notification_success_rate == 0.5

这组断言说明历史摘要能跨多个归档文件稳定工作。

本章更新与代码仓库

本章更新内容:

  • 新增app/run_history.py
  • 实现RunHistorySummary
  • 从日报归档目录读取历史报告。
  • 统计报告数量、最新状态、阻断次数和通知成功率。
  • 增加paper-ops-check联动示例,展示两日归档汇总后的运行历史。
  • 补充运行质量统计和收益统计的区别。
  • 新增tests/test_run_history.py,覆盖正常目录和空目录。

代码仓库:

https://github.com/ax2/zi-quant-platform

本章代码:

git clone https://github.com/ax2/zi-quant-platform.git cd zi-quant-platform git checkout chapter-33 uv sync --extra dev uv run pytest tests/test_run_history.py

第 33 章提交为9f55d07,tag 为chapter-33

本篇小结

历史摘要让模拟盘从“今天是否跑完”变成“最近是否稳定”。

第 33 篇读取归档报告,拿到最新状态、阻断次数和通知成功率。下一篇会继续补一个常见的生产问题:行情数据缺口应该如何被显式识别,而不是被策略静默忽略。