Coverage for generate_evaluation_report.py: 100%

381 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""Rewrites the generated blocks of README.md (the shipped book) and development/research_results.md (the retired rank book 

2and past rule chains) from whatever `aq evaluate` and `aq train --walk-forward` last wrote to ml/evaluation/ and ml/versions/. 

3 

4A block lives in whichever file carries its markers, and degrades to a not-run line when its source doesn't exist, so a fresh 

5checkout still gets a readable page. 

6 

7Usage: 

8 python generate_evaluation_report.py [--readme README.md] 

9""" 

10 

11from __future__ import annotations 

12 

13import argparse 

14import json 

15import sys 

16from datetime import datetime, timezone 

17from pathlib import Path 

18 

19from evaluation.readme_research import ( 

20 AS_LIVE_MARKER_END, 

21 AS_LIVE_MARKER_START, 

22 LEAN_COMPARE_MARKER_END, 

23 LEAN_COMPARE_MARKER_START, 

24 RESEARCH_MARKER_END, 

25 RESEARCH_MARKER_START, 

26 build_as_live_markdown, 

27 build_lean_vs_offline_markdown, 

28 build_research_markdown, 

29) 

30from evaluation.readme_statistics import ALPHA_MARKERS, STATUS_MARKERS, build_alpha_block, build_backtest_statistics_blocks, build_status_block 

31from evaluation.readme_statistics import MARKERS as BTSTATS_MARKERS 

32from generate_backtest_report import ( 

33 README_PATH, 

34 _atomic_write, 

35 _replace_between_markers, 

36 find_latest_backtest_result_json, 

37 load_backtest_summary, 

38 research_doc_beside, 

39) 

40 

41ROOT_DIR = Path(__file__).resolve().parent 

42ML_DIR = ROOT_DIR / "ml" 

43EVALUATION_DIR = ML_DIR / "evaluation" 

44VERSIONS_DIR = ML_DIR / "versions" 

45 

46EVAL_MARKER_START = "<!-- AQ:EVAL_START -->" 

47EVAL_MARKER_END = "<!-- AQ:EVAL_END -->" 

48EVAL_FULL_STATS_MARKER_START = "<!-- AQ:EVAL_FULL_STATS_START -->" 

49EVAL_FULL_STATS_MARKER_END = "<!-- AQ:EVAL_FULL_STATS_END -->" 

50 

51WALKFORWARD_MARKER_START = "<!-- AQ:WALKFORWARD_START -->" 

52WALKFORWARD_MARKER_END = "<!-- AQ:WALKFORWARD_END -->" 

53WALKFORWARD_FULL_STATS_MARKER_START = "<!-- AQ:WALKFORWARD_FULL_STATS_START -->" 

54WALKFORWARD_FULL_STATS_MARKER_END = "<!-- AQ:WALKFORWARD_FULL_STATS_END -->" 

55 

56OTHER_METRICS_MARKER_START = "<!-- AQ:OTHER_METRICS_START -->" 

57OTHER_METRICS_MARKER_END = "<!-- AQ:OTHER_METRICS_END -->" 

58 

59MONTECARLO_MARKER_START = "<!-- AQ:MONTECARLO_START -->" 

60MONTECARLO_MARKER_END = "<!-- AQ:MONTECARLO_END -->" 

61MONTECARLO_FULL_STATS_MARKER_START = "<!-- AQ:MONTECARLO_FULL_STATS_START -->" 

62MONTECARLO_FULL_STATS_MARKER_END = "<!-- AQ:MONTECARLO_FULL_STATS_END -->" 

63MONTECARLO_CHART_PATH = ROOT_DIR / "development" / "monte_carlo_equity_curves.png" 

64 

65BENCHMARK_MARKER_START = "<!-- AQ:BENCHMARK_START -->" 

66BENCHMARK_MARKER_END = "<!-- AQ:BENCHMARK_END -->" 

67 

68_MODEL_KINDS = ("sequence", "multitask") 

69 

70 

71def _load_json(path: Path) -> dict | list | None: 

72 if not path.exists(): 

73 return None 

74 try: 

75 with path.open("r", encoding="utf-8") as f: 

76 return json.load(f) 

77 except (json.JSONDecodeError, OSError): 

78 return None 

79 

80 

81def _fmt(value: object, spec: str = "") -> str: 

82 """Formats a number with `spec`, or returns an em-dash for 

83 None/missing - every table cell in this module goes through this so a 

84 partial `aq evaluate` run degrades to a clean placeholder, never a 

85 KeyError/TypeError.""" 

86 if value is None: 

87 return "—" 

88 try: 

89 return format(value, spec) if spec else str(value) 

90 except (ValueError, TypeError): 

91 return str(value) 

92 

93 

94def _updated_at(*artifacts: str) -> str: 

95 """The README stamp. With artifact names it reports when the newest of those files in ml/evaluation was computed and 

96 when the block was rendered (V6.1.0: a re-render used to make a V5.8.0 result look fresh); without names, the render 

