Coverage for evaluation/paper_protocol.py: 100%
130 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"""Paper-period protocol and band check (V6.4.0, lead L12).
3The paper period is the only out-of-sample test left and its success is NOT "make money": a fixed-config run is inside the
4bands a reference Lean run (the pinned final backtest) spans over windows of the same number of rebalances. This module
5turns a finished run folder (a Lean backtest, or a paper run with `diagnostics.book_history.paper_enabled`) into the
6protocol's checklist, builds the reference bands from every contiguous window of the reference run, and compares.
8Pure apart from `paper_metrics_for_run_dir`, which reads the run folder and the Lean data zips.
9"""
11from __future__ import annotations
13import math
14import statistics
15from bisect import bisect_left, bisect_right
16from collections import defaultdict
17from pathlib import Path
19MIN_REBALANCES = 6
20MIN_TRADING_DAYS = 120
21DEFAULT_QUANTILES = (0.05, 0.95)
22WARMUP_REASON = "thin_universe_or_zero_top_n"
24# metric -> label; every one is a ratio or per-day figure so windows of different length stay comparable
25METRICS = {
26 "veto_rate": "share of rebalances vetoed (gate / spread)",
27 "lock_rebalance_share": "share of rebalances with a kill-switch-locked member decision",
28 "strategy_gross_exposure": "mean strategy gross exposure, x NAV, T-bill sweep excluded",
29 "fills_per_rebalance": "fills per rebalance",
30 "median_slippage_bps": "median adverse fill vs the bar open, bps",
31 "p90_slippage_bps": "90th percentile adverse fill vs the bar open, bps",
32 "fee_bps_per_turnover": "broker fees per traded notional, bps",
33 "strategy_pnl_bps_per_day": "mean daily strategy P&L (sweep excluded), bps of NAV",
34 "sweep_pnl_bps_per_day": "mean daily T-bill sweep P&L, bps of NAV",
35 "daily_hit_ratio": "share of days with a positive strategy P&L",
36 "annualized_turnover": "traded notional / mean NAV / years, sweep excluded",
37}
40def live_rebalances(history: list[dict]) -> list[dict]:
41 """The run's rebalance records in date order, warm-up records (universe not ready) dropped."""
42 return sorted((record for record in history if record.get("gate_veto_reason") != WARMUP_REASON), key=lambda r: r.get("date", ""))
45def _quantile(values: list[float], q: float) -> float:
46 ordered = sorted(values)
47 position = q * (len(ordered) - 1)
48 low, high = math.floor(position), math.ceil(position)
49 return ordered[low] + (ordered[high] - ordered[low]) * (position - low)
52def daily_table(ticker_pnl: dict, nav_by_date: dict, closes: dict, sorted_closes: dict, sweep_tickers: set, rates=None) -> dict:
53 """{date: {exposure, strategy_pnl, sweep_pnl, fees, notional, fills}}: the per-date figures every window is a slice of.
54 `ticker_pnl` = `lean_attribution.daily_ticker_pnl` output; exposure marks each held position at its last close."""
55 rates = rates or {}
56 table = {}
57 for day in sorted(nav_by_date):
58 nav = nav_by_date[day]
59 entries = ticker_pnl.get(day, {})
60 exposure = strategy_pnl = sweep_pnl = fees = notional = 0.0
61 fills = 0
62 for ticker, entry in entries.items():
63 net = entry["pnl"] - entry["fee"]
64 if ticker in sweep_tickers:
65 sweep_pnl += net
66 continue
67 strategy_pnl += net
68 fees += entry["fee"]
69 notional += entry["notional"]
70 fills += entry["fills"]
71 series = closes.get(ticker) or {}
72 if entry["position"] and series:
73 order = sorted_closes.get(ticker, [])
74 position = bisect_right(order, day) - 1
75 if position >= 0:
76 exposure += abs(entry["position"] * series[order[position]] * rates.get((ticker, day), 1.0))
77 table[day] = {"exposure": exposure / nav if nav > 0.0 else 0.0, "strategy_pnl": strategy_pnl / nav if nav > 0.0 else 0.0,
78 "sweep_pnl": sweep_pnl / nav if nav > 0.0 else 0.0, "fees": fees, "notional": notional, "fills": fills,
79 "nav": nav}
80 return table
83def metrics_for_window(table: dict, rebalances: list[dict], slippage_by_date: dict[str, list[float]], start: str | None = None,
84 end: str | None = None) -> dict:
85 """The protocol's checklist over `[start, end]` (inclusive; None = open). Metrics that cannot be computed are None."""
86 days = [day for day in sorted(table) if (start is None or day >= start) and (end is None or day <= end)]
87 window = [record for record in rebalances if (start is None or record["date"] >= start) and (end is None or record["date"] <= end)]
88 if not days:
89 return {"rebalances": len(window), "trading_days": 0, **dict.fromkeys(METRICS)}
90 vetoed = sum(1 for record in window if not record.get("allocations"))
91 locked = sum(
92 1 for record in window
93 if any(str(reason).startswith("kill_switch") for decision in (record.get("book_member_decisions") or {}).values()
94 for reason in decision.get("reasons", []))
95 )
96 slippage = [value for day in days for value in slippage_by_date.get(day, [])]
97 fills = sum(table[day]["fills"] for day in days)
98 notional = sum(table[day]["notional"] for day in days)
99 fees = sum(table[day]["fees"] for day in days)
100 navs = [table[day]["nav"] for day in days]
101 years = max(len(days), 1) / 365.0
102 strategy = [table[day]["strategy_pnl"] for day in days]
103 return {
104 "rebalances": len(window), "trading_days": len(days),
105 "veto_rate": vetoed / len(window) if window else None,
106 "lock_rebalance_share": locked / len(window) if window else None,
107 "strategy_gross_exposure": statistics.fmean(table[day]["exposure"] for day in days),
108 "fills_per_rebalance": fills / len(window) if window else None,
109 "median_slippage_bps": statistics.median(slippage) if slippage else None,
110 "p90_slippage_bps": _quantile(slippage, 0.9) if slippage else None,
111 "fee_bps_per_turnover": fees / notional * 1e4 if notional > 0.0 else None,
112 "strategy_pnl_bps_per_day": statistics.fmean(strategy) * 1e4,
113 "sweep_pnl_bps_per_day": statistics.fmean(table[day]["sweep_pnl"] for day in days) * 1e4,
114 "daily_hit_ratio": sum(1 for value in strategy if value > 0.0) / len(strategy),
115 "annualized_turnover": notional / statistics.fmean(navs) / years if navs and statistics.fmean(navs) > 0.0 else None,
116 }
119def reference_bands(table: dict, rebalances: list[dict], slippage_by_date: dict, window_rebalances: int = MIN_REBALANCES,
120 quantiles: tuple[float, float] = DEFAULT_QUANTILES) -> dict:
121 """Per metric: the empirical `quantiles` range over every contiguous window of `window_rebalances` rebalances of the
122 reference run. {"bands": {metric: {"low", "high", "windows"}}, "windows": n, "window_rebalances": W}."""
123 dates = [record["date"] for record in rebalances]
124 days = sorted(table)
125 samples: dict[str, list[float]] = defaultdict(list)
126 count = 0
127 for index in range(len(dates) - window_rebalances + 1):
128 # a window = W rebalances and the days up to (excluding) the next rebalance: a whole number of cadences
129 following = index + window_rebalances
130 end = days[bisect_left(days, dates[following]) - 1] if following < len(dates) else None
131 metrics = metrics_for_window(table, rebalances, slippage_by_date, dates[index], end)
132 count += 1
133 for name in METRICS:
134 if metrics.get(name) is not None and math.isfinite(metrics[name]):
135 samples[name].append(metrics[name])
136 bands = {name: {"low": _quantile(values, quantiles[0]), "high": _quantile(values, quantiles[1]), "windows": len(values)}
137 for name, values in samples.items() if values}
138 return {"bands": bands, "windows": count, "window_rebalances": window_rebalances, "quantiles": list(quantiles)}
141def band_check(metrics: dict, bands: dict) -> dict:
142 """{"inside": every metric with a band is within it, "outside": [names], "rows": [...]}. A metric the run could not
143 compute counts as outside; a metric without a band is reported but not judged."""
144 rows, outside = [], []
145 for name, label in METRICS.items():
146 band = (bands.get("bands") or {}).get(name)
147 value = metrics.get(name)
148 if band is None:
149 rows.append({"metric": name, "label": label, "value": value, "low": None, "high": None, "inside": None})
150 continue
151 inside = value is not None and band["low"] <= value <= band["high"]
152 if not inside:
153 outside.append(name)
154 rows.append({"metric": name, "label": label, "value": value, "low": band["low"], "high": band["high"], "inside": inside})
155 enough = (metrics.get("rebalances") or 0) >= MIN_REBALANCES and (metrics.get("trading_days") or 0) >= MIN_TRADING_DAYS
156 return {"inside": not outside, "outside": outside, "rows": rows, "minimum_met": enough,
157 "minimum": {"rebalances": MIN_REBALANCES, "trading_days": MIN_TRADING_DAYS}}
160def _slippage_by_date(run: dict, data_root: Path) -> dict[str, list[float]]:
161 from evaluation.fill_price_audit import fills_from_run, zip_opens_for_fills
163 fills = fills_from_run(run)
164 references = zip_opens_for_fills(fills, data_root)
165 out: dict[str, list[float]] = defaultdict(list)
166 for fill in fills:
167 reference = references.get((fill["symbol"], fill["date"]))
168 if reference and reference > 0.0:
169 out[fill["date"]].append(fill["direction"] * (fill["price"] - reference) / reference * 1e4)
170 return out
173def target_weight_rebalances(table: dict) -> list[dict]:
174 """A target-weights run writes no book history (it has no book and no vetoes): each day with a strategy fill is a rebalance."""
175 return [{"date": day, "allocations": {"filled": True}} for day in sorted(table) if table[day]["fills"] > 0]
178def paper_metrics_for_run_dir(run_dir, config: dict, root, *, start: str | None = None, end: str | None = None) -> dict:
179 """Load one run folder (+ its book history) and return {"table", "rebalances", "slippage_by_date", "metrics"}; the
180 first three feed `reference_bands` when this run is the reference."""
181 import json
183 from evaluation.backtest_audit import CASH_SWEEP_CLASS, class_by_ticker_from_config, daily_equity_from_chart, load_backtest_run
184 from evaluation.lean_attribution import (
185 closes_for_universe,
186 daily_ticker_pnl,
187 fills_from_order_events,
188 find_book_history_for_run,
189 quote_to_usd_rate,
190 )
192 root = Path(root)
193 run = load_backtest_run(Path(run_dir))
194 class_by_ticker = class_by_ticker_from_config(config)
195 sweep = {ticker for ticker, kind in class_by_ticker.items() if kind == CASH_SWEEP_CLASS}
196 forex = {ticker for ticker, kind in class_by_ticker.items() if kind == "forex"}
197 points = daily_equity_from_chart(run["result"])
198 dates = [day for day, _ in points]
199 nav_by_date = dict(points)
200 fills = fills_from_order_events(run.get("order_events", []))
201 closes = closes_for_universe(config, root, {fill.ticker for fill in fills})
202 sorted_closes = {ticker: sorted(series) for ticker, series in closes.items()}
203 ticker_pnl = daily_ticker_pnl(fills, closes, dates, forex)
204 rates = {}
205 for day, entries in ticker_pnl.items():
206 for ticker in entries:
207 if ticker in forex:
208 rates[(ticker, day)] = quote_to_usd_rate(ticker, day, closes, sorted_closes)
209 table = daily_table(ticker_pnl, nav_by_date, closes, sorted_closes, sweep, rates)
210 history_path = find_book_history_for_run(Path(run_dir), root / "visualization" / "book_history")
211 history = []
212 if history_path is not None:
213 history = [json.loads(line) for line in Path(history_path).read_text(encoding="utf-8").splitlines() if line.strip()]
214 rebalances = live_rebalances(history)
215 if not rebalances and ((config.get("phase_v2") or {}).get("target_weights") or {}).get("enabled"):
216 rebalances = target_weight_rebalances(table)
217 slippage = _slippage_by_date(run, root / "data")
218 return {"table": table, "rebalances": rebalances, "slippage_by_date": slippage,
219 "metrics": metrics_for_window(table, rebalances, slippage, start, end),
220 "book_history": str(history_path) if history_path else None}