Coverage for scripts/build_legacy_probability.py: 100%
95 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"""The legacy signal's probability for every dataset row (V6.1.0, rule R-CAL2 / R-LEGACY; Problems.md #190).
3main.py's legacy signal trades non-members on `final_probability_up`: the gating blend of the baseline model, the four
4regime experts (quality- and regime-weighted) and the sequence model's direction head (`moe.gating.build_gating_decision`,
5`phase_v2.gating_network`). The dataset has no such column; this replays it per row with the installed models (or a
6candidate's sequence members, averaged as live's ensemble does) so the offline simulator can model the legacy component.
8The gating regime is `regime.market_regime.build_market_regime_vector` on the row's raw features with the configured
9thresholds and `portfolio_drawdown=0.0`: live passes the account drawdown, which a dataset row cannot know (in a
10backtest the drawdown never triggers risk-off - `bypass_regime_drawdown_gate` - so only the risk-on clause differs).
12 python scripts/build_legacy_probability.py [--dataset ml/datasets/full_dataset.csv] [--ml-dir ml]
13 [--sequence-members DIR ...] [--splits validation backtest holdout] [--out ml/datasets/legacy_probability.csv]
14 [--emit-components ml/datasets/legacy_components.csv]
16V6.4.0 (lead L8): `--emit-components` also writes every row's gating inputs (baseline, the four experts, the sequence
17direction and the three regime labels), and `legacy_probability_from_components` recombines them - with any expert
18excluded - through the same gating call, so an expert ablation costs seconds, not another inference pass.
19"""
21from __future__ import annotations
23import argparse
24import json
25import sys
26from pathlib import Path
28import numpy as np
29import pandas as pd
31ROOT_DIR = Path(__file__).resolve().parents[1]
32sys.path.insert(0, str(ROOT_DIR))
34CONTEXT_DAYS = 60 # the sequence windows of the first rows need earlier bars
37def regime_thresholds(config: dict) -> dict:
38 """The thresholds main.py passes to build_market_regime_vector (dynamic_risk volatility, regime_detection)."""
39 risk = config.get("phase_v2", {}).get("dynamic_risk", {})
40 regime = config.get("phase_v2", {}).get("regime_detection", {})
41 return {
42 "bullish_threshold": float(regime.get("bullish_threshold", 0.02)),
43 "bearish_threshold": float(regime.get("bearish_threshold", -0.02)),
44 "low_volatility_threshold": float(risk.get("low_volatility_threshold", 0.01)),
45 "high_volatility_threshold": float(risk.get("high_volatility_threshold", 0.03)),
46 "risk_off_drawdown_threshold": float(regime.get("risk_off_drawdown_threshold", 0.08)),
47 "risk_on_drawdown_threshold": float(regime.get("risk_on_drawdown_threshold", 0.03)),
48 "high_correlation_threshold": float(regime.get("high_correlation_threshold", 0.75)),
49 }
52EXPERT_COLUMNS = ("bullish", "bearish", "sideways", "volatility")
53REGIME_COLUMNS = ("trend_regime", "volatility_regime", "risk_regime")
56def legacy_probability(raw_features: dict, baseline: float | None, experts: dict[str, float | None],
57 sequence_direction: float | None, expert_metrics: dict, config: dict,
58 excluded_experts: tuple[str, ...] = ()) -> float:
59 """One row's final_probability_up, through the same gating call main.py's Pass 1c makes (learned gating off)."""
60 from regime.market_regime import build_market_regime_vector
62 regime = build_market_regime_vector(
63 raw_features, portfolio_drawdown=0.0,
64 average_correlation=float(raw_features.get("topology_correlation_strength", 0.0) or 0.0), **regime_thresholds(config),
65 ).to_dict()
66 return _gate(regime, baseline, experts, sequence_direction, expert_metrics, config, excluded_experts)
69def _gate(regime: dict, baseline, experts, sequence_direction, expert_metrics: dict, config: dict, excluded_experts=()) -> float:
70 from moe.gating import build_gating_decision
72 gating = config.get("phase_v2", {}).get("gating_network", {})
73 decision = build_gating_decision(
74 regime=regime, expert_training_metrics=expert_metrics, expert_probabilities=experts,
75 baseline_probability_up=baseline, baseline_weight=float(gating.get("baseline_weight", 0.25)),
76 sequence_prediction={"direction": sequence_direction} if sequence_direction is not None else None,
77 sequence_weight=float(gating.get("sequence_weight", 0.0)),
78 excluded_experts=tuple(excluded_experts),
79 )
80 return float(decision.final_probability_up)
83def legacy_probability_from_components(row, expert_metrics: dict, config: dict, excluded_experts: tuple[str, ...] = ()) -> float:
84 """final_probability_up from one row of the components file (`--emit-components`): the same gating call on the stored
85 baseline, expert and sequence outputs and regime labels, optionally without `excluded_experts`."""
86 def _value(name):
87 value = row.get(name)
88 return None if value is None or value != value else float(value)
90 regime = {name: str(row.get(name, "unknown")) for name in REGIME_COLUMNS}
91 experts = {name: _value(name) for name in EXPERT_COLUMNS}
92 return _gate(regime, _value("baseline"), experts, _value("sequence_direction"), expert_metrics, config, excluded_experts)
95def main() -> int:
96 from evaluation.model_predictions import predict_heads_ensemble
97 from inference.exported_model import convert_state_dict_arrays, run_exported_model_rows
98 from moe.gating import EXPERT_NAMES
100 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
101 parser.add_argument("--dataset", default=str(ROOT_DIR / "ml" / "datasets" / "full_dataset.csv"))
102 parser.add_argument("--ml-dir", default=str(ROOT_DIR / "ml"))
103 parser.add_argument("--sequence-members", nargs="*", default=None, help="sequence version dirs (an ensemble)")
104 parser.add_argument("--splits", nargs="*", default=["validation", "backtest", "holdout"])
105 parser.add_argument("--out", default=str(ROOT_DIR / "ml" / "datasets" / "legacy_probability.csv"))
106 parser.add_argument("--emit-components", default=None, help="also write each row's gating inputs here (V6.4.0, lead L8)")
107 args = parser.parse_args()
108 config = json.loads((ROOT_DIR / "config.json").read_text(encoding="utf-8"))
109 ml_dir = Path(args.ml_dir)
110 window_name = {"train": "training"}.get(args.splits[0], args.splits[0])
111 first_start = pd.Timestamp(config["phase1"]["windows"][window_name]["start"])
112 context_start = (first_start - pd.Timedelta(CONTEXT_DAYS, unit="D")).strftime("%Y-%m-%d")
113 parts = [chunk[chunk["date"].astype(str) >= context_start] for chunk in pd.read_csv(args.dataset, chunksize=40_000)]
114 frame = pd.concat(parts, ignore_index=True).sort_values(["ticker", "date"]).reset_index(drop=True)
115 wanted = frame["split"].isin(args.splits).to_numpy()
117 schema = json.loads((ml_dir / "feature_schema.json").read_text(encoding="utf-8"))
118 inputs = frame[schema["model_input_names"]].to_numpy(dtype=np.float64).tolist()
119 baseline_export = json.loads((ml_dir / "model_weights.json").read_text(encoding="utf-8"))
120 convert_state_dict_arrays(baseline_export)
121 baseline = np.asarray(run_exported_model_rows(baseline_export, inputs))
122 experts: dict[str, np.ndarray] = {}
123 for name in EXPERT_NAMES:
124 path = ml_dir / "expert_models" / name / "model_weights.json"
125 if path.exists():
126 export = json.loads(path.read_text(encoding="utf-8"))
127 convert_state_dict_arrays(export)
128 experts[name] = np.asarray(run_exported_model_rows(export, inputs))
129 del inputs
130 metrics_path = ml_dir / "expert_training_metrics.json"
131 expert_metrics = json.loads(metrics_path.read_text(encoding="utf-8")) if metrics_path.exists() else {}
133 sequence_schema = json.loads((ml_dir / "sequence_feature_schema.json").read_text(encoding="utf-8"))
134 member_dirs = [Path(item) for item in (args.sequence_members or [])] or [ml_dir]
135 sequence_exports = [json.loads((directory / "sequence_model.json").read_text(encoding="utf-8")) for directory in member_dirs]
136 window = int(config.get("phase_v2", {}).get("sequence_model", {}).get("window_size", 30))
137 direction = predict_heads_ensemble(
138 frame, sequence_exports, sequence_schema["model_input_names"], ["direction"], model_kind="sequence",
139 sequence_feature_schema=sequence_schema, configured_window_size=window, batched=True,
140 )["direction"]
142 from regime.market_regime import build_market_regime_vector
144 raw_names = [name for name in schema["feature_names"] if name in frame.columns]
145 raw = frame[raw_names].to_dict("records")
146 probabilities = np.full(len(frame), np.nan)
147 components = []
148 thresholds = regime_thresholds(config)
149 for index in np.flatnonzero(wanted):
150 expert_values = {name: float(values[index]) for name, values in experts.items()}
151 seq = float(direction[index]) if direction[index] == direction[index] else None
152 probabilities[index] = legacy_probability(raw[index], float(baseline[index]), expert_values, seq, expert_metrics, config)
153 if args.emit_components:
154 regime = build_market_regime_vector(
155 raw[index], portfolio_drawdown=0.0,
156 average_correlation=float(raw[index].get("topology_correlation_strength", 0.0) or 0.0), **thresholds,
157 ).to_dict()
158 components.append({"baseline": float(baseline[index]), **{name: expert_values.get(name) for name in EXPERT_COLUMNS},
159 "sequence_direction": seq, **{name: regime[name] for name in REGIME_COLUMNS}})
160 out = frame.loc[wanted, ["date", "ticker"]].assign(final_probability_up=probabilities[wanted])
161 Path(args.out).parent.mkdir(parents=True, exist_ok=True)
162 out.to_csv(args.out, index=False)
163 if args.emit_components:
164 pd.concat([frame.loc[wanted, ["date", "ticker"]].reset_index(drop=True), pd.DataFrame(components)], axis=1).to_csv(
165 args.emit_components, index=False)
166 print(f"written {args.emit_components}: {len(components)} component rows")
167 print(f"written {args.out}: {len(out)} rows, mean {np.nanmean(out['final_probability_up']):.4f}")
168 return 0
171if __name__ == "__main__":
172 raise SystemExit(main())