Coverage for evaluation/readme_statistics.py: 100%

151 statements  

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

1"""README "Backtest Statistics" blocks (V6.3.0), rendered from `ml/evaluation/backtest_statistics.json` 

2(`evaluation/backtest_statistics.py`, written by `aq evaluate --backtest-stats` / `--lean-report` and after `aq backtest`). 

3 

4One compact table per section, a "Strategy" column next to the portfolio (the run without its T-bill sweep), and one 

5footer line naming the run. `generate_evaluation_report.update_readme_evaluation_sections` writes every block, so any 

6`aq evaluate` re-renders them from the saved JSON.""" 

7 

8from __future__ import annotations 

9 

10import json 

11from pathlib import Path 

12 

13SECTIONS = ("general", "performance", "runs", "shortfall", "efficiency", "classification", "attribution", "benchmarks") 

14MARKERS = { 

15 section: (f"<!-- AQ:BTSTATS_{section.upper()}_START -->", f"<!-- AQ:BTSTATS_{section.upper()}_END -->") 

16 for section in SECTIONS 

17} 

18STATISTICS_FILE = "backtest_statistics.json" 

19ALPHA_FILE = "alpha_proof.json" 

20PIN_FILE = "readme_lean_run.json" 

21ALPHA_MARKERS = ("<!-- AQ:ALPHA_START -->", "<!-- AQ:ALPHA_END -->") 

22STATUS_MARKERS = ("<!-- AQ:STATUS_START -->", "<!-- AQ:STATUS_END -->") 

23PERIOD_LABELS = {"full": "Whole run", "backtest": "First half", "holdout": "Second half"} 

24 

25# Every Lean `statistics` key has one home in the new sections (tests/test_readme_statistics.py checks a real run). 

26LEAN_STAT_SECTION = { 

27 "Start Equity": "general", "End Equity": "general", "Total Orders": "general", "Estimated Strategy Capacity": "general", 

28 "Lowest Capacity Asset": "general", "Portfolio Turnover": "general", 

29 "Net Profit": "performance", "Compounding Annual Return": "performance", "Win Rate": "performance", 

30 "Loss Rate": "performance", "Average Win": "performance", "Average Loss": "performance", 

31 "Profit-Loss Ratio": "performance", "Expectancy": "performance", 

32 "Drawdown": "runs", "Drawdown Recovery": "runs", 

33 "Total Fees": "shortfall", 

34 "Sharpe Ratio": "efficiency", "Sortino Ratio": "efficiency", "Probabilistic Sharpe Ratio": "efficiency", 

35 "Information Ratio": "efficiency", "Tracking Error": "efficiency", "Treynor Ratio": "efficiency", 

36 "Alpha": "efficiency", "Beta": "efficiency", "Annual Standard Deviation": "efficiency", "Annual Variance": "efficiency", 

37} 

38 

39_NOT_RUN = "_Not computed yet: `aq evaluate --backtest-stats` (runs after every `aq backtest`)._" 

40 

41 

42def _format(value, fmt: str) -> str: 

43 if value is None: 

44 return "n/a" 

45 if fmt == "text": 

46 return str(value) 

47 try: 

48 number = float(value) 

49 except (TypeError, ValueError): 

50 return str(value) 

51 if fmt == "usd": 

52 return f"${number:,.0f}" 

53 if fmt == "usd_signed": 

54 return f"{'+' if number >= 0 else '-'}${abs(number):,.0f}" 

55 if fmt == "pct": 

56 return f"{number:.2%}" 

57 if fmt == "pct_signed": 

58 return f"{number:+.2%}" 

59 if fmt == "pct_raw": 

60 return f"{number:.3f}%" 

61 if fmt == "bps": 

62 return f"{number:+.1f} bps" if number < 0 else f"{number:.1f} bps" 

63 if fmt == "x": 

64 return f"{number:.2f}x" 

65 if fmt == "int": 

66 return f"{number:,.0f}" 

67 decimals = {"num1": 1, "num2": 2, "num3": 3, "num4": 4}.get(fmt, 3) 

68 return f"{number:.{decimals}f}" 

69 

70 

71def _footer(stats: dict) -> str: 

72 return f"_Run `{stats.get('run', 'n/a')}` · computed {stats.get('computed_at', 'n/a')}_" 

73 

74 

75def _metric_table(rows: list[dict], stats: dict) -> str: 

76 has_strategy = any(row.get("strategy") is not None for row in rows) 

77 has_note = any(row.get("reason") for row in rows) 

78 header = ["Metric", "Portfolio"] + (["Strategy"] if has_strategy else []) + (["Note"] if has_note else []) 

79 lines = ["| " + " | ".join(header) + " |", "|" + "---|" * len(header)] 

80 for row in rows: 

81 portfolio = row.get("portfolio") 

82 # a bet-level metric exists for the strategy only (buying T-bills is not a bet) 

83 portfolio_cell = "—" if portfolio is None and row.get("strategy") is not None else _format(portfolio, row.get("format", "num")) 

84 cells = [row["metric"], portfolio_cell] 