97 time as before.""" 

98 rendered = datetime.now(tz=timezone.utc).strftime("%Y-%m-%d %H:%M UTC") 

99 stamps = [] 

100 for name in artifacts: 

101 path = EVALUATION_DIR / name 

102 if path.exists(): 

103 stamps.append(path.stat().st_mtime) 

104 if not stamps: 

105 return rendered 

106 computed = datetime.fromtimestamp(max(stamps), tz=timezone.utc).strftime("%Y-%m-%d %H:%M UTC") 

107 return f"{computed} (rendered {rendered})" 

108 

109 

110# -------------------------------------------------------------------------- 

111# Offline Evaluation 

112# -------------------------------------------------------------------------- 

113 

114 

115def load_offline_evaluation_summary() -> dict[str, dict | None]: 

116 """Per-model rank_book/capacity/stress reports, keyed by model_kind - 

117 each value is None (not the whole function) when that model has never 

118 been evaluated, so a report with only a sequence run still renders a 

119 complete multitask="not yet run" row instead of omitting the section.""" 

120 summary: dict[str, dict | None] = {} 

121 for model_kind in _MODEL_KINDS: 

122 rank_book = _load_json(EVALUATION_DIR / f"rank_book_simulation_{model_kind}.json") 

123 capacity = _load_json(EVALUATION_DIR / f"capacity_report_{model_kind}.json") 

124 stress = _load_json(EVALUATION_DIR / f"cost_stress_report_{model_kind}.json") 

125 if rank_book is None and capacity is None and stress is None: 

126 summary[model_kind] = None 

127 continue 

128 summary[model_kind] = {"rank_book": rank_book, "capacity": capacity, "stress": stress} 

129 return summary 

130 

131 

132def _build_eval_compact_markdown(summary: dict[str, dict | None]) -> str: 

133 lines = [ 

134 "| Metric | Multitask | Sequence |", 

135 "|---|---|---|", 

136 ] 

137 row_specs: list[tuple[str, str, str]] = [ 

138 ("Gross Sharpe", "rank_book.gross_sharpe", ".3f"), 

139 ("Net Sharpe", "rank_book.net_sharpe", ".3f"), 

140 ("Net total return", "rank_book.net_total_return", ".2%"), 

141 ("Max drawdown", "rank_book.net_max_drawdown", ".2%"), 

142 ("Annualized turnover", "rank_book.annualized_turnover", ".2f"), 

143 ("Cost drag (bps/yr)", "rank_book.cost_drag_annual_bps", ".1f"), 

144 ("Capacity (USD)", "capacity.capacity_usd", ",.0f"), 

145 ] 

146 for label, dotted_path, spec in row_specs: 

147 section, field = dotted_path.split(".") 

148 cells = [] 

149 for model_kind in ("multitask", "sequence"): 

150 model_summary = summary.get(model_kind) 

151 value = (model_summary.get(section) or {}).get(field) if model_summary else None 

152 cells.append(_fmt(value, spec)) 

153 lines.append(f"| {label} | {cells[0]} | {cells[1]} |") 

154 body = "\n".join(lines) 

155 body += f"\n\n_Backtest split, full history. Data computed {_updated_at('rank_book_simulation_sequence.json', 'rank_book_simulation_multitask.json')} (auto-generated by `aq evaluate --all`)._" 

156 return body 

157 

158 

159def _build_eval_full_stats_markdown(summary: dict[str, dict | None]) -> str: 

160 sections: list[str] = [] 

161 for model_kind in ("multitask", "sequence"): 

162 model_summary = summary.get(model_kind) 

163 sections.append(f"**{model_kind.capitalize()} model**") 

164 if model_summary is None: 

165 sections.append(f"_Not yet evaluated - run `aq evaluate --all --model {model_kind}`._") 

166 continue 

167 

168 rank_book = model_summary.get("rank_book") or {} 

169 lines = ["| Metric | Value |", "|---|---|"] 

170 for key in ( 

171 "gross_sharpe", "net_sharpe", "gross_total_return", "net_total_return", "net_max_drawdown", 

172 "annualized_turnover", "cost_drag_annual_bps", "num_rebalances", "num_dates_used", 

173 "mean_names_long", "mean_names_short", 

174 ): 

175 if key in rank_book: 

176 lines.append(f"| {key} | {rank_book[key]} |") 

177 sections.append("\n".join(lines)) 

178 

179 capacity = model_summary.get("capacity") 

180 if capacity: 

181 cap_lines = [ 

182 "", 

183 f"Capacity: ${capacity.get('capacity_usd', 0):,.0f} (binding: {capacity.get('binding_ticker', '—')})", 

184 "", 

185 "| top_n | Net Sharpe |", 

186 "|---|---|", 

187 ] 

188 for row in capacity.get("per_top_n", []): 

189 cap_lines.append(f"| {row.get('top_n')} | {row.get('net_sharpe', 0):.4f} |") 

190 sections.append("\n".join(cap_lines)) 

191 

192 stress = model_summary.get("stress") 

193 if stress and stress.get("stress"): 

194 stress_lines = ["", "| Cost multiplier | Gross Sharpe | Net Sharpe | Cost drag (bps/yr) |", "|---|---|---|---|"] 

195 for row in stress["stress"]: 

196 stress_lines.append( 

197 f"| {row.get('cost_multiplier')}x | {row.get('gross_sharpe', 0):.4f} | " 

198 f"{row.get('net_sharpe', 0):.4f} | {row.get('cost_drag_annual_bps', 0):.1f} |" 

199 ) 

200 sections.append("\n".join(stress_lines)) 

201 

202 return "\n\n".join(sections) 

203 

204 

205# -------------------------------------------------------------------------- 

206# Walk-Forward Training/Testing 

207# -------------------------------------------------------------------------- 

208 

209 

210def load_latest_walk_forward_summary() -> dict | None: 

211 """Newest ml/versions/walk-forward-*/walk_forward_summary.json by 

