Coverage for evaluation/hello_world.py: 100%

178 statements  

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

1"""`aq hello` (V6.6.5, #343): the shipped book's rule on real daily bars, a cost-aware backtest and an honest report. 

2 

3The rule is the forward definition in `ml/forward/candidates.json` (`t3_crypto_trend_blend_x_eos`): long a coin while its 

4trailing return over 20, 60 and 120 sessions is positive (one vote each), vol-scaled and capped by 

5`portfolio.premia_signals`, rebalanced every 5 sessions. Timing is the live path's: a decision on session D reads the bars 

6dated before D, and its orders fill at the close of the bar dated D. Costs are Coinbase's taker fee plus the simulator's 

7crypto slippage, with the live path's 0.2% deadband. The overfitting block runs the same rule over an 8-variant lookback 

8grid (PBO by CSCV, the deflated Sharpe on that grid) and haircuts the Sharpe for the project's own trial count. 

9""" 

10 

11from __future__ import annotations 

12 

13import html 

14import math 

15import time 

16from collections.abc import Callable 

17from dataclasses import dataclass, field 

18from datetime import date, datetime, timedelta, timezone 

19from itertools import product 

20from pathlib import Path 

21 

22import numpy as np 

23import pandas as pd 

24 

25from evaluation.backtest_api import BacktestResult, backtest, summary_statistics 

26from evaluation.backtest_statistics import deflated_sharpe_ratio, probabilistic_sharpe_ratio 

27from evaluation.overfitting import haircut_sharpe, minimum_track_record_length 

28from evaluation.pbo import probability_of_backtest_overfitting 

29from execution.cost_models import coinbase_model 

30from portfolio.premia_signals import ResearchPanel, SleeveSpec, WeightSettings, signal_to_weights, sleeve_signal 

31 

32__all__ = [ 

33 "HELLO_RULE", "RESEARCH_TRIALS", "StatsRow", "HelloReport", "known_at_sessions", "load_closes", "rule_weights", "run_hello", "render_text", "render_html", 

34] 

35 

36HELLO_RULE: dict[str, object] = { 

37 "id": "t3_crypto_trend_blend_x_eos", 

38 "kind": "time_series", 

39 "family": "crypto_trend", 

40 "universe": ["crypto"], 

41 "rebalance_every": 5, 

42 "params": {"lookback_a": 20, "lookback_b": 60, "lookback_c": 120}, 

43} 

44# The deflated-Sharpe N of the project's research record after V6.6.4 (development/Problems.md #336). 

45RESEARCH_TRIALS = 258 

46GRID_A = (10, 20, 30, 40) 

47GRID_C = (120, 180) 

48DEADBAND = 0.002 # portfolio.target_weights.TargetWeightsConfig.min_weight_change 

49PERIODS_PER_YEAR = 365 

50NOTE = "No verified edge: this is the project's shipped book, labelled improved, not verified. Past results say nothing certain about the future." 

51 

52 

53@dataclass(frozen=True) 

54class StatsRow: 

55 """One column of the report.""" 

56 

57 name: str 

58 cagr: float 

59 volatility: float 

60 sharpe: float 

61 sortino: float 

62 max_drawdown: float 

63 calmar: float 

64 turnover: float 

65 cost_bps: float 

66 average_gross: float 

67 

68 @classmethod 

69 def from_result(cls, name: str, result: BacktestResult) -> StatsRow: 

70 stats = result.stats() 

71 gross = float(result.weights.abs().sum(axis=1).mean()) if len(result.weights) else 0.0 

72 return cls(name, stats["cagr"], stats["annual_volatility"], stats["sharpe_ratio"], stats["sortino_ratio"], stats["max_drawdown"], 

73 stats["calmar_ratio"], stats["turnover_annual"], stats["cost_drag_bps_annual"], gross) 

74 

75 

76@dataclass(frozen=True) 

77class HelloReport: 

78 """Everything `aq hello` prints, plus the equity curves.""" 

79 

80 start: str 

81 end: str 

82 coins: tuple[str, ...] 

83 data_source: str 

84 strategy: StatsRow 

85 btc_buy_hold: StatsRow 

86 equal_weight: StatsRow 

87 psr: float 

88 dsr_grid: float | None 

89 pbo: float | None 

90 min_track_record_years: float 

91 haircut_sharpe: float 

