Coverage for train_topology.py: 100%
185 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 topology model (Phase V2-17.5).
3Separate script from train.py: different data source (Postgres
4experience_events, not the OHLCV/phase1 dataset pipeline train.py owns),
5and must be independently best-effort/failable without ever blocking or
6rejecting the primary probability-model candidate - see
7retraining/orchestrator.py::train_topology(), which runs this as its own
8subprocess between the main `train` and `validate` stages and treats any
9failure here as a warning, not a candidate rejection.
11Free to use numpy/scikit-learn, unlike topology/learned_topology.py's pure-
12Python runtime inference path: this script never runs inside the Lean
13container, only as a retraining-pipeline subprocess or manual CLI call.
15Usage:
16 python train_topology.py --version-id <uuid> [--postgres-dsn ...] [--config-path config.json]
18Writes ml/versions/<version_id>/topology_model.json,
19topology_training_metrics.json and topology_feature_schema.json. Exits 0
20(not an error) when there isn't enough training data yet - "skipped" must
21never look like "failed" to the caller.
22"""
24from __future__ import annotations
26import argparse
27import json
28import logging
29import sys
30from collections import Counter
31from datetime import datetime, timedelta, timezone
32from pathlib import Path
34import numpy as np
35from sklearn.cluster import KMeans
37from execution.secrets_io import secret_env
38from performance.postgres_triggers import fetch_recent_events
39from topology.learned_topology import FEATURE_KEYS, liquidity_score_from_decision
41LOGGER = logging.getLogger("aether_quant.train_topology")
42ROOT = Path(__file__).resolve().parent
43ML_DIR = ROOT / "ml"
44CONFIG_PATH = ROOT / "config.json"
47def parse_args() -> argparse.Namespace:
48 parser = argparse.ArgumentParser(description="Aether Quant learned-topology trainer (V2-17.5)")
49 parser.add_argument("--version-id", type=str, required=True, help="Candidate model_version_id (UUID)")
50 parser.add_argument("--postgres-dsn", type=str, default="", help="Overridden by AETHER_POSTGRES_DSN env")
51 parser.add_argument("--config-path", type=str, default=str(CONFIG_PATH))
52 parser.add_argument(
53 "--source", choices=["postgres", "dataset"], default="postgres",
54 help="V5.8.0: 'dataset' builds the training events from ml/datasets/train_dataset.csv instead of Postgres "
55 "experience events (a full-information replay, like train_rl_sizing.py), so the model is retrainable offline.",
56 )
57 parser.add_argument("--dataset-path", type=str, default=str(ML_DIR / "datasets" / "train_dataset.csv"))
58 parser.add_argument("--max-rows", type=int, default=60_000, help="with --source dataset: deterministic row sample cap")
59 return parser.parse_args()
62def primary_regime_label(row: dict) -> str:
63 """regime.market_regime's `primary_regime` rebuilt from the dataset's one-hot columns, in the exact format the live topology
64 compares prototypes against: '<trend>_risk_off', 'sideways_<volatility>' or '<trend>_<volatility>' (e.g.
65 'bullish_high_volatility'). A trend-only label would never equal a live cluster label, so every node would read as a
66 regime mismatch and the sizing multiplier would shrink permanently."""
67 def _flag(name: str) -> bool:
68 try:
69 return float(row.get(name, 0) or 0) > 0.5
70 except (TypeError, ValueError):
71 return False
73 trend = next((label for label in ("bullish", "bearish", "sideways") if _flag(f"regime_trend_{label}")), None)
74 volatility = next(
75 (label for label in ("low_volatility", "normal_volatility", "high_volatility") if _flag(f"regime_volatility_{label.split('_')[0]}")),
76 None,
77 )
78 if trend is None or volatility is None:
79 return "unknown"
80 if _flag("regime_risk_off"):
81 return f"{trend}_risk_off"
82 return f"{trend}_{volatility}"
85def dataset_feature_vectors(
86 rows: list[dict], probabilities: list[float], *, nominal_notional: float = 5_000.0
87) -> tuple[list[dict], list[str | None], list[str]]:
88 _indices, vectors, outcomes, regimes = dataset_feature_vectors_indexed(rows, probabilities, nominal_notional=nominal_notional)
89 return vectors, outcomes, regimes
92def dataset_feature_vectors_indexed(
93 rows: list[dict], probabilities: list[float], *, nominal_notional: float = 5_000.0
94) -> tuple[list[int], list[dict], list[str | None], list[str]]:
95 """V5.8.0 - FEATURE_KEYS vectors, win/loss labels and regime labels from dataset rows (the offline counterpart of
96 build_feature_vector() over experience events). `probabilities` is the multitask direction head per row (live uses
97 the model's probability_up the same way). Approximations, documented in the parity contract: volatility_pressure is
98 the annualised 20-day rolling volatility (live: the topology window's annualised volatility) and the liquidity score
99 uses a nominal order notional against the row's dollar volume. A row is a "win" when the realised 20-day return has
100 the sign the probability called."""
101 indices, vectors, outcomes, regimes = [], [], [], []
102 for index, (row, probability) in enumerate(zip(rows, probabilities, strict=False)):
103 try:
104 volatility = float(row["rolling_volatility_20d"]) * (252.0 ** 0.5)
105 close, volume = float(row["close"]), float(row["volume"])
106 forward = float(row["target_return_20d"])
107 vector = {
108 "volatility": volatility,
109 "momentum": float(probability) - 0.5,
110 "correlation_strength": float(row.get("topology_correlation_strength", 0.0) or 0.0),
111 "liquidity_score": liquidity_score_from_decision({
112 "participation_rate": nominal_notional / (close * volume) if close * volume > 0 else 1.0,
113 "estimated_slippage": float(row.get("liquidity_spread_proxy", 0.0) or 0.0) / 2.0,
114 }),
115 "regime_risk_score": float(row.get("regime_signal_risk_score", 0.0) or 0.0),
116 }
117 except (KeyError, TypeError, ValueError):
118 continue
119 if not all(np.isfinite(list(vector.values()))) or not np.isfinite(forward):
120 continue
121 indices.append(index)
122 vectors.append(vector)
123 outcomes.append("win" if (float(probability) - 0.5) * forward > 0 else "loss")
124 regimes.append(primary_regime_label(row))
125 return indices, vectors, outcomes, regimes
128def load_dataset_events(dataset_path: Path, max_rows: int) -> tuple[list[dict], list[str | None], list[str]]:
129 """Reads the train split, scores the multitask direction head on it and returns dataset_feature_vectors()."""
130 import pandas as pd
132 from evaluation.model_predictions import predict_multitask_head
134 schema = json.loads((ML_DIR / "multitask_feature_schema.json").read_text(encoding="utf-8"))
135 model = json.loads((ML_DIR / "multitask_model.json").read_text(encoding="utf-8"))
136 names = list(schema["model_input_names"])
137 needed = set(names) | {"rolling_volatility_20d", "close", "volume", "target_return_20d", "topology_correlation_strength",
138 "liquidity_spread_proxy", "regime_signal_risk_score", "regime_trend_bullish",
139 "regime_trend_bearish", "regime_trend_sideways", "regime_volatility_low",
140 "regime_volatility_normal", "regime_volatility_high", "regime_risk_off", "training_eligible", "date"}
141 frame = pd.read_csv(dataset_path, usecols=lambda column: column in needed)
142 if "training_eligible" in frame.columns:
143 frame = frame[frame["training_eligible"].astype(bool)]
144 frame = frame.dropna(subset=["target_return_20d"]).reset_index(drop=True)
145 if len(frame) > max_rows:
146 frame = frame.iloc[np.linspace(0, len(frame) - 1, max_rows).astype(int)].reset_index(drop=True)
147 probabilities = predict_multitask_head(frame, model, names, "direction")
148 return dataset_feature_vectors(frame.to_dict("records"), list(probabilities))
151def load_topology_learning_config(config_path: Path = CONFIG_PATH) -> dict:
152 with Path(config_path).open("r", encoding="utf-8") as f:
153 config = json.load(f)
154 return config.get("phase_v2", {}).get("topology_learning", {}).get("training", {})
157def topology_candidate_output_paths(version_id: str) -> dict[str, Path]:
158 """Own local helper mirroring train.py's candidate_output_paths(), kept
159 independent (not imported from train.py) so this script stays free of
160 train.py's torch/pandas import weight."""
161 version_dir = ML_DIR / "versions" / version_id
162 return {
163 "version_dir": version_dir,
164 "topology_model": version_dir / "topology_model.json",
165 "topology_training_metrics": version_dir / "topology_training_metrics.json",
166 "topology_feature_schema": version_dir / "topology_feature_schema.json",
167 }
170def derive_realized_outcomes(events: list[dict]) -> list[str | None]:
171 """Per-ticker, chronological: track the latest action=="trade" event as
172 "open"; when a later event for the same ticker carries a non-null
173 portfolio.last_realized_pnl, every event in that open->realize span
174 (inclusive) is back-labeled win/loss/neutral. Events with no subsequent
175 realization keep outcome_label=None and are excluded from win-rate
176 weighting downstream (still usable, unlabeled, for centroid geometry).
178 Reuses the same "realized pnl closes the previous trade" signal
179 experience/observation_metrics.py's simulated_win_loss() already relies
180 on, just attributed per-ticker instead of portfolio-wide.
182 `events` is assumed already sorted chronologically ascending (the shape
183 performance.postgres_triggers.fetch_recent_events() returns). Returns a
184 list aligned index-for-index with `events`.
185 """
186 outcomes: list[str | None] = [None] * len(events)
187 open_index_by_ticker: dict[str, int] = {}
189 for index, event in enumerate(events):
190 ticker = event.get("ticker")
191 if not ticker:
192 continue
194 if event.get("action") == "trade" and event.get("signal") in ("buy", "sell"):
195 open_index_by_ticker[ticker] = index
197 pnl = (event.get("portfolio") or {}).get("last_realized_pnl")
198 if pnl is None:
199 continue
201 label = "win" if pnl > 0 else "loss" if pnl < 0 else "neutral"
202 open_index = open_index_by_ticker.pop(ticker, None)
203 if open_index is None:
204 outcomes[index] = label
205 continue
206 # Only back-label this ticker's own events within the span - other
207 # tickers' events are interleaved chronologically in between and
208 # must not be touched.
209 for span_index in range(open_index, index + 1):
210 if events[span_index].get("ticker") == ticker:
211 outcomes[span_index] = label
213 return outcomes
216def build_feature_vector(event: dict) -> dict | None:
217 """Pulls a topology.learned_topology.FEATURE_KEYS-shaped feature vector
218 out of one experience_events payload. Returns None if the event has no
219 topology payload (e.g. warmup bars).
221 "momentum" isn't itself a field topology/market_topology.py persists on
222 a node - probability_up-0.5 is used as a directional-strength proxy
223 that's actually present on every event, rather than inventing a new
224 field the runtime side would also have to compute and pass through.
225 """
226 topology = event.get("topology")
227 if not isinstance(topology, dict) or "volatility_pressure" not in topology:
228 return None
230 regime = event.get("regime") or {}
231 liquidity = event.get("liquidity") or {}
233 return {
234 "volatility": float(topology.get("volatility_pressure", 0.0) or 0.0),
235 "momentum": float(event.get("probability_up", 0.5) or 0.5) - 0.5,
236 "correlation_strength": float(topology.get("correlation_strength", 0.0) or 0.0),
237 "liquidity_score": liquidity_score_from_decision(liquidity),
238 "regime_risk_score": float(regime.get("risk_score", 0.0) or 0.0),
239 }
242def fit_prototypes(
243 feature_vectors: list[dict],
244 outcome_labels: list,
245 regime_labels: list[str],
246 num_prototypes: int,
247 distance_scale_percentile: float,
248) -> dict:
249 """KMeans over z-scored features. Returns prototypes (with a small,
250 win-rate-signed offset later bounded by topology.learned_topology's
251 max_offset_xy/z at inference time - never a full replacement embedding),
252 per-feature normalization stats, and a distance_scale (p`distance_scale_percentile`
253 of within-cluster nearest-centroid distances) used as the novelty/stress
254 reference scale.
256 The offset's x/y components are absolute scene units; z is normalized
257 to [-1, 1] and scaled by max_offset_z at apply time - see the offset
258 construction below for why z's contract differs from x/y's."""
259 matrix = np.array([[vector[key] for key in FEATURE_KEYS] for vector in feature_vectors], dtype=float)
260 means = matrix.mean(axis=0)
261 stds = matrix.std(axis=0)
262 stds[stds == 0] = 1.0
263 normalized = (matrix - means) / stds
265 n_clusters = max(1, min(int(num_prototypes), len(feature_vectors)))
266 kmeans = KMeans(n_clusters=n_clusters, n_init=10, random_state=42)
267 labels = kmeans.fit_predict(normalized)
269 distances_to_own_centroid = np.linalg.norm(normalized - kmeans.cluster_centers_[labels], axis=1)
270 distance_scale = (
271 float(np.percentile(distances_to_own_centroid, distance_scale_percentile))
272 if len(distances_to_own_centroid)
273 else 1.0
274 )
275 distance_scale = distance_scale or 1.0
277 prototypes = []
278 for cluster_index in range(n_clusters):
279 member_indices = [i for i, label in enumerate(labels) if label == cluster_index]
280 if not member_indices:
281 continue
283 member_regimes = [regime_labels[i] for i in member_indices if regime_labels[i]]
284 dominant_regime_label = Counter(member_regimes).most_common(1)[0][0] if member_regimes else "unknown"
286 member_outcomes = [outcome_labels[i] for i in member_indices if outcome_labels[i] is not None]
287 total_labeled = len(member_outcomes)
288 win_rate = (sum(1 for label in member_outcomes if label == "win") / total_labeled) if total_labeled else None
290 # Offset direction is a coarse, bounded nudge signed by win rate.
291 # x/y are absolute scene units: apply_learned_topology() clamps the
292 # applied shift to max_offset_xy regardless, so these raw values
293 # only need to encode direction/relative magnitude, not final
294 # scale - true in both the 2D and 3D (V4-W3) embedding modes,
295 # since x/y's scale never changes between them.
296 offset_sign = 0.0 if win_rate is None else (1.0 if win_rate >= 0.5 else -1.0)
298 # z is normalized to [-1, 1] instead (development/Problems.md #56):
299 # unlike x/y, z's scene scale itself changes between the 2D
300 # (volatility encoding, 0..1) and 3D (spatial embedding, 0..100)
301 # modes, so a raw offset tuned for one scale is meaningless on the
302 # other. apply_learned_topology() multiplies this by the active
303 # max_offset_z before clamping, the same way confidence already
304 # scales it - see _score_node()'s z line. Graded by win rate
305 # (unlike x/y's binary sign) since z was already a graded encoding
306 # before V4-W3 and there is no reason to lose that resolution.
307 centroid = kmeans.cluster_centers_[cluster_index]
308 prototypes.append(
309 {
310 "label": f"proto_{cluster_index}",
311 "centroid": {key: float(value) for key, value in zip(FEATURE_KEYS, centroid, strict=False)},
312 "dominant_regime_label": dominant_regime_label,
313 "offset": {
314 "x": offset_sign * 2.0,
315 "y": offset_sign * 1.0,
316 "z": 0.0 if win_rate is None else (win_rate - 0.5) * 2.0,
317 },
318 "sample_count": len(member_indices),
319 "win_rate": win_rate,
320 }
321 )
323 feature_stats = {key: {"mean": float(mean), "std": float(std)} for key, mean, std in zip(FEATURE_KEYS, means, stds, strict=False)}
325 return {
326 "prototypes": prototypes,
327 "feature_stats": feature_stats,
328 "distance_scale": distance_scale,
329 "n_clusters": n_clusters,
330 }
333def main() -> int:
334 logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
335 args = parse_args()
337 try:
338 training_config = load_topology_learning_config(Path(args.config_path))
339 min_training_events = int(training_config.get("min_training_events", 500))
340 lookback_days = int(training_config.get("lookback_days", 90))
341 num_prototypes = int(training_config.get("num_prototypes", 6))
342 distance_scale_percentile = float(training_config.get("distance_scale_percentile", 90))
344 if getattr(args, "source", "postgres") == "dataset":
345 feature_vectors, outcome_labels, regime_labels = load_dataset_events(Path(args.dataset_path), args.max_rows)
346 else:
347 import psycopg
349 dsn = secret_env("POSTGRES_DSN", args.postgres_dsn)
350 conn = psycopg.connect(dsn, autocommit=False)
351 try:
352 since = datetime.now(timezone.utc) - timedelta(days=lookback_days)
353 events = fetch_recent_events(conn, limit=max(min_training_events * 4, 5000), since=since)
354 finally:
355 conn.close()
357 outcomes = derive_realized_outcomes(events)
359 feature_vectors = []
360 outcome_labels = []
361 regime_labels = []
362 for event, outcome in zip(events, outcomes, strict=False):
363 vector = build_feature_vector(event)
364 if vector is None:
365 continue
366 feature_vectors.append(vector)
367 outcome_labels.append(outcome)
368 regime_labels.append((event.get("regime") or {}).get("primary_regime", "unknown"))
370 if len(feature_vectors) < min_training_events:
371 LOGGER.info(
372 "train_topology: only %d usable events (need %d) - skipping, not writing artifacts.",
373 len(feature_vectors),
374 min_training_events,
375 )
376 return 0
378 fit_result = fit_prototypes(feature_vectors, outcome_labels, regime_labels, num_prototypes, distance_scale_percentile)
379 trained_at = datetime.now(timezone.utc).isoformat()
381 model_payload = {
382 "version_id": args.version_id,
383 # development/Problems.md #56: format identity for the
384 # prototypes[].offset contract, distinct from version_id
385 # (a pipeline run identity, not a schema version). 2 = z
386 # normalized to [-1, 1] (V4.1); no schema 1 model has ever
387 # existed to migrate from, so apply_learned_topology() has no
388 # legacy branch - this is purely a detection hook for any
389 # future contract change.
390 "offset_schema": 2,
391 "trained_at": trained_at,
392 "prototypes": fit_result["prototypes"],
393 "distance_scale": fit_result["distance_scale"],
394 "n_clusters": fit_result["n_clusters"],
395 }
396 feature_schema_payload = {
397 "feature_keys": list(FEATURE_KEYS),
398 "feature_stats": fit_result["feature_stats"],
399 }
400 training_metrics_payload = {
401 "project": "aether_quant",
402 "phase": "V2-17.5",
403 "version_id": args.version_id,
404 "trained_at": trained_at,
405 "training_window_days": lookback_days,
406 "source": getattr(args, "source", "postgres"),
407 "sample_count": len(feature_vectors),
408 "labeled_sample_count": sum(1 for label in outcome_labels if label is not None),
409 "n_clusters": fit_result["n_clusters"],
410 "distance_scale": fit_result["distance_scale"],
411 "per_cluster": [
412 {
413 "label": prototype["label"],
414 "sample_count": prototype["sample_count"],
415 "win_rate": prototype["win_rate"],
416 "dominant_regime_label": prototype["dominant_regime_label"],
417 }
418 for prototype in fit_result["prototypes"]
419 ],
420 }
422 paths = topology_candidate_output_paths(args.version_id)
423 paths["version_dir"].mkdir(parents=True, exist_ok=True)
424 paths["topology_model"].write_text(json.dumps(model_payload, indent=2), encoding="utf-8")
425 paths["topology_feature_schema"].write_text(json.dumps(feature_schema_payload, indent=2), encoding="utf-8")
426 paths["topology_training_metrics"].write_text(json.dumps(training_metrics_payload, indent=2), encoding="utf-8")
428 LOGGER.info(
429 "train_topology: wrote topology artifacts for version %s (%d clusters, %d samples).",
430 args.version_id,
431 fit_result["n_clusters"],
432 len(feature_vectors),
433 )
434 return 0
435 except Exception as exc: # never let an unexpected failure look ambiguous to the caller
436 LOGGER.error("train_topology: unexpected failure - %s", exc)
437 return 1
440if __name__ == "__main__":
441 sys.exit(main())