212 mtime - same "latest run" definition as 

213 monitoring/evaluation_state.py::_latest_walk_forward_summary().""" 

214 if not VERSIONS_DIR.exists(): 

215 return None 

216 candidates = sorted( 

217 VERSIONS_DIR.glob("walk-forward-*/walk_forward_summary.json"), 

218 key=lambda path: path.stat().st_mtime, 

219 reverse=True, 

220 ) 

221 summary = _load_json(candidates[0]) if candidates else None 

222 if isinstance(summary, dict): 

223 # the summary holds no timestamp of its own: the file's write time is when the walk-forward finished 

224 summary["_computed_at"] = datetime.fromtimestamp(candidates[0].stat().st_mtime, tz=timezone.utc).strftime("%Y-%m-%d %H:%M UTC") 

225 return summary 

226 

227 

228def _build_walk_forward_compact_markdown(summary: dict | None) -> str: 

229 if summary is None: 

230 return "_No walk-forward run found yet - run `aq train --walk-forward` first._" 

231 

232 run_id = summary.get("run_id", "unknown") 

233 num_windows = summary.get("num_windows", 0) 

234 stability = summary.get("stability_by_metric") or {} 

235 net_perf = summary.get("net_performance_by_window") or [] 

236 

237 lines = ["| Metric | Mean | 95% CI | Stable? |", "|---|---|---|---|"] 

238 for metric_name in ("backtest_mcc", "rank_5d_ic", "rank_20d_ic", "residual_rank_20d_ic"): 

239 stats = stability.get(metric_name) 

240 if not stats: 

241 continue 

242 bootstrap = stats.get("bootstrap", {}) 

243 stable_label = "yes" if stats.get("stable") else "**NO**" 

244 lines.append( 

245 f"| {metric_name} | {_fmt(stats.get('mean'), '.4f')} | " 

246 f"[{_fmt(bootstrap.get('lower_bound'), '.4f')}, {_fmt(bootstrap.get('upper_bound'), '.4f')}] | " 

247 f"{stable_label} |" 

248 ) 

249 

250 if net_perf: 

251 net_sharpes = [w.get("simulation", {}).get("net_sharpe") for w in net_perf if w.get("simulation")] 

252 net_sharpes = [s for s in net_sharpes if s is not None] 

253 if net_sharpes: 

254 mean_sharpe = sum(net_sharpes) / len(net_sharpes) 

255 num_positive = sum(1 for s in net_sharpes if s > 0) 

256 lines.append( 

257 f"| net_sharpe (per-window) | {mean_sharpe:.3f} | — | " 

258 f"{num_positive}/{len(net_sharpes)} windows positive |" 

259 ) 

260 

261 body = "\n".join(lines) 

262 computed = summary.get("_computed_at") 

263 stamp = f"computed {computed} (rendered {_updated_at()})" if computed else f"Last updated {_updated_at()}" 

264 body += ( 

265 f"\n\n{num_windows} expanding/rolling windows, run `{run_id}`, {stamp} (auto-generated by `aq train --walk-forward`; " 

266 "a retrain refreshes it, a re-render does not)." 

267 ) 

268 return body 

269 

270 

271def _build_walk_forward_full_stats_markdown(summary: dict | None) -> str: 

272 if summary is None: 

273 return "_No walk-forward run found yet._" 

274 

275 window_results = summary.get("window_results") or [] 

276 net_perf_by_window = {w.get("window_index"): w for w in (summary.get("net_performance_by_window") or [])} 

277 

278 lines = [ 

279 "| Window | Backtest period | Model | Backtest MCC | Gross Sharpe | Net Sharpe | Net return | Max DD | Turnover |", 

280 "|---|---|---|---|---|---|---|---|---|", 

281 ] 

282 for index, window in enumerate(window_results): 

283 backtest_window = window.get("window", {}).get("backtest", {}) 

284 period = f"{backtest_window.get('start', '?')} → {backtest_window.get('end', '?')}" 

285 net_perf = net_perf_by_window.get(index, {}) 

286 sim = net_perf.get("simulation", {}) 

287 lines.append( 

288 f"| {index} | {period} | {net_perf.get('model_kind', '—')} | " 

289 f"{_fmt(window.get('backtest_mcc'), '.4f')} | {_fmt(sim.get('gross_sharpe'), '.3f')} | " 

290 f"{_fmt(sim.get('net_sharpe'), '.3f')} | {_fmt(sim.get('net_total_return'), '.2%')} | " 

291 f"{_fmt(sim.get('net_max_drawdown'), '.2%')} | {_fmt(sim.get('annualized_turnover'), '.2f')}x |" 

292 ) 

293 if summary.get("_computed_at"): 

294 lines += ["", f"_Run `{summary.get('run_id', 'unknown')}`, computed {summary['_computed_at']}._"] 

295 return "\n".join(lines) 

296 

297 

298# -------------------------------------------------------------------------- 

299# Other Metrics (Lean vs. offline comparison, reconciliation, kill-switch) 

300# -------------------------------------------------------------------------- 

301 

302 

303def _load_lean_sharpe() -> tuple[float | None, str | None]: 

304 """Returns (sharpe, backtest_window_label) from the same latest 

