Coverage for scripts/as_live_levers.py: 100%
233 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"""One-lever-at-a-time attribution of the as-live rank book (V5.6.0, rebuilt in V5.7.0).
3`aq evaluate --rank-book --as-live` reports one number; this scores the dataset ONCE with the live blended head, then
4re-runs the same simulator with each live mechanism switched off (or each gate value changed) so the gap between the
5idealized and the as-live Sharpe is attributed instead of guessed. Investigation-only; writes
6ml/evaluation/as_live_levers.json. The slow part is scoring (minutes, cached on disk per split and model fingerprint);
7every variant afterwards takes seconds because the rolling-IC state is computed once per score set.
9 python scripts/as_live_levers.py [--split backtest] [--only "veto" "hold-on"]
11`AsLiveHarness` is the reusable part (scripts/gate_research.py builds its grids on it).
12"""
14from __future__ import annotations
16import argparse
17import hashlib
18import json
19import sys
20from pathlib import Path
21from time import perf_counter
23import numpy as np
24import pandas as pd
26ROOT_DIR = Path(__file__).resolve().parents[1]
27sys.path.insert(0, str(ROOT_DIR))
29ML_DIR = ROOT_DIR / "ml"
30CACHE_DIR = ML_DIR / "evaluation" / "cache"
31LEGACY_PROBABILITY_COLUMN = "legacy_probability_up"
32MODEL_FINGERPRINT_FILES = (
33 "multitask_model.json", "multitask_feature_schema.json", "sequence_model.json", "sequence_feature_schema.json",
34 "multitask_training_metrics.json", "sequence_training_metrics.json",
35)
38def _fingerprint(config: dict, dataset_path: Path, ml_dir: Path = ML_DIR) -> str:
39 digest = hashlib.sha1()
40 if ml_dir != ML_DIR:
41 digest.update(str(ml_dir.resolve()).encode())
42 for name in MODEL_FINGERPRINT_FILES:
43 path = ml_dir / name
44 digest.update(f"{name}:{path.stat().st_size if path.exists() else 0}:{int(path.stat().st_mtime) if path.exists() else 0}".encode())
45 digest.update(f"dataset:{dataset_path.stat().st_size}:{int(dataset_path.stat().st_mtime)}".encode())
46 digest.update(json.dumps(config.get("phase_v2", {}).get("rank_signal", {}), sort_keys=True).encode())
47 # V6.4.4: the scores also depend on the ranked-input setting and the seed ensemble (and its members' files)
48 extra = {
49 "cross_sectional_inputs": ((config.get("phase1") or {}).get("features") or {}).get("cross_sectional_inputs"),
50 "model_ensemble": (config.get("phase_v2") or {}).get("model_ensemble"),
51 }
52 if any(value not in (None, {}) and (not isinstance(value, dict) or value.get("enabled")) for value in extra.values()):
53 digest.update(json.dumps(extra, sort_keys=True).encode())
54 ensemble = extra["model_ensemble"] or {}
55 if ensemble.get("enabled"):
56 for kind in ("multitask_dir", "sequence_dir"):
57 for member in sorted((ml_dir / str(ensemble.get(kind, ""))).glob("*.json")):
58 digest.update(f"{member.name}:{member.stat().st_size}:{int(member.stat().st_mtime)}".encode())
59 return digest.hexdigest()[:16]
62class AsLiveHarness:
63 """The scored dataset of one split plus everything needed to run any as-live variant of it."""
65 def __init__(
66 self, split: str, *, use_cache: bool = True, dataset_path: str | Path | None = None, rl_model_path: str | Path | None = None,
67 topology_inputs_fn=None, ml_dir: str | Path | None = None, config: dict | None = None,
68 legacy_probability_path: str | Path | None = None, gate_warmup_days: int = 0,
69 ):
70 from aq_cli import _blend_raw_scores_for_dataset, _core_quality_tickers, _universe_asset_metadata
71 from evaluation.live_parity import LATE_BAR_ASSET_CLASSES, build_candidate_metadata, lag_predictions_for_tickers
72 from execution.cost_model import commission_bps_by_ticker, min_commission_usd_by_ticker
73 from features import load_sector_mapping
75 self.split = split
76 splits = (split,) if isinstance(split, str) else tuple(split) # V6.0.0: e.g. ("backtest", "holdout") for one Lean run
77 self.rl_model_path = str(rl_model_path) if rl_model_path else None
78 self.topology_inputs_fn = topology_inputs_fn
79 self.config = config if config is not None else json.loads((ROOT_DIR / "config.json").read_text(encoding="utf-8"))
80 ranking = self.config["phase1"]["target"]["ranking"]
81 net_perf = ranking["net_performance"]
82 dataset_path = Path(dataset_path) if dataset_path else ML_DIR / "datasets" / "full_dataset.csv"
83 # Every row, observation-only names included: main.py's percentile normalisation (hysteresis margins, the
84 # confidence the sizing chain reads) runs over every symbol with features, eligible or not. Read in chunks
85 # and keep only this split's rows: the whole 250-column file is ~0.5 GB resident on the 4 GB dev PC (V5.8.0).
86 # V6.1.0: `gate_warmup_days` also keeps the rows that far before the first split's start, so the rolling-IC gate is
87 # warm on day one as live's is (main.py fills its event buffer through the warm-up); they never enter the book.
88 warmup_start = None
89 if gate_warmup_days > 0:
90 window_name = {"train": "training"}.get(splits[0], splits[0])
91 first_start = self.config["phase1"]["windows"].get(window_name, {}).get("start")
92 if first_start:
93 warmup_start = (pd.Timestamp(first_start) - pd.Timedelta(int(gate_warmup_days), unit="D")).strftime("%Y-%m-%d")
94 parts, context_parts = [], []
95 for chunk in pd.read_csv(dataset_path, chunksize=40_000):
96 parts.append(chunk[chunk["split"].isin(splits)])
97 if warmup_start is not None:
98 dates = chunk["date"].astype(str)
99 context_parts.append(chunk[~chunk["split"].isin(splits) & (dates >= warmup_start) & (dates < str(first_start))])
100 dataset = pd.concat(parts, ignore_index=True) if parts else pd.DataFrame()
101 context = pd.concat(context_parts, ignore_index=True) if context_parts else pd.DataFrame()
102 del parts, context_parts
103 window = int(self.config.get("phase_v2", {}).get("sequence_model", {}).get("window_size", 30))
105 self.ml_dir = Path(ml_dir) if ml_dir else ML_DIR
106 warm_tag = f"_warm{int(gate_warmup_days)}" if warmup_start is not None else ""
107 cache_path = CACHE_DIR / f"live_rank_score_allrows_{'+'.join(splits)}{warm_tag}_{_fingerprint(self.config, dataset_path, self.ml_dir)}.npy"
108 scored = pd.concat([context, dataset], ignore_index=True) if len(context) else dataset
109 if use_cache and cache_path.exists():
110 raw_scores = np.load(cache_path)
111 else:
112 raw_scores, _policy = _blend_raw_scores_for_dataset(scored, self.config, window, ml_dir=self.ml_dir)
113 raw_scores = np.asarray(raw_scores, dtype=float)
114 CACHE_DIR.mkdir(parents=True, exist_ok=True)
115 np.save(cache_path, raw_scores)
116 context_scores, raw_scores = raw_scores[: len(context)], raw_scores[len(context):]
118 self.asset_class_by_ticker, eligible_by_ticker = _universe_asset_metadata(self.config)
119 self.metadata = build_candidate_metadata(self.asset_class_by_ticker, eligible_by_ticker)
120 from evaluation.live_parity import build_rank_groups
122 self.rank_groups = build_rank_groups(self.config, self.asset_class_by_ticker)
123 from evaluation.live_parity import load_live_venue_listing_dates
125 self.venue_listing_dates = load_live_venue_listing_dates(self.config, ROOT_DIR)
126 self.core_crypto = _core_quality_tickers()
127 self.frame = dataset
128 self.frame["live_rank_score"] = raw_scores
129 self.context_frame = context.assign(live_rank_score=context_scores) if len(context) else None
130 if legacy_probability_path:
131 # V6.1.0: final_probability_up per (date, ticker) from scripts/build_legacy_probability.py (the legacy signal)
132 probability = pd.read_parquet(legacy_probability_path) if str(legacy_probability_path).endswith(".parquet") \
133 else pd.read_csv(legacy_probability_path)
134 probability = probability.assign(date=probability["date"].astype(str).str[:10])[["date", "ticker", "final_probability_up"]]
135 self.frame = self.frame.assign(date=self.frame["date"].astype(str).str[:10]).merge(
136 probability.rename(columns={"final_probability_up": LEGACY_PROBABILITY_COLUMN}), on=["date", "ticker"], how="left"
137 )
138 from evaluation.live_parity import add_next_intraday_return
140 add_next_intraday_return(self.frame)
141 late = {t for t, kind in self.asset_class_by_ticker.items() if kind in LATE_BAR_ASSET_CLASSES}
142 self.late_bar_tickers = frozenset(late)
143 self.lagged_frame = lag_predictions_for_tickers(self.frame, prediction_column="live_rank_score", tickers=late)
144 if self.context_frame is not None:
145 self.context_frame = lag_predictions_for_tickers(self.context_frame, prediction_column="live_rank_score", tickers=late)
146 security_types = {str(a["ticker"]): str(a["security_type"]) for a in self.config["phase1"]["universe"]["assets"]}
147 self.base = dict(
148 prediction_column="live_rank_score", forward_return_column="target_return_1d", ticker_column="ticker", date_column="date",
149 top_n=int(net_perf.get("top_n", 6)), bottom_n=int(net_perf.get("bottom_n", 6)),
150 rebalance_every_bars=int(net_perf.get("rebalance_every_bars", 10)),
151 cost_bps_per_side=float(net_perf.get("cost_bps_per_side", 5.0)), commission_bps=float(net_perf.get("commission_bps", 1.0)),
152 gross_exposure=float(net_perf.get("gross_exposure", 1.0)), dollar_neutral=bool(net_perf.get("dollar_neutral", True)),
153 sector_neutral=bool(net_perf.get("sector_neutral", True)), sector_by_ticker=load_sector_mapping(self.config),
154 hysteresis_rank_margin=float(net_perf.get("hysteresis_rank_margin", 0.0)),
155 max_weight_per_name=float(net_perf.get("max_weight_per_name", 0.12)),
156 min_universe_size=int(ranking.get("min_universe_size", 20)),
157 commission_bps_by_ticker=commission_bps_by_ticker(self.config["phase_v2"].get("costs", {}), security_types) or None,
158 )
159 # V6.0.0: the broker's per-order dollar floor at the live NAV (used when an as-live run asks for it).
160 self.min_commission_usd_by_ticker = min_commission_usd_by_ticker(self.config["phase_v2"].get("costs", {}), security_types)
161 # V6.0.0: live's cadence counts equity sessions only; the as-live runs rebalance on those dates.
162 equity_tickers = {ticker for ticker, kind in security_types.items() if kind == "equity"}
163 self.session_dates = {
164 str(date) for date in self.frame.loc[self.frame["ticker"].astype(str).isin(equity_tickers), "date"].unique()
165 }
166 self.initial_cash = float(self.config.get("runtime", {}).get("initial_cash", 100_000.0))
167 self.phase_v2 = self.config["phase_v2"]
168 self.ic_config = dict(self.phase_v2.get("rolling_ic_gate", {}))
169 self._states: dict = {}
170 self._gates: dict = {}
171 self._mechanisms: dict = {}
173 # -- gates ---------------------------------------------------------------------------------------------------
174 def gate_for(self, frame, *, ic_floor=None, horizon_days=None, rolling_window_days=None, min_names=None,
175 late_bar_event_count=None):
176 """Rolling-IC gate for `frame`'s scores. The state depends on (horizon, window, min names, how late-bar events
177 are counted) only, so every floor variant shares it; the floor is applied afterwards."""
178 from evaluation.live_parity import make_rolling_ic_gate_fn
179 from evaluation.rolling_ic_gate_calibration import build_event_buffer
180 from evaluation.rolling_ic_series import make_rolling_ic_state_fn
181 from portfolio.rolling_ic_gate import resolve_late_bar_event_count
183 horizon = int(horizon_days if horizon_days is not None else self.ic_config.get("horizon_days", 20))
184 window = int(rolling_window_days if rolling_window_days is not None else self.ic_config.get("rolling_window_days", 40))
185 names = int(min_names if min_names is not None else self.ic_config.get("min_names_per_date", 10))
186 event_count = resolve_late_bar_event_count(
187 {"late_bar_event_count": late_bar_event_count} if late_bar_event_count else self.ic_config
188 )
189 state_key = (id(frame), horizon, window, names, event_count)
190 if state_key not in self._states:
191 from evaluation.live_parity import main_group_tickers
193 main_tickers = main_group_tickers(self.rank_groups, frame["ticker"].unique())
194 event_frame = frame
195 if self.context_frame is not None:
196 event_frame = pd.concat([self.context_frame[frame.columns.intersection(self.context_frame.columns)], frame],
197 ignore_index=True)
198 event_frame = event_frame if main_tickers is None else event_frame[event_frame["ticker"].astype(str).isin(main_tickers)]
199 # live records a crypto event on its own tick and again on the equity tick (evaluation.live_parity.with_live_event_duplicates)
200 from evaluation.live_parity import with_live_event_duplicates
202 if event_count == "per_tick":
203 event_frame = with_live_event_duplicates(event_frame, self.late_bar_tickers)
204 self._states[state_key] = make_rolling_ic_state_fn(
205 build_event_buffer(event_frame, raw_score_column="live_rank_score"),
206 horizon_days=horizon, rolling_window_days=window, min_names_per_date=names,
207 )
208 gate_config = dict(self.ic_config, horizon_days=horizon, rolling_window_days=window, min_names_per_date=names)
209 if ic_floor is not None:
210 gate_config["min_rolling_mean_ic"] = ic_floor
211 gate_key = (state_key, gate_config.get("min_rolling_mean_ic"), gate_config.get("min_resolved_dates_required"))
212 if gate_key not in self._gates:
213 self._gates[gate_key] = make_rolling_ic_gate_fn(
214 frame, raw_score_column="live_rank_score", gate_config=gate_config, state_fn=self._states[state_key]
215 )
216 return self._gates[gate_key]
218 def mechanisms(self, frame, include):
219 from evaluation.live_parity import build_live_mechanisms
221 key = (id(frame), tuple(include))
222 if key not in self._mechanisms:
223 self._mechanisms[key] = build_live_mechanisms(
224 self.config, frame, core_crypto_tickers=self.core_crypto, include=tuple(include), rl_model_path=self.rl_model_path,
225 topology_inputs_fn=self.topology_inputs_fn,
226 )
227 return self._mechanisms[key]
229 def v610_mechanisms(self, config: dict | None = None, *, legacy: bool = True, extra_returns: dict | None = None) -> dict:
230 """The V6.1.0 simulator options (rule R-CAL2), all replicas of live mechanisms: the daily member pass between
231 rebalances, weekend accrual, the position cap, the legacy probability signal (when the harness has its column)
232 and P&L outside the simulation that the kill switch reads."""
233 from evaluation.live_parity import build_live_member_weight_fn
234 from portfolio.legacy_sleeve import resolve_legacy_signal_params, resolve_legacy_sleeve_config
236 config = config or self.config
237 phase_v2 = config["phase_v2"]
238 options = {
239 "mid_cycle_member_updates": True,
240 "accrue_skipped_dates": True,
241 "max_active_positions": int(config.get("phase9", {}).get("portfolio", {}).get("max_active_positions", 12)),
242 "kill_switch_extra_returns": extra_returns,
243 }
244 sleeve = resolve_legacy_sleeve_config(phase_v2.get("legacy_sleeve"))
245 if legacy and sleeve["enabled"] and LEGACY_PROBABILITY_COLUMN in self.frame.columns:
246 weights = json.loads((self.ml_dir / "model_weights.json").read_text(encoding="utf-8"))
247 exits = phase_v2.get("exits", {})
248 assets = config["phase1"]["universe"]["assets"]
249 options["legacy_component"] = {
250 "probability_column": LEGACY_PROBABILITY_COLUMN,
251 "sleeve_config": sleeve,
252 "signal": resolve_legacy_signal_params(config, float(weights["training"]["decision_threshold"])),
253 "asset_classes": ("equity", "crypto"),
254 "weight_fn": build_live_member_weight_fn(
255 config, security_type_by_ticker={str(a["ticker"]): str(a.get("security_type", "equity")) for a in assets},
256 nav=self.initial_cash, core_crypto_tickers=self.core_crypto, topology_inputs_fn=self.topology_inputs_fn,
257 use_live_analyzer=True,
258 ),
259 "max_holding_dates": int(exits["max_holding_bars"]) if exits.get("enabled") and exits.get("max_holding_bars") else None,
260 "trailing_stop_pct": float(exits["trailing_stop_pct"]) if exits.get("enabled") and exits.get("trailing_stop_pct") else None,
261 }
262 return options
264 # -- runs ----------------------------------------------------------------------------------------------------
265 def idealized(self):
266 from evaluation import simulate_rank_book
268 return simulate_rank_book(self.frame, **dict(self.base))
270 def as_live(self, *, lagged=True, ic_floor=None, gate="on", include=("kill_switch", "member_sizing", "hrp", "impact"),
271 gate_window=None, gate_horizon=None, gate_min_names=None, config_overrides=None, cash_sweep=False,
272 gate_event_count=None, tranches=1, **overrides):
273 """One as-live run. `include` selects the optional mechanisms (kill switch, member sizing chain, HRP, impact);
274 `config_overrides` ({dotted.phase_v2.key: value}) changes the live config for this run only; `cash_sweep` adds
275 the V6.2.0 T-bill sweep (its own component, outside the kill switch) whatever the config says; `tranches` > 1 the
276 staggered book (evaluation.tranche_book)."""
277 from evaluation import simulate_rank_book
278 from evaluation.live_parity import build_as_live_kwargs
279 from portfolio.book_construction import resolve_class_weight_caps
281 frame = self.lagged_frame if lagged else self.frame
282 config = self.config
283 if config_overrides:
284 import copy
286 config = copy.deepcopy(self.config)
287 for dotted, value in config_overrides.items():
288 node = config["phase_v2"]
289 *parents, leaf = dotted.split(".")
290 for part in parents:
291 node = node.setdefault(part, {})
292 node[leaf] = value
293 phase_v2 = config["phase_v2"]
294 gate_fn = None
295 if gate != "off":
296 gate_fn = self.gate_for(
297 frame, ic_floor=ic_floor if ic_floor is not None else phase_v2.get("rolling_ic_gate", {}).get("min_rolling_mean_ic"),
298 horizon_days=gate_horizon, rolling_window_days=gate_window, min_names=gate_min_names,
299 late_bar_event_count=gate_event_count
300 or (phase_v2.get("rolling_ic_gate", {}) or {}).get("late_bar_event_count"),
301 )
302 if config is self.config:
303 mechanisms = self.mechanisms(frame, include)
304 else:
305 from evaluation.live_parity import build_live_mechanisms
307 mechanisms = build_live_mechanisms(
308 config, frame, core_crypto_tickers=self.core_crypto, include=tuple(include), rl_model_path=self.rl_model_path,
309 topology_inputs_fn=self.topology_inputs_fn,
310 )
311 kwargs = build_as_live_kwargs(
312 dict(self.base), book_config=phase_v2.get("portfolio_book", {}), exits_config=phase_v2.get("exits", {}),
313 max_position_weight=float(config.get("phase6", {}).get("risk", {}).get("max_position_weight", 0.25)),
314 candidate_metadata=self.metadata, rolling_ic_gate_fn=gate_fn, topology_config=phase_v2.get("topology", {}),
315 rank_group_by_ticker=self.rank_groups, venue_listing_dates=self.venue_listing_dates,
316 rank_signal_config=phase_v2.get("rank_signal", {}),
317 sector_relative_min_size=int(self.config["phase1"]["target"]["ranking"].get("sector_neutral", {}).get("min_sector_size", 3)),
318 class_weight_caps=resolve_class_weight_caps(phase_v2.get("class_weight_caps")),
319 resize_threshold_weight=_resize_threshold(phase_v2),
320 trade_cooldown_bars=int(config.get("phase6", {}).get("risk", {}).get("trade_cooldown_bars", 0)),
321 **mechanisms,
322 )
323 kwargs["rebalance_session_dates"] = self.session_dates
324 if cash_sweep:
325 from evaluation.live_parity import build_cash_sweep_kwarg
327 kwargs["cash_sweep"] = build_cash_sweep_kwarg(config, ROOT_DIR, force_enabled=True)
328 kwargs.update(overrides)
329 reset_member_state(kwargs)
330 if int(tranches) > 1:
331 from evaluation.tranche_book import simulate_tranche_book
333 def fresh_run(data, **sub): # every tranche run starts with a clean RL guard, as one whole run does
334 reset_member_state(sub)
335 return simulate_rank_book(data, **sub)
337 return simulate_tranche_book(frame, tranches=int(tranches), simulate=fresh_run, **kwargs)
338 return simulate_rank_book(frame, **kwargs)
341def reset_member_state(kwargs: dict) -> None:
342 """The member chain keeps the RL shadow guard's history between calls (`member_weight_fn.rl_state`); a closure reused by
343 the next run (the harness caches it, a rule chain reuses one per split) would start that run with the previous run's
344 guard verdict, so two identical runs could differ. Each run starts from a clean guard."""
345 functions = [kwargs.get("member_weight_fn"), (kwargs.get("legacy_component") or {}).get("weight_fn")]
346 for function in functions:
347 holder = getattr(function, "rl_state", None)
348 if isinstance(holder, dict):
349 holder.update(history=[], positions={}, last_date=None, allows=True)
352def _resize_threshold(phase_v2: dict) -> float:
353 scaling = phase_v2.get("functionality", {}).get("position_scaling", {})
354 return float(scaling.get("rebalance_threshold_weight", 0.03)) if scaling.get("enabled", False) else 0.0
357def add_split_dataset_args(parser) -> None:
358 """--dataset-validation / --dataset-backtest: dataset CSVs holding those splits (V5.8.0: a candidate's split files)."""
359 parser.add_argument("--dataset-validation", default=None, help="dataset CSV holding the validation split")
360 parser.add_argument("--dataset-backtest", default=None, help="dataset CSV holding the backtest split")
363def dataset_for_split(args, split: str):
364 return {"validation": args.dataset_validation, "backtest": args.dataset_backtest}[split]
367def summarize(result) -> dict:
368 return {
369 "net_sharpe": result.net_sharpe, "net_total_return": result.net_total_return,
370 "net_max_drawdown": result.net_max_drawdown, "num_rebalances": result.num_rebalances,
371 "num_vetoed_rebalances": result.num_vetoed_rebalances, "veto_reasons": result.veto_reasons,
372 "mean_names_long": result.mean_names_long, "mean_names_short": result.mean_names_short,
373 "kill_switch_locked_dates": result.num_kill_switch_locked_dates,
374 "kill_switch_frozen_decisions": result.num_kill_switch_frozen_decisions,
375 "annualized_turnover": result.annualized_turnover, "cost_drag_annual_bps": result.cost_drag_annual_bps,
376 "mean_gross_exposure": result.mean_gross_exposure, "mean_net_exposure": result.mean_net_exposure,
377 }
380def main() -> int:
381 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
382 parser.add_argument("--split", default="backtest")
383 parser.add_argument("--only", nargs="*", help="run only variants whose name contains one of these substrings (plus the as-live baseline)")
384 parser.add_argument("--no-cache", action="store_true", help="re-score the dataset instead of reading the cached scores")
385 args = parser.parse_args()
387 harness = AsLiveHarness(args.split, use_cache=not args.no_cache)
388 variants = {
389 "idealized (no live mechanism)": harness.idealized,
390 "as-live (config)": harness.as_live,
391 "as-live without kill switch": lambda: harness.as_live(include=("member_sizing", "hrp", "impact")),
392 "as-live without member sizing chain": lambda: harness.as_live(include=("kill_switch", "hrp", "impact")),
393 "as-live without either (V5.6 simulator)": lambda: harness.as_live(include=("hrp", "impact")),
394 "no gates at all": lambda: harness.as_live(gate="off", min_rank_confidence_spread=0.0),
395 "spread gate only": lambda: harness.as_live(gate="off"),
396 "IC gate only": lambda: harness.as_live(min_rank_confidence_spread=0.0),
397 "no elevated-topology entry veto": lambda: harness.as_live(entry_veto_column=None),
398 "veto applies to members (pre-round-3)": lambda: harness.as_live(entry_veto_column="topology_risk_elevated"),
399 "no max-holding age exit": lambda: harness.as_live(max_holding_dates=None),
400 "entry lag 0": lambda: harness.as_live(entry_lag_bars=0),
401 "forex/crypto not lagged a day": lambda: harness.as_live(lagged=False),
402 "no hold-on-veto (anchor kept)": lambda: harness.as_live(hold_positions_on_veto=False),
403 "no hold-on-veto (anchor also off)": lambda: harness.as_live(hold_positions_on_veto=False, hysteresis_anchor_on_formed_book=False),
404 "no confidence weighting": lambda: harness.as_live(live_weighting=False),
405 "no hysteresis": lambda: harness.as_live(hysteresis_rank_margin=0.0),
406 "spread 0.2831 (old models' value)": lambda: harness.as_live(min_rank_confidence_spread=0.2831),
407 "IC floor 0.00": lambda: harness.as_live(ic_floor=0.0),
408 "IC floor 0.02": lambda: harness.as_live(ic_floor=0.02),
409 "IC floor 0.10": lambda: harness.as_live(ic_floor=0.10),
410 "HRP allocation": lambda: harness.as_live(config_overrides={"portfolio_book.allocation_method": "hrp"}),
411 }
412 if args.only:
413 variants = {name: run for name, run in variants.items() if name.startswith("as-live (") or any(token in name for token in args.only)}
414 rows = {}
415 print(f"{'variant':44s} {'net_sharpe':>10s} {'net_ret%':>9s} {'maxDD%':>8s} {'rebal':>6s} {'veto':>5s} {'ks_lock':>7s} {'names L/S':>10s}")
416 for name, run in variants.items():
417 started = perf_counter()
418 result = run()
419 rows[name] = summarize(result)
420 print(
421 f"{name:44s} {result.net_sharpe:10.3f} {100 * result.net_total_return:9.2f} {100 * result.net_max_drawdown:8.2f} "
422 f"{result.num_rebalances:6d} {result.num_vetoed_rebalances:5d} {result.num_kill_switch_locked_dates:7d} "
423 f"{result.mean_names_long:4.1f}/{result.mean_names_short:4.1f} ({perf_counter() - started:.0f}s)",
424 flush=True,
425 )
426 suffix = "" if args.split == "backtest" else "_" + args.split
427 out = ML_DIR / "evaluation" / f"as_live_levers{suffix}.json"
428 out.write_text(json.dumps({"split": args.split, "variants": rows}, indent=2), encoding="utf-8")
429 print(f"written {out}")
430 return 0
433if __name__ == "__main__":
434 raise SystemExit(main())