Coverage for scripts/v610_research.py: 100%
296 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"""V6.1.0 research chain (pre-registered rules R-MODEL9 -> R-HEAD2 -> R-BOOK2 -> R-LEGACY -> R-GATE; plan V6.1.0).
3Every score is the modelled portfolio (main book + the legacy signal) on the V6.1.0 simulator - the R-CAL2 `v610` rung of
4`scripts/lean_calibration.py`: live's daily member pass, weekend accrual, the position cap, the live analyzer, the legacy
5probability signal, next-open fills, the broker floor, the resize / cooldown / trailing-stop gates and the learned
6topology sizing. Each variant runs on EVERY rebalance phase (`rebalance_counter_start` 0..N-1; live picks one, and one
7Lean path cannot rank configs - Problems.md #186), and a statistic is the median across phases plus the share of phases
8that beat the comparator's median. Branch B (R-CAL2 not calibrated) scores the UNGATED book only; branch A also scores
9the as-live (gated) book. The holdout is reported for the final configuration, never used.
11Stages (each applies the previous stages' adoptions first; one change per variant):
12 model R-MODEL9: candidates from --candidates (model IC from --model-ic, R-HEAD from the candidate's training metrics)
13 head R-HEAD2: H1 = the R-HEAD-passing heads weighted by validation IC, each head from its better model
14 book R-BOOK2: K1 10/20, K2 15/30, K3 30/60 against K0 = current 20/40; the cap report (gross 1.0 / 0.75 / 0.5)
15 is informational
16 costs the net-edge gate's holding period: N1 = the book cadence, N2 = 40 bars (the age exit)
17 legacy R-LEGACY: L1 gross 0.10, L2 gross 0.15 + per name 0.03, L3 trade while the book is vetoed
18 gate R-GATE (branch A only): rolling-IC window / floor, spread floor, kill-switch floor
20 python scripts/v610_research.py --dataset ml/datasets/full_dataset.csv --legacy-probability ml/datasets/legacy_probability.csv \\
21 [--candidates ml/evaluation/v610/candidates.json] [--model-ic ml/evaluation/v610/model_ic.json] [--branch B]
22 [--stages model head book costs legacy gate] [--max-phases 20] [--out ml/evaluation/v610/research.json]
23"""
25from __future__ import annotations
27import argparse
28import copy
29import json
30import statistics
31import sys
32from pathlib import Path
34ROOT_DIR = Path(__file__).resolve().parents[1]
35sys.path.insert(0, str(ROOT_DIR))
36sys.path.insert(0, str(Path(__file__).resolve().parent))
38MIN_GAIN = 0.10
39MAX_VALIDATION_LOSS = 0.02
40MAX_DRAWDOWN_WORSENING = 0.01
41MIN_PHASE_SHARE = 0.60
42MAX_LATENCY_RATIO = 1.5
43SPLITS = ("validation", "backtest")
45BOOK_VARIANTS = {
46 "K1": {"portfolio_book.rebalance_every_bars": 10, "exits.max_holding_bars": 20},
47 "K2": {"portfolio_book.rebalance_every_bars": 15, "exits.max_holding_bars": 30},
48 "K3": {"portfolio_book.rebalance_every_bars": 30, "exits.max_holding_bars": 60},
49}
50# The net-edge gate prices the expected edge for `costs.holding_bars` (10) while the book holds up to 40 bars; it diverted
51# 306 member decisions in V6 BT2. Independent of the cadence, so its own stage (after the book is settled).
52COST_VARIANTS = {
53 "N1": {"costs.holding_bars": "@cadence"},
54 "N2": {"costs.holding_bars": 40},
55}
56LEGACY_VARIANTS = {
57 "L1": {"legacy_sleeve.max_gross_exposure": 0.10},
58 "L2": {"legacy_sleeve.max_gross_exposure": 0.15, "legacy_sleeve.max_weight_per_name": 0.03},
59 "L3": {"legacy_sleeve.trade_when_book_vetoed": True},
60}
61GATE_VARIANTS = {
62 "G1": {"rolling_ic_gate.min_rolling_mean_ic": -0.02},
63 "G2": {"rolling_ic_gate.rolling_window_days": 60},
64 "G3": {"rolling_ic_gate.enabled": False},
65 "G4": {"portfolio_book.min_rank_confidence_spread": 0.05},
66 "G5": {"risk.kill_switch.min_rolling_sharpe": -2.0},
67}
68CAP_REPORT = (1.0, 0.75, 0.5)
71def apply_dotted(config: dict, changes: dict) -> dict:
72 """A deep copy of `config` with `{dotted.phase_v2.key: value}` set; "@cadence" resolves to the book's cadence."""
73 result = copy.deepcopy(config)
74 cadence = int(result["phase_v2"]["portfolio_book"].get("rebalance_every_bars", 20))
75 for dotted, value in (changes or {}).items():
76 node = result["phase_v2"]
77 *parents, leaf = dotted.split(".")
78 for part in parents:
79 node = node.setdefault(part, {})
80 if leaf == "rebalance_every_bars":
81 cadence = int(value)
82 node[leaf] = value
83 for dotted, value in (changes or {}).items():
84 if value == "@cadence":
85 node = result["phase_v2"]
86 *parents, leaf = dotted.split(".")
87 for part in parents:
88 node = node[part]
89 node[leaf] = cadence
90 return result
93def phases_for(cadence: int, max_phases: int) -> list[int]:
94 """Every rebalance phase, or `max_phases` evenly spaced ones when the cadence is longer."""
95 if max_phases <= 0 or cadence <= max_phases:
96 return list(range(cadence))
97 step = cadence / max_phases
98 return sorted({int(round(index * step)) % cadence for index in range(max_phases)})
101def phase_summary(per_phase: list[dict]) -> dict:
102 sharpes = [row["net_sharpe"] for row in per_phase]
103 drawdowns = [row["net_max_drawdown"] for row in per_phase]
104 returns = [row["net_total_return"] for row in per_phase]
105 return {
106 "median_net_sharpe": statistics.median(sharpes), "min_net_sharpe": min(sharpes), "max_net_sharpe": max(sharpes),
107 "median_net_max_drawdown": statistics.median(drawdowns), "median_net_total_return": statistics.median(returns),
108 "phases": len(per_phase), "net_sharpe_by_phase": sharpes,
109 }
112def rule_verdict(base: dict, variant: dict) -> dict:
113 """The shared R-BOOK2 / R-LEGACY / R-GATE / R-MODEL9-clause-4 margins on one scoring mode. `base` / `variant` =
114 {split: phase_summary}."""
115 gain = variant["backtest"]["median_net_sharpe"] - base["backtest"]["median_net_sharpe"]
116 change = variant["validation"]["median_net_sharpe"] - base["validation"]["median_net_sharpe"]
117 shares = {
118 split: sum(1 for value in variant[split]["net_sharpe_by_phase"] if value > base[split]["median_net_sharpe"])
119 / max(1, len(variant[split]["net_sharpe_by_phase"]))
120 for split in SPLITS
121 }
122 checks = {
123 "backtest_gain_ge_0.10": gain >= MIN_GAIN,
124 "validation_not_worse_than_0.02": change >= -MAX_VALIDATION_LOSS,
125 "beats_base_median_on_60pct_of_phases": all(share >= MIN_PHASE_SHARE for share in shares.values()),
126 "positive_median_on_both_splits": all(variant[split]["median_net_sharpe"] > 0.0 for split in SPLITS),
127 "drawdown_within_1pp": all(
128 variant[split]["median_net_max_drawdown"] - base[split]["median_net_max_drawdown"] >= -MAX_DRAWDOWN_WORSENING
129 for split in SPLITS
130 ),
131 }
132 return {"checks": checks, "backtest_gain": gain, "validation_change": change, "phase_share": shares,
133 "passes": all(checks.values())}
136def legacy_clause(scores: dict) -> dict:
137 """R-LEGACY's extra clause: the legacy component itself must earn a positive median return on both splits (a sleeve that
138 only pays in a rising market is not a steady component). The sign of the median return is the sign of its Sharpe."""
139 return {"legacy_component_positive_on_both_splits": all(
140 scores["ungated"][split].get("legacy_net_return_median", 0.0) > 0.0 for split in SPLITS
141 )}
144def decide(base: dict, variant: dict, branch: str, extra_checks: dict | None = None) -> dict:
145 verdict = {"ungated": rule_verdict(base["ungated"], variant["ungated"])}
146 adopted = verdict["ungated"]["passes"]
147 if branch == "A":
148 verdict["as_live"] = rule_verdict(base["as_live"], variant["as_live"])
149 verdict["as_live"]["checks"].pop("positive_median_on_both_splits", None)
150 verdict["as_live"]["passes"] = all(verdict["as_live"]["checks"].values())
151 adopted = adopted and verdict["as_live"]["passes"]
152 for name, value in (extra_checks or {}).items():
153 verdict.setdefault("extra_checks", {})[name] = bool(value)
154 adopted = adopted and bool(value)
155 verdict["adopted"] = bool(adopted)
156 return verdict
159DECISION_KEYS = ("decision_rank_20d", "decision_rank_20d_swapped_priority")
162def best_decision_key(entry: dict) -> str:
163 """The decision score (live priority, or the other model served first) with the higher validation non-overlapping IC:
164 chosen on validation, then judged on backtest by the same key (R-HEAD2 adopts the matching priority)."""
165 validation = entry["ensemble"]["validation"]
166 scored = {key: (validation.get(key) or {}).get("non_overlapping_mean_ic") for key in DECISION_KEYS}
167 return max((key for key in DECISION_KEYS if scored[key] is not None), key=lambda key: scored[key], default=DECISION_KEYS[0])
170def model_ic_checks(model_ic: dict, name: str, control: str = "installed", spread_from: str = "ctl") -> dict:
171 """R-MODEL9 clauses 1-2 from scripts/model_candidate_research.py's output: the candidate's validation decision IC
172 beats the INSTALLED models' (what it would replace) by more than the seed spread of the retrained control config
173 (`spread_from`: the range of its single members' validation IC) and is > 0; its backtest IC is at least the installed
174 models' with HAC t >= 2. Each candidate and the control use their own best decision key (best_decision_key)."""
175 candidates = model_ic["candidates"]
176 candidate_key, control_key = best_decision_key(candidates[name]), best_decision_key(candidates[control])
177 decision = lambda entry, split, key: entry["ensemble"][split][key] # noqa: E731
178 member_ics = []
179 spread_key = candidate_key
180 for scored in (candidates[spread_from].get("members_scored") or {}).values():
181 value = (scored["validation"].get(spread_key) or {}).get("non_overlapping_mean_ic")
182 if value is not None:
183 member_ics.append(value)
184 spread = (max(member_ics) - min(member_ics)) if len(member_ics) > 1 else 0.0
185 cand_val = decision(candidates[name], "validation", candidate_key)["non_overlapping_mean_ic"] or 0.0
186 ctl_val = decision(candidates[control], "validation", control_key)["non_overlapping_mean_ic"] or 0.0
187 cand_bt = decision(candidates[name], "backtest", candidate_key)
188 ctl_bt = decision(candidates[control], "backtest", control_key)
189 return {
190 "validation_beats_control_by_seed_spread": cand_val - ctl_val > spread and cand_val > 0.0,
191 "backtest_ic_not_below_control": (cand_bt["daily_mean_ic"] or 0.0) >= (ctl_bt["daily_mean_ic"] or 0.0),
192 "backtest_hac_t_ge_2": (cand_bt["hac_t"] or 0.0) >= 2.0,
193 "decision_priority": "swapped" if candidate_key.endswith("swapped_priority") else "live",
194 }
197def head_blend_from_ic(model_ic: dict, candidate: str, passing_heads: set[str]) -> dict | None:
198 """R-HEAD2's H1: every head in `passing_heads` with a positive validation IC, weighted by that IC, served by the model
199 with the higher validation IC for it. Returns {"heads": {...}, "model_priority": [...]} or None."""
200 validation = model_ic["candidates"][candidate]["ensemble"]["validation"]
201 weights, preferred = {}, {}
202 for key, stats in validation.items():
203 if "." not in key:
204 continue
205 model, head = key.split(".", 1)
206 ic = stats.get("daily_mean_ic")
207 if head not in passing_heads or ic is None or ic <= 0.0:
208 continue
209 if ic > weights.get(head, 0.0):
210 weights[head], preferred[head] = ic, model
211 if not weights:
212 return None
213 total = sum(weights.values())
214 votes: dict[str, float] = {}
215 for head, model in preferred.items():
216 votes[model] = votes.get(model, 0.0) + weights[head]
217 priority = sorted(votes, key=lambda model: -votes[model]) + [m for m in ("sequence", "multitask") if m not in votes]
218 return {"heads": {head: round(value / total, 4) for head, value in weights.items()}, "model_priority": priority}
221_JOB: dict = {}
224def _phase_worker(phase: int) -> dict:
225 """One rebalance phase of the job set in `_JOB` (runs in a forked child that inherited the scored harness)."""
226 from as_live_levers import summarize
227 from lean_calibration import ANALYZER_INCLUDE, calibrated_overrides
229 job = _JOB
230 harness = job["harness"]
231 kwargs = dict(calibrated_overrides(harness, phase=phase), **job["mechanisms"], include=ANALYZER_INCLUDE)
232 if job["mode"] == "ungated":
233 kwargs.update(gate="off", min_rank_confidence_spread=0.0)
234 result = harness.as_live(config_overrides=job["resolved"] or None, **kwargs)
235 summary = summarize(result)
236 summary["legacy_net_return"] = sum(result.per_date_component_returns.get("legacy", {}).values())
237 return summary
240def map_phases(phases: list[int], workers: int) -> list[dict]:
241 """The phases of the job in `_JOB`, across `workers` forked processes where fork exists (Linux: the Codespace has two
242 cores), else one after another."""
243 import multiprocessing
244 import sys as _sys
246 if workers > 1 and len(phases) > 1 and _sys.platform.startswith("linux"):
247 with multiprocessing.get_context("fork").Pool(min(workers, len(phases))) as pool:
248 return pool.map(_phase_worker, phases)
249 return [_phase_worker(phase) for phase in phases]
252def main() -> int:
253 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
254 parser.add_argument("--dataset", default=str(ROOT_DIR / "ml" / "datasets" / "full_dataset.csv"))
255 parser.add_argument("--legacy-probability", required=True)
256 parser.add_argument("--candidates", default=None, help="JSON {name: {ml_dir, ensemble, legacy_probability}}")
257 parser.add_argument("--model-ic", default=str(ROOT_DIR / "ml" / "evaluation" / "v610" / "model_ic.json"))
258 parser.add_argument("--branch", choices=("A", "B"), default=None, help="default: ml/evaluation/v610/calibration.json")
259 parser.add_argument("--stages", nargs="*", default=["model", "head", "book", "costs", "legacy", "gate"])
260 parser.add_argument("--max-phases", type=int, default=20)
261 parser.add_argument("--workers", type=int, default=1, help="forked processes across the phases of one score (Linux)")
262 parser.add_argument("--gate-warmup-days", type=int, default=400)
263 parser.add_argument("--out", default=str(ROOT_DIR / "ml" / "evaluation" / "v610" / "research.json"))
264 args = parser.parse_args()
266 from as_live_levers import AsLiveHarness
267 from lean_calibration import topology_inputs_fn_for, use_topology
269 base_config = json.loads((ROOT_DIR / "config.json").read_text(encoding="utf-8"))
270 branch = args.branch or json.loads((ROOT_DIR / "ml" / "evaluation" / "v610" / "calibration.json").read_text(encoding="utf-8"))["verdict"]["branch"]
271 out_path = Path(args.out)
272 report = json.loads(out_path.read_text(encoding="utf-8")) if out_path.exists() else {}
273 report.update({"branch": branch, "max_phases": args.max_phases})
274 adopted = report.setdefault("adopted", {"config": {}, "model": None, "rank_signal": None})
275 candidates = json.loads(Path(args.candidates).read_text(encoding="utf-8")) if args.candidates else {}
276 cache: dict = {}
278 def model_spec(name: str | None) -> dict:
279 return candidates.get(name, {}) if name else {}
281 def harness_for(model: str | None, rank_signal: dict | None, split: str):
282 spec = model_spec(model)
283 key = (model, json.dumps(rank_signal, sort_keys=True), split)
284 if key not in cache:
285 if len(cache) >= 2: # bounded memory: two harnesses resident at most
286 cache.pop(next(iter(cache)))
287 cfg = copy.deepcopy(base_config)
288 if rank_signal:
289 cfg["phase_v2"]["rank_signal"].update(rank_signal)
290 cfg["phase_v2"]["rank_signal"]["demote_not_promotable_heads"] = False # R-HEAD is judged by the rule itself
291 if spec.get("ensemble"):
292 cfg["phase_v2"]["model_ensemble"]["enabled"] = True
293 harness = AsLiveHarness(
294 split, dataset_path=args.dataset, config=cfg, ml_dir=(ROOT_DIR / spec["ml_dir"]) if spec.get("ml_dir") else None,
295 legacy_probability_path=spec.get("legacy_probability") or args.legacy_probability,
296 gate_warmup_days=args.gate_warmup_days,
297 )
298 cache[key] = (harness, topology_inputs_fn_for(harness, cfg), cfg)
299 return cache[key]
301 memo: dict = {}
303 def score(changes: dict, *, model: str | None = None, rank_signal: dict | None = None,
304 splits=SPLITS, modes=None) -> dict:
305 modes = modes or (("ungated", "as_live") if branch == "A" else ("ungated",))
306 memo_key = json.dumps([changes, model, rank_signal, list(splits), list(modes)], sort_keys=True, default=str)
307 if memo_key in memo: # a stage's base is the previous stage's adopted config: score it once
308 return memo[memo_key]
309 scored = score_uncached(changes, model=model, rank_signal=rank_signal, splits=splits, modes=modes)
310 memo[memo_key] = scored
311 return scored
313 def score_uncached(changes: dict, *, model, rank_signal, splits, modes) -> dict:
314 out: dict = {mode: {} for mode in modes}
315 for split in splits:
316 harness, topology_fn, cfg = harness_for(model, rank_signal, split)
317 merged = apply_dotted(cfg, changes)
318 cadence = int(merged["phase_v2"]["portfolio_book"].get("rebalance_every_bars", 20))
319 resolved = {key: (cadence if value == "@cadence" else value) for key, value in (changes or {}).items()}
320 use_topology(harness, topology_fn)
321 mechanisms = harness.v610_mechanisms(merged)
322 for mode in modes:
323 _JOB.update(harness=harness, mechanisms=mechanisms, resolved=resolved, mode=mode)
324 per_phase = map_phases(phases_for(cadence, args.max_phases), args.workers)
325 out[mode][split] = phase_summary(per_phase)
326 out[mode][split]["legacy_net_return_median"] = statistics.median(row["legacy_net_return"] for row in per_phase)
327 return out
329 def save():
330 out_path.parent.mkdir(parents=True, exist_ok=True)
331 out_path.write_text(json.dumps(report, indent=1, default=float), encoding="utf-8")
333 def stage_header(name):
334 print(f"=== stage {name}; adopted so far {json.dumps(adopted)}", flush=True)
336 current = lambda: adopted["config"] # noqa: E731
338 if "model" in args.stages and candidates:
339 stage_header("model")
340 model_ic = json.loads(Path(args.model_ic).read_text(encoding="utf-8"))
341 base = score(current())
342 stage = {"base": base, "variants": {}}
343 for name in candidates:
344 if name == "installed":
345 continue
346 if not candidates[name].get("ic_pass"):
347 # R-MODEL9 clauses 1-2 fail on IC alone: no book scores (a candidate without a model dir would be scored as
348 # the installed models), the failing clauses are the evidence
349 stage["variants"][name] = {"skipped": "IC clauses failed", "ic_checks": candidates[name].get("ic_checks")}
350 print(f" {name}: skipped, IC clauses {candidates[name].get('ic_checks')}", flush=True)
351 continue
352 ic = model_ic_checks(model_ic, name)
353 # a candidate judged on the swapped-priority decision is scored with that priority, against the installed models
354 # at the same priority, so only the model differs
355 signal = {"model_priority": ["multitask", "sequence"]} if ic.get("decision_priority") == "swapped" else None
356 result = score(current(), model=name, rank_signal=signal)
357 base_same_priority = score(current(), rank_signal=signal)
358 head_ok = bool(candidates[name].get("decision_heads_pass_r_head", False))
359 latency_ok = float(candidates[name].get("latency_ratio", 1.0)) <= MAX_LATENCY_RATIO
360 ic_flags = {key: value for key, value in ic.items() if key != "decision_priority"}
361 verdict = decide(base_same_priority, result, branch, {**ic_flags, "decision_heads_pass_r_head": head_ok, "latency_within_1.5x": latency_ok})
362 stage["variants"][name] = {"scores": result, "verdict": verdict, "rank_signal": signal, "base": base_same_priority}
363 print(f" {name}: adopted={verdict['adopted']} gain {verdict['ungated']['backtest_gain']:+.3f}", flush=True)
364 save()
365 winners = [name for name, entry in stage["variants"].items() if (entry.get("verdict") or {}).get("adopted")]
366 if winners:
367 adopted["model"] = max(winners, key=lambda name: stage["variants"][name]["scores"]["ungated"]["validation"]["median_net_sharpe"])
368 adopted["rank_signal"] = stage["variants"][adopted["model"]].get("rank_signal") # the priority it was judged under
369 stage["adopted"] = adopted["model"]
370 report["model"] = stage
371 save()
373 if "head" in args.stages:
374 stage_header("head")
375 model_ic = json.loads(Path(args.model_ic).read_text(encoding="utf-8"))
376 source = adopted["model"] or "installed"
377 passing = set(model_spec(adopted["model"]).get("passing_heads") or candidates.get("installed", {}).get("passing_heads") or [])
378 blend = head_blend_from_ic(model_ic, source, passing) if source in model_ic.get("candidates", {}) else None
379 current_signal = json.loads(json.dumps(base_config["phase_v2"]["rank_signal"]))
380 # H2: the same heads and weights, the multitask model served first (validation IC: multitask rank heads 0.06, sequence 0.01)
381 variants = {"H2": {"model_priority": ["multitask", "sequence"]}}
382 if blend:
383 variants["H1"] = blend
384 base = score(current(), model=adopted["model"])
385 stage = {"source": source, "h1": blend, "base": base, "variants": {}}
386 for name, signal in variants.items():
387 result = score(current(), model=adopted["model"], rank_signal=signal)
388 verdict = decide(base, result, branch)
389 stage["variants"][name] = {"rank_signal": signal, "scores": result, "verdict": verdict}
390 print(f" {name} {signal}: adopted={verdict['adopted']} gain {verdict['ungated']['backtest_gain']:+.3f}", flush=True)
391 save()
392 winners = [name for name, entry in stage["variants"].items() if entry["verdict"]["adopted"]]
393 if winners:
394 best = max(winners, key=lambda n: stage["variants"][n]["scores"]["ungated"]["validation"]["median_net_sharpe"])
395 adopted["rank_signal"] = stage["variants"][best]["rank_signal"]
396 stage["adopted"] = best
397 else:
398 stage["adopted"] = None
399 stage["incumbent_rank_signal"] = {k: current_signal[k] for k in ("heads", "model_priority")}
400 report["head"] = stage
401 save()
403 def single_change_stage(name: str, variants: dict, extra_report=None, extra_checks_fn=None):
404 stage_header(name)
405 base = score(current(), model=adopted["model"], rank_signal=adopted["rank_signal"])
406 stage = {"base": base, "variants": {}}
407 for variant, changes in variants.items():
408 result = score({**current(), **changes}, model=adopted["model"], rank_signal=adopted["rank_signal"])
409 verdict = decide(base, result, branch, extra_checks_fn(result) if extra_checks_fn else None)
410 stage["variants"][variant] = {"changes": changes, "scores": result, "verdict": verdict}
411 print(f" {variant} {changes}: adopted={verdict['adopted']} gain {verdict['ungated']['backtest_gain']:+.3f} "
412 f"val {verdict['ungated']['validation_change']:+.3f} share {verdict['ungated']['phase_share']}", flush=True)
413 save()
414 winners = [variant for variant, entry in stage["variants"].items() if entry["verdict"]["adopted"]]
415 chosen = max(winners, key=lambda v: stage["variants"][v]["scores"]["ungated"]["validation"]["median_net_sharpe"]) if winners else None
416 if chosen:
417 adopted["config"].update(variants[chosen])
418 stage["adopted"] = chosen
419 if extra_report:
420 stage.update(extra_report())
421 report[name] = stage
422 save()
424 if "book" in args.stages:
425 single_change_stage("book", BOOK_VARIANTS, extra_report=lambda: {"cap_report": {
426 str(cap): score({**current(), "portfolio_book.neutrality.gross_exposure_cap": cap}, model=adopted["model"],
427 rank_signal=adopted["rank_signal"], modes=("ungated",))
428 for cap in CAP_REPORT
429 }})
430 if "costs" in args.stages:
431 single_change_stage("costs", COST_VARIANTS)
432 if "legacy" in args.stages:
433 single_change_stage("legacy", LEGACY_VARIANTS, extra_checks_fn=legacy_clause)
434 if "gate" in args.stages:
435 if branch == "A":
436 single_change_stage("gate", GATE_VARIANTS)
437 else:
438 report["gate"] = {"skipped": "R-CAL2 branch B: the gates stay frozen as safety controls"}
439 save()
441 report["final_holdout_seen"] = score(current(), model=adopted["model"], rank_signal=adopted["rank_signal"],
442 splits=("holdout",), modes=("ungated", "as_live"))
443 save()
444 print("adopted:", json.dumps(adopted))
445 print(f"written {out_path}")
446 return 0
449if __name__ == "__main__":
450 raise SystemExit(main())