305 complete Lean run generate_backtest_report.py's own Lean Backtest 

306 section displays - never a different/staler run, so the comparison 

307 below is always apples-to-apples with what's shown just above it.""" 

308 result_json_path = find_latest_backtest_result_json() 

309 if result_json_path is None: 

310 return None, None 

311 lean_summary = load_backtest_summary(result_json_path) 

312 statistics = lean_summary["statistics"] 

313 sharpe_str = statistics.get("Sharpe Ratio") 

314 try: 

315 sharpe = float(sharpe_str) if sharpe_str is not None else None 

316 except ValueError: 

317 sharpe = None 

318 start_date, end_date = lean_summary["start_date"], lean_summary["end_date"] 

319 window = f"{start_date.date().isoformat()} to {end_date.date().isoformat()}" if start_date and end_date else None 

320 return sharpe, window 

321 

322 

323def _count_real_kill_switch_trips() -> int | None: 

324 """V5.3.1 (development/Problems.md #91/#97): always returns None now - 

325 this used to count `kill_switch_tripped` occurrences in the real 

326 backtest's Lean text log, but that was never a real measurement. 

327 main.py's actual trip-audit event (`self._audit_queue.push(... 

328 "kill_switch_tripped"...)`) is pushed ONLY to a Redis Stream 

329 (audit/redis_queue.py::AuditQueue), never to the text log, and 

330 AuditQueue.push() fails silently with no Redis reachable - which a 

331 standalone `lean backtest .` run never has. So the old count was 

332 ALWAYS 0 regardless of how many real trips occurred, not a genuine 

333 "0 trips" finding (V5.2.10's Changelog entry stated this as if it 

334 were real - that was wrong, corrected here). No cheap, reliable 

335 offline proxy exists either: `trade_lock_active` transitions are only 

336 durably logged per-bar into book_history.jsonl's 

337 `book_member_decisions`, itself gated to rebalance bars and book- 

338 selected symbols only - too sparse to reconstruct true rising-edge 

339 trip counts. Kept as a function (not deleted) so 

340 _build_other_metrics_markdown() has one clear place to render an 

341 honest "not measurable from a standalone backtest" caveat instead.""" 

342 return None 

343 

344 

345def _build_other_metrics_markdown( 

346 eval_summary: dict[str, dict | None], 

347 walk_forward_summary: dict | None, 

348 reconciliation: dict | None, 

349 kill_switch_replay: dict | None, 

350) -> str: 

351 lean_sharpe, lean_window = _load_lean_sharpe() 

352 sequence_net_sharpe = (eval_summary.get("sequence") or {}).get("rank_book", {}).get("net_sharpe") 

353 multitask_net_sharpe = (eval_summary.get("multitask") or {}).get("rank_book", {}).get("net_sharpe") 

354 walk_forward_net_perf = (walk_forward_summary or {}).get("net_performance_by_window") or [] 

355 walk_forward_net_sharpes = [ 

356 w.get("simulation", {}).get("net_sharpe") for w in walk_forward_net_perf if w.get("simulation") 

357 ] 

358 walk_forward_net_sharpes = [s for s in walk_forward_net_sharpes if s is not None] 

359 walk_forward_mean_sharpe = ( 

360 sum(walk_forward_net_sharpes) / len(walk_forward_net_sharpes) if walk_forward_net_sharpes else None 

361 ) 

362 

363 lines = [ 

364 "**Sharpe: real Lean backtest vs. offline estimates** — offline numbers are consistently more " 

365 "optimistic than the real backtest; treat the gap itself as the headline number, not either side alone.", 

366 "", 

367 "| Source | Sharpe |", 

368 "|---|---|", 

369 f"| Real Lean backtest{f' ({lean_window})' if lean_window else ''} | {_fmt(lean_sharpe, '.3f')} |", 

370 f"| Offline evaluation — sequence model (full backtest split) | {_fmt(sequence_net_sharpe, '.3f')} |", 

371 f"| Offline evaluation — multitask model (full backtest split) | {_fmt(multitask_net_sharpe, '.3f')} |", 

372 f"| Walk-forward mean (out-of-sample, per-window) | {_fmt(walk_forward_mean_sharpe, '.3f')} |", 

373 ] 

374 

375 if lean_sharpe is not None and sequence_net_sharpe is not None: 

376 lines.append(f"| Gap: sequence offline − real Lean | {sequence_net_sharpe - lean_sharpe:+.3f} |") 

377 if lean_sharpe is not None and walk_forward_mean_sharpe is not None: 

378 lines.append(f"| Gap: walk-forward − real Lean | {walk_forward_mean_sharpe - lean_sharpe:+.3f} |") 

379 

380 lines.append("") 

381 lines.append("**Book-history reconciliation** (real Lean selections vs. a fresh offline re-derivation of the same dates)") 

382 lines.append("") 