85 if has_strategy: 

86 strategy = row.get("strategy") 

87 cells.append(_format(strategy, row.get("format", "num")) if strategy is not None else "") 

88 if has_note: 

89 cells.append(row.get("reason") or "") 

90 lines.append("| " + " | ".join(cells) + " |") 

91 return "\n".join(lines + ["", _footer(stats)]) 

92 

93 

94def _classification_table(rows: list[dict], stats: dict) -> str: 

95 lines = ["| Source | Calls | Accuracy | Precision | Recall | F1 | Neg. log-loss |", "|---|---|---|---|---|---|---|"] 

96 for row in rows: 

97 loss = row.get("neg_log_loss") 

98 lines.append( 

99 f"| {row['source']} | {row.get('n', 0):,} | {_format(row.get('accuracy'), 'pct')} | {_format(row.get('precision'), 'pct')} | " 

100 f"{_format(row.get('recall'), 'pct')} | {_format(row.get('f1'), 'num3')} | " 

101 f"{_format(loss, 'num3') if loss is not None else 'n/a (' + (row.get('reason') or 'no probabilities') + ')'} |" 

102 ) 

103 if not any(row["source"].startswith("Offline") for row in rows): 

104 lines += ["", "_Offline rows appear after `aq evaluate --classification` (part of `--all`)._"] 

105 return "\n".join(lines + ["", _footer(stats)]) 

106 

107 

108def _attribution_table(attribution: dict, stats: dict) -> str: 

109 lines = [ 

110 "| Class | Net PnL | Return on AUM (annual) | Volatility (annual) | Sharpe | Max drawdown (on AUM) | Risk share | Fees |", 

111 "|---|---|---|---|---|---|---|---|", 

112 ] 

113 for row in attribution.get("classes", []): 

114 lines.append( 

115 f"| {row['class']} | {_format(row.get('net_pnl'), 'usd_signed')} | {_format(row.get('annual_return_on_aum'), 'pct_signed')} | " 

116 f"{_format(row.get('annual_volatility'), 'pct')} | {_format(row.get('sharpe'), 'num2')} | " 

117 f"{_format(row.get('max_drawdown_on_aum'), 'pct')} | {_format(row.get('risk_share'), 'pct')} | {_format(row.get('fees'), 'usd')} |" 

118 ) 

119 unattributed = attribution.get("unattributed_pnl") 

120 if unattributed is not None and abs(float(unattributed)) >= 1.0: 

121 lines.append(f"| unattributed (Lean minus rebuilt) | {_format(unattributed, 'usd_signed')} | | | | | | |") 

122 components = attribution.get("components") or [] 

123 if components: 

124 lines += ["", "| Component | Net PnL | Fees | Fills |", "|---|---|---|---|"] 

125 for row in components: 

126 lines.append(f"| {row['component']} | {_format(row.get('net_pnl'), 'usd_signed')} | {_format(row.get('fees'), 'usd')} | {row.get('fills', 0)} |") 

127 return "\n".join(lines + ["", _footer(stats)]) 

128 

129 

130def _benchmark_table(rows: list[dict], stats: dict) -> str: 

131 lines = ["| Series | Total return | Annual return | Volatility | Sharpe | Max drawdown |", "|---|---|---|---|---|---|"] 

132 for row in rows: 

133 lines.append( 

134 f"| {row['series']} | {_format(row.get('total_return'), 'pct_signed')} | {_format(row.get('annual_return'), 'pct_signed')} | " 

135 f"{_format(row.get('volatility'), 'pct')} | {_format(row.get('sharpe'), 'num2')} | {_format(row.get('max_drawdown'), 'pct')} |" 

136 ) 

137 return "\n".join(lines + ["", _footer(stats)[:-1] + " · same sessions to the last equity close, no risk-free rate_"]) 

138 

139 

140def _load(path: Path) -> dict | None: 

141 try: 

142 payload = json.loads(path.read_text(encoding="utf-8")) if path.exists() else None 

143 except (OSError, ValueError): 

144 return None 

145 return payload if isinstance(payload, dict) else None 

146 

147 

148def _alpha_rows(report: dict, periods: dict[str, str]) -> list[str]: 

149 rows = [] 

150 for key, label in periods.items(): 

151 part = (report.get("periods") or {}).get(key) or {} 

152 if not part.get("n"): 

153 continue 

154 ci = part.get("sharpe_ci95") or [None, None] 

155 alpha = part.get("alpha") or {} 

156 rows.append( 

157 f"| {label} | {part.get('start', '?')} to {part.get('end', '?')} | {_format(part.get('sharpe'), 'num2')} | " 

158 f"{_format(ci[0], 'num2')} to {_format(ci[1], 'num2')} | {_format(alpha.get('alpha_annual'), 'pct_signed')} | " 

159 f"{_format(alpha.get('t_hac'), 'num2')} | {_format(part.get('dsr'), 'pct')} |" 

160 ) 

161 return rows 

162 

163 

164def build_alpha_block(evaluation_dir: Path) -> str: 

