Coverage for scripts/topology_sizing_research.py: 100%
72 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"""Learned-topology sizing multiplier (V5.8.0 P5.6, rule R-TOPO): keep `phase_v2.topology_learning` ON or switch it off?
3Live, a node whose learned confidence clears `min_confidence_for_learned` gets a bounded shrink-only size multiplier
4`0.5 + 0.5 * confidence * (1 - disagreement)` (`risk.position_sizing.topology_sizing_multiplier`). The offline
5simulator did not model it. This scores it per dataset row with the SAME prototype distances and softmax
6(`topology.learned_topology.learned_sizing_inputs`) and runs the as-live book with it plugged into the member sizing
7chain (`evaluation.live_parity.build_live_member_weight_fn(topology_inputs_fn=...)`).
9What the dataset cannot give is the live peer term (the learned neighbours vs the deterministic cluster's peers, a
10whole-bar quantity), so it is bracketed: peer distance 0 (best case), 0.5 (mid, the reported estimate), 1 (worst).
11The cluster's dominant regime is approximated by the row's own regime label.
13R-TOPO (fixed before any number was seen): the shipped state is ON, so it is switched OFF only if OFF beats ON(mid) by
14the R-GATE margins (backtest-split net Sharpe >= +0.10 better, validation not worse by > 0.02, drawdown not worse by
15> 1 pp); otherwise it stays ON. Best and worst are reported, never used to decide.
17 python scripts/topology_sizing_research.py [--dataset-validation PATH --dataset-backtest PATH] [--no-cache]
18 -> ml/evaluation/topology_sizing_research.json
19"""
21from __future__ import annotations
23import argparse
24import json
25import sys
26from pathlib import Path
28import numpy as np
30ROOT_DIR = Path(__file__).resolve().parents[1]
31sys.path.insert(0, str(ROOT_DIR))
32sys.path.insert(0, str(Path(__file__).resolve().parent))
34from as_live_levers import AsLiveHarness, add_split_dataset_args, dataset_for_split, summarize # noqa: E402
35from gate_research import decide as r_gate # noqa: E402
37PEER_DISTANCE = {"on_best": 0.0, "on_mid": 0.5, "on_worst": 1.0}
40def decide(results: dict) -> dict:
41 """`results` = {"off": {split: summary}, "on_mid": {split: summary}, ...}. OFF must pass R-GATE against ON(mid)."""
42 verdict = r_gate(results["on_mid"], results["off"])
43 if verdict["passes_r_gate"]:
44 return {"branch": "switch_off", "topology_learning_enabled": False, "r_gate_off_vs_on_mid": verdict}
45 return {"branch": "keep_on", "topology_learning_enabled": True, "r_gate_off_vs_on_mid": verdict}
48def topology_inputs_by_row(frame, topo_model: dict, topo_schema: dict, probabilities, peer_distance: float, *,
49 temperature: float, min_confidence: float) -> dict:
50 """{(date, ticker): inputs} from every dataset row's topology feature vector (train_topology.dataset_feature_vectors)."""
51 from topology.learned_topology import learned_sizing_inputs
52 from train_topology import dataset_feature_vectors_indexed
54 records = frame.to_dict("records")
55 indices, vectors, _outcomes, regimes = dataset_feature_vectors_indexed(records, list(probabilities))
56 out = {}
57 for index, vector, regime in zip(indices, vectors, regimes, strict=False):
58 row = records[index]
59 out[(str(row["date"])[:10], str(row["ticker"]))] = learned_sizing_inputs(
60 vector, topo_model, topo_schema, cluster_regime_label=regime, peer_distance=peer_distance,
61 temperature=temperature, min_confidence_for_learned=min_confidence,
62 )
63 return out
66def main() -> int:
67 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
68 parser.add_argument("--topology-model", default=str(ROOT_DIR / "ml" / "topology_model.json"))
69 parser.add_argument("--topology-schema", default=str(ROOT_DIR / "ml" / "topology_feature_schema.json"))
70 add_split_dataset_args(parser)
71 parser.add_argument("--no-cache", action="store_true")
72 args = parser.parse_args()
74 from evaluation.model_predictions import predict_heads
76 config = json.loads((ROOT_DIR / "config.json").read_text(encoding="utf-8"))
77 learning = config["phase_v2"].get("topology_learning", {})
78 temperature = float(learning.get("temperature", 0.35))
79 min_confidence = float(learning.get("min_confidence_for_learned", 0.2))
80 topo_model = json.loads(Path(args.topology_model).read_text(encoding="utf-8"))
81 topo_schema = json.loads(Path(args.topology_schema).read_text(encoding="utf-8"))
82 mt_schema = json.loads((ROOT_DIR / "ml" / "multitask_feature_schema.json").read_text(encoding="utf-8"))
83 mt_model = json.loads((ROOT_DIR / "ml" / "multitask_model.json").read_text(encoding="utf-8"))
85 results: dict[str, dict] = {"off": {}, **{name: {} for name in PEER_DISTANCE}}
86 multiplier_stats: dict[str, dict] = {}
87 for split in ("validation", "backtest"):
88 harness = AsLiveHarness(split, use_cache=not args.no_cache, dataset_path=dataset_for_split(args, split))
89 probabilities = predict_heads(
90 harness.frame, mt_model, list(mt_schema["model_input_names"]), ["direction"], model_kind="multitask", batched=True
91 )["direction"]
92 results["off"][split] = summarize(harness.as_live())
93 print(f"[{split}] off: net sharpe {results['off'][split]['net_sharpe']:+.3f}", flush=True)
94 for name, peer in PEER_DISTANCE.items():
95 table = topology_inputs_by_row(harness.frame, topo_model, topo_schema, probabilities, peer,
96 temperature=temperature, min_confidence=min_confidence)
97 harness.topology_inputs_fn = lambda symbol, date, table=table: table.get((str(date)[:10], str(symbol)))
98 harness._mechanisms.clear()
99 results[name][split] = summarize(harness.as_live())
100 learned = [v for v in table.values() if v["topology_source"] == "learned"]
101 from risk.position_sizing import topology_sizing_multiplier
103 multipliers = [topology_sizing_multiplier(v["topology_source"], v["topology_confidence"], v["topology_disagreement"])[0]
104 for v in table.values()]
105 multiplier_stats.setdefault(name, {})[split] = {
106 "rows": len(table), "learned_share": len(learned) / max(len(table), 1),
107 "mean_multiplier": float(np.mean(multipliers)) if multipliers else None,
108 }
109 print(f"[{split}] {name}: net sharpe {results[name][split]['net_sharpe']:+.3f} "
110 f"(mean multiplier {multiplier_stats[name][split]['mean_multiplier']:.3f}, learned share "
111 f"{multiplier_stats[name][split]['learned_share']:.2f})", flush=True)
112 harness.topology_inputs_fn = None
113 harness._mechanisms.clear()
115 decision = decide(results)
116 print("decision:", json.dumps({k: v for k, v in decision.items() if k != "r_gate_off_vs_on_mid"}))
117 out = ROOT_DIR / "ml" / "evaluation" / "topology_sizing_research.json"
118 out.write_text(json.dumps({"results": results, "multiplier_stats": multiplier_stats, "decision": decision}, indent=2, default=float),
119 encoding="utf-8")
120 print(f"written {out}")
122 from evaluation.readme_research import refresh_readme_best_effort
124 refresh_readme_best_effort()
125 return 0
128if __name__ == "__main__":
129 raise SystemExit(main())