383 if reconciliation and reconciliation.get("summary"): 

384 recon_summary = reconciliation["summary"] 

385 lines.extend( 

386 [ 

387 "| Metric | Value |", 

388 "|---|---|", 

389 f"| Dates reconciled | {recon_summary.get('num_dates', '—')} |", 

390 f"| Exact matches | {recon_summary.get('num_dates_exact_match', '—')} |", 

391 f"| Mean overlap fraction | {_fmt(recon_summary.get('mean_overlap_fraction'), '.2%')} |", 

392 f"| Mean raw-score delta | {_fmt(recon_summary.get('mean_raw_score_delta_abs'), '.4f')} |", 

393 f"| Replay mode | {reconciliation.get('mode', '—')} |", 

394 ] 

395 ) 

396 diversion = reconciliation.get("diversion_summary") or {} 

397 action_counts = diversion.get("action_counts") or {} 

398 if action_counts: 

399 total_decisions = sum(action_counts.values()) 

400 lines.append("") 

401 lines.append(f"Book-member decision outcomes ({total_decisions} total, real Lean run):") 

402 lines.append("") 

403 lines.append("| Action | Count | Share |") 

404 lines.append("|---|---|---|") 

405 for action, count in sorted(action_counts.items(), key=lambda item: -item[1]): 

406 lines.append(f"| {action} | {count} | {count / total_decisions:.1%} |") 

407 else: 

408 lines.append("_Not yet reconciled - run `aq evaluate --reconcile-book-history --replay-hysteresis` first._") 

409 

410 lines.append("") 

411 lines.append("**Kill-switch: real trips vs. offline replay estimate**") 

412 lines.append("") 

413 # V5.3.1 (development/Problems.md #91/#97) - _count_real_kill_switch_trips() 

414 # always returns None now (see its own docstring for why the old 

415 # count was never a real measurement) - render an explicit caveat 

416 # instead of a bare "—" that could be misread as "zero trips". 

417 if kill_switch_replay and kill_switch_replay.get("summary"): 

418 ks_summary = kill_switch_replay["summary"] 

419 lines.append("| Source | Trips | Locked days |") 

420 lines.append("|---|---|---|") 

421 lines.append( 

422 f"| Real Lean backtest{f' ({lean_window})' if lean_window else ''} | " 

423 "_not measurable from a standalone backtest (see Disclaimer)_ | — |" 

424 ) 

425 lines.append( 

426 f"| Offline replay (approximation, see Disclaimer) | {ks_summary.get('trip_count', '—')} | " 

427 f"{_fmt(ks_summary.get('locked_day_fraction'), '.1%')} |" 

428 ) 

429 else: 

430 lines.append("_Not yet available - run `aq evaluate --replay-kill-switch`._") 

431 

432 lines.append("") 

433 lines.append(f"_Data computed {_updated_at('kill_switch_replay.json', 'book_history_reconciliation.json')} (auto-generated by `aq evaluate`)._") 

434 return "\n".join(lines) 

435 

436 

437# -------------------------------------------------------------------------- 

438# Wiring 

439# -------------------------------------------------------------------------- 

440 

441 

442def load_monte_carlo() -> tuple[dict | None, object]: 

443 """Loads ml/evaluation/monte_carlo.json (+ curves .npz) - (summary, runs) 

444 where runs is the downsampled per-run curve matrix for the PNG, or 

445 (None, None) when either file is missing/unreadable.""" 

446 summary = _load_json(EVALUATION_DIR / "monte_carlo.json") 

447 if not isinstance(summary, dict): 

448 return None, None 

449 runs = None 

450 npz_path = EVALUATION_DIR / "monte_carlo_curves.npz" 

451 try: 

452 import numpy as np 

453 

454 with np.load(npz_path) as payload: 

455 runs = payload["runs_curves"] 

456 except Exception: 

457 runs = None 

458 return summary, runs 

459 

460 

461def load_lean_monte_carlo() -> tuple[dict | None, object]: 

462 """ml/evaluation/monte_carlo_lean.json and its curves: (summary, runs), summary None unless the bootstrap succeeded.""" 

463 summary = _load_json(EVALUATION_DIR / "monte_carlo_lean.json") 

464 if not isinstance(summary, dict) or summary.get("status") != "OK": 

465 return None, None 

466 try: 

467 import numpy as np 

468 

469 with np.load(EVALUATION_DIR / "monte_carlo_lean_curves.npz") as payload: 

470 return summary, payload["runs_curves"] 

471 except Exception: 

472 return summary, None 

473 

474 

475def _render_monte_carlo_chart(runs, avg_curve: list[float], config: dict, out_path: Path, num_days: int | None = None) -> bool: 

476 """Draws every resampled run as a faint line plus the red average - 

477 regenerated on every evaluate run so the README visual is always in sync.""" 

478 try: 

479 import matplotlib 

480 

481 matplotlib.use("Agg") 

482 import matplotlib.pyplot as plt 

483 import numpy as np 

484 except Exception: 

485 return False 

486 if runs is None or getattr(runs, "size", 0) == 0 or not avg_curve: 

487 return False 

488 fig, ax = plt.subplots(figsize=(11, 6), dpi=140) 

489 x = np.linspace(0, num_days, runs.shape[1]) if num_days else np.arange(runs.shape[1]) 