92 grid_sharpes: tuple[float, ...] 

93 equity: pd.Series = field(repr=False) 

94 benchmark_equity: pd.Series = field(repr=False) 

95 elapsed_s: float = 0.0 

96 

97 def to_dict(self) -> dict[str, object]: 

98 """JSON-ready (finite numbers, curves as {date: value}).""" 

99 def row(stats: StatsRow) -> dict[str, object]: 

100 return {key: _finite(value) if isinstance(value, float) else value for key, value in stats.__dict__.items()} 

101 

102 return { 

103 "rule": HELLO_RULE["id"], "start": self.start, "end": self.end, "coins": list(self.coins), "data_source": self.data_source, 

104 "strategy": row(self.strategy), "btc_buy_hold": row(self.btc_buy_hold), "equal_weight": row(self.equal_weight), 

105 "psr": _finite(self.psr), "dsr_grid": _finite(self.dsr_grid), "research_trials": RESEARCH_TRIALS, 

106 "pbo": _finite(self.pbo), "min_track_record_years": _finite(self.min_track_record_years), "haircut_sharpe": _finite(self.haircut_sharpe), 

107 "grid_sharpes": [_finite(value) for value in self.grid_sharpes], "elapsed_s": round(self.elapsed_s, 2), 

108 "equity": {str(key): _finite(float(value)) for key, value in self.equity.items()}, 

109 "benchmark_equity": {str(key): _finite(float(value)) for key, value in self.benchmark_equity.items()}, 

110 "note": NOTE, 

111 } 

112 

113 

114def _finite(value: float | None) -> float | None: 

115 if value is None: 

116 return None 

117 number = float(value) 

118 return number if math.isfinite(number) else None 

119 

120 

121def known_at_sessions(closes: pd.DataFrame, sessions: list[str]) -> pd.DataFrame: 

122 """Closes known on each session: the bar dated before it (a crypto bar dated D closes at the midnight after D).""" 

123 calendar = closes.sort_index().ffill() 

124 lagged = calendar.shift(1) 

125 return lagged.reindex(lagged.index.union(sessions)).ffill().reindex(sessions) 

126 

127 

128def _weekday_sessions(index: pd.Index, start: str, end: str) -> list[str]: 

129 days = pd.to_datetime(pd.Index(index)) 

130 return [day.strftime("%Y-%m-%d") for day in days if day.weekday() < 5 and start <= day.strftime("%Y-%m-%d") <= end] 

131 

132 

133def rule_weights(closes: pd.DataFrame, *, start: str, end: str, params: dict[str, float] | None = None, 

134 rebalance_every: int | None = None) -> pd.DataFrame: 

135 """The rule's decisions as a calendar dates x coins frame (rows without a decision are NaN), from `start` to `end`.""" 

136 sessions = _weekday_sessions(closes.index, closes.index.min(), end) 

137 known = known_at_sessions(closes, sessions) 

138 rule_params = dict(params or HELLO_RULE["params"]) # type: ignore[arg-type] 

139 spec = SleeveSpec(str(HELLO_RULE["id"]), "hello", str(HELLO_RULE["kind"]), str(HELLO_RULE["family"]), tuple(HELLO_RULE["universe"]), # type: ignore[arg-type] 

140 int(rebalance_every or HELLO_RULE["rebalance_every"]), rule_params) # type: ignore[call-overload] 

141 panel = ResearchPanel(known, dict.fromkeys(closes.columns, "crypto")) 

142 rows = signal_to_weights(sleeve_signal(spec, panel), panel, kind=spec.kind, rebalance_every=spec.rebalance_every, settings=WeightSettings(), start=start, end=end) 

143 # Built row by row: pandas 2 `from_dict` drops a date whose dict is empty, pandas 3 keeps it. An empty decision (no live 

144 # coin) means hold nothing, as `simulate_target_weights` and the forward ledger read it. 

145 days = sorted(rows) 

146 frame = pd.DataFrame([[float(rows[day].get(ticker, 0.0)) for ticker in closes.columns] for day in days], index=days, columns=closes.columns, dtype=float) 

147 frame = frame.reindex(closes.index) 

148 return frame[(frame.index >= start) & (frame.index <= end)].reindex(closes.index) 

149 

150 

151SAMPLE_SOURCE = "bundled sample (Coinbase public candles, 2021-06-01 to 2026-10-31)" 

