Coverage for scripts/v630_research.py: 100%
188 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.3.0 research chain (pre-registered rules R-KILL -> R-STAGGER2 -> R-GATE3; plan V6.3.0). Written before any score.
3Scoring is V6.2.0's (scripts/v620_research.py): the modelled portfolio (main book + legacy signal) on the calibrated
4simulator, every rebalance phase (10 at cadence 20) of both splits, the T-bill sweep off (alpha judged ex-carry),
5`rule_verdict` margins (backtest median gain >= +0.10, validation not worse than -0.02, >= 60% of phases beat the base
6median on both splits, positive median on both splits, median drawdown within 1 pp). Each stage scores on top of what
7the earlier stages adopted. The holdout is never read.
9 gate R-CAL3 (scripts/lean_calibration.py, R-CAL2's unchanged clauses against V6.2.0's BT2: daily correlation >= 0.50,
10 |annual gap| <= 2 pp, decision agreement >= 80% on every window), passed in as --calibration. Branch A allows
11 stage 3; branch B keeps the gates frozen as safety controls (V6.0-V6.2).
12 kill R-KILL (todo lead 3, Problems #200 / #205: the kill switch at its -1.0 floor flips its lock path on cents).
13 Scored UNGATED (the gates are frozen under branch B; the kill switch is the mechanism under change and stays on).
14 KS1 risk.kill_switch.evaluation_bars 120
15 KS2 risk.kill_switch.release_rolling_sharpe -0.5 (a trip holds until the rolling Sharpe recovers above -0.5)
16 KS3 KS1 + KS2
17 Clauses, per variant:
18 (a) stability: the kill switch's input perturbed by N(0, 0.5 bp) noise (seeds 1-3) on 5 backtest phases; the
19 median Jaccard overlap of locked dates against the unperturbed run is >= 0.80 and >= KS0's;
20 (b) safety: the median number of locked dates is >= 50% of KS0's on both splits;
21 (c) performance: `rule_verdict` against KS0.
22 Branch A: variants passing (a)+(b)+(c); the highest backtest median ships.
23 Branch B: none passes (c); variants passing (a)+(b) that are non-inferior (median Sharpe change >= -0.02 on both
24 splits); the most stable (highest median Jaccard) ships - the defect is path fragility, not return.
25 Branch C: nothing qualifies; KS0 stays and #200 closes as a documented design limit.
26 stagger R-STAGGER2 (todo lead 1): the SECOND look at S2 (2 tranches; S4 failed R-STAGGER), ungated. It counts in the
27 deflated Sharpe's trial registry. Clauses: `rule_verdict`, the median annual cost drag rises <= 30%, and two
28 measures that do not reward one lucky phase in place of R-STAGGER's max-min range: the validation interquartile
29 range of phase Sharpe widens by <= 25%, and the worst phase is not worse than the base's by more than 0.10 on
30 both splits. Adopted iff all pass.
31 gates R-GATE3 (only on R-CAL3 branch A), as-live: G1 rolling_ic_gate.min_rolling_mean_ic -0.01, G2 -0.02,
32 G3 rolling_ic_gate.rolling_window_days 60, G4 240. Clauses: `rule_verdict` on the as-live scores; the passing
33 variant with the highest backtest median ships.
35 python scripts/v630_research.py --dataset ml/datasets/v610_full_dataset.csv --legacy-probability ml/datasets/legacy_probability.csv
36 [--calibration ml/evaluation/v630/calibration.json] [--stages kill stagger gates] [--max-phases 10] [--workers 2]
37 [--out ml/evaluation/v630/research.json] [--adopted-config-out ml/evaluation/v630/adopted_changes.json]
38"""
40from __future__ import annotations
42import argparse
43import copy
44import json
45import random
46import statistics
47import sys
48from pathlib import Path
50ROOT_DIR = Path(__file__).resolve().parents[1]
51sys.path.insert(0, str(ROOT_DIR))
52sys.path.insert(0, str(Path(__file__).resolve().parent))
54from v610_research import SPLITS, apply_dotted, phase_summary, phases_for, rule_verdict # noqa: E402
56KILL_VARIANTS = {
57 "KS1": {"risk.kill_switch.evaluation_bars": 120},
58 "KS2": {"risk.kill_switch.release_rolling_sharpe": -0.5},
59 "KS3": {"risk.kill_switch.evaluation_bars": 120, "risk.kill_switch.release_rolling_sharpe": -0.5},
60}
61GATE_VARIANTS = {
62 "G1": {"rolling_ic_gate.min_rolling_mean_ic": -0.01},
63 "G2": {"rolling_ic_gate.min_rolling_mean_ic": -0.02},
64 "G3": {"rolling_ic_gate.rolling_window_days": 60},
65 "G4": {"rolling_ic_gate.rolling_window_days": 240},
66}
67STAGGER_TRANCHES = 2
68NOISE_STD = 0.5e-4
69NOISE_SEEDS = (1, 2, 3)
70STABILITY_PHASES = 5
71MIN_JACCARD = 0.80
72MIN_LOCK_SHARE = 0.50
73NON_INFERIOR = -0.02
74MAX_IQR_WIDENING = 0.25
75MAX_WORST_PHASE_LOSS = 0.10
76MAX_COST_RISE = 0.30
79# ---------------------------------------------------------------- pure clause functions
82def jaccard(first, second) -> float:
83 """Overlap of two locked-date sets; two empty sets agree completely."""
84 first, second = set(first), set(second)
85 union = first | second
86 return 1.0 if not union else len(first & second) / len(union)
89def perturbation(dates, seed: int, base: dict | None = None, std: float = NOISE_STD) -> dict:
90 """{date: base extra return + N(0, std)}: noise on the kill switch's input only (the book's P&L is untouched)."""
91 rng = random.Random(seed)
92 base = base or {}
93 return {str(date): float(base.get(str(date), 0.0)) + rng.gauss(0.0, std) for date in sorted(map(str, dates))}
96def interquartile_range(values) -> float:
97 q1, _median, q3 = statistics.quantiles(list(values), n=4, method="inclusive")
98 return q3 - q1
101def kill_checks(base: dict, variant: dict, base_stability: float, variant_stability: float) -> dict:
102 """R-KILL clauses (a) and (b); `base` / `variant` = {split: phase_summary with `locked_dates_by_phase`}."""
103 lock_share = {
104 split: statistics.median(variant[split]["locked_dates_by_phase"])
105 >= MIN_LOCK_SHARE * statistics.median(base[split]["locked_dates_by_phase"])
106 for split in SPLITS
107 }
108 return {
109 "stability_jaccard_ge_0.80": variant_stability >= MIN_JACCARD,
110 "stability_not_below_ks0": variant_stability >= base_stability,
111 "locks_ge_half_of_ks0_on_both_splits": all(lock_share.values()),
112 }
115def non_inferior(verdict: dict) -> bool:
116 return verdict["backtest_gain"] >= NON_INFERIOR and verdict["validation_change"] >= NON_INFERIOR
119def kill_branch(variants: dict) -> tuple[str, str | None]:
120 """(branch, chosen variant) from {name: {"verdict", "extra_checks", "stability"}} (rule R-KILL)."""
121 safe = {name: entry for name, entry in variants.items() if all(entry["extra_checks"].values())}
122 passing = [name for name, entry in safe.items() if entry["verdict"]["passes"]]
123 if passing:
124 return "A", max(passing, key=lambda name: variants[name]["scores"]["backtest"]["median_net_sharpe"])
125 stable = [name for name, entry in safe.items() if non_inferior(entry["verdict"])]
126 if stable:
127 return "B", max(stable, key=lambda name: variants[name]["stability"])
128 return "C", None
131def stagger2_checks(base: dict, variant: dict) -> dict:
132 """R-STAGGER2's clauses beyond `rule_verdict` (ungated scores)."""
133 base_cost = statistics.median(base["validation"]["cost_drag_by_phase"] + base["backtest"]["cost_drag_by_phase"])
134 variant_cost = statistics.median(variant["validation"]["cost_drag_by_phase"] + variant["backtest"]["cost_drag_by_phase"])
135 return {
136 "cost_drag_rise_le_30pct": variant_cost <= (1.0 + MAX_COST_RISE) * max(base_cost, 1e-9),
137 "validation_iqr_widening_le_25pct": interquartile_range(variant["validation"]["net_sharpe_by_phase"])
138 <= (1.0 + MAX_IQR_WIDENING) * interquartile_range(base["validation"]["net_sharpe_by_phase"]),
139 "worst_phase_within_0.10_on_both_splits": all(
140 min(variant[split]["net_sharpe_by_phase"]) >= min(base[split]["net_sharpe_by_phase"]) - MAX_WORST_PHASE_LOSS
141 for split in SPLITS
142 ),
143 }
146# ---------------------------------------------------------------- scoring
149_JOB: dict = {}
152def _phase_worker(task: tuple[int, int | None]) -> dict:
153 from as_live_levers import summarize
154 from lean_calibration import ANALYZER_INCLUDE, calibrated_overrides
156 phase, seed = task
157 job = _JOB
158 harness = job["harness"]
159 kwargs = dict(calibrated_overrides(harness, phase=phase), **job["mechanisms"], include=ANALYZER_INCLUDE)
160 if job["mode"] == "ungated":
161 kwargs.update(gate="off", min_rank_confidence_spread=0.0)
162 if seed is not None:
163 kwargs["kill_switch_extra_returns"] = perturbation(job["dates"], seed, kwargs.get("kill_switch_extra_returns"))
164 result = harness.as_live(config_overrides=job["resolved"] or None, tranches=job.get("tranches", 1), **kwargs)
165 summary = summarize(result)
166 components = result.per_date_component_returns or {}
167 summary["legacy_net_return"] = sum(components.get("legacy", {}).values())
168 summary["locked_dates"] = list(result.kill_switch_locked_date_list or [])
169 return summary
172def map_tasks(tasks: list, workers: int) -> list[dict]:
173 import multiprocessing
175 if workers > 1 and len(tasks) > 1 and sys.platform.startswith("linux"):
176 with multiprocessing.get_context("fork").Pool(min(workers, len(tasks))) as pool:
177 return pool.map(_phase_worker, tasks)
178 return [_phase_worker(task) for task in tasks]
181def main() -> int:
182 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
183 parser.add_argument("--dataset", default=str(ROOT_DIR / "ml" / "datasets" / "full_dataset.csv"))
184 parser.add_argument("--legacy-probability", required=True)
185 parser.add_argument("--calibration", default=str(ROOT_DIR / "ml" / "evaluation" / "v630" / "calibration.json"))
186 parser.add_argument("--stages", nargs="*", default=["kill", "stagger", "gates"])
187 parser.add_argument("--max-phases", type=int, default=10)
188 parser.add_argument("--workers", type=int, default=1)
189 parser.add_argument("--gate-warmup-days", type=int, default=400)
190 parser.add_argument("--out", default=str(ROOT_DIR / "ml" / "evaluation" / "v630" / "research.json"))
191 parser.add_argument("--adopted-config-out", default=str(ROOT_DIR / "ml" / "evaluation" / "v630" / "adopted_changes.json"))
192 args = parser.parse_args()
194 from as_live_levers import AsLiveHarness
195 from lean_calibration import topology_inputs_fn_for, use_topology
197 base_config = json.loads((ROOT_DIR / "config.json").read_text(encoding="utf-8"))
198 out_path = Path(args.out)
199 report = json.loads(out_path.read_text(encoding="utf-8")) if out_path.exists() else {}
200 calibration_path = Path(args.calibration)
201 calibration = json.loads(calibration_path.read_text(encoding="utf-8")) if calibration_path.exists() else {}
202 branch = (calibration.get("verdict") or {}).get("branch", "B")
203 report.update({"calibration_branch": branch, "max_phases": args.max_phases, "sweep_in_rule_scores": False})
204 adopted = report.setdefault("adopted", {"config": {}, "tranches": 1})
205 harnesses: dict = {}
207 def harness_for(split: str):
208 if split not in harnesses:
209 harness = AsLiveHarness(split, dataset_path=args.dataset, config=copy.deepcopy(base_config),
210 legacy_probability_path=args.legacy_probability, gate_warmup_days=args.gate_warmup_days)
211 harnesses[split] = (harness, topology_inputs_fn_for(harness, base_config))
212 return harnesses[split]
214 def score(changes: dict, *, tranches: int = 1, mode: str = "ungated", stability: bool = False) -> dict:
215 out: dict = {}
216 for split in SPLITS:
217 harness, topology_fn = harness_for(split)
218 merged = apply_dotted(base_config, changes)
219 use_topology(harness, topology_fn)
220 cadence = int(merged["phase_v2"]["portfolio_book"].get("rebalance_every_bars", 20))
221 phases = phases_for(cadence, args.max_phases)
222 _JOB.update(harness=harness, mechanisms=harness.v610_mechanisms(merged), resolved=dict(changes), mode=mode,
223 tranches=tranches, dates=sorted(map(str, harness.frame["date"].unique())))
224 per_phase = map_tasks([(phase, None) for phase in phases], args.workers)
225 summary = phase_summary(per_phase)
226 summary["cost_drag_by_phase"] = [row["cost_drag_annual_bps"] for row in per_phase]
227 summary["locked_dates_by_phase"] = [len(row["locked_dates"]) for row in per_phase]
228 if stability and split == "backtest":
229 picked = phases[:: max(1, len(phases) // STABILITY_PHASES)][:STABILITY_PHASES]
230 locked = {phase: row["locked_dates"] for phase, row in zip(phases, per_phase, strict=False)}
231 tasks = [(phase, seed) for phase in picked for seed in NOISE_SEEDS]
232 perturbed = map_tasks(tasks, args.workers)
233 overlaps = [jaccard(locked[phase], row["locked_dates"]) for (phase, _seed), row in zip(tasks, perturbed, strict=False)]
234 summary["stability_jaccard_median"] = statistics.median(overlaps)
235 summary["stability_jaccards"] = overlaps
236 out[split] = summary
237 return out
239 def save():
240 out_path.parent.mkdir(parents=True, exist_ok=True)
241 out_path.write_text(json.dumps(report, indent=1, default=float), encoding="utf-8")
243 if "kill" in args.stages:
244 print("=== stage kill (R-KILL, ungated)", flush=True)
245 base = score(adopted["config"], stability=True)
246 base_stability = base["backtest"]["stability_jaccard_median"]
247 stage = {"base": base, "variants": {}}
248 for name, changes in KILL_VARIANTS.items():
249 result = score({**adopted["config"], **changes}, stability=True)
250 verdict = rule_verdict(base, result)
251 stability = result["backtest"]["stability_jaccard_median"]
252 extra = kill_checks(base, result, base_stability, stability)
253 stage["variants"][name] = {"changes": changes, "scores": result, "verdict": verdict, "extra_checks": extra,
254 "stability": stability}
255 print(f" {name}: passes={verdict['passes']} gain {verdict['backtest_gain']:+.3f} val {verdict['validation_change']:+.3f} "
256 f"stability {stability:.3f} (KS0 {base_stability:.3f}) extra {extra}", flush=True)
257 save()
258 stage["branch"], stage["adopted"] = kill_branch(stage["variants"])
259 if stage["adopted"]:
260 adopted["config"].update(KILL_VARIANTS[stage["adopted"]])
261 report["kill"] = stage
262 print(f" R-KILL branch {stage['branch']}, adopted {stage['adopted']}", flush=True)
263 save()
265 if "stagger" in args.stages:
266 print("=== stage stagger (R-STAGGER2, ungated)", flush=True)
267 base = score(adopted["config"])
268 result = score(adopted["config"], tranches=STAGGER_TRANCHES)
269 verdict = rule_verdict(base, result)
270 extra = stagger2_checks(base, result)
271 chosen = verdict["passes"] and all(extra.values())
272 report["stagger"] = {"base": base, "variant": result, "verdict": verdict, "extra_checks": extra, "adopted": chosen}
273 if chosen:
274 adopted["tranches"] = STAGGER_TRANCHES
275 print(f" S2: adopted={chosen} gain {verdict['backtest_gain']:+.3f} val {verdict['validation_change']:+.3f} extra {extra}", flush=True)
276 save()
278 if "gates" in args.stages:
279 if branch != "A":
280 report["gates"] = {"skipped": f"R-CAL3 branch {branch}: the gates stay frozen as safety controls"}
281 print(f"=== stage gates skipped (R-CAL3 branch {branch})", flush=True)
282 else:
283 print("=== stage gates (R-GATE3, as-live)", flush=True)
284 base = score(adopted["config"], tranches=adopted["tranches"], mode="as_live")
285 stage = {"base": base, "variants": {}}
286 for name, changes in GATE_VARIANTS.items():
287 result = score({**adopted["config"], **changes}, tranches=adopted["tranches"], mode="as_live")
288 verdict = rule_verdict(base, result)
289 stage["variants"][name] = {"changes": changes, "scores": result, "verdict": verdict}
290 print(f" {name}: passes={verdict['passes']} gain {verdict['backtest_gain']:+.3f}", flush=True)
291 save()
292 winners = [name for name, entry in stage["variants"].items() if entry["verdict"]["passes"]]
293 stage["adopted"] = max(winners, key=lambda n: stage["variants"][n]["scores"]["backtest"]["median_net_sharpe"]) if winners else None
294 if stage["adopted"]:
295 adopted["config"].update(GATE_VARIANTS[stage["adopted"]])
296 report["gates"] = stage
297 save()
299 Path(args.adopted_config_out).parent.mkdir(parents=True, exist_ok=True)
300 Path(args.adopted_config_out).write_text(json.dumps(adopted, indent=1), encoding="utf-8")
301 print("adopted:", json.dumps(adopted))
302 print(f"written {out_path}")
303 return 0
306if __name__ == "__main__":
307 raise SystemExit(main())