490 for row in runs: 

491 ax.plot(x, row, color="#6f9fc4", alpha=0.05, lw=0.5, zorder=1) 

492 ax.plot(x, avg_curve, color="red", lw=2.4, zorder=3, 

493 label=f"Average of all {config.get('n_runs', '?')} runs") 

494 ax.axhline(1.0, color="black", lw=0.8, ls="--", zorder=2, label="Start (1.0x)") 

495 ax.set_xlabel("Days resampled") 

496 ax.set_ylabel("Equity multiple (start = 1.0x)") 

497 ax.set_title( 

498 f"Monte Carlo equity curves - {config.get('n_runs')} runs, " 

499 f"method={config.get('method')}, block={config.get('block_size')}d, seed={config.get('seed')}" 

500 ) 

501 ax.grid(alpha=0.25) 

502 ax.legend(loc="best") 

503 out_path.parent.mkdir(parents=True, exist_ok=True) 

504 fig.savefig(out_path) 

505 plt.close(fig) 

506 return True 

507 

508 

509def _monte_carlo_table(summary: dict) -> list[str]: 

510 fr, sh, md = summary["final_return_pct"], summary["sharpe"], summary["max_drawdown"] 

511 return [ 

512 "| Metric | p5 | p50 | p95 |", 

513 "|---|---|---|---|", 

514 f"| Final return | {fr['p5']}% | {fr['p50']}% | {fr['p95']}% |", 

515 f"| Annualized Sharpe | {sh['p5']} | {sh['p50']} | {sh['p95']} |", 

516 f"| Max drawdown | {md['p5']}% | {md['p50']}% | {md['p95']}% |", 

517 f"| P(negative total return): **{summary['prob_negative_return']}** |||", 

518 ] 

519 

520 

521def _build_monte_carlo_compact_markdown(summary: dict | None, lean_summary: dict | None = None) -> str: 

522 if isinstance(lean_summary, dict) and lean_summary.get("status") == "OK": 

523 cfg = lean_summary.get("config", {}) 

524 return "\n".join([ 

525 f"![Monte Carlo equity curves]({MONTECARLO_CHART_PATH.relative_to(ROOT_DIR).as_posix()})", 

526 "", 

527 *_monte_carlo_table(lean_summary), 

528 "", 

529 f"_{cfg.get('n_runs', '?')} block-bootstrapped histories (block {cfg.get('block_size', '?')} days, seed {cfg.get('seed', '?')}) of Lean run " 

530 f"`{lean_summary.get('run', '?')}`'s {lean_summary.get('num_daily_returns', '?')} daily returns, {lean_summary.get('first_date', '?')} to " 

531 f"{lean_summary.get('last_date', '?')}. The run itself returned {lean_summary.get('observed_total_return_pct', 'n/a')}%; " 

532 f"computed {_updated_at('monte_carlo_lean.json')}._", 

533 ]) 

534 if not isinstance(summary, dict): 

535 return ( 

536 "Monte Carlo simulation has not been run yet - generate it with\n" 

537 "`aq evaluate --rank-book --monte-carlo` (see CLI Reference)." 

538 ) 

539 cfg = summary["config"] 

540 return "\n".join([ 

541 f"{cfg['n_runs']}-run stationary-block bootstrap of the offline rank book's daily net returns", 

542 f"(method=`{cfg['method']}`, block={cfg['block_size']}d, seed={cfg['seed']}). The red line marks the" 

543 "\naverage of all generated runs; faint lines are individual resampled histories.", 

544 "", 

545 f"![Monte Carlo equity curves]({MONTECARLO_CHART_PATH.relative_to(ROOT_DIR).as_posix()})", 

546 "", 

547 *_monte_carlo_table(summary), 

548 "", 

549 f"_Source: the offline idealized rank book, model `{summary.get('model_kind', '?')}`, head `{summary.get('head', '?')}`, " 

550 f"split `{summary.get('split', '?')}`, computed {_updated_at('monte_carlo.json')} (a simulation at the configured book cadence, not the engine)._", 

551 ]) 

552 

553 

554def _build_monte_carlo_full_stats_markdown(summary: dict | None) -> str: 

555 if not isinstance(summary, dict): 

556 return "No Monte Carlo data on disk yet." 

557 cfg = summary["config"] 

558 

559 def table(title: str, stats: dict) -> list[str]: 

560 return [ 

561 f"**{title}**", 

562 "", 

563 "| p5 | p25 | p50 | p75 | p95 |", 

564 "|---|---|---|---|---|", 

565 f"| {stats['p5']} | {stats['p25']} | {stats['p50']} | {stats['p75']} | {stats['p95']} |", 

566 "", 

567 ] 

568 

569 lines = [ 

570 "Deeper distribution statistics across all Monte Carlo runs:", 

571 "", 

572 *table("Final total return (%)", summary["final_return_pct"]), 

573 *table("Annualized Sharpe", summary["sharpe"]), 

574 *table("Max drawdown (%)", summary["max_drawdown"]), 

575 f"- Best run total return: **{summary['best_run_total_return']}%**", 

576 f"- Worst run total return: **{summary['worst_run_total_return']}%**", 

577 f"- Probability of a negative total return: **{summary['prob_negative_return']}**", 

578 f"- Config: n_runs={cfg['n_runs']}, method=`{cfg['method']}`, block_size={cfg['block_size']}d, " 

579 f"seed={cfg['seed']} (pinned - the section only changes when underlying results change)", 

580 "", 

581 "The red line in the chart above is the element-wise AVERAGE of all run " 

582 "equity curves; faint blue lines are the individual bootstrap histories.", 

583 ] 

