Coverage for evaluation/premia_research.py: 100%
162 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"""Scores a sleeve on the offline engine (V6.5.0): the median over rebalance phases, by sub-period, and against placebos.
3One Lean run is one rebalance phase and phase luck is real (a tranche study once ranged from -1.02 to +0.57 Sharpe on a single
4split), so a sleeve is judged on the median over `PHASES` offsets. The rule R-SLEEVE2 itself (`selection_gate`) is a pure
5function of these scores, so its text and its code can be compared directly.
6"""
8from __future__ import annotations
10import datetime
11import math
12from collections.abc import Callable, Mapping
13from dataclasses import dataclass, field
14from pathlib import Path
15from typing import TYPE_CHECKING, Any
17import numpy as np
18import pandas as pd
20from evaluation.target_weights_engine import MarketPanel, load_market_panel, simulate_target_weights
21from portfolio.financing import load_rate_series
22from portfolio.premia_signals import (
23 DIRECT,
24 POOLED,
25 TS,
26 XS,
27 ResearchPanel,
28 SleeveSpec,
29 WeightSettings,
30 fred_series_table,
31 known_closes,
32 null_signal,
33 sleeve_signal,
34)
35from portfolio.target_weights import TargetWeightsConfig, resolve_target_weights_config
37if TYPE_CHECKING:
38 from collections.abc import Iterable
40PHASES = 5
41ANNUALIZATION = 365.0
42SESSION_ANNUALIZATION = 252.0
43FRED_KEYS = ("treasury_10yr", "treasury_3mo", "credit_spread_baa10y", "implied_volatility_vix", "implied_volatility_3m")
46def annual_sharpe(daily: pd.Series, *, sessions: Iterable[str] | None=None) -> float | None:
47 """Given `sessions`, the series is compounded onto them and annualised at 252: a panel has no weekend rows before its first
48 crypto bar, and sqrt(365) on session rows inflates a Sharpe about 1.2 times. Without them, calendar rows at sqrt(365)."""
49 annualization = ANNUALIZATION
50 if sessions is not None:
51 from evaluation.alpha_proof import to_sessions
53 daily = to_sessions(daily, sessions)
54 annualization = SESSION_ANNUALIZATION
55 values = daily.to_numpy(dtype=float)
56 values = values[np.isfinite(values)]
57 if len(values) < 20 or values.std(ddof=1) <= 0.0:
58 return None
59 return float(values.mean() / values.std(ddof=1) * math.sqrt(annualization))
62def annual_volatility(daily: pd.Series, *, sessions: Iterable[str] | None = None) -> float | None:
63 """Annualised standard deviation of the daily returns, on the same calendar rule as `annual_sharpe`."""
64 annualization = ANNUALIZATION
65 if sessions is not None:
66 from evaluation.alpha_proof import to_sessions
68 daily = to_sessions(daily, sessions)
69 annualization = SESSION_ANNUALIZATION
70 values = daily.to_numpy(dtype=float)
71 values = values[np.isfinite(values)]
72 return float(values.std(ddof=1) * math.sqrt(annualization)) if len(values) >= 20 else None
75def class_breadth(weights: Mapping[str, Mapping[str, float]], asset_class: Mapping[str, str], *, minimum: int = 3) -> float:
76 """The share of rebalance rows that hold a non-zero weight in at least `minimum` asset classes (0.0 with no rows)."""
77 if not weights:
78 return 0.0
79 broad = sum(len({asset_class.get(ticker) for ticker, weight in row.items() if weight}) >= minimum for row in weights.values())
80 return broad / len(weights)
83def max_drawdown(daily: pd.Series) -> float:
84 """The largest peak-to-trough fall of the compounded daily returns, as a positive fraction."""
85 if daily.empty:
86 return 0.0
87 curve = (1.0 + daily.fillna(0.0)).cumprod().to_numpy()
88 return float(1.0 - (curve / np.maximum.accumulate(curve)).min())
91def phase_offsets(rebalance_every: int, phases: int = PHASES) -> list[int]:
92 """The start offsets a rebalance cycle is averaged over, so no trial depends on its starting day."""
93 return sorted({int(i * rebalance_every / phases) for i in range(phases)})
96def nulls_for(spec: SleeveSpec) -> tuple[str, ...]:
97 """A ranking can be relabelled across assets; a direction or a timing rule has no cross-section to relabel."""
98 return ("asset_block", "time_shift") if spec.kind in (XS, POOLED) else ("sign_block", "time_shift")
101@dataclass
102class ResearchContext:
103 """Everything a research trial runs against: the market panel, the signal panel, the path config and the simulator."""
104 market: MarketPanel
105 panel: ResearchPanel
106 config: TargetWeightsConfig
107 sweep: dict
108 rf_dates: list[str]
109 rf_rates: list[float]
110 carry: Callable[[str, str], float]
111 listed: Callable[[str, str], bool]
112 settings: WeightSettings = field(default_factory=WeightSettings)
113 disabled_classes: frozenset[str] = frozenset()
115 def simulate(self, weights: Mapping[str, Mapping[str, float]], start: str, end: str, *, max_drawdown_velocity: float | None = None, max_total_drawdown: float | None = None) -> dict[str, Any]:
116 return simulate_target_weights(
117 weights, self.market, self.config, start=start, end=end, sweep_config=self.sweep, rf_dates=self.rf_dates,
118 rf_rates=self.rf_rates, carry_fn=self.carry, max_drawdown_velocity=max_drawdown_velocity,
119 max_total_drawdown=max_total_drawdown, disabled_classes=self.disabled_classes,
120 )
122 def sessions_for(self, spec: SleeveSpec) -> set[str] | None:
123 """Sessions to score a sleeve on; None for a crypto-only sleeve, whose calendar is every day."""
124 return None if tuple(spec.universe) == ("crypto",) else self.market.sessions
127def build_context(root: Path, config: dict[str, Any], *, data_dir: str = "data", respect_disabled_classes: bool = False) -> ResearchContext:
128 """Build a `ResearchContext` from the repo's data: the market panel, known closes, FRED, CFTC and carry inputs, and listing dates.
129 With `respect_disabled_classes` the engine drops the classes `config` disables, as `main.py` does (#384); off, a research round
130 that closed before V6.6.9 scores exactly as it did."""
131 from data_pipeline.cftc_cot import change_by_session, fx_pair_scores, macro_scores, read_positioning
132 from data_pipeline.fred_backfill import load_cached_fred_series
133 from features.fx_carry import fx_carry_3m
134 from risk.asset_class_router import asset_listed_on_venue, load_venue_listing_dates
136 root = Path(root)
137 market = load_market_panel(root, config, data_dir=data_dir)
138 known = known_closes(market.dates, market.tickers, market.closes, market.asset_class, market.sessions)
139 fred_rows = load_cached_fred_series()
140 forex = [ticker for ticker in known.columns if market.asset_class.get(ticker) == "forex"]
142 def carry(ticker: str, date: str) -> float:
143 return fx_carry_3m(ticker, "forex", datetime.date.fromisoformat(str(date)[:10]), fred_rows)
145 sessions = list(known.index)
146 # A signal row reads the rate of the session before: FRED's daily marks post after the equity tick. The USD side of
147 # `fx_carry_3m` reads the same day; financing above may, since it accrues after the fact.
148 carry_table = pd.DataFrame(
149 {ticker: [carry(ticker, sessions[max(0, position - 1)]) for position in range(len(sessions))] for ticker in forex},
150 index=sessions, dtype=float,
151 )
152 extras: dict[str, pd.DataFrame] = {"fx_carry": carry_table}
153 cot_path = root / "data" / "reference" / "cot_positioning.csv"
154 if cot_path.exists():
155 change = change_by_session(read_positioning(cot_path), sessions)
156 extras["cot_fx"] = fx_pair_scores(change, forex)
157 extras["cot_macro"] = macro_scores(change)
158 panel = ResearchPanel(known, market.asset_class, fred_series_table(fred_rows, FRED_KEYS), extras)
159 guard = config["phase_v2"].get("venue_listing_guard") or {}
160 listing_dates = load_venue_listing_dates(root / str(guard.get("path"))) if guard.get("enabled") else {}
161 rf_dates, rf_rates = load_rate_series(root / data_dir / "alternative" / "interest-rate" / "usa" / "interest-rate.csv")
162 disabled = frozenset(
163 asset_class for asset_class, key in (("future", "futures_risk"), ("option", "options_risk"), ("forex", "forex_risk"))
164 if respect_disabled_classes and not (config["phase_v2"].get(key) or {}).get("enabled", False)
165 )
166 return ResearchContext(
167 market, panel, resolve_target_weights_config(config["phase_v2"].get("target_weights")), config["phase_v2"]["cash_sweep"],
168 rf_dates, rf_rates, carry, lambda ticker, date: asset_listed_on_venue(ticker, date, listing_dates),
169 disabled_classes=disabled,
170 )
173def weights_for(spec: SleeveSpec, context: ResearchContext, signal: pd.DataFrame, *, start: str, end: str, phase_offset: int) -> dict[str, Any]:
174 """The sleeve's weights over [start, end] in this context, from one phase offset. A spec naming an `optimizer` in its
175 params (`portfolio.book_optimizer`, V6.6.9) is sized by it; a spec with none is sized as before."""
176 from portfolio.model_book import spec_weights
178 return spec_weights(spec, context.panel, signal, settings=context.settings, listed=context.listed, start=start, end=end, phase_offset=phase_offset)
181def score_sleeve(spec: SleeveSpec, context: ResearchContext, *, start: str, split: str, end: str, signal: pd.DataFrame | None = None) -> dict[str, Any]:
182 """Median over the phases of the ex-T-bill Sharpe: pooled and on both sides of `split`."""
183 signal = sleeve_signal(spec, context.panel) if signal is None else signal
184 sessions = context.sessions_for(spec)
185 pooled, first, second, drawdowns, turnover, gross, volatility, breadth = [], [], [], [], [], [], [], []
186 daily_by_phase: dict[int, pd.Series] = {}
187 for offset in phase_offsets(spec.rebalance_every):
188 weights = weights_for(spec, context, signal, start=start, end=end, phase_offset=offset)
189 result = context.simulate(weights, start, end)
190 strategy = result["strategy_excess"]
191 volatility.append(annual_volatility(strategy, sessions=sessions))
192 breadth.append(class_breadth(weights, context.panel.asset_class))
193 pooled.append(annual_sharpe(strategy, sessions=sessions))
194 first.append(annual_sharpe(strategy[strategy.index < split], sessions=sessions))
195 second.append(annual_sharpe(strategy[strategy.index >= split], sessions=sessions))
196 drawdowns.append(max_drawdown(strategy))
197 turnover.append(result["turnover"])
198 gross.append(float(result["gross"].mean()) if not result["gross"].empty else 0.0)
199 daily_by_phase[offset] = strategy
201 def median(values: list[Any]) -> float | None:
202 finite = [value for value in values if value is not None]
203 return float(np.median(finite)) if finite else None
205 return {
206 "id": spec.id, "track": spec.track, "kind": spec.kind, "phases": len(pooled), "sharpe": median(pooled),
207 "sharpe_first_half": median(first), "sharpe_second_half": median(second), "max_drawdown": median(drawdowns),
208 "turnover": median(turnover), "mean_gross": median(gross), "volatility": median(volatility), "class_breadth": median(breadth),
209 "daily": daily_by_phase,
210 }
213def placebo_sharpes(spec: SleeveSpec, context: ResearchContext, mode: str, *, start: str, end: str, draws: int, seed: int = 1) -> list[float]:
214 """Sharpes of `draws` placebo runs over the same window, one random rebalance phase each."""
215 signal = sleeve_signal(spec, context.panel)
216 rng = np.random.default_rng(seed)
217 offsets = phase_offsets(spec.rebalance_every)
218 out: list[float] = []
219 for draw in range(draws):
220 placebo = null_signal(signal, mode, seed=seed * 100_003 + draw, asset_class=context.panel.asset_class)
221 offset = int(offsets[int(rng.integers(len(offsets)))])
222 simulated = context.simulate(weights_for(spec, context, placebo, start=start, end=end, phase_offset=offset), start, end)
223 value = annual_sharpe(simulated["strategy_excess"], sessions=context.sessions_for(spec))
224 if value is not None:
225 out.append(value)
226 return out
229def placebo_p_value(observed: float | None, placebos: list[float]) -> float:
230 """Share of placebos at or above the observed Sharpe, counting the observation itself (never exactly zero)."""
231 if observed is None or not placebos:
232 return 1.0
233 return (1.0 + sum(value >= observed for value in placebos)) / (len(placebos) + 1.0)
236def passes_sharpe_clauses(score: Mapping[str, Any], *, half_floor: float = 0.40, pooled_floor: float = 0.50) -> bool:
237 """Whether a trial's pooled Sharpe and both halves' Sharpes clear their floors (R-SLEEVE3's Sharpe clauses)."""
238 values = (score.get("sharpe"), score.get("sharpe_first_half"), score.get("sharpe_second_half"))
239 return (
240 all(value is not None for value in values)
241 and values[0] >= pooled_floor and values[1] >= half_floor and values[2] >= half_floor
242 )
245def selection_gate(scores: list[dict], p_values: Mapping[str, Mapping[str, float]], *, max_survivors: int = 5, max_correlation: float = 0.7, alpha: float = 0.05) -> dict[str, Any]:
246 """R-SLEEVE2. A survivor passes both Sharpe clauses and every placebo test; among survivors the higher Sharpe keeps its place
247 against any other with daily correlation above `max_correlation`; at most `max_survivors` remain."""
248 passing = []
249 failed: dict[str, str] = {}
250 for score in sorted(scores, key=lambda item: item.get("sharpe") if item.get("sharpe") is not None else -math.inf, reverse=True):
251 name = score["id"]
252 if not passes_sharpe_clauses(score):
253 failed[name] = "sharpe"
254 elif not p_values.get(name) or any(value >= alpha for value in p_values[name].values()):
255 failed[name] = "placebo"
256 else:
257 passing.append(score)
258 survivors: list[dict] = []
259 for score in passing:
260 series = _first_phase(score)
261 too_close = any(
262 series is not None and _first_phase(kept) is not None
263 and float(pd.concat([series, _first_phase(kept)], axis=1, join="inner").corr().iloc[0, 1]) > max_correlation
264 for kept in survivors
265 )
266 if too_close:
267 failed[score["id"]] = "correlated"
268 elif len(survivors) >= max_survivors:
269 failed[score["id"]] = "budget"
270 else:
271 survivors.append(score)
272 return {"survivors": [score["id"] for score in survivors], "failed": failed}
275def _first_phase(score: Mapping[str, Any]) -> pd.Series | None:
276 daily = score.get("daily") or {}
277 return daily[min(daily)] if daily else None
280__all__ = [
281 "DIRECT", "TS", "XS", "PHASES", "ResearchContext", "annual_sharpe", "annual_volatility", "class_breadth", "build_context", "max_drawdown", "nulls_for",
282 "phase_offsets", "passes_sharpe_clauses", "placebo_p_value", "placebo_sharpes", "score_sleeve", "selection_gate", "weights_for",
283]