152 

153 

154def load_closes(*, offline: bool = False, start: str = "2022-01-01", end: str | None = None, cache_dir: Path | None = None, 

155 get_json: Callable[[str], object] | None = None) -> tuple[pd.DataFrame, str, str | None]: 

156 """(closes, source, notice). Downloads the 11 coins from Coinbase's public candles (about 6 months before `start`, 

157 for the 120-session lookback) unless `offline`; any failure falls back to the bundled sample, with a one-line notice.""" 

158 from aether_quant import samples 

159 from data_pipeline.public_candles import bars_to_panel, default_get_json, fetch_daily_bars 

160 

161 sample = samples.load_sample_prices() 

162 if offline: 

163 return sample, SAMPLE_SOURCE, None 

164 last = date.fromisoformat(end) if end else datetime.now(timezone.utc).date() 

165 first = date.fromisoformat(start) - timedelta(days=200) 

166 try: 

167 bars, failed = fetch_daily_bars(list(sample.columns), first, last, get_json=get_json or default_get_json, cache_dir=cache_dir) 

168 except Exception as exc: 

169 bars, failed = {}, [f"network: {exc}"] 

170 if bars and "BTCUSD" in bars and not failed: 

171 cache = "cache off" if cache_dir is None else f"cache {cache_dir}" 

172 return bars_to_panel(bars, "close"), f"Coinbase public candles, downloaded ({cache})", None 

173 return sample, SAMPLE_SOURCE, f"download incomplete ({', '.join(failed) or 'no data'}); using the bundled sample." 

174 

175 

176def _run(weights: pd.DataFrame, closes: pd.DataFrame, start: str, end: str) -> BacktestResult: 

177 window = closes[(closes.index >= start) & (closes.index <= end)] 

178 return backtest(weights.reindex(window.index), window, fill="close", cost_model=coinbase_model(end), periods_per_year=PERIODS_PER_YEAR, 

179 min_weight_change=DEADBAND) 

180 

181 

182def run_hello(closes: pd.DataFrame, *, start: str = "2022-01-01", end: str | None = None, data_source: str = "sample") -> HelloReport: 

183 """The whole demo on a calendar dates x coins frame of closes (needs ~6 months of history before `start`).""" 

184 began = time.perf_counter() 

185 closes = closes.sort_index().astype(float) 

186 end = end or str(closes.index.max()) 

187 weights = rule_weights(closes, start=start, end=end) 

188 result = _run(weights, closes, start, end) 

189 

190 window = closes[(closes.index >= start) & (closes.index <= end)] 

191 btc = pd.DataFrame(np.nan, index=window.index, columns=window.columns) 

192 btc.iloc[0] = 0.0 

193 btc.iloc[0, list(window.columns).index("BTCUSD")] = 1.0 

194 btc_result = backtest(btc, window, fill="close", cost_model=coinbase_model(end), periods_per_year=PERIODS_PER_YEAR) 

195 equal = pd.DataFrame(np.nan, index=window.index, columns=window.columns) 

196 month_starts = ~pd.Series(pd.to_datetime(window.index).to_period("M"), index=window.index).duplicated() 

197 for day in window.index[month_starts.to_numpy()]: 

198 live = window.loc[day].notna() 

199 equal.loc[day] = np.where(live, 1.0 / max(int(live.sum()), 1), 0.0) 

200 equal_result = backtest(equal, window, fill="close", cost_model=coinbase_model(end), periods_per_year=PERIODS_PER_YEAR) 

201 

202 grid_returns, grid_sharpes = [], [] 

203 for lookback_a, lookback_c in product(GRID_A, GRID_C): 

204 variant = _run(rule_weights(closes, start=start, end=end, params={"lookback_a": lookback_a, "lookback_b": 60, "lookback_c": lookback_c}), closes, start, end) 

205 grid_returns.append(variant.returns.to_numpy(float)) 

206 grid_sharpes.append(summary_statistics(variant.returns, periods_per_year=PERIODS_PER_YEAR)["sharpe_ratio"]) 

207 matrix = np.column_stack(grid_returns)[1:] 

208 usable = len(matrix) - len(matrix) % 8 

209 pbo_value = probability_of_backtest_overfitting(matrix[-usable:], blocks=8, periods_per_year=PERIODS_PER_YEAR)["pbo"] if usable >= 80 else None 

