Coverage for generate_backtest_report.py: 100%
276 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""Regenerates the Overview of README.md's "Backtest Statistics" section (equity
2chart, headline table, run history) from the most recent real Lean backtest
3run under backtests/.
5A static markdown file can't truly "live update," so this is the practical
6substitute: `aq backtest` calls this module after a successful `lean
7backtest .` run, and it rewrites a chart image plus a small stats table
8in-place between two HTML comment markers in README.md, so the README stays
9current with whatever backtest you last ran without any manual copy-pasting.
11Data source: Lean's own backtest result JSON (`backtests/<run>/<id>.json`)
12already contains everything needed, natively time-aligned, in one file - no
13cross-file join needed:
14- `statistics`: a flat dict of ready-to-use strings (Sharpe Ratio, Net
15 Profit, Drawdown, ...).
16- `charts["Strategy Equity"]["series"]["Equity"]["values"]`: the algorithm's
17 own dated equity curve.
18- `charts["Benchmark"]["series"]["Benchmark"]["values"]`: Lean's own
19 benchmark series, time-aligned with "Strategy Equity" in the same file.
20 Since V6.0.0 `main.py` points it at the daily SPY subscription
21 (`runtime.benchmark_ticker`); before that Lean used its internal hourly SPY
22 feed, whose local zip ends 2021-03-31, so every later run carries a constant
23 benchmark. For such a run the chart redraws SPY from the daily zip.
25Usage:
26 python generate_backtest_report.py [--backtests-dir backtests] [--backtest-dir backtests/<run>] [--readme README.md]
27 [--chart-path development/backtest_equity_chart.png]
28"""
30from __future__ import annotations
32import argparse
33import json
34import re
35import sys
36import zipfile
37from collections.abc import Iterator
38from datetime import datetime, timedelta, timezone
39from pathlib import Path
41import matplotlib
43matplotlib.use("Agg")
44import matplotlib.pyplot as plt
46from evaluation.backtest_audit import configured_run_window
48ROOT_DIR = Path(__file__).resolve().parent
49BACKTESTS_DIR = ROOT_DIR / "backtests"
50README_PATH = ROOT_DIR / "README.md"
51RESEARCH_DOC_RELATIVE = Path("development") / "research_results.md"
52CHART_PATH = ROOT_DIR / "development" / "backtest_equity_chart.png"
53DAILY_SPY_ZIP = ROOT_DIR / "data" / "equity" / "usa" / "daily" / "spy.zip"
54LEAN_EQUITY_PRICE_SCALE = 10_000.0
55# Lean stamps a daily chart point at New York midnight; UTC-4 maps every point to its own session date.
56_NEW_YORK_OFFSET = timedelta(hours=4)
58_RESULT_JSON_PATTERN = re.compile(r"^\d+\.json$")
59BACKTEST_MARKER_START = "<!-- AQ:BACKTEST_START -->"
60BACKTEST_MARKER_END = "<!-- AQ:BACKTEST_END -->"
62_STAT_KEYS_FOR_TABLE = [
63 "Sharpe Ratio",
64 "Net Profit",
65 "Compounding Annual Return",
66 "Drawdown",
67 "Total Orders",
68 "Win Rate",
69]
72def _iter_backtest_result_jsons(backtests_dir: Path) -> Iterator[Path]:
73 """Yields every backtest run's bare <digits>.json result file (never
74 *-summary.json), newest folder first. Sorted by each folder's own mtime,
75 not by name: the standard `lean backtest .` folders are named
76 YYYY-MM-DD_HH-MM-SS (lexicographic == chronological), but this
77 directory can also contain differently-named ad-hoc/manual run folders
78 (e.g. `lean-local-test-N`) that would otherwise sort ahead of every
79 real timestamped folder and get picked as "latest" by mistake."""
80 if not backtests_dir.exists():
81 return
82 run_dirs = sorted(
83 (d for d in backtests_dir.iterdir() if d.is_dir()),
84 # equal mtimes (folders created within one filesystem tick) fall back to the name, chronological for Lean's folders
85 key=lambda d: (d.stat().st_mtime, d.name),
86 reverse=True,
87 )
88 for run_dir in run_dirs:
89 for candidate in sorted(run_dir.iterdir()):
90 if candidate.is_file() and _RESULT_JSON_PATTERN.match(candidate.name):
91 yield candidate
92 break # at most one result JSON per backtest folder
95PIN_PATH = ROOT_DIR / "ml" / "evaluation" / "readme_lean_run.json"
98def pinned_run_dir(backtests_dir: Path = BACKTESTS_DIR, pin_path: Path | None = None) -> Path | None:
99 """The run folder the README's Lean blocks were pinned to with `--backtest-dir` (V6.1.0): the newest run is not always the
100 shipped configuration's (a rejected-config run can come last), and every block that reads "the Lean run" must read the same
101 one. None when nothing is pinned, the pin names a missing folder, or `backtests_dir` is not the default one."""
102 pin_path = pin_path or PIN_PATH
103 if backtests_dir != BACKTESTS_DIR or not pin_path.exists():
104 return None
105 try:
106 name = json.loads(pin_path.read_text(encoding="utf-8")).get("run")
107 except (OSError, ValueError):
108 return None
109 candidate = backtests_dir / str(name) if name else None
110 return candidate if candidate is not None and candidate.is_dir() else None
113def set_pinned_run(run_dir: Path | None, pin_path: Path | None = None) -> None:
114 """Pin the README's Lean blocks to `run_dir`, or clear the pin (`None`: a fresh `aq backtest` unpins)."""
115 pin_path = pin_path or PIN_PATH
116 if run_dir is None:
117 pin_path.unlink(missing_ok=True)
118 return
119 pin_path.parent.mkdir(parents=True, exist_ok=True)
120 # a companion long-window run belongs to this pin, and goes with it when the pin moves to another run
121 previous = json.loads(pin_path.read_text(encoding="utf-8")) if pin_path.exists() else {}
122 payload = {"run": Path(run_dir).name}
123 if previous.get("run") == payload["run"] and previous.get("long_run"):
124 payload["long_run"] = previous["long_run"]
125 pin_path.write_text(json.dumps(payload), encoding="utf-8")
128def find_latest_backtest_result_json(backtests_dir: Path = BACKTESTS_DIR) -> Path | None:
129 """Returns the newest backtest run's result JSON that actually contains
130 both a populated Strategy Equity curve AND a populated statistics
131 block - skips runs that errored out or were interrupted before
132 finishing (Lean can write a result JSON with a partially-populated
133 equity curve but an empty `statistics` dict if the process didn't reach
134 the end of the run), so an incomplete run never clobbers the README
135 with a chart but no Sharpe/drawdown/etc. numbers."""
136 pinned = pinned_run_dir(backtests_dir)
137 if pinned is not None:
138 pinned_result = _result_json_in(pinned)
139 if pinned_result is not None:
140 return pinned_result
141 for candidate in _iter_backtest_result_jsons(backtests_dir):
142 try:
143 data = json.loads(candidate.read_text(encoding="utf-8"))
144 except (OSError, ValueError):
145 continue
146 values = data.get("charts", {}).get("Strategy Equity", {}).get("series", {}).get("Equity", {}).get("values", [])
147 statistics = data.get("statistics", {})
148 if values and statistics:
149 return candidate
150 return None
153def resolve_lean_run_dir(explicit: Path | str | None = None, backtests_dir: Path = BACKTESTS_DIR) -> Path | None:
154 """The one Lean run every run-reading tool uses (V6.3.0): an explicit folder, else the README pin, else the newest
155 finished run (`find_latest_backtest_result_json`). Before this each `aq evaluate` flag picked "latest" its own way and
156 none honoured the pin, so two README blocks could describe two different runs."""
157 if explicit:
158 return Path(explicit)
159 latest = find_latest_backtest_result_json(backtests_dir)
160 return latest.parent if latest is not None else None
163def load_backtest_summary(result_json_path: Path) -> dict:
164 """Parses a Lean backtest result JSON into a clean summary: the
165 statistics dict, plus dated (timestamp, value) strategy/benchmark
166 series."""
167 data = json.loads(result_json_path.read_text(encoding="utf-8"))
168 statistics = data.get("statistics", {})
169 charts = data.get("charts", {})
171 strategy_points = charts.get("Strategy Equity", {}).get("series", {}).get("Equity", {}).get("values", [])
172 benchmark_points = charts.get("Benchmark", {}).get("series", {}).get("Benchmark", {}).get("values", [])
174 # Equity points are [timestamp, open, high, low, close] with all four
175 # OHLC values identical (an equity total, not a real price bar) -
176 # benchmark points are plain [timestamp, price]. The last element is
177 # the value we want in both cases.
178 strategy_series = [(int(point[0]), float(point[-1])) for point in strategy_points]
179 # a benchmark function answers 0.0 until the first price exists: such leading points cannot be rebased
180 benchmark_series = [(int(point[0]), float(point[-1])) for point in benchmark_points if float(point[-1]) > 0.0]
182 configured_start, configured_end = configured_run_window(data)
183 start_date = configured_start or (datetime.fromtimestamp(strategy_series[0][0], tz=timezone.utc) if strategy_series else None)
184 end_date = configured_end or (datetime.fromtimestamp(strategy_series[-1][0], tz=timezone.utc) if strategy_series else None)
186 return {
187 "statistics": statistics,
188 "strategy_series": strategy_series,
189 "benchmark_series": benchmark_series,
190 "start_date": start_date,
191 "end_date": end_date,
192 "result_json_path": result_json_path,
193 }
196def benchmark_is_flat(series: list[tuple[int, float]]) -> bool:
197 """True when Lean's benchmark carries at most one distinct value (a stale benchmark feed, see the module doc)."""
198 return len({value for _, value in series}) <= 1
201def read_daily_closes(zip_path: Path) -> list[tuple[str, float]]:
202 """(YYYYMMDD, close) per bar of a Lean daily equity zip, prices unscaled."""
203 with zipfile.ZipFile(zip_path) as archive:
204 member = next(name for name in archive.namelist() if name.endswith(".csv"))
205 rows = archive.read(member).decode("utf-8").splitlines()
206 closes = []
207 for row in rows:
208 fields = row.split(",")
209 if len(fields) >= 5:
210 closes.append((fields[0][:8], float(fields[4]) / LEAN_EQUITY_PRICE_SCALE))
211 return closes
214def daily_benchmark_series(strategy_series: list[tuple[int, float]], closes: list[tuple[str, float]]) -> list[tuple[int, float]]:
215 """The benchmark at each strategy timestamp: the last daily close on or before that point's session date."""
216 import bisect
218 dates = [day for day, _ in closes]
219 series = []
220 for timestamp, _ in strategy_series:
221 session = (datetime.fromtimestamp(timestamp, tz=timezone.utc) - _NEW_YORK_OFFSET).strftime("%Y%m%d")
222 index = bisect.bisect_right(dates, session) - 1
223 if index >= 0:
224 series.append((timestamp, closes[index][1]))
225 return series
228def with_daily_benchmark_fallback(summary: dict, spy_zip: Path | None = None) -> dict:
229 """Replace a flat Lean benchmark with SPY from the daily zip; flags the summary so the chart says so."""
230 spy_zip = spy_zip or DAILY_SPY_ZIP
231 if not benchmark_is_flat(summary["benchmark_series"]) or not summary["strategy_series"] or not spy_zip.is_file():
232 return summary
233 rebuilt = daily_benchmark_series(summary["strategy_series"], read_daily_closes(spy_zip))
234 if not rebuilt:
235 return summary
236 return dict(summary, benchmark_series=rebuilt, benchmark_source="daily_zip")
239def _rebase_to_100(series: list[tuple[int, float]]) -> list[tuple[int, float]]:
240 """Both series need a common visual scale: strategy equity starts at
241 the algorithm's starting cash (e.g. $100,000), the benchmark is a raw
242 SPY price - neither is directly comparable to the other in absolute
243 terms, so both are indexed to start at 100."""
244 if not series:
245 return []
246 base = series[0][1]
247 if base == 0:
248 return [(timestamp, 100.0) for timestamp, _ in series]
249 return [(timestamp, value / base * 100.0) for timestamp, value in series]
252def generate_equity_chart(summary: dict, output_path: Path = CHART_PATH) -> None:
253 """Renders the strategy-vs-benchmark equity chart as a PNG, embedded in
254 README.md by update_readme_backtest_section()."""
255 strategy = _rebase_to_100(summary["strategy_series"])
256 benchmark = _rebase_to_100(summary["benchmark_series"])
258 output_path.parent.mkdir(parents=True, exist_ok=True)
260 fig, ax = plt.subplots(figsize=(9, 4.5), dpi=150)
261 if strategy:
262 strategy_dates = [datetime.fromtimestamp(ts, tz=timezone.utc) for ts, _ in strategy]
263 ax.plot(
264 strategy_dates,
265 [value for _, value in strategy],
266 label="Aether Quant Strategy",
267 color="#2E86AB",
268 linewidth=1.6,
269 )
270 if benchmark:
271 benchmark_dates = [datetime.fromtimestamp(ts, tz=timezone.utc) for ts, _ in benchmark]
272 ax.plot(
273 benchmark_dates,
274 [value for _, value in benchmark],
275 label=(
276 "S&P 500 (SPY, daily file; Lean's benchmark feed was stale)"
277 if summary.get("benchmark_source") == "daily_zip"
278 else "S&P 500 (SPY) Benchmark"
279 ),
280 color="#A23B72",
281 linewidth=1.6,
282 linestyle="--",
283 )
285 ax.set_title("Backtest Equity: Strategy vs. S&P 500 Benchmark (indexed to 100)")
286 ax.set_ylabel("Indexed value (start = 100)")
287 ax.legend(loc="best", frameon=False)
288 ax.grid(True, alpha=0.25)
289 fig.autofmt_xdate()
290 fig.tight_layout()
291 fig.savefig(output_path)
292 plt.close(fig)
295def _build_stats_markdown(summary: dict, chart_relative_path: str) -> str:
296 statistics = summary["statistics"]
297 start_date, end_date = summary["start_date"], summary["end_date"]
298 window = (
299 f"{start_date.date().isoformat()} to {end_date.date().isoformat()}" if start_date and end_date else "unknown"
300 )
301 updated_at = datetime.now(tz=timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
303 lines = [
304 f"",
305 "",
306 "| Metric | Value |",
307 "|---|---|",
308 f"| Backtest window | {window} |",
309 ]
310 for key in _STAT_KEYS_FOR_TABLE:
311 if key in statistics:
312 lines.append(f"| {key} | {statistics[key]} |")
313 lines.append(f"| Last updated | {updated_at} (auto-generated by `aq backtest`) |")
314 if summary.get("benchmark_source") == "daily_zip":
315 lines += [
316 "",
317 "_Lean's benchmark feed was stale for this run (a constant series), so its Alpha, Beta, Information Ratio, "
318 "Tracking Error and Treynor Ratio are meaningless; the chart redraws SPY from the daily file._",
319 ]
320 return "\n".join(lines)
323def _replace_between_markers(text: str, start_marker: str, end_marker: str, body: str) -> str | None:
324 """Shared atomic marker-replace helper. Returns the updated text, or
325 None if the markers aren't present or nothing changed."""
326 if start_marker not in text or end_marker not in text:
327 return None
328 pattern = re.compile(re.escape(start_marker) + r".*?" + re.escape(end_marker), re.DOTALL)
329 replacement = f"{start_marker}\n{body}\n{end_marker}"
330 updated_text = pattern.sub(replacement, text, count=1)
331 return updated_text if updated_text != text else None
334def _atomic_write(path: Path, text: str) -> None:
335 tmp_path = path.with_suffix(path.suffix + ".tmp")
336 tmp_path.write_text(text, encoding="utf-8")
337 tmp_path.replace(path)
340HISTORY_MARKER_START = "<!-- AQ:BACKTEST_HISTORY_START -->"
341HISTORY_MARKER_END = "<!-- AQ:BACKTEST_HISTORY_END -->"
342HISTORY_LIMIT = 10
345VERDICTS_GLOB = "*/r_lean*.json"
348def load_lean_verdicts(evaluation_dir: Path | None = None) -> list[dict]:
349 """Every `evaluation.lean_verdict` output (`ml/evaluation/<phase>/r_lean*.json`) that names a candidate run."""
350 evaluation_dir = evaluation_dir or (ROOT_DIR / "ml" / "evaluation")
351 verdicts = []
352 for path in sorted(evaluation_dir.glob(VERDICTS_GLOB)):
353 try:
354 payload = json.loads(path.read_text(encoding="utf-8"))
355 except (OSError, ValueError):
356 continue
357 if isinstance(payload, dict) and payload.get("candidate") and "keep" in payload:
358 number = re.match(r"r_lean(\d+)", path.stem)
359 # the file names the rule it records (r_lean16_*.json = R-LEAN16); `rule` inside is lean_verdict's clause set
360 label = payload.get("reported_as") or (f"R-LEAN{number.group(1)}" if number else None) or payload.get("rule") or path.stem
361 verdicts.append(dict(payload, rule=label))
362 return verdicts
365def run_status(run_name: str, pinned_run: str | None, verdicts: list[dict]) -> str:
366 """The history table's Status cell: the README pin is the shipped configuration's run, a verdict file says whether a
367 candidate run was kept or rejected; anything else is a plain run."""
368 labels = []
369 if pinned_run and run_name == pinned_run:
370 labels.append("shipped (README pin)")
371 for verdict in verdicts:
372 if verdict.get("candidate") == run_name:
373 labels.append(f"{'kept' if verdict.get('keep') else 'rejected'} ({verdict.get('rule') or 'verdict'})")
374 return ", ".join(labels) or "-"
377def build_history_markdown(backtests_dir: Path = BACKTESTS_DIR, limit: int = HISTORY_LIMIT, verdicts: list[dict] | None = None, judged_only: bool = False) -> str:
378 """One row per finished Lean run, newest first: the README's main table shows only the latest run, so two runs on
379 different windows (the backtest window, then backtest + holdout) would otherwise overwrite each other."""
380 pinned = pinned_run_dir(backtests_dir)
381 pinned_name = pinned.name if pinned is not None else None
382 verdicts = load_lean_verdicts() if verdicts is None else verdicts
383 rows: list[str] = []
384 pinned_listed = False
385 for candidate in _iter_backtest_result_jsons(backtests_dir):
386 # a batch of later research runs must not push the shipped configuration's run off the table
387 if len(rows) >= limit and (pinned_listed or pinned_name is None):
388 break
389 if len(rows) >= limit and candidate.parent.name != pinned_name:
390 continue
391 pinned_listed = pinned_listed or candidate.parent.name == pinned_name
392 if judged_only and pinned_name and run_status(candidate.parent.name, pinned_name, verdicts) == "-":
393 continue
394 try:
395 summary = load_backtest_summary(candidate)
396 except (OSError, ValueError, IndexError):
397 continue
398 statistics = summary["statistics"]
399 if not summary["strategy_series"] or not statistics:
400 continue
401 start, end = summary["start_date"], summary["end_date"]
402 window = f"{start.date().isoformat()} to {end.date().isoformat()}" if start and end else "unknown"
403 rows.append(
404 f"| `{candidate.parent.name}` | {window} | {statistics.get('Sharpe Ratio', 'n/a')} | "
405 f"{statistics.get('Net Profit', 'n/a')} | {statistics.get('Drawdown', 'n/a')} | {statistics.get('Total Orders', 'n/a')} | "
406 f"{run_status(candidate.parent.name, pinned_name, verdicts)} |"
407 )
408 if not rows:
409 return "_No finished Lean run yet._"
410 computed = datetime.now(tz=timezone.utc).date().isoformat()
411 return "\n".join([
412 "| Run | Window | Sharpe | Net profit | Drawdown | Orders | Status |", "|---|---|---|---|---|---|---|", *rows,
413 "", f"_{len(rows)} rows, computed {computed}; Status from the README pin and the "
414 "`evaluation.lean_verdict` files (`ml/evaluation/*/r_lean*.json`)._",
415 ])
418def research_doc_beside(readme_path: Path) -> Path:
419 """The archive that carries the retired book's generated blocks; a scratch README in a test has none."""
420 return Path(readme_path).parent / RESEARCH_DOC_RELATIVE
423def update_readme_backtest_section(
424 summary: dict, readme_path: Path = README_PATH, chart_path: Path = CHART_PATH, history_markdown: str | None = None
425) -> bool:
426 """Atomically replaces the content between the AQ:BACKTEST markers in
427 README.md with a fresh headline table + chart image reference (every other
428 Lean statistic lives in the Backtest Statistics sections, rendered by
429 evaluation/readme_statistics.py). Returns False (never raises) if the README or
430 its markers are missing - a report-generation bug must never break
431 `aq backtest` itself."""
432 if not readme_path.exists():
433 return False
434 text = readme_path.read_text(encoding="utf-8")
436 try:
437 chart_relative_path = chart_path.relative_to(readme_path.resolve().parent).as_posix()
438 except ValueError:
439 chart_relative_path = chart_path.as_posix()
441 updated_text = _replace_between_markers(
442 text, BACKTEST_MARKER_START, BACKTEST_MARKER_END, _build_stats_markdown(summary, chart_relative_path)
443 )
444 if updated_text is None:
445 return False
446 text = updated_text
448 if history_markdown is not None:
449 history_text = _replace_between_markers(text, HISTORY_MARKER_START, HISTORY_MARKER_END, history_markdown)
450 if history_text is not None:
451 text = history_text
452 research_doc = research_doc_beside(readme_path)
453 if research_doc.exists():
454 research_text = _replace_between_markers(research_doc.read_text(encoding="utf-8"), HISTORY_MARKER_START, HISTORY_MARKER_END, history_markdown)
455 if research_text is not None:
456 _atomic_write(research_doc, research_text)
458 _atomic_write(readme_path, text)
459 return True
462def _result_json_in(run_dir: Path) -> Path | None:
463 return next((path for path in sorted(Path(run_dir).iterdir()) if _RESULT_JSON_PATTERN.match(path.name)), None)
466def update_readme_from_latest_backtest(
467 backtests_dir: Path = BACKTESTS_DIR,
468 readme_path: Path = README_PATH,
469 chart_path: Path = CHART_PATH,
470 backtest_dir: Path | None = None,
471) -> bool:
472 """Top-level entrypoint `aq_cli.py::cmd_backtest` calls after a
473 successful `lean backtest .` run. Callers should still wrap this in a
474 try/except - a report-generation bug must never fail the backtest
475 command itself."""
476 if backtests_dir == BACKTESTS_DIR and readme_path == README_PATH:
477 dropped = pinned_run_dir(backtests_dir) if backtest_dir is None else None
478 set_pinned_run(backtest_dir) # an explicit run pins every Lean block to it; the default (a fresh run) unpins
479 if dropped is not None:
480 print(f"README unpinned from {dropped.name}: it now describes the newest run. Re-pin with "
481 f"`aq evaluate --lean-report --backtest-dir backtests/{dropped.name}`.", file=sys.stderr)
482 result_json_path = find_latest_backtest_result_json(backtests_dir) if backtest_dir is None else _result_json_in(backtest_dir)
483 if result_json_path is None:
484 return False
485 summary = with_daily_benchmark_fallback(load_backtest_summary(result_json_path))
486 generate_equity_chart(summary, chart_path)
487 return update_readme_backtest_section(summary, readme_path, chart_path, build_history_markdown(backtests_dir, judged_only=True))
490def main() -> int:
491 parser = argparse.ArgumentParser(
492 description="Regenerate the Overview of README.md's Backtest Statistics from the latest (or --backtest-dir) Lean run."
493 )
494 parser.add_argument("--backtests-dir", type=Path, default=BACKTESTS_DIR)
495 parser.add_argument("--readme", type=Path, default=README_PATH)
496 parser.add_argument("--chart-path", type=Path, default=CHART_PATH)
497 parser.add_argument("--backtest-dir", type=Path, default=None, help="render this run instead of the newest one")
498 args = parser.parse_args()
500 updated = update_readme_from_latest_backtest(args.backtests_dir, args.readme, args.chart_path, args.backtest_dir)
501 if updated:
502 print(f"Updated {args.readme} with the latest backtest results.")
503 return 0
504 print("No backtest results found (or README markers missing) - nothing updated.", file=sys.stderr)
505 return 1
508if __name__ == "__main__":
509 sys.exit(main())