165 """The strategy without its T-bill sweep, per period, against SPY / AGG / BTC; a pinned long run adds one row.""" 

166 evaluation_dir = Path(evaluation_dir) 

167 report = _load(evaluation_dir / ALPHA_FILE) 

168 if not report or not report.get("periods"): 

169 return "_Not computed yet: `aq evaluate --alpha-proof` (part of `--lean-report`)._" 

170 rows = _alpha_rows(report, PERIOD_LABELS) 

171 long_run = (_load(evaluation_dir / PIN_FILE) or {}).get("long_run") 

172 long_report = _load(evaluation_dir / f"alpha_proof_{long_run}.json") if long_run else None 

173 if long_report: 

174 rows += _alpha_rows(long_report, {"full": "Long run, same rule"}) 

175 verdict = report.get("r_alpha1") or {} 

176 reasons = "; ".join(verdict.get("failed") or []) 

177 trials = ((report.get("periods") or {}).get("full") or {}).get("dsr_trials", "n/a") 

178 aligned = (((report.get("periods") or {}).get("full") or {}).get("alpha_session_aligned") or {}).get("t_hac") 

179 note = [f"_With SPY and AGG read a session late, as the crypto series is, the full-window alpha t is {_format(aligned, 'num2')} (#330). R-ALPHA1 reads the figure in the table._", ""] if aligned is not None else [] 

180 return "\n".join([ 

181 "| Period | Dates | Sharpe | 95% interval | Alpha per year | Alpha t | Deflated Sharpe |", "|---|---|---|---|---|---|---|", *rows, "", 

182 f"**Proof of alpha (R-ALPHA1): {verdict.get('verdict', 'n/a')}**" + (f" ({reasons})." if reasons else "."), 

183 "", *note, 

184 f"_Run `{report.get('run', 'n/a')}` · computed {report.get('computed_at', 'n/a')} · alpha against " 

185 f"{' / '.join(report.get('benchmarks') or [])} with a Newey-West t · deflated over {trials} ledger trials_", 

186 ]) 

187 

188 

189def build_status_block(evaluation_dir: Path) -> str: 

190 """The headline table at the top of the README.""" 

191 evaluation_dir = Path(evaluation_dir) 

192 stats = _load(evaluation_dir / STATISTICS_FILE) 

193 if not stats or stats.get("status") != "OK": 

194 return _NOT_RUN 

195 sections = stats.get("sections", {}) 

196 rows = {row["metric"]: row for name in ("efficiency", "performance", "runs") for row in sections.get(name) or []} 

197 full = ((_load(evaluation_dir / ALPHA_FILE) or {}).get("periods") or {}).get("full") or {} 

198 general = {row["metric"]: row for row in sections.get("general") or []} 

199 time_range = (general.get("Time range") or {}).get("portfolio", "n/a") 

200 

201 def value(metric: str, column: str, fmt: str) -> str: 

202 return _format((rows.get(metric) or {}).get(column), fmt) 

203 

204 return "\n".join([ 

205 "| Lean Sharpe | Net profit | Max drawdown | Sharpe without T-bill carry | Alpha t | Deflated Sharpe |", "|---|---|---|---|---|---|", 

206 f"| {value('Annualized Sharpe ratio (Lean: risk-free rate subtracted)', 'portfolio', 'num2')} | {value('Net profit (Lean)', 'portfolio', 'pct_raw')} | " 

207 f"{value('Maximum drawdown', 'portfolio', 'pct')} | {value('Annualized Sharpe ratio (no risk-free rate)', 'strategy', 'num2')} | " 

208 f"{_format((full.get('alpha') or {}).get('t_hac'), 'num2')} | {_format(full.get('dsr'), 'pct')} |", 

209 "", 

210 f"_Lean run `{stats.get('run', 'n/a')}`, {time_range}, computed {stats.get('computed_at', 'n/a')}. Details: [Backtest Statistics](#backtest-statistics)._", 

211 ]) 

212 

213 

214def build_backtest_statistics_blocks(evaluation_dir: Path) -> dict[str, str]: 

215 """{section: markdown body} for every Backtest Statistics block; each degrades to a not-run line without the JSON.""" 

216 path = Path(evaluation_dir) / STATISTICS_FILE 

217 try: 

218 stats = json.loads(path.read_text(encoding="utf-8")) if path.exists() else None 

219 except (OSError, ValueError): 

220 stats = None 

221 if not stats or stats.get("status") != "OK": 

222 return dict.fromkeys(SECTIONS, _NOT_RUN) 

223 sections = stats.get("sections", {}) 

224 blocks = {} 

225 for section in SECTIONS: 

226 content = sections.get(section) 

227 if content is None: 

228 blocks[section] = _NOT_RUN 

229 elif section == "classification": 

230 blocks[section] = _classification_table(content, stats) 

231 elif section == "attribution": 

232 blocks[section] = _attribution_table(content, stats) 

233 elif section == "benchmarks": 

234 blocks[section] = _benchmark_table(content, stats) 

235 else: 

236 blocks[section] = _metric_table(content, stats) 

237 return blocks