584 return "\n".join(lines) 

585 

586 

587def load_benchmark_comparison() -> dict | None: 

588 """Loads ml/evaluation/benchmark_comparison.json - `aq evaluate 

589 --benchmarks`' persisted report (all five baselines + run context), or 

590 None when it has never been written.""" 

591 return _load_json(EVALUATION_DIR / "benchmark_comparison.json") 

592 

593 

594def _build_benchmark_markdown(summary: dict | None, eval_summary: dict[str, dict | None]) -> str: 

595 """Renders the Benchmark Comparison section: the rank book's own net 

596 Sharpe rows first (the number being benchmarked, per model), then every 

597 baseline. All from the same dataset window/split, so the comparison is 

598 like-for-like; a baseline that couldn't compute shows its SKIPPED 

599 status instead of fabricated numbers.""" 

600 if not isinstance(summary, dict) or not summary.get("baselines"): 

601 return ( 

602 "Benchmark comparison has not been run yet - generate it with\n" 

603 "`aq evaluate --benchmarks` (or `aq evaluate --all`)." 

604 ) 

605 lines = [ 

606 "| Strategy | Net Sharpe | Total return | Note |", 

607 "|---|---|---|---|", 

608 ] 

609 for model_kind in _MODEL_KINDS: 

610 rank_book = (eval_summary or {}).get(model_kind, {}) or {} 

611 rank_book_report = rank_book.get("rank_book") or {} 

612 if rank_book_report: 

613 lines.append( 

614 f"| **Rank book ({model_kind})** | {_fmt(rank_book_report.get('net_sharpe'), '.3f')} | " 

615 f"{_fmt(rank_book_report.get('net_total_return'), '.2%')} | the strategy being benchmarked |" 

616 ) 

617 for baseline in summary["baselines"]: 

618 note = baseline.get("status", "OK") 

619 if note == "OK": 

620 note = "public benchmark" if baseline["strategy"] in ("sp500", "60_40") else "naive strategy baseline" 

621 lines.append( 

622 f"| {baseline['strategy']} | {_fmt(baseline.get('net_sharpe'), '.3f')} | " 

623 f"{_fmt(baseline.get('total_return_pct'), '.2f')}% | {note} |" 

624 ) 

625 lines.append("") 

626 lines.append( 

627 f"_Same dataset window/split (`{summary.get('split', 'backtest')}`) as the rank-book simulation " 

628 f"above; Sharpe formula identical across every row. Data computed {_updated_at('benchmark_comparison.json')} " 

629 "(auto-generated by `aq evaluate --benchmarks`)._" 

630 ) 

631 return "\n".join(lines) 

632 

633 

634 

635 

636 

637def update_readme_evaluation_sections(readme_path: Path = README_PATH) -> bool: 

638 """Rebuilds every generated block of the README and, beside it, of `development/research_results.md` (a block lives in 

639 whichever file carries its markers). Never raises, so a report bug never fails the `aq evaluate`/`aq train` command that 

640 triggered it. Returns True if a file was modified.""" 

641 changed = _update_evaluation_blocks(readme_path) 

642 return _update_evaluation_blocks(research_doc_beside(readme_path)) or changed 

643 

644 

645def _update_evaluation_blocks(readme_path: Path) -> bool: 

646 if not readme_path.exists(): 

647 return False 

648 text = readme_path.read_text(encoding="utf-8") 

649 changed = False 

650 

651 eval_summary = load_offline_evaluation_summary() 

652 walk_forward_summary = load_latest_walk_forward_summary() 

653 reconciliation = _load_json(EVALUATION_DIR / "book_history_reconciliation.json") 

654 kill_switch_replay = _load_json(EVALUATION_DIR / "kill_switch_replay.json") 

655 

656 mc_summary, mc_runs = load_monte_carlo() 

657 # V5.4.4 guard (development/Problems.md #114): the chart is a repo 

658 # asset OF the repo README - only (re)render it when this call is 

659 # actually refreshing the real README. A caller passing a scratch/ 

660 # tmp readme (the tests, offline experiments) previously rendered 

661 # whatever its EVALUATION_DIR contained straight over the REAL 

662 # development/monte_carlo_equity_curves.png - which is exactly how 

663 # the committed chart got replaced by a degenerate test-fixture 

664 # render (10 flat runs, 2-point x-axis): every full test-suite run 

665 # silently clobbered it, and the README showed only the red average 

666 # line until the next `aq evaluate --monte-carlo` regenerated it. 

667 lean_mc, lean_runs = load_lean_monte_carlo() 

668 chart_summary, chart_runs = (lean_mc, lean_runs) if lean_runs is not None else (mc_summary, mc_runs) 

669 if ( 

670 chart_summary is not None 

671 and chart_summary.get("status") == "OK" 

672 and readme_path.resolve() == README_PATH.resolve() 

673 ): 

