Coverage for train_strategy_selector.py: 100%
106 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"""Offline trainer for the learned multi-leg strategy-selector model
2(V4.7, development/Problems.md #29's own framing - a model that picks
3which enabled strategy to prefer per bar, replacing/augmenting
4portfolio/options_strategy.py::order_enabled_strategies()'s static
5risk-tier-preference reordering, once trained from real per-strategy
6realized P&L).
8Separate script from train.py, exact same rationale as train_topology.py:
9different data source (Postgres experience_events, specifically the new
10"option_strategy_outcome" event type - experience/redis_queue.py::
11build_option_strategy_outcome_event()), and must be independently
12best-effort/failable without ever blocking or rejecting the primary
13probability-model candidate - see retraining/orchestrator.py::
14train_strategy_selector(), which runs this as its own subprocess between
15`train_sequence` and `validate` and treats any failure here as a warning,
16not a candidate rejection.
18Free to use numpy/scikit-learn, unlike inference/strategy_selector_inference.py's
19pure-Python runtime scoring path: this script never runs inside the Lean
20container, only as a retraining-pipeline subprocess or manual CLI call.
22IMPORTANT - the central scoping fact this trainer exists to make explicit:
23unlike train_topology.py (which is dormant only until enough real
24Postgres experience_events VOLUME accumulates from an already-running
25system), this trainer has NO data source at all until real option
26positions actually trade. Confirmed during scoping research: every
27options code path in this repo is "code-complete, IB-unverified" (no IB
28key, zero option assets in the live universe), so the continuously-running
29instance operates in observation mode, where main.py::
30_emit_option_strategy_outcome_if_pending() is the ONLY thing that can ever
31emit an "option_strategy_outcome" event - and it only fires for a
32multi-leg option position that was actually opened AND closed in
33observation mode. Until real option assets are configured and this
34algorithm actually runs against them, this script's "skip, not enough
35data" branch below is not a temporary/volume gate the way train_topology.py's
36is - it is the ONLY reachable branch, indefinitely. Ships code-complete
37and dormant, exactly as scoped.
39Usage:
40 python train_strategy_selector.py --version-id <uuid> [--postgres-dsn ...] [--config-path config.json]
42Writes ml/versions/<version_id>/strategy_selector_model.json,
43strategy_selector_training_metrics.json and
44strategy_selector_feature_schema.json. Exits 0 (not an error) when there
45isn't enough training data yet - "skipped" must never look like "failed"
46to the caller.
47"""
49from __future__ import annotations
51import argparse
52import json
53import logging
54import sys
55from datetime import datetime, timedelta, timezone
56from pathlib import Path
58import numpy as np
59from sklearn.linear_model import LogisticRegression
61from execution.secrets_io import secret_env
62from inference.strategy_selector_inference import FEATURE_KEYS
63from performance.postgres_triggers import fetch_recent_events
65LOGGER = logging.getLogger("aether_quant.train_strategy_selector")
66ROOT = Path(__file__).resolve().parent
67ML_DIR = ROOT / "ml"
68CONFIG_PATH = ROOT / "config.json"
71def parse_args() -> argparse.Namespace:
72 parser = argparse.ArgumentParser(description="Aether Quant learned strategy-selector trainer (V4.7)")
73 parser.add_argument("--version-id", type=str, required=True, help="Candidate model_version_id (UUID)")
74 parser.add_argument("--postgres-dsn", type=str, default="", help="Overridden by AETHER_POSTGRES_DSN env")
75 parser.add_argument("--config-path", type=str, default=str(CONFIG_PATH))
76 return parser.parse_args()
79def load_strategy_selector_training_config(config_path: Path = CONFIG_PATH) -> dict:
80 with Path(config_path).open("r", encoding="utf-8") as f:
81 config = json.load(f)
82 return config.get("phase_v2", {}).get("strategy_selector", {}).get("training", {})
85def strategy_selector_candidate_output_paths(version_id: str) -> dict[str, Path]:
86 """Own local helper mirroring train.py's candidate_output_paths(), kept
87 independent (not imported from train.py) so this script stays free of
88 train.py's torch/pandas import weight - same rationale
89 train_topology.py's own topology_candidate_output_paths() documents."""
90 version_dir = ML_DIR / "versions" / version_id
91 return {
92 "version_dir": version_dir,
93 "strategy_selector_model": version_dir / "strategy_selector_model.json",
94 "strategy_selector_training_metrics": version_dir / "strategy_selector_training_metrics.json",
95 "strategy_selector_feature_schema": version_dir / "strategy_selector_feature_schema.json",
96 }
99def build_feature_vector(event: dict) -> dict | None:
100 """Pulls a FEATURE_KEYS-shaped feature vector out of one
101 option_strategy_outcome event's regime/topology sub-payloads - the
102 SAME bare key names main.py::_emit_option_strategy_outcome_if_pending()
103 writes onto the event at push time (regime={"risk_score": ...},
104 topology=self.latest_topology_payload), so this trainer and
105 inference/strategy_selector_inference.py's runtime scorer read/produce
106 an identical feature vocabulary by construction - train/runtime parity,
107 the same discipline train_topology.py's own build_feature_vector()
108 establishes for the topology model.
110 Returns None only when the event carries NEITHER sub-payload at all (a
111 genuinely unusable row, e.g. a malformed/foreign event that slipped
112 through the event_type filter) - missing individual keys within a
113 present sub-payload degrade to 0.0 instead, never raising."""
114 regime = event.get("regime")
115 topology = event.get("topology")
116 if not isinstance(regime, dict) and not isinstance(topology, dict):
117 return None
118 regime = regime or {}
119 topology = topology or {}
120 return {
121 "regime_risk_score": float(regime.get("risk_score", 0.0) or 0.0),
122 "regime_trend_score": float(regime.get("trend_score", 0.0) or 0.0),
123 "topology_correlation_strength": float(topology.get("correlation_strength", 0.0) or 0.0),
124 }
127def fit_strategy_scorers(
128 features_by_strategy: dict[str, list[dict]],
129 labels_by_strategy: dict[str, list[int]],
130 min_events_per_strategy: int,
131) -> tuple[dict, list[dict]]:
132 """One independent logistic-regression classifier per strategy_name,
133 predicting P(realized_pnl > 0 | features) - kept deliberately simple
134 (plain sklearn LogisticRegression, no hyperparameter search): this is
135 a brand-new data stream that will realistically stay below
136 min_training_events for a long time (see this module's own docstring),
137 not worth a more complex model until real training data exists to
138 justify one. Trained directly on RAW (not z-scored) feature values, so
139 inference/strategy_selector_inference.py::score_strategies()'s runtime
140 dot-product needs no separate normalization step/feature_stats file.
142 Skips (never raises) a strategy_name with fewer than
143 min_events_per_strategy samples, or where every sample shares the same
144 outcome label (LogisticRegression needs both classes present to fit).
145 Returns ({strategy_name: {"weights": {...}, "bias": b}}, per_strategy_metrics)."""
146 scorers: dict[str, dict] = {}
147 per_strategy_metrics: list[dict] = []
148 for strategy_name, vectors in features_by_strategy.items():
149 labels = labels_by_strategy[strategy_name]
150 win_rate = sum(labels) / len(labels) if labels else None
151 if len(vectors) < min_events_per_strategy or len(set(labels)) < 2:
152 per_strategy_metrics.append(
153 {"strategy_name": strategy_name, "sample_count": len(vectors), "win_rate": win_rate, "scored": False}
154 )
155 continue
157 matrix = np.array([[vector[key] for key in FEATURE_KEYS] for vector in vectors], dtype=float)
158 targets = np.array(labels)
159 model = LogisticRegression(max_iter=1000)
160 model.fit(matrix, targets)
162 scorers[strategy_name] = {
163 "weights": {key: float(weight) for key, weight in zip(FEATURE_KEYS, model.coef_[0], strict=False)},
164 "bias": float(model.intercept_[0]),
165 }
166 per_strategy_metrics.append(
167 {"strategy_name": strategy_name, "sample_count": len(vectors), "win_rate": win_rate, "scored": True}
168 )
169 return scorers, per_strategy_metrics
172def main() -> int:
173 logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
174 args = parse_args()
176 try:
177 training_config = load_strategy_selector_training_config(Path(args.config_path))
178 min_training_events = int(training_config.get("min_training_events", 300))
179 lookback_days = int(training_config.get("lookback_days", 90))
180 min_events_per_strategy = int(training_config.get("min_events_per_strategy", 20))
182 import psycopg
184 dsn = secret_env("POSTGRES_DSN", args.postgres_dsn)
185 conn = psycopg.connect(dsn, autocommit=False)
186 try:
187 since = datetime.now(timezone.utc) - timedelta(days=lookback_days)
188 events = fetch_recent_events(conn, limit=max(min_training_events * 4, 5000), since=since)
189 finally:
190 conn.close()
192 outcome_events = [event for event in events if event.get("event_type") == "option_strategy_outcome"]
194 if len(outcome_events) < min_training_events:
195 LOGGER.info(
196 "train_strategy_selector: only %d option_strategy_outcome events (need %d) - "
197 "skipping, not writing artifacts.",
198 len(outcome_events),
199 min_training_events,
200 )
201 return 0
203 features_by_strategy: dict[str, list[dict]] = {}
204 labels_by_strategy: dict[str, list[int]] = {}
205 usable_event_count = 0
206 for event in outcome_events:
207 strategy_name = event.get("strategy_name")
208 realized_pnl = event.get("realized_pnl")
209 if not strategy_name or realized_pnl is None:
210 continue
211 vector = build_feature_vector(event)
212 if vector is None:
213 continue
214 usable_event_count += 1
215 features_by_strategy.setdefault(strategy_name, []).append(vector)
216 labels_by_strategy.setdefault(strategy_name, []).append(1 if realized_pnl > 0 else 0)
218 scorers, per_strategy_metrics = fit_strategy_scorers(
219 features_by_strategy, labels_by_strategy, min_events_per_strategy
220 )
222 if not scorers:
223 LOGGER.info(
224 "train_strategy_selector: no strategy_name cleared min_events_per_strategy=%d with both "
225 "outcome classes present - skipping, not writing artifacts.",
226 min_events_per_strategy,
227 )
228 return 0
230 trained_at = datetime.now(timezone.utc).isoformat()
231 model_payload = {
232 "version_id": args.version_id,
233 "trained_at": trained_at,
234 "strategy_names": list(scorers.keys()),
235 "scorers": scorers,
236 "feature_keys": list(FEATURE_KEYS),
237 }
238 feature_schema_payload = {"feature_keys": list(FEATURE_KEYS)}
239 training_metrics_payload = {
240 "project": "aether_quant",
241 "phase": "V4.7",
242 "version_id": args.version_id,
243 "trained_at": trained_at,
244 "training_window_days": lookback_days,
245 "sample_count": usable_event_count,
246 "strategies_scored": len(scorers),
247 "per_strategy": per_strategy_metrics,
248 }
250 paths = strategy_selector_candidate_output_paths(args.version_id)
251 paths["version_dir"].mkdir(parents=True, exist_ok=True)
252 paths["strategy_selector_model"].write_text(json.dumps(model_payload, indent=2), encoding="utf-8")
253 paths["strategy_selector_feature_schema"].write_text(
254 json.dumps(feature_schema_payload, indent=2), encoding="utf-8"
255 )
256 paths["strategy_selector_training_metrics"].write_text(
257 json.dumps(training_metrics_payload, indent=2), encoding="utf-8"
258 )
260 LOGGER.info(
261 "train_strategy_selector: wrote strategy_selector artifacts for version %s "
262 "(%d strategies scored, %d samples).",
263 args.version_id,
264 len(scorers),
265 usable_event_count,
266 )
267 return 0
268 except Exception as exc: # never let an unexpected failure look ambiguous to the caller
269 LOGGER.error("train_strategy_selector: unexpected failure - %s", exc)
270 return 1
273if __name__ == "__main__":
274 sys.exit(main())