Coverage for evaluation/ablation.py: 100%
74 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"""V5.1 Phase 5 (item 9): declarative ablation harness over the offline
2rank-book simulator - "how much does each piece of the adaptive machinery
3actually contribute", answered honestly. Only pieces genuinely represented
4in the offline dataset/simulator get a real number; everything runtime-only
5(the MoE gating blend, learned-topology sizing, rank-magnitude position
6sizing, the portfolio-book selection process itself, the net-edge cost
7gate) gets an explicit `{"status": "not_offline_measurable", "reason": ...}`
8sentinel, never a fabricated comparison. A fabricated ablation number is
9worse than an absent one - this repo's own convention of recording honest
10negatives (development/Changelog.md) supports being blunt here.
12Deliberately its own module, not folded into rank_book_simulator.py: this
13module composes multiple simulate_rank_book() runs into one declarative
14table; rank_book_simulator.py stays the single-run primitive both this
15module and `aq evaluate --rank-book` build on.
17Torch-free (see evaluation/__init__.py's docstring) - only imports
18rank_book_simulator.py, itself pure numpy/pandas plus the pure
19portfolio/book_construction.py and portfolio/book_neutrality.py.
20"""
22from __future__ import annotations
24import math
26import numpy as np
27import pandas as pd
29from .rank_book_simulator import simulate_rank_book
31# Variants whose live-path mechanism has NO representation anywhere in the
32# offline dataset or in simulate_rank_book() - "ablating" them here would
33# either compare the baseline against itself (a mechanism that was never
34# modeled offline in the first place) or would require runtime state this
35# module structurally cannot see. Each reason is specific enough to explain
36# to a reader why the number is genuinely absent, not just "not implemented
37# yet".
38NOT_OFFLINE_MEASURABLE_VARIANTS: dict[str, str] = {
39 "no_gating": (
40 "The MoE gating blend (moe/gating.py) drives probability_up/magnitude/"
41 "volatility - none of those enter the rank book at all. Absent from "
42 "the offline dataset; there is nothing to ablate."
43 ),
44 "no_topology_sizing": (
45 "Topology-derived sizing (risk/position_sizing.py::topology_sizing_multiplier()) "
46 "depends on per-bar learned-topology runtime state (confidence/disagreement) "
47 "that is computed live in main.py and never written to the offline dataset."
48 ),
49 "no_rank_sizing": (
50 "Rank-magnitude position sizing (risk/position_sizing.py::rank_sizing_multiplier()) "
51 "is a LIVE-ONLY behavior driven by main.py's runtime confidence signal. "
52 "simulate_rank_book() has never modeled it - every leg is already flat, "
53 "equal-weighted offline (see _simulate_rank_book_core()'s own per_name = "
54 "gross_exposure/2/len(leg) formula) - 'ablating' it here would compare the "
55 "baseline against itself, not a real finding."
56 ),
57 "no_portfolio_book": (
58 "The 'portfolio book' IS build_rank_based_book()'s cross-sectional top/"
59 "bottom-N selection - the thing simulate_rank_book() exists to simulate. "
60 "There is no simpler, non-book trading logic implemented anywhere offline "
61 "to fall back to (main.py's non-book code path is a different, per-symbol-"
62 "independent decision path with no offline dataset representation)."
63 ),
64 "no_net_edge_gate": (
65 "The net-edge cost gate (execution/cost_model.py::build_net_edge_decision(), "
66 "wired into analyzer/market_analyzer.py's Priority 6.5) is evaluated per-bar "
67 "against live liquidity/order-value context main.py computes at runtime. "
68 "simulate_rank_book() has no representation of liquidity or this gate at all."
69 ),
70 # "no_retraining" is handled separately by compare_static_vs_retrained()
71 # below - it IS offline-measurable, but only from Phase 4's walk-forward
72 # artifacts, not from a single simulate_rank_book() call the way every
73 # other variant in ABLATION_VARIANTS is. See run_ablation()'s docstring.
74}
76# Variants that ARE offline-measurable: kwarg overrides applied on top of
77# the caller's base_kwargs before calling simulate_rank_book(). Each one
78# documents exactly which live mechanism it approximates, and the one
79# respect in which it is only an approximation - never silently pretend
80# the offline number is a perfect stand-in for the live behavior.
81ABLATION_VARIANTS: dict[str, dict] = {
82 "no_neutrality": {
83 "dollar_neutral": False,
84 "sector_neutral": False,
85 },
86 # Bypasses apply_book_neutrality()'s two constraint steps. The per-name
87 # cap and gross-exposure cap (both still config-driven via base_kwargs)
88 # are NOT part of "neutrality" in this codebase's own naming (see
89 # portfolio/book_neutrality.py's own 4-step docstring) and stay active.
90 "no_hysteresis": {
91 "hysteresis_rank_margin": 0.0,
92 },
93 # build_rank_based_book()'s own documented no-op default - every
94 # rebalance re-selects top/bottom-N purely by that bar's current rank,
95 # no incumbent retention across rebalances.
96 "no_cost_model": {
97 "cost_bps_per_side": 0.0,
98 "commission_bps": 0.0,
99 },
100 # Zeroes the SIMULATOR's own cost terms - the offline analogue of
101 # execution/cost_model.py's round-trip cost estimate, simplified here to
102 # a fixed bps rate rather than main.py's per-bar liquidity-derived one
103 # (that per-bar estimate is itself absent from the offline dataset, the
104 # same reason no_net_edge_gate above is not offline-measurable).
105}
108def simulate_static_baseline(
109 frame: pd.DataFrame,
110 *,
111 forward_return_column: str = "target_return_1d",
112 ticker_column: str = "ticker",
113 date_column: str = "date",
114 min_universe_size: int = 20,
115 trading_days_per_year: int = 252,
116) -> dict:
117 """The "did the adaptive machinery add anything over just holding
118 everything" reference point every other variant's delta is measured
119 against. Equal-weight, long-only, buy-and-hold: the universe is fixed
120 ONCE, on the first date with >= min_universe_size eligible names, and
121 never rebalanced again (by construction, zero turnover and zero cost
122 after the single initial buy - deliberately NOT re-equal-weighting the
123 surviving membership each date, which would itself be a form of active
124 rebalancing and defeat the point of a static reference).
126 A ticker that later has a missing/NaN forward return on some date is
127 simply excluded from that date's equal-weighted average (not
128 renormalized against the full original count) - the same "skip, don't
129 zero-fill" convention _simulate_rank_book_core() already follows for
130 thin dates.
132 Returns the SAME shape as RankBookSimulationResult.to_dict() (a plain
133 dict, not the frozen dataclass itself, since this function has no
134 turnover/rebalance concept to compute num_rebalances/annualized_turnover
135 from - both are reported as 0)."""
136 working = frame.dropna(subset=[forward_return_column]).copy()
137 unique_dates = sorted(working[date_column].unique())
139 initial_tickers: set | None = None
140 net_returns: list[float] = []
141 per_date_used: list = []
142 names_held_series: list[int] = []
144 for date in unique_dates:
145 date_frame = working[working[date_column] == date]
146 if initial_tickers is None:
147 if len(date_frame) < min_universe_size:
148 continue
149 initial_tickers = set(date_frame[ticker_column])
151 held_frame = date_frame[date_frame[ticker_column].isin(initial_tickers)]
152 if held_frame.empty:
153 continue
154 bar_return = float(held_frame[forward_return_column].mean())
155 net_returns.append(bar_return)
156 per_date_used.append(str(date))
157 names_held_series.append(len(held_frame))
159 if not per_date_used:
160 return {
161 "gross_sharpe": 0.0, "net_sharpe": 0.0, "gross_total_return": 0.0,
162 "net_total_return": 0.0, "net_max_drawdown": 0.0, "annualized_turnover": 0.0,
163 "cost_drag_annual_bps": 0.0, "num_rebalances": 0, "num_dates_used": 0,
164 "mean_names_long": 0.0, "mean_names_short": 0.0,
165 "per_date_net_return": [], "per_date": [],
166 }
168 net_array = np.asarray(net_returns, dtype=float)
169 cumprod = np.cumprod(1.0 + net_array)
170 running_peak = np.maximum.accumulate(np.concatenate(([1.0], cumprod)))[1:]
171 max_drawdown = float(np.min(cumprod / running_peak - 1.0))
172 sharpe = 0.0
173 if len(net_array) >= 2:
174 std = float(net_array.std(ddof=1))
175 if std > 0.0:
176 sharpe = float(net_array.mean() / std) * math.sqrt(trading_days_per_year)
178 return {
179 "gross_sharpe": sharpe,
180 "net_sharpe": sharpe,
181 "gross_total_return": float(cumprod[-1] - 1.0),
182 "net_total_return": float(cumprod[-1] - 1.0),
183 "net_max_drawdown": max_drawdown,
184 "annualized_turnover": 0.0,
185 "cost_drag_annual_bps": 0.0,
186 "num_rebalances": 1 if initial_tickers else 0,
187 "num_dates_used": len(per_date_used),
188 "mean_names_long": float(np.mean(names_held_series)) if names_held_series else 0.0,
189 "mean_names_short": 0.0,
190 "per_date_net_return": [float(v) for v in net_returns],
191 "per_date": per_date_used,
192 }
195def run_ablation(frame: pd.DataFrame, base_kwargs: dict, variants: list[str]) -> dict:
196 """Runs simulate_rank_book() once per requested variant (base_kwargs
197 overridden per ABLATION_VARIANTS' declarative dict) on the SAME
198 predictions and dates, plus simulate_static_baseline() if
199 "static_baseline" is requested. Any requested variant in
200 NOT_OFFLINE_MEASURABLE_VARIANTS or equal to "no_retraining" returns the
201 honesty-contract sentinel instead of a number - "no_retraining" is
202 offline-measurable, but only via compare_static_vs_retrained() below,
203 which needs Phase 4 walk-forward artifacts this function does not
204 receive (a single frame/base_kwargs pair cannot answer a
205 trained-once-vs-retrained-per-window question).
207 Returns {variant_name: {...RankBookSimulationResult shape...,
208 "delta_vs_static_baseline": float} | {"status": "not_offline_measurable"
209 | "unknown_variant", "reason": str}}."""
210 results: dict[str, dict] = {}
212 static_result = simulate_static_baseline(
213 frame,
214 forward_return_column=base_kwargs.get("forward_return_column", "target_return_1d"),
215 ticker_column=base_kwargs.get("ticker_column", "ticker"),
216 date_column=base_kwargs.get("date_column", "date"),
217 min_universe_size=base_kwargs.get("min_universe_size", 20),
218 trading_days_per_year=base_kwargs.get("trading_days_per_year", 252),
219 )
220 static_sharpe = static_result["net_sharpe"]
221 if "static_baseline" in variants:
222 results["static_baseline"] = {**static_result, "delta_vs_static_baseline": 0.0}
224 for name in variants:
225 if name == "static_baseline":
226 continue
227 if name == "no_retraining":
228 results[name] = {
229 "status": "not_offline_measurable",
230 "reason": (
231 "Offline-measurable, but only via compare_static_vs_retrained() "
232 "against a Phase 4 walk-forward run's artifacts - run_ablation() "
233 "only has a single frame/base_kwargs pair, not per-window models."
234 ),
235 }
236 continue
237 if name in NOT_OFFLINE_MEASURABLE_VARIANTS:
238 results[name] = {"status": "not_offline_measurable", "reason": NOT_OFFLINE_MEASURABLE_VARIANTS[name]}
239 continue
240 if name not in ABLATION_VARIANTS:
241 results[name] = {"status": "unknown_variant", "reason": f"{name!r} is not a recognized ablation variant"}
242 continue
244 variant_kwargs = {**base_kwargs, **ABLATION_VARIANTS[name]}
245 result = simulate_rank_book(frame, **variant_kwargs)
246 results[name] = {**result.to_dict(), "delta_vs_static_baseline": result.net_sharpe - static_sharpe}
248 return results
251def compare_static_vs_retrained(
252 frozen_net_performance_by_window: dict[int, dict],
253 retrained_net_performance_by_window: dict[int, dict],
254 *,
255 min_windows: int = 2,
256) -> dict:
257 """The "no_retraining" ablation - pure comparison of two ALREADY-COMPUTED
258 result sets, matching train.py::assess_net_performance_quality()'s own
259 "assess what's given, never run a simulation itself" convention.
261 frozen_net_performance_by_window: {window_index: <net_performance_by_window
262 entry shape, "simulation" key with net_sharpe>} - window 0's model's OWN
263 predictions run (via evaluation.predict_head() + run_net_performance_simulation(),
264 by the caller) against every LATER window's own backtest frame, i.e.
265 "what if we had never retrained past window 0".
266 retrained_net_performance_by_window: the corresponding entries already
267 in a Phase 4 walk_forward_summary.json's net_performance_by_window
268 (window N's OWN freshly-trained model on window N's own data) - "what
269 the walk-forward run actually did".
271 Both dicts must share window_index keys for windows 1+ (window 0 is
272 excluded from the comparison by construction - it IS the frozen model,
273 comparing it against itself is not a retraining ablation). Returns
274 {"status": "insufficient_windows", "reason": ...} when fewer than
275 min_windows comparable windows are present in both dicts - never a
276 fabricated delta from 0 or 1 windows."""
277 comparable_windows = sorted(
278 (set(frozen_net_performance_by_window) & set(retrained_net_performance_by_window)) - {0}
279 )
280 if len(comparable_windows) < min_windows:
281 return {
282 "status": "insufficient_windows",
283 "reason": (
284 f"need >= {min_windows} windows (excluding window 0, the frozen model itself) "
285 f"present in both frozen and retrained result sets, found {len(comparable_windows)}"
286 ),
287 }
289 per_window: list[dict] = []
290 deltas: list[float] = []
291 for window_index in comparable_windows:
292 frozen_sharpe = float(frozen_net_performance_by_window[window_index]["simulation"]["net_sharpe"])
293 retrained_sharpe = float(retrained_net_performance_by_window[window_index]["simulation"]["net_sharpe"])
294 delta = retrained_sharpe - frozen_sharpe
295 deltas.append(delta)
296 per_window.append(
297 {
298 "window_index": window_index,
299 "frozen_net_sharpe": frozen_sharpe,
300 "retrained_net_sharpe": retrained_sharpe,
301 "delta": delta,
302 }
303 )
305 return {
306 "status": "walk_forward_derived",
307 "num_windows": len(comparable_windows),
308 "per_window": per_window,
309 "mean_delta_retrained_minus_frozen": float(np.mean(deltas)),
310 }