210 

211 net = result.returns.iloc[1:].to_numpy(float) 

212 stats = summary_statistics(result.returns, periods_per_year=PERIODS_PER_YEAR) 

213 dsr_grid = deflated_sharpe_ratio(net, grid_sharpes, periods_per_year=PERIODS_PER_YEAR)["value"] 

214 psr = probabilistic_sharpe_ratio(net, 0.0) 

215 min_trl = minimum_track_record_length(net, periods_per_year=PERIODS_PER_YEAR) / PERIODS_PER_YEAR 

216 haircut = haircut_sharpe(stats["sharpe_ratio"], len(net), RESEARCH_TRIALS, periods_per_year=PERIODS_PER_YEAR)["haircut_sharpe"] 

217 return HelloReport( 

218 start=str(window.index.min()), end=str(window.index.max()), coins=tuple(str(column) for column in closes.columns), data_source=data_source, 

219 strategy=StatsRow.from_result("Shipped rule", result), btc_buy_hold=StatsRow.from_result("BTC buy & hold", btc_result), 

220 equal_weight=StatsRow.from_result("Equal weight", equal_result), psr=float(psr) if psr is not None else float("nan"), 

221 dsr_grid=dsr_grid, pbo=pbo_value, min_track_record_years=min_trl, haircut_sharpe=haircut, grid_sharpes=tuple(grid_sharpes), 

222 equity=result.nav / result.nav.iloc[0], benchmark_equity=btc_result.nav / btc_result.nav.iloc[0], elapsed_s=time.perf_counter() - began, 

223 ) 

224 

225 

226def _pct(value: float | None) -> str: 

227 return "n/a" if value is None or not math.isfinite(value) else f"{value:.1%}" 

228 

229 

230def _num(value: float | None) -> str: 

231 return "n/a" if value is None or not math.isfinite(value) else f"{value:.2f}" 

232 

233 

234def _table(report: HelloReport) -> list[tuple[str, str, str, str]]: 

235 rows = (report.strategy, report.btc_buy_hold, report.equal_weight) 

236 return [ 

237 ("", *(row.name for row in rows)), 

238 ("CAGR", *(_pct(row.cagr) for row in rows)), 

239 ("Volatility", *(_pct(row.volatility) for row in rows)), 

240 ("Sharpe (no T-bill)", *(_num(row.sharpe) for row in rows)), 

241 ("Sortino", *(_num(row.sortino) for row in rows)), 

242 ("Max drawdown", *(_pct(row.max_drawdown) for row in rows)), 

243 ("Calmar", *(_num(row.calmar) for row in rows)), 

244 ("Avg gross exposure", *(_pct(row.average_gross) for row in rows)), 

245 ("Turnover / yr", *(f"{row.turnover:.1f}x" for row in rows)), 

246 ("Costs / yr", *(f"{row.cost_bps:.0f} bps" for row in rows)), 

247 ] # type: ignore[list-item] 

248 

249 

250def _checks(report: HelloReport) -> list[tuple[str, str]]: 

251 return [ 

252 ("Probabilistic Sharpe (vs 0)", _pct(report.psr)), 

253 ("PBO over an 8-variant lookback grid (CSCV)", f"{_num(report.pbo)} (above 0.5: the best variant tends to lose out of sample)"), 

254 ("Deflated Sharpe, 8 grid trials", _pct(report.dsr_grid)), 

255 (f"Haircut Sharpe, the project's {RESEARCH_TRIALS} trials (BHY)", _num(report.haircut_sharpe)), 

256 ("Minimum track record for Sharpe > 0", f"{_num(report.min_track_record_years)} years"), 

257 ] 

258 

259 

260def _aligned(pairs: list[tuple[str, str]]) -> list[str]: 

261 width = max(len(name) for name, _ in pairs) 

262 return [f"{name.ljust(width)} {value}" for name, value in pairs] 

263 

264 

265def render_text(report: HelloReport) -> str: 

266 """The plain-text report `aq hello` prints.""" 

267 table = _table(report) 

268 widths = [max(len(str(row[column])) for row in table) for column in range(4)] 

269 lines = [ 

270 "Aether Quant: hello world", 

271 "=========================", 

272 f"Rule {HELLO_RULE['id']} (trend votes over 20/60/120 sessions, rebalanced every 5)", 

273 f"Data {len(report.coins)} coins, {report.start} to {report.end}, {report.data_source}", 

274 "Costs Coinbase taker fee 80 bps + 10 bps slippage per trade, 0.2% deadband", 

275 "", 

276 ] 