674 _render_monte_carlo_chart(chart_runs, chart_summary.get("avg_curve", []), chart_summary.get("config", {}), MONTECARLO_CHART_PATH, 

675 num_days=chart_summary.get("num_daily_returns")) 

676 

677 updated = _replace_between_markers(text, MONTECARLO_MARKER_START, MONTECARLO_MARKER_END, _build_monte_carlo_compact_markdown(mc_summary, lean_mc)) 

678 if updated is not None: 

679 text, changed = updated, True 

680 

681 # V5.4.4 - benchmark comparison section (rank book vs strategy + 

682 # public baselines, all on the same window). Rendered from the 

683 # persisted ml/evaluation/benchmark_comparison.json; like every other 

684 # section here it degrades to its not-run-yet fallback when that file 

685 # doesn't exist yet. 

686 benchmark_summary = load_benchmark_comparison() 

687 updated = _replace_between_markers( 

688 text, 

689 BENCHMARK_MARKER_START, 

690 BENCHMARK_MARKER_END, 

691 _build_benchmark_markdown(benchmark_summary, eval_summary), 

692 ) 

693 if updated is not None: 

694 text, changed = updated, True 

695 

696 updated = _replace_between_markers( 

697 text, 

698 MONTECARLO_FULL_STATS_MARKER_START, 

699 MONTECARLO_FULL_STATS_MARKER_END, 

700 _build_monte_carlo_full_stats_markdown(lean_mc if lean_mc is not None else mc_summary), 

701 ) 

702 if updated is not None: 

703 text, changed = updated, True 

704 

705 

706 updated = _replace_between_markers(text, EVAL_MARKER_START, EVAL_MARKER_END, _build_eval_compact_markdown(eval_summary)) 

707 if updated is not None: 

708 text, changed = updated, True 

709 

710 updated = _replace_between_markers( 

711 text, EVAL_FULL_STATS_MARKER_START, EVAL_FULL_STATS_MARKER_END, _build_eval_full_stats_markdown(eval_summary) 

712 ) 

713 if updated is not None: 

714 text, changed = updated, True 

715 

716 updated = _replace_between_markers( 

717 text, WALKFORWARD_MARKER_START, WALKFORWARD_MARKER_END, _build_walk_forward_compact_markdown(walk_forward_summary) 

718 ) 

719 if updated is not None: 

720 text, changed = updated, True 

721 

722 updated = _replace_between_markers( 

723 text, 

724 WALKFORWARD_FULL_STATS_MARKER_START, 

725 WALKFORWARD_FULL_STATS_MARKER_END, 

726 _build_walk_forward_full_stats_markdown(walk_forward_summary), 

727 ) 

728 if updated is not None: 

729 text, changed = updated, True 

730 

731 updated = _replace_between_markers(text, AS_LIVE_MARKER_START, AS_LIVE_MARKER_END, build_as_live_markdown(EVALUATION_DIR)) 

732 if updated is not None: 

733 text, changed = updated, True 

734 

735 updated = _replace_between_markers(text, RESEARCH_MARKER_START, RESEARCH_MARKER_END, build_research_markdown(EVALUATION_DIR)) 

736 if updated is not None: 

737 text, changed = updated, True 

738 

739 updated = _replace_between_markers( 

740 text, LEAN_COMPARE_MARKER_START, LEAN_COMPARE_MARKER_END, build_lean_vs_offline_markdown(EVALUATION_DIR) 

741 ) 

742 if updated is not None: 

743 text, changed = updated, True 

744 

745 updated = _replace_between_markers( 

746 text, 

747 OTHER_METRICS_MARKER_START, 

748 OTHER_METRICS_MARKER_END, 

749 _build_other_metrics_markdown(eval_summary, walk_forward_summary, reconciliation, kill_switch_replay), 

750 ) 

751 if updated is not None: 

752 text, changed = updated, True 

753 

754 for markers, body in ((ALPHA_MARKERS, build_alpha_block(EVALUATION_DIR)), (STATUS_MARKERS, build_status_block(EVALUATION_DIR))): 

755 updated = _replace_between_markers(text, *markers, body) 

756 if updated is not None: 

757 text, changed = updated, True 

758 

759 for section, body in build_backtest_statistics_blocks(EVALUATION_DIR).items(): 

760 start_marker, end_marker = BTSTATS_MARKERS[section] 

761 updated = _replace_between_markers(text, start_marker, end_marker, body) 

762 if updated is not None: 

763 text, changed = updated, True 

764 

765 if changed: 

766 _atomic_write(readme_path, text) 

767 return changed 

768 

769 

770def main() -> int: 

771 parser = argparse.ArgumentParser( 

772 description="Regenerate the generated blocks of README.md and development/research_results.md." 

773 ) 

774 parser.add_argument("--readme", type=Path, default=README_PATH) 

775 args = parser.parse_args() 

776 

777 updated = update_readme_evaluation_sections(args.readme) 

778 if updated: 

779 print(f"Updated {args.readme} with the latest evaluation/walk-forward results.") 

780 return 0 

781 print("Nothing to update (no source files found, or README markers missing).", file=sys.stderr) 

782 return 1 

783 

784 

785if __name__ == "__main__": 

786 sys.exit(main())