Coverage for evaluation/alpha_proof.py: 100%
177 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"""Proof of alpha for one finished Lean run (V6.4.4, `aq evaluate --alpha-proof`, rule R-ALPHA1).
3The question is whether the strategy (the run without its T-bill carry) earns a return its market exposures do not
4explain, beyond what the number of configurations tried would produce by luck. Per period it reports:
6 * the annualised Sharpe and its stationary-block-bootstrap 95% interval,
7 * the alpha of an OLS of the strategy's daily return on SPY, AGG and BTC daily returns, with a Newey-West t
8 (`evaluation.factor_spanning`, the same HAC estimator the factor-spanning test uses),
9 * the probabilistic and deflated Sharpe ratios (`evaluation.backtest_statistics`, trials from the registry).
11R-ALPHA1 is descriptive - it ships nothing: "demonstrated" iff the full-window alpha t >= 2, the deflated Sharpe >=
120.95, and the alpha is positive in the holdout and in the fresh (never-seen) period, when that period is long enough.
13"""
15from __future__ import annotations
17import json
18import math
19from pathlib import Path
20from typing import TYPE_CHECKING, Any
22import numpy as np
23import pandas as pd
25if TYPE_CHECKING:
26 from collections.abc import Iterable, Sequence
28 from numpy.typing import ArrayLike
30PERIODS = {
31 "backtest": ("2023-07-01", "2025-06-30"),
32 "holdout": ("2025-07-01", "2026-11-02"),
33}
34# V6.5.0 froze its data at 2026-11-02: everything after it was unseen by every rule of that phase, which makes it the forward test.
35FRESH_START = "2026-11-03"
36# One bar for both fresh-period checks, counted in equity sessions: a run's series also has weekend rows.
37FORWARD_MIN_SESSIONS = 60
38BENCHMARKS = ("SPY", "AGG", "BTCUSD")
41def strategy_daily_returns(run: dict[str, Any], config: dict[str, Any], root: Path, *, data_dir: str = "data") -> pd.Series:
42 """Daily strategy return (NAV change minus the T-bill sweep's net P&L, over the previous NAV), indexed by the date
43 the return ends on - the same series `backtest_statistics.compute_backtest_statistics` calls the strategy."""
44 from evaluation.backtest_audit import CASH_SWEEP_CLASS, class_by_ticker_from_config, daily_equity_from_chart
45 from evaluation.backtest_statistics import _interval_sums
46 from evaluation.lean_attribution import closes_for_universe, daily_ticker_pnl, fills_from_order_events
48 points = daily_equity_from_chart(run["result"])
49 dates = [day for day, _ in points]
50 nav = [value for _, value in points]
51 if len(nav) < 3:
52 return pd.Series(dtype=float)
53 class_by_ticker = class_by_ticker_from_config(config)
54 sweep = {ticker for ticker, kind in class_by_ticker.items() if kind == CASH_SWEEP_CLASS}
55 forex = {ticker for ticker, kind in class_by_ticker.items() if kind == "forex"}
56 fills = fills_from_order_events(run.get("order_events", []))
57 closes = closes_for_universe(config, root, {fill.ticker for fill in fills}, data_dir=data_dir)
58 ticker_pnl = daily_ticker_pnl(fills, closes, dates, forex)
59 sweep_by_day = {day: sum(e["pnl"] - e["fee"] for t, e in tickers.items() if t in sweep) for day, tickers in ticker_pnl.items()}
60 carry = _interval_sums(sweep_by_day, dates)
61 returns = {}
62 for index, (before, after, sweep_pnl) in enumerate(zip(nav, nav[1:], carry, strict=False), start=1):
63 if before > 0.0:
64 returns[dates[index]] = ((after - before) - sweep_pnl) / before
65 return pd.Series(returns, dtype=float).sort_index()
68def benchmark_daily_returns(
69 root: Path, config: dict[str, Any], tickers: Sequence[str]=BENCHMARKS, *, start: str, end: str, data_dir: str = "data", required: bool = False, lag_equity: bool = False,
70) -> pd.DataFrame:
71 """Session-calendar daily returns of the benchmark tickers from their config zips: the calendar is the first
72 ticker's (SPY, US equity sessions); a ticker that also trades on other days (BTC) is priced at its last close on or
73 before each session, so every column spans the same session-to-session interval. Tickers not in the universe are
74 left out, or raise with `required`, since a verdict must not quietly lose a benchmark. Before a ticker's first bar its
75 return is 0, not NaN: the regression drops any row with a NaN, which would cut a window back to BTC's first bar.
76 `lag_equity` also reads an equity column a session late, like the crypto and forex ones: a crypto book's daily sample holds the bar dated before it, so SPY and AGG on their own date sit a session
77 out of line with it (#330). It is off by default, so the pre-registered R-ALPHA1 figures are unchanged, and `alpha_session_aligned` reports the aligned one beside them."""
78 from data_pipeline.data_audit import asset_zip_paths, read_lean_daily_zip
80 assets = {str(asset["ticker"]): asset for asset in config["phase1"]["universe"]["assets"]}
81 closes = {}
82 for ticker in tickers:
83 asset = assets.get(ticker)
84 if asset is None:
85 if required:
86 raise ValueError(f"benchmark {ticker} is not in this run's universe")
87 continue
88 frame = read_lean_daily_zip(asset_zip_paths(asset, Path(root) / data_dir)["trade"], str(asset.get("security_type")))
89 series = frame.set_index(frame["date"].dt.strftime("%Y-%m-%d"))["close"].astype(float).sort_index()
90 # A crypto or forex bar dated D ends at the midnight after the equity close of D, so a run's daily sample of D holds the bar
91 # dated before it. On the bar's own date this column led the strategy by a day, which hid a crypto book's beta and
92 # booked it as alpha (a long-only crypto sleeve's t read 2.76, and 1.30 aligned).
93 late = str(asset.get("security_type")) in ("crypto", "forex") or (lag_equity and str(asset.get("security_type")) == "equity")
94 closes[ticker] = series.shift(1).dropna() if late else series
95 if not closes:
96 return pd.DataFrame()
97 sessions = closes[next(iter(closes))].index
98 table = pd.DataFrame({ticker: series.reindex(series.index.union(sessions)).ffill().reindex(sessions)
99 for ticker, series in closes.items()})
100 returns = table.pct_change(fill_method=None).iloc[1:].fillna(0.0)
101 return returns[(returns.index >= start) & (returns.index <= end)]
104def to_sessions(daily: pd.Series, sessions: Sequence[str] | pd.Index) -> pd.Series:
105 """Compounds a calendar-daily return series onto `sessions`: each session gets every return dated after the previous
106 session and up to itself (weekend crypto moves land on Monday, as they do in a session-based benchmark)."""
107 sessions = sorted(str(day) for day in sessions)
108 if not sessions or daily.empty:
109 return pd.Series(dtype=float)
110 position = np.searchsorted(np.asarray(sessions), np.asarray([str(day) for day in daily.index]), side="left")
111 keep = position < len(sessions)
112 labels = np.asarray(sessions)[position[keep]]
113 grouped = (1.0 + daily[keep]).groupby(labels).prod() - 1.0
114 return grouped.sort_index()
117def alpha_regression(y: pd.Series, x: pd.DataFrame, *, hac_lags: int = 5, annualization: float = 252.0) -> dict[str, Any]:
118 """OLS alpha of `y` on `x` (inner-joined dates, NaN rows dropped) with a Newey-West t; `annualization` is the
119 number of `y` periods a year (session data: 252)."""
120 from evaluation.factor_spanning import factor_spanning
122 out = factor_spanning(y, x, hac_lags=hac_lags, periods_per_year=int(annualization))
123 return {
124 "n": out.get("num_dates"),
125 "alpha_daily": out.get("alpha_daily"),
126 "alpha_annual": out.get("alpha_annual"),
127 "t_hac": out.get("alpha_t"),
128 "betas": out.get("betas"),
129 "r2": out.get("r2"),
130 }
133def sharpe(values: np.ndarray, annualization: float) -> float | None:
134 """The annualised Sharpe of the finite values; None with fewer than two or no variance."""
135 values = values[np.isfinite(values)]
136 if len(values) < 2 or values.std(ddof=1) <= 0.0:
137 return None
138 return float(values.mean() / values.std(ddof=1) * math.sqrt(annualization))
141def sharpe_bootstrap_ci(y: pd.Series, *, annualization: float, block: int = 10, draws: int = 2000, seed: int = 7) -> tuple[float | None, float | None]:
142 """95% interval of the annualised Sharpe by a stationary block bootstrap (Politis & Romano, mean block `block`)."""
143 values = y.to_numpy(dtype=float)
144 values = values[np.isfinite(values)]
145 n = len(values)
146 if n < 10:
147 return None, None
148 rng = np.random.default_rng(seed)
149 stats = []
150 p = 1.0 / max(block, 1)
151 for _ in range(draws):
152 index = np.empty(n, dtype=int)
153 index[0] = rng.integers(n)
154 jumps = rng.random(n) < p
155 starts = rng.integers(n, size=n)
156 for i in range(1, n):
157 index[i] = starts[i] if jumps[i] else (index[i - 1] + 1) % n
158 value = sharpe(values[index], annualization)
159 if value is not None:
160 stats.append(value)
161 if not stats:
162 return None, None
163 return float(np.percentile(stats, 2.5)), float(np.percentile(stats, 97.5))
166def period_report(y: pd.Series, benchmarks: pd.DataFrame, *, annualization: float, trial_sharpes: list[float], deflation: dict[str, Any] | None = None) -> dict[str, Any]:
167 """`deflation` (`evaluation.trial_ledger.deflation_inputs`) replaces the spread of `trial_sharpes`, which mixes windows and
168 annualisations, when the caller has one."""
169 from evaluation.backtest_statistics import deflated_sharpe_ratio, probabilistic_sharpe_ratio
171 values = y.to_numpy(dtype=float)
172 low, high = sharpe_bootstrap_ci(y, annualization=annualization)
173 if len(values) < 3:
174 dsr = {"value": None}
175 elif deflation:
176 dsr = deflated_sharpe_from_inputs(values, num_trials=deflation["N"], trial_variance=deflation["var"], annualization=annualization)
177 else:
178 dsr = deflated_sharpe_ratio(values, trial_sharpes, int(annualization))
179 return {
180 "start": str(y.index.min()) if len(y) else None,
181 "end": str(y.index.max()) if len(y) else None,
182 "n": int(len(y)),
183 "total_return": float(np.prod(1.0 + values) - 1.0) if len(values) else 0.0,
184 "sharpe": sharpe(values, annualization),
185 "sharpe_ci95": [low, high],
186 "psr": probabilistic_sharpe_ratio(values) if len(values) >= 3 else None,
187 "dsr": dsr.get("value"),
188 "dsr_trials": dsr.get("num_trials"),
189 "alpha": alpha_regression(to_sessions(y, benchmarks.index), benchmarks) if len(y) > 10 and not benchmarks.empty else None,
190 }
193def deflated_sharpe_from_inputs(returns: ArrayLike, *, num_trials: int, trial_variance: float | None, annualization: float) -> dict[str, Any]:
194 """The deflated Sharpe with N and the trial variance given (`evaluation.trial_ledger.deflation_inputs`), not derived from
195 a list of trial Sharpes: the variance must come from trials on the window being judged."""
196 from evaluation.backtest_statistics import expected_max_sharpe, probabilistic_sharpe_ratio
198 if trial_variance is None:
199 return {"value": None, "expected_max_sharpe_annual": None, "num_trials": num_trials}
200 sr0 = expected_max_sharpe(num_trials, trial_variance)
201 if sr0 is None:
202 return {"value": None, "expected_max_sharpe_annual": None, "num_trials": num_trials}
203 value = probabilistic_sharpe_ratio(np.asarray(returns, dtype=float), sr0 / math.sqrt(annualization))
204 return {"value": value, "expected_max_sharpe_annual": sr0, "num_trials": num_trials}
207def window_report(y: pd.Series, benchmarks: pd.DataFrame, *, start: str, end: str, annualization: float, deflation: dict[str, Any] | None = None) -> dict[str, Any]:
208 """Sharpe, alpha, max drawdown and (with `deflation`) the deflated Sharpe of a strategy series on one window."""
209 part = y[(y.index >= start) & (y.index <= end)]
210 if part.empty:
211 return {"start": start, "end": end, "n": 0}
212 values = part.to_numpy(dtype=float)
213 curve = np.cumprod(1.0 + values)
214 report = {
215 "start": str(part.index.min()), "end": str(part.index.max()), "n": int(len(part)),
216 "total_return": float(curve[-1] - 1.0), "sharpe": sharpe(values, annualization),
217 "max_drawdown": float(1.0 - (curve / np.maximum.accumulate(curve)).min()),
218 "alpha": alpha_regression(to_sessions(part, benchmarks.index), benchmarks) if len(part) > 10 and not benchmarks.empty else None,
219 }
220 if deflation:
221 report["dsr"] = deflated_sharpe_from_inputs(values, num_trials=deflation["N"], trial_variance=deflation["var"], annualization=annualization)
222 report["dsr_legacy_variance"] = deflated_sharpe_from_inputs(values, num_trials=deflation["N"], trial_variance=deflation.get("legacy_var"), annualization=annualization)
223 return report
226def r_alpha1(report: dict[str, Any]) -> dict[str, Any]:
227 """The descriptive verdict over the per-period figures."""
228 periods = report["periods"]
229 failed = []
230 full_alpha = (periods.get("full") or {}).get("alpha") or {}
231 if not (full_alpha.get("t_hac") is not None and full_alpha["t_hac"] >= 2.0):
232 failed.append("full-window alpha t < 2.0")
233 if not ((periods.get("full") or {}).get("dsr") is not None and periods["full"]["dsr"] >= 0.95):
234 failed.append("deflated Sharpe < 0.95")
235 holdout_alpha = ((periods.get("holdout") or {}).get("alpha") or {}).get("alpha_annual")
236 if not (holdout_alpha is not None and holdout_alpha > 0.0):
237 failed.append("holdout alpha <= 0")
238 fresh = periods.get("fresh") or {}
239 if fresh.get("judgeable"):
240 fresh_alpha = (fresh.get("alpha") or {}).get("alpha_annual")
241 if not (fresh_alpha is not None and fresh_alpha > 0.0):
242 failed.append("fresh-period alpha <= 0")
243 return {"rule": "R-ALPHA1", "verdict": "demonstrated" if not failed else "not demonstrated", "failed": failed,
244 "fresh_judged": bool(fresh.get("judgeable"))}
247def measured_annualization(index: Sequence[str] | pd.Index, *, fallback: float) -> float:
248 """Rows a year of this very series: a run with no crypto has no weekend rows, and a fixed 365 would inflate its Sharpe
249 by about 1.2 times. A weekend-free series is 252; one with weekend rows keeps the config's own figure."""
250 dates = pd.to_datetime(pd.Index([str(day) for day in index]))
251 if len(dates) < 20:
252 return fallback
253 return fallback if bool((dates.day_of_week >= 5).any()) else 252.0
256def fresh_sessions(y: pd.Series, sessions: Iterable[str], *, start: str = FRESH_START) -> int:
257 """Equity sessions after the data freeze, whatever else the series holds."""
258 return int(sum(1 for day in sessions if str(day) >= start and str(day) <= str(y.index.max()))) if len(y) else 0
261def alpha_proof_report(run_dir: Path, config: dict[str, Any], root: Path, *, trial_sharpes: list[float], deflation: dict[str, Any] | None = None, data_dir: str = "data") -> dict[str, Any]:
262 """Every period's figures and the R-ALPHA1 verdict for one Lean run folder (its frozen config when present). `data_dir`
263 is the run's data root; a closes or benchmark read from any other root would silently come back empty or wrong."""
264 from evaluation.backtest_audit import load_backtest_run
265 from evaluation.lean_attribution import run_config_path
267 run_dir, root = Path(run_dir), Path(root)
268 run = load_backtest_run(run_dir)
269 snapshot = run_config_path(run_dir, root)
270 run_config = json.loads(snapshot.read_text(encoding="utf-8")) if snapshot else config
271 annualization = float((run_config.get("runtime", {}) or {}).get("trading_days_per_year", 365) or 365)
272 y = strategy_daily_returns(run, run_config, root, data_dir=data_dir)
273 if y.empty:
274 return {"run": run_dir.name, "status": "no equity curve"}
275 annualization = measured_annualization(y.index, fallback=annualization)
276 benchmarks = benchmark_daily_returns(root, run_config, start=str(y.index.min()), end=str(y.index.max()), data_dir=data_dir)
277 aligned = benchmark_daily_returns(root, run_config, start=str(y.index.min()), end=str(y.index.max()), data_dir=data_dir, lag_equity=True)
278 windows = {"full": (str(y.index.min()), str(y.index.max())), **PERIODS, "fresh": (FRESH_START, str(y.index.max()))}
279 periods = {}
280 for name, (start, end) in windows.items():
281 part = y[(y.index >= start) & (y.index <= end)]
282 if part.empty:
283 periods[name] = {"n": 0}
284 continue
285 periods[name] = period_report(part, benchmarks, annualization=annualization, trial_sharpes=trial_sharpes, deflation=deflation)
286 # beside the pre-registered figure, never in place of it: R-ALPHA1 does not read this key
287 periods[name]["alpha_session_aligned"] = alpha_regression(to_sessions(part, aligned.index), aligned) if len(part) > 10 and not aligned.empty else None
288 sessions_after_freeze = fresh_sessions(y, benchmarks.index)
289 periods["fresh"]["sessions"] = sessions_after_freeze
290 periods["fresh"]["judgeable"] = sessions_after_freeze >= FORWARD_MIN_SESSIONS
291 periods["fresh"]["forward_judgeable"] = periods["fresh"]["judgeable"]
292 report = {"run": run_dir.name, "config": str(snapshot) if snapshot else "config.json", "annualization": annualization,
293 "benchmarks": list(benchmarks.columns), "periods": periods}
294 report["r_alpha1"] = r_alpha1(report)
295 return report