277 lines += [" ".join(str(cell).rjust(widths[i]) if i else str(cell).ljust(widths[i]) for i, cell in enumerate(row)) for row in table] 

278 lines += [ 

279 "", 

280 "Overfitting checks", 

281 "------------------", 

282 *_aligned(_checks(report)), 

283 "", 

284 NOTE, 

285 "", 

286 "Next: the notebooks (notebooks/README.md, each opens in Colab), the docs (https://leon1706-lol.github.io/Aether-quant/),", 

287 " `aq hello --html report.html` for a page with the equity curve, and `aq --help`.", 

288 f"({report.elapsed_s:.1f} s)", 

289 ] 

290 return "\n".join(lines) 

291 

292 

293def _svg_curve(series: list[pd.Series], colors: list[str], width: int = 720, height: int = 260) -> str: 

294 values = np.concatenate([curve.to_numpy(float) for curve in series]) 

295 values = values[np.isfinite(values)] 

296 low, high = (float(values.min()), float(values.max())) if values.size else (0.0, 1.0) 

297 span = high - low or 1.0 

298 paths = [] 

299 for curve, color in zip(series, colors, strict=False): 

300 data = curve.to_numpy(float) 

301 steps = max(len(data) - 1, 1) 

302 points = " ".join(f"{i / steps * width:.1f},{height - (value - low) / span * height:.1f}" for i, value in enumerate(data) if math.isfinite(value)) 

303 paths.append(f'<polyline fill="none" stroke="{color}" stroke-width="1.6" points="{points}"/>') 

304 return f'<svg viewBox="0 0 {width} {height}" width="100%" role="img" aria-label="Equity curves">{"".join(paths)}</svg>' 

305 

306 

307def render_html(report: HelloReport) -> str: 

308 """A self-contained page: the table, the checks and the equity curve against BTC (no scripts, no external files).""" 

309 table = _table(report) 

310 head = "".join(f"<th>{html.escape(str(cell))}</th>" for cell in table[0]) 

311 body = "".join("<tr>" + "".join(f"<td>{html.escape(str(cell))}</td>" for cell in row) + "</tr>" for row in table[1:]) 

312 checks = _checks(report) 

313 check_rows = "".join(f"<tr><td>{html.escape(name)}</td><td>{html.escape(value)}</td></tr>" for name, value in checks) 

314 svg = _svg_curve([report.equity, report.benchmark_equity], ["#d97706", "#64748b"]) 

315 return f"""<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"> 

316<title>Aether Quant hello world</title><style> 

317:root{{color-scheme:light dark;--fg:#111827;--bg:#ffffff;--muted:#6b7280;--line:#e5e7eb}} 

318@media (prefers-color-scheme: dark){{:root{{--fg:#f3f4f6;--bg:#111827;--muted:#9ca3af;--line:#374151}}}} 

319body{{font:15px/1.5 system-ui,sans-serif;color:var(--fg);background:var(--bg);max-width:900px;margin:2rem auto;padding:0 16px}} 

320table{{border-collapse:collapse;width:100%;margin:1rem 0}}td,th{{border-bottom:1px solid var(--line);padding:.35rem .5rem;text-align:right}} 

321td:first-child,th:first-child{{text-align:left}}.muted{{color:var(--muted)}}</style></head><body> 

322<h1>Aether Quant: hello world</h1> 

323<p class="muted">{html.escape(str(HELLO_RULE["id"]))} on {len(report.coins)} coins, {html.escape(report.start)} to {html.escape(report.end)} ({html.escape(report.data_source)}). Coinbase taker fee plus slippage.</p> 

324<h2>Equity</h2>{svg}<p class="muted"><span style="color:#d97706">&#9632;</span> shipped rule &nbsp; <span style="color:#64748b">&#9632;</span> BTC buy &amp; hold</p> 

325<h2>Statistics</h2><table><thead><tr>{head}</tr></thead><tbody>{body}</tbody></table> 

326<h2>Overfitting checks</h2><table><tbody>{check_rows}</tbody></table> 

327<p><strong>{html.escape(NOTE)}</strong></p></body></html> 

328"""