Coverage for train.py: 100%
2443 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"""
2Training pipeline for Aether Quant.
4Phase 3 extends the dataset pipeline with a first PyTorch model:
5- inspect and inventory the configured Lean data universe
6- build synchronized feature datasets with time-based splits
7- fit and persist a scaler
8- train an MLP classifier with validation and early stopping
9- export model metrics, checkpoint and Lean-readable weights
10"""
12from __future__ import annotations
14import argparse
15import bisect
16import copy
17import gc
18import json
19import logging
20import math
21import subprocess
22import sys
23import uuid
24from collections import Counter
25from datetime import datetime, timezone
26from pathlib import Path
27from zipfile import ZipFile
29import joblib
30import numpy as np
31import pandas as pd
32import torch
33from sklearn.preprocessing import StandardScaler
34from torch import nn
35from torch.utils.data import DataLoader, TensorDataset
37from data_pipeline.fred_backfill import ALT_DATA_PUBLICATION_LAG_DAYS, load_cached_fred_series, series_change_asof, series_value_asof
38from evaluation.model_predictions import predict_head
39from evaluation.rank_book_simulator import capacity_curve, simulate_rank_book, stress_test_costs, summarize_metric_stability
40from evaluation.rank_ic_core import rank_ic_from_arrays
41from execution.cost_model import commission_bps_by_ticker
42from experts import EXPERT_DEFINITIONS, build_expert_dataset_manifest, write_expert_dataset_artifacts
43from features import (
44 CREDIT_SPREAD_LEVEL_NEUTRAL,
45 CROSS_ASSET_SENSITIVITY_FEATURE_NAMES,
46 FINANCIAL_CONDITIONS_CHANGE_NEUTRAL,
47 IMPLIED_VOL_TERM_STRUCTURE_NEUTRAL,
48 IMPLIED_VOLATILITY_LEVEL_NEUTRAL,
49 YIELD_CURVE_CURVATURE_NEUTRAL,
50 YIELD_CURVE_LEVEL_NEUTRAL,
51 analytic_convexity,
52 analytic_modified_duration,
53 average_true_range_pct,
54 bollinger_pctb,
55 bond_dv01,
56 bond_yield_curve_slope,
57 compute_greeks,
58 credit_spread_level,
59 credit_spread_proxy,
60 cross_sectional_momentum_rank,
61 crypto_risk_appetite_proxy,
62 distance_from_52w_high,
63 empirical_duration_beta,
64 futures_term_structure_slope,
65 implied_vol_term_structure,
66 implied_volatility,
67 implied_volatility_level,
68 macd_histogram_normalized,
69 nearest_yield_curve_point,
70 options_implied_vol_skew,
71 options_put_call_ratio,
72 relative_strength_index,
73 rolling_sensitivity,
74 sensitivity_interaction,
75 volume_zscore,
76 yield_curve_curvature,
77 yield_curve_level,
78 yield_curve_slope_proxy,
79)
80from features import (
81 load_sector_mapping as _features_load_sector_mapping,
82)
83from features.bond_features import resolve_bond_duration_beta_mode, rolling_duration_beta_series
84from features.cross_asset_timing import (
85 CrossAssetTimeline,
86 day_ordinal,
87 fill_forward_open_forex_days,
88 resolve_forex_lean_holidays,
89)
90from features.fx_carry import FX_CARRY_FEATURE_NAME, FX_RATE_PUBLICATION_LAG_DAYS, fx_carry_3m
91from json_safety import atomic_write_json, load_json_lenient
93# V6.7.1: the networks, losses and training mechanics live in the shipped lab package; re-exported here because the
94# trainers, saved artifacts and tests name them as train.<name>.
95from lab.architectures import ( # noqa: F401
96 DEFAULT_HORIZON_HEAD_CONFIG,
97 EXTRA_HORIZON_HEAD_SPECS,
98 HORIZON_HEAD_SPECS,
99 AetherNet,
100 AetherNetMultiTask,
101 AetherNetMultiTaskHorizons,
102 AetherNetSequenceMultiTask,
103 AetherNetSequenceMultiTaskHorizons,
104 _export_conv1d_trunk,
105 _export_head,
106 _export_sequential_layers,
107 build_activation,
108 build_normalization,
109 enabled_extra_heads,
110 export_architecture,
111 export_multitask_architecture,
112 export_multitask_horizons_architecture,
113 export_sequence_multitask_architecture,
114 export_sequence_multitask_horizons_architecture,
115 export_state_dict,
116 horizon_head_specs,
117 resolve_horizon_head_config,
118)
119from lab.losses import ( # noqa: F401
120 _pairwise_consistency_penalty,
121 add_rank_label_noise,
122 class_group_ids,
123 compute_combined_multitask_loss,
124 compute_cross_sectional_ranking_loss,
125 compute_horizon_consistency_loss,
126 ic_pearson_loss,
127 listnet_loss,
128 long_short_sharpe_loss,
129 masked_bce_with_logits_loss,
130 masked_mse_loss,
131 rank_turnover_penalty,
132 row_context_targets,
133 soft_rank_within_groups,
134 soft_spearman_loss,
135)
136from lab.objectives import CONTEXT_CLASSES, CONTEXT_OBJECTIVES, RANKING_OBJECTIVES # noqa: F401
137from lab.training_utils import ( # noqa: F401
138 CrossSectionalDateBatchSampler,
139 build_cross_sectional_date_batches,
140 build_date_group_ids,
141 build_lr_scheduler,
142 build_optimizer,
143 is_new_best_epoch,
144 set_seed,
145 smoothed_metric,
146 swa_accumulate,
147 swa_finalize,
148)
149from liquidity import estimate_high_low_spread
150from liquidity.market_liquidity import TYPICAL_SPREAD_BY_TYPE
151from performance_probe import install_sigterm_witness
152from regime import build_model_input_regime_vector
153from topology import build_market_topology
154from topology.market_topology import ELEVATED_VOLATILITY_THRESHOLD, resolve_elevated_volatility_thresholds
156LOGGER = logging.getLogger("aether_quant.train")
157ROOT = Path(__file__).resolve().parent
158DATA_DIR = ROOT / "data"
159FACTOR_FILES_DIR = DATA_DIR / "equity" / "usa" / "factor_files"
160SECTOR_MAPPING_PATH = DATA_DIR / "reference" / "sector_mapping.json"
161ML_DIR = ROOT / "ml"
162DATASET_DIR = ML_DIR / "datasets"
163EXPERT_DATASET_DIR = ML_DIR / "expert_datasets"
164EXPERT_MODEL_DIR = ML_DIR / "expert_models"
165BACKTESTS_DIR = ROOT / "backtests"
166VIS_DIR = ROOT / "visualization"
167GRAFANA_DIR = VIS_DIR / "grafana"
168CONFIG_PATH = ROOT / "config.json"
169MODEL_WEIGHTS_PATH = ML_DIR / "model_weights.json"
170MODEL_CHECKPOINT_PATH = ML_DIR / "model.pt"
171TRAINING_METRICS_PATH = ML_DIR / "training_metrics.json"
172EXPERT_TRAINING_METRICS_PATH = ML_DIR / "expert_training_metrics.json"
173INVENTORY_PATH = ML_DIR / "dataset_inventory.json"
174DATASET_MANIFEST_PATH = ML_DIR / "dataset_manifest.json"
175EXPERT_DATASET_MANIFEST_PATH = ML_DIR / "expert_dataset_manifest.json"
176FEATURE_SCHEMA_PATH = ML_DIR / "feature_schema.json"
177SCALER_PATH = ML_DIR / "scaler.pkl"
178SCALER_STATS_PATH = ML_DIR / "scaler_stats.json"
179STATE_PATH = VIS_DIR / "state.json"
180SCENE_PATH = VIS_DIR / "scene.json"
181GRAFANA_METRICS_PATH = GRAFANA_DIR / "metrics_snapshot.json"
182GRAFANA_EQUITY_CURVES_PATH = GRAFANA_DIR / "equity_curves.csv"
183GRAFANA_ASSET_PERFORMANCE_PATH = GRAFANA_DIR / "asset_performance.csv"
184STRATEGY_REPORT_PATH = BACKTESTS_DIR / "strategy_report.json"
185EQUITY_CURVES_PATH = BACKTESTS_DIR / "equity_curves.csv"
187FULL_DATASET_PATH = DATASET_DIR / "full_dataset.csv"
188TRAIN_DATASET_PATH = DATASET_DIR / "train_dataset.csv"
189VALIDATION_DATASET_PATH = DATASET_DIR / "validation_dataset.csv"
190BACKTEST_DATASET_PATH = DATASET_DIR / "backtest_dataset.csv"
192RAW_COLUMNS = ["timestamp", "open", "high", "low", "close", "volume"]
193# Lean's forex daily bars are 10-column quote bars (bid OHLCV + ask OHLCV
194# after the timestamp), not the 5-column trade-bar shape every other asset
195# class here uses - see data_pipeline/yfinance_backfill.py's forex writer.
196# load_lean_bars() collapses these to a midpoint trade bar for training.
197FOREX_RAW_COLUMNS = [
198 "timestamp",
199 "bid_open", "bid_high", "bid_low", "bid_close", "bid_volume",
200 "ask_open", "ask_high", "ask_low", "ask_close", "ask_volume",
201]
202PRICE_COLUMNS = ["open", "high", "low", "close"]
205def parse_args() -> argparse.Namespace:
206 parser = argparse.ArgumentParser(description="Aether Quant training pipeline")
207 parser.add_argument(
208 "--init-only",
209 action="store_true",
210 help="Refresh inventory and placeholders without building datasets or training."
211 )
212 parser.add_argument(
213 "--dataset-only",
214 action="store_true",
215 help="Build dataset artifacts and scaler, but skip model training."
216 )
217 parser.add_argument(
218 "--experts-only",
219 action="store_true",
220 help="Build datasets and train V2 expert models, but skip the baseline model."
221 )
222 parser.add_argument(
223 "--candidate",
224 action="store_true",
225 help="Train a candidate model into ml/versions/<version-id>/ without touching the active model (V2-17)."
226 )
227 parser.add_argument(
228 "--version-id",
229 type=str,
230 default=None,
231 help="Candidate model_version_id (UUID). Required with --candidate."
232 )
233 parser.add_argument(
234 "--walk-forward",
235 action="store_true",
236 help=(
237 "Phase 4 of the 5/10 -> 9/10 roadmap: run the baseline model's dataset-build + "
238 "training pipeline once per walk-forward window (see generate_walk_forward_windows()) "
239 "instead of once on the fixed phase1.windows. Never touches active ml/ - each window "
240 "writes to ml/versions/<run-id>/window_<i>/, same as --candidate."
241 ),
242 )
243 parser.add_argument(
244 "--step-days",
245 type=int,
246 default=None,
247 help="Walk-forward step size in days. Defaults to phase_v2.retraining.walk_forward.step_days.",
248 )
249 parser.add_argument(
250 "--mode",
251 type=str,
252 choices=("rolling", "expanding"),
253 default=None,
254 help="Walk-forward mode. Defaults to phase_v2.retraining.walk_forward.mode.",
255 )
256 parser.add_argument(
257 "--resume-run-id",
258 type=str,
259 default=None,
260 help="Continue an interrupted --walk-forward run: windows with a window_result.json under "
261 "ml/versions/<run-id>/ are loaded instead of retrained (a VM reboot then only costs the window in flight).",
262 )
263 # V5.1 Phase 4 (item 4) - one-run overrides of walk_forward.train_multitask/
264 # train_sequence/tracked_metrics, same --seed/--ranking-objective
265 # precedent as train_multitask.py/train_sequence.py: None (default)
266 # leaves config.json's own values unchanged, only --walk-forward reads
267 # these (aq_cli.py::cmd_train() warns, doesn't silently ignore, if
268 # passed without --walk-forward - same convention as --seed there).
269 # V6.6.10: `low` keeps the frame float32 before training and passes the profile to every walk-forward window's trainers
270 # (lazy sequence windows, chunked reads, per-epoch checkpoints), so the stack retrains on a 4 GB machine.
271 parser.add_argument(
272 "--run-id-file",
273 type=str,
274 default=None,
275 help="With --walk-forward: write the run id here as soon as it is known, so a stopped run can be resumed (`aq cycle retrain --resume`)",
276 )
277 parser.add_argument(
278 "--write-dataset",
279 action="store_true",
280 help="With --candidate: also write the built dataset to ml/versions/<version-id>/full_dataset.csv (the stack retrain's later trainers read it)",
281 )
282 parser.add_argument(
283 "--memory-profile",
284 choices=("standard", "low"),
285 default="standard",
286 help="standard (default) or low: train on a small machine (the trainers' own --memory-profile)",
287 )
288 parser.add_argument(
289 "--include-multitask",
290 action="store_true",
291 default=None,
292 help="Force walk_forward.train_multitask on for this run (only with --walk-forward).",
293 )
294 parser.add_argument(
295 "--include-sequence",
296 action="store_true",
297 default=None,
298 help="Force walk_forward.train_sequence on for this run (only with --walk-forward).",
299 )
300 parser.add_argument(
301 "--metrics",
302 type=str,
303 default=None,
304 help=(
305 "Comma-separated tracked-metric names to restrict walk_forward.tracked_metrics to for this run "
306 "(only with --walk-forward) - each name must already exist in config.json's tracked_metrics list."
307 ),
308 )
309 return parser.parse_args()
312def setup_logging() -> None:
313 logging.basicConfig(
314 level=logging.INFO,
315 format="%(asctime)s %(levelname)s %(name)s: %(message)s",
316 )
319def ensure_directories() -> None:
320 for path in (
321 ML_DIR,
322 DATASET_DIR,
323 EXPERT_DATASET_DIR,
324 EXPERT_MODEL_DIR,
325 ML_DIR / "versions",
326 VIS_DIR,
327 GRAFANA_DIR,
328 BACKTESTS_DIR,
329 ):
330 path.mkdir(parents=True, exist_ok=True)
333def candidate_output_paths(version_id: str) -> dict[str, Path]:
334 """Every artifact path a `--candidate --version-id <id>` run writes to,
335 all under ml/versions/<id>/ - never the active ml/ paths (Phase V2-17)."""
336 version_dir = ML_DIR / "versions" / version_id
337 return {
338 "version_dir": version_dir,
339 "model_checkpoint": version_dir / "model.pt",
340 "model_weights": version_dir / "model_weights.json",
341 "training_metrics": version_dir / "training_metrics.json",
342 "strategy_report": version_dir / "strategy_report.json",
343 "equity_curves": version_dir / "equity_curves.csv",
344 "scaler": version_dir / "scaler.pkl",
345 "scaler_stats": version_dir / "scaler_stats.json",
346 "feature_schema": version_dir / "feature_schema.json",
347 "dataset_manifest": version_dir / "dataset_manifest.json",
348 # V5.1 Phase 4, Step 4.1 - only _run_walk_forward() writes this today
349 # (per-window data genuinely differs; the regular --candidate path
350 # trains against the shared active ml/datasets/full_dataset.csv and
351 # has no per-candidate dataset of its own).
352 "full_dataset": version_dir / "full_dataset.csv",
353 }
356def validate_training_inputs(config: dict) -> list[str]:
357 issues: list[str] = []
358 phase1 = config.get("phase1", {})
359 universe = phase1.get("universe", {})
360 windows = phase1.get("windows", {})
361 assets = universe.get("assets", [])
363 if not assets:
364 issues.append("No assets configured in phase1.universe.assets.")
366 for asset in assets:
367 ticker = asset.get("ticker", "<missing ticker>")
368 data_path = asset.get("data_path")
369 if not data_path:
370 issues.append(f"{ticker}: missing data_path.")
371 continue
372 if not (ROOT / data_path).exists() and not asset.get("derived_from"):
373 issues.append(f"{ticker}: data file does not exist: {data_path}.")
375 for split_name in ("training", "validation", "backtest"):
376 split_window = windows.get(split_name)
377 if not split_window:
378 issues.append(f"Missing phase1.windows.{split_name}.")
379 continue
380 try:
381 start = pd.Timestamp(split_window["start"])
382 end = pd.Timestamp(split_window["end"])
383 except (KeyError, ValueError, TypeError) as error:
384 issues.append(f"{split_name}: invalid date window: {error}.")
385 continue
386 if start > end:
387 issues.append(f"{split_name}: start date is after end date.")
389 return issues
392def raise_if_validation_failed(issues: list[str]) -> None:
393 if not issues:
394 return
395 formatted = "\n".join(f"- {issue}" for issue in issues)
396 raise ValueError(f"Training input validation failed:\n{formatted}")
399def load_project_config() -> dict:
400 return json.loads(CONFIG_PATH.read_text(encoding="utf-8"))
403def ensure_derived_crypto_daily_series(config: dict) -> None:
404 for asset in config["phase1"]["universe"]["assets"]:
405 derived_from = asset.get("derived_from")
406 aggregation = asset.get("aggregation")
407 if not derived_from or aggregation != "daily_from_minute_trade":
408 continue
410 source_dir = ROOT / derived_from
411 output_zip = ROOT / asset["data_path"]
412 if not source_dir.exists():
413 continue
415 trade_files = sorted(source_dir.glob("*_trade.zip"))
416 if not trade_files:
417 continue
419 daily_rows: list[str] = []
420 for trade_zip in trade_files:
421 date_token = trade_zip.stem.split("_")[0]
422 try:
423 session_date = datetime.strptime(date_token, "%Y%m%d")
424 except ValueError:
425 continue
427 with ZipFile(trade_zip) as archive:
428 member = archive.namelist()[0]
429 with archive.open(member) as handle:
430 frame = pd.read_csv(handle, header=None, names=RAW_COLUMNS)
432 frame["timestamp"] = pd.to_numeric(frame["timestamp"], errors="coerce")
433 for column in PRICE_COLUMNS + ["volume"]:
434 frame[column] = pd.to_numeric(frame[column], errors="coerce")
436 frame = frame.dropna(subset=["timestamp", "open", "high", "low", "close", "volume"]).sort_values("timestamp")
437 if frame.empty:
438 continue
440 open_price = float(frame.iloc[0]["open"])
441 high_price = float(frame["high"].max())
442 low_price = float(frame["low"].min())
443 close_price = float(frame.iloc[-1]["close"])
444 volume_value = float(frame["volume"].sum())
445 daily_rows.append(
446 f"{session_date.strftime('%Y%m%d')} 00:00,{open_price},{high_price},{low_price},{close_price},{volume_value}"
447 )
449 if not daily_rows:
450 continue
452 # Merge with whatever is already on disk (e.g. yfinance-backfilled
453 # history from data_pipeline/yfinance_backfill.py) instead of
454 # clobbering it — freshly computed minute-derived rows win on any
455 # overlapping date since they're real trade data, but backfilled
456 # rows for dates with no minute data must survive this rebuild.
457 existing_lines: dict[str, str] = {}
458 if output_zip.exists():
459 with ZipFile(output_zip) as archive:
460 member = archive.namelist()[0]
461 with archive.open(member) as handle:
462 for line in handle.read().decode("utf-8").splitlines():
463 if line.strip():
464 existing_lines[line.split(",")[0].split()[0]] = line
466 for line in daily_rows:
467 existing_lines[line.split(",")[0].split()[0]] = line
469 merged_lines = [existing_lines[key] for key in sorted(existing_lines)]
471 output_zip.parent.mkdir(parents=True, exist_ok=True)
472 member_name = f"{asset['ticker'].lower()}.csv"
473 with ZipFile(output_zip, "w") as archive:
474 archive.writestr(member_name, "\n".join(merged_lines) + "\n")
477def summarize_data_tree(limit: int = 12) -> dict:
478 if not DATA_DIR.exists():
479 return {"available": False, "asset_groups": [], "sample_files": []}
481 group_counter: Counter[str] = Counter()
482 sample_files: list[str] = []
484 for file_path in DATA_DIR.rglob("*"):
485 if not file_path.is_file():
486 continue
488 relative_parts = file_path.relative_to(DATA_DIR).parts
489 if relative_parts:
490 group_counter[relative_parts[0]] += 1
491 if len(sample_files) < limit:
492 sample_files.append(str(file_path.relative_to(ROOT)))
494 return {
495 "available": True,
496 "asset_groups": [{"name": name, "files": count} for name, count in sorted(group_counter.items())],
497 "sample_files": sample_files,
498 }
501def inspect_zip_timeseries(relative_path: str) -> dict:
502 path = ROOT / relative_path
503 if not path.exists():
504 return {
505 "path": relative_path,
506 "available": False,
507 "rows": 0,
508 "start": None,
509 "end": None,
510 }
512 with ZipFile(path) as archive:
513 member = archive.namelist()[0]
514 rows = archive.read(member).decode("utf-8").splitlines()
516 first_timestamp = rows[0].split(",")[0].split()[0] if rows else None
517 last_timestamp = rows[-1].split(",")[0].split()[0] if rows else None
518 return {
519 "path": relative_path,
520 "available": True,
521 "rows": len(rows),
522 "start": first_timestamp,
523 "end": last_timestamp,
524 }
527def list_directory(relative_path: str) -> list[str]:
528 path = ROOT / relative_path
529 if not path.exists():
530 return []
531 return sorted(item.name for item in path.iterdir())
534def build_phase_inventory(config: dict, data_summary: dict) -> dict:
535 phase1 = config["phase1"]
536 coverage_checks = []
537 for asset in phase1["universe"]["assets"]:
538 coverage = inspect_zip_timeseries(asset["data_path"])
539 coverage_checks.append(
540 {
541 "ticker": asset["ticker"],
542 "security_type": asset["security_type"],
543 "market": asset["market"],
544 **coverage,
545 }
546 )
548 candidates = {
549 "equity_daily": list_directory("data/equity/usa/daily"),
550 "equity_hour": list_directory("data/equity/usa/hour"),
551 "equity_minute": list_directory("data/equity/usa/minute"),
552 "crypto_coinbase_daily": list_directory("data/crypto/coinbase/daily"),
553 "crypto_coinbase_minute": list_directory("data/crypto/coinbase/minute"),
554 "cryptofuture_binance_daily": list_directory("data/cryptofuture/binance/daily"),
555 "cryptofuture_binance_minute": list_directory("data/cryptofuture/binance/minute"),
556 }
558 return {
559 "project": config["name"],
560 "phase": 3,
561 "created_at": datetime.now(timezone.utc).isoformat(),
562 "objective": phase1["objective"],
563 "high_level_data_summary": data_summary,
564 "candidate_sets": candidates,
565 "configured_universe": phase1["universe"],
566 "configured_windows": phase1["windows"],
567 "configured_features": phase1["features"],
568 "configured_target": phase1["target"],
569 "configured_model": config["phase3"]["model"],
570 "coverage_checks": coverage_checks,
571 }
574def load_factor_file(ticker: str) -> pd.DataFrame | None:
575 """Reads a Lean-format equity factor file (date, price_factor,
576 split_factor, reference_price - no header), the exact file Lean's own
577 engine consults to apply DataNormalizationMode.Adjusted (the default
578 main.py's runtime self.add_equity(ticker, self.resolution) subscription
579 already gets - see apply_split_adjustments()'s docstring). Returns None
580 when the file doesn't exist (e.g. AAA's thin history) - callers must
581 degrade to an identity/no-adjustment fallback, never raise."""
582 path = FACTOR_FILES_DIR / f"{ticker.lower()}.csv"
583 if not path.exists():
584 return None
586 factors = pd.read_csv(path, header=None, names=["factor_date", "price_factor", "split_factor", "reference_price"])
587 factors["factor_date"] = pd.to_datetime(factors["factor_date"], format="%Y%m%d", errors="coerce")
588 factors = factors.dropna(subset=["factor_date"]).sort_values("factor_date").reset_index(drop=True)
589 return factors if not factors.empty else None
592def apply_split_adjustments(frame: pd.DataFrame, ticker: str) -> pd.DataFrame:
593 """Backward-adjusts a raw per-asset OHLCV frame for splits/dividends
594 using Lean's own factor files - the same adjustment
595 DataNormalizationMode.Adjusted already applies to main.py's live/
596 backtest data feed at runtime (Lean's default for AddEquity()), which
597 load_lean_bars() never applied until now since it reads the raw daily
598 zip directly, bypassing Lean's data engine entirely.
600 Without this, a raw stock split (e.g. AAPL's 2020-08-31 4-for-1 split,
601 or USO's 2020-04-28 1-for-8 reverse split) shows up as an impossible
602 single-day return in every offline trainer's dataset even though
603 main.py's real backtest never sees it - a genuine train/runtime
604 feature-parity gap, not merely a label-outlier nuisance (see
605 development/Problems.md's full incident writeup). No main.py mirror is
606 needed for this fix, unlike the volume_change_1d clamp above - Lean's
607 engine already does this adjustment for main.py, only train.py's
608 from-scratch zip reader was missing it.
610 For each row dated D, finds the factor-file row with the smallest
611 factor_date >= D (pd.merge_asof(direction="forward"), Lean's own
612 lookup convention) and multiplies open/high/low/close by that row's
613 price_factor * split_factor, dividing volume by split_factor alone (a
614 cash dividend doesn't change share count, only a split does). Rows
615 dated after every factor-file entry (none in this dataset's window,
616 but a safe fallback matching Lean's own far-future sentinel row) get
617 factor 1.0 - i.e. no adjustment.
618 """
619 factors = load_factor_file(ticker)
620 if factors is None:
621 return frame
623 result = frame.sort_values("date").reset_index(drop=True)
624 merged = pd.merge_asof(
625 result[["date"]],
626 factors.rename(columns={"factor_date": "date"}),
627 on="date",
628 direction="forward",
629 )
630 price_factor = merged["price_factor"].fillna(1.0).to_numpy()
631 split_factor = merged["split_factor"].fillna(1.0).to_numpy()
632 combined_factor = price_factor * split_factor
634 result = result.copy()
635 for column in ("open", "high", "low", "close"):
636 result[column] = result[column].to_numpy() * combined_factor
637 result["volume"] = result["volume"].to_numpy() / split_factor
638 return result
641def load_lean_bars(asset: dict, common_window: dict, apply_factor_files: bool = True) -> pd.DataFrame:
642 """`apply_factor_files=False` is for the out-of-window holdout root (V5.7.0), whose zips are written from Yahoo's
643 already split/dividend-adjusted prices: Lean's factor files would adjust them a second time (Problems.md #130)."""
644 path = ROOT / asset["data_path"]
645 is_forex = asset["security_type"] == "forex"
646 with ZipFile(path) as archive:
647 member = archive.namelist()[0]
648 with archive.open(member) as handle:
649 frame = pd.read_csv(handle, header=None, names=FOREX_RAW_COLUMNS if is_forex else RAW_COLUMNS)
651 if is_forex:
652 # Collapse the 10-column bid/ask quote bar to a midpoint trade bar:
653 # open/high/low/close = (bid + ask) / 2, volume 0.0 - byte-for-byte
654 # the same midpoint main.py's runtime _quote_bar_to_trade_bar_midpoint()
655 # feeds the model for forex symbols, so offline training and live
656 # inference see the identical price series (train/serve parity).
657 for column in PRICE_COLUMNS:
658 bid = pd.to_numeric(frame[f"bid_{column}"], errors="coerce")
659 ask = pd.to_numeric(frame[f"ask_{column}"], errors="coerce")
660 frame[column] = (bid + ask) / 2.0
661 frame["volume"] = 0.0
662 frame = frame[["timestamp", *PRICE_COLUMNS, "volume"]]
664 frame["timestamp"] = pd.to_datetime(frame["timestamp"], format="%Y%m%d %H:%M", errors="coerce")
665 for column in PRICE_COLUMNS + ["volume"]:
666 frame[column] = pd.to_numeric(frame[column], errors="coerce")
668 if asset["security_type"] == "equity":
669 frame[PRICE_COLUMNS] = frame[PRICE_COLUMNS] / 10000.0
671 frame = frame.dropna(subset=["timestamp", "open", "high", "low", "close", "volume"]).copy()
672 frame["date"] = frame["timestamp"].dt.normalize()
673 frame = frame.sort_values("date").drop_duplicates(subset="date", keep="last")
675 if asset["security_type"] == "equity" and apply_factor_files:
676 frame = apply_split_adjustments(frame, asset["ticker"])
678 start = pd.Timestamp(common_window["start"])
679 end = pd.Timestamp(common_window["end"])
680 frame = frame[(frame["date"] >= start) & (frame["date"] <= end)].copy()
682 frame["ticker"] = asset["ticker"]
683 frame["security_type"] = asset["security_type"]
684 frame["market"] = asset["market"]
685 return frame.reset_index(drop=True)
688def synchronize_assets(asset_frames: dict[str, pd.DataFrame]) -> tuple[dict[str, pd.DataFrame], list[pd.Timestamp]]:
689 common_dates: set[pd.Timestamp] | None = None
691 for frame in asset_frames.values():
692 date_set = set(frame["date"].tolist())
693 common_dates = date_set if common_dates is None else common_dates & date_set
695 ordered_dates = sorted(common_dates or [])
696 synchronized = {}
697 for ticker, frame in asset_frames.items():
698 synchronized[ticker] = (
699 frame[frame["date"].isin(ordered_dates)]
700 .sort_values("date")
701 .reset_index(drop=True)
702 )
703 return synchronized, ordered_dates
706from features.training_splits import _SPLIT_ORDER, assign_split, assign_split_series, purge_label_overlap, purge_label_overlap_calendar, purged_embargoed_folds # noqa: E402,F401
709def resident_memory_mb() -> tuple[float, float] | None:
710 """(current, peak) resident set of this process in MB from /proc/self/status; on Windows from GetProcessMemoryInfo (V6.6.10,
711 so a run on the 4 GB PC logs its memory too); None where neither exists."""
712 if sys.platform == "win32":
713 from retraining.slicing import process_memory_mb
715 return process_memory_mb()
716 try:
717 values = {}
718 with open("/proc/self/status", encoding="ascii") as handle:
719 for line in handle:
720 if line.startswith(("VmRSS:", "VmHWM:")):
721 values[line.split(":")[0]] = float(line.split()[1]) / 1024.0
722 return values["VmRSS"], values["VmHWM"]
723 except (OSError, KeyError, ValueError):
724 return None
727def log_resident_memory(label: str) -> None:
728 """One INFO line with the process's resident and peak memory - the Codespace SIGTERMs a process that crowds its
729 7.8 GB with no swap (Problems #83), and without this line a kill is a mystery (V5.8.0)."""
730 memory = resident_memory_mb()
731 if memory is not None:
732 LOGGER.info("memory %s: rss=%.0f MB peak=%.0f MB", label, memory[0], memory[1])
735def compact_dataset_for_training(dataset: pd.DataFrame) -> pd.DataFrame:
736 """float64 -> float32 for the in-memory frame that the baseline and expert trainers read (V5.8.0): the CSVs are already
737 written in float64, every trainer converts to float32 tensors, and the 280k x 251 frame is 560 MB that sat beside the
738 trainers' own copies on a machine that kills at ~5 GB. Columns that are not float64 are untouched."""
739 float_columns = dataset.columns[dataset.dtypes == np.float64]
740 if len(float_columns):
741 dataset[float_columns] = dataset[float_columns].astype(np.float32)
742 gc.collect()
743 return dataset
746# volume_change_1d clamp bounds - see the comment at its append() call
747# below for why. Duplicated (not imported) in main.py::_build_model_input()
748# since main.py never imports train.py (heavy training-only deps).
749VOLUME_CHANGE_FLOOR = -1.0
750VOLUME_CHANGE_CEILING = 20.0
752# Matches main.py's self.symbol_long_windows (deque(maxlen=260)) - the
753# long-lookback indicators (macd_histogram_normalized/distance_from_52w_high)
754# recompute fresh from whatever window they're given (see
755# features/technical_indicators.py's docstring), so offline must slice to
756# this SAME bounded window for train/runtime parity, not pass unbounded
757# full history (which would make the offline EMA/high-water-mark reflect a
758# different, longer lookback than the live buffer ever sees).
759LONG_LOOKBACK_WINDOW_BARS = 260
762# Fallback per-security-type bounds for the label-outlier guards below,
763# used when config.json's phase1.target.max_abs_* keys are absent (older
764# configs / test fixtures) - real config values should be preferred, these
765# are only safety-net defaults. Horizon bounds widen with the window since
766# more trading days give more room for genuine cumulative moves.
767DEFAULT_MAX_ABS_DAILY_RETURN = {"equity": 0.5, "crypto": 1.5}
768DEFAULT_MAX_ABS_RETURN_5D = {"equity": 0.9, "crypto": 2.5}
769DEFAULT_MAX_ABS_RETURN_20D = {"equity": 1.5, "crypto": 4.0}
772def resolve_extra_horizon_days(config: dict) -> tuple[int, ...]:
773 """`phase1.target.ranking.extra_horizon_days` (V6.0.0): forward-return / rank targets beyond the built-in 5 and 20
774 days (empty = none, the old dataset). The label purge must cover the longest one, or the last rows of a split would
775 carry the next split's prices."""
776 target = config.get("phase1", {}).get("target", {})
777 days = tuple(sorted({int(day) for day in target.get("ranking", {}).get("extra_horizon_days", []) or []} - {5, 20}))
778 purge = int(config.get("phase1", {}).get("windows", {}).get("purge_label_horizon_days", 0) or 0)
779 if days and purge < max(days):
780 raise ValueError(f"purge_label_horizon_days {purge} is shorter than the {max(days)}-day target")
781 return days
784def extra_horizon_return_bound(horizon_days: int, security_type: str, bounds_20d: dict) -> float:
785 """|forward return| above which an extra-horizon target is treated as a data error: the 20-day bound scaled by
786 sqrt(horizon / 20), like a random walk's spread."""
787 base = float(bounds_20d.get(security_type, bounds_20d.get("equity", 1.5)))
788 return base * float(np.sqrt(horizon_days / 20.0))
791def engineer_features(
792 frame: pd.DataFrame,
793 feature_names: list[str],
794 windows: dict,
795 *,
796 security_type: str = "equity",
797 max_abs_daily_return: dict | None = None,
798 max_abs_return_5d: dict | None = None,
799 max_abs_return_20d: dict | None = None,
800 extra_horizon_days: tuple[int, ...] = (),
801) -> pd.DataFrame:
802 result = frame.copy()
803 closes = result["close"].tolist()
804 opens = result["open"].tolist()
805 highs = result["high"].tolist()
806 lows = result["low"].tolist()
807 volumes = result["volume"].tolist()
809 close_to_close_return_1d: list[float] = [np.nan]
810 close_to_close_return_5d: list[float] = [np.nan]
811 close_to_close_return_20d: list[float] = [np.nan]
812 rolling_volatility_5d: list[float] = [np.nan]
813 rolling_volatility_20d: list[float] = [np.nan]
814 momentum_5d: list[float] = [np.nan]
815 momentum_20d: list[float] = [np.nan]
816 high_low_range_pct: list[float] = [np.nan]
817 open_close_range_pct: list[float] = [np.nan]
818 volume_change_1d: list[float] = [np.nan]
819 # Phase 6 technical indicators - shared pure implementations
820 # (features/technical_indicators.py) imported at module level above, so
821 # this loop and main.py::_build_model_input() compute every one
822 # identically by construction. rsi_14/atr_pct_14/bollinger_pctb_20/
823 # volume_zscore_20 only ever look at their own trailing period (<=20
824 # bars), so passing this loop's full growing `closes[:index+1]` slice
825 # produces the same result as main.py's bounded 25-bar
826 # self.symbol_windows buffer once enough history exists - no explicit
827 # truncation needed. macd_histogram_normalized/distance_from_52w_high
828 # DO care about how much history they're given (fresh EMA/rolling-max
829 # each call), so those two are explicitly capped to
830 # LONG_LOOKBACK_WINDOW_BARS to match main.py's self.symbol_long_windows
831 # buffer size.
832 rsi_14: list[float] = [np.nan]
833 atr_pct_14: list[float] = [np.nan]
834 bollinger_pctb_20: list[float] = [np.nan]
835 volume_zscore_20: list[float] = [np.nan]
836 macd_histogram_norm: list[float] = [np.nan]
837 dist_52w_high: list[float] = [np.nan]
839 for index in range(1, len(result)):
840 previous_close = closes[index - 1]
841 previous_volume = volumes[index - 1]
842 current_close = closes[index]
843 current_open = opens[index]
845 lookback_5_index = max(0, index - 5)
846 lookback_20_index = max(0, index - 20)
847 close_5 = closes[lookback_5_index]
848 close_20 = closes[lookback_20_index]
850 all_recent_returns = [
851 closes[position] / closes[position - 1] - 1.0
852 for position in range(1, index + 1)
853 if closes[position - 1] != 0
854 ]
855 recent_returns_5 = all_recent_returns[-5:]
856 recent_returns_20 = all_recent_returns[-20:]
858 close_to_close_return_1d.append(current_close / previous_close - 1.0 if previous_close else 0.0)
859 close_to_close_return_5d.append(current_close / close_5 - 1.0 if close_5 else 0.0)
860 close_to_close_return_20d.append(current_close / close_20 - 1.0 if close_20 else 0.0)
861 rolling_volatility_5d.append(float(np.std(recent_returns_5, ddof=1)) if len(recent_returns_5) >= 2 else 0.0)
862 rolling_volatility_20d.append(float(np.std(recent_returns_20, ddof=1)) if len(recent_returns_20) >= 2 else 0.0)
863 momentum_5d.append(current_close / close_5 - 1.0 if close_5 else 0.0)
864 momentum_20d.append(current_close / close_20 - 1.0 if close_20 else 0.0)
865 high_low_range_pct.append((highs[index] - lows[index]) / current_close if current_close else 0.0)
866 open_close_range_pct.append((current_close - current_open) / current_open if current_open else 0.0)
867 raw_volume_change = 0.0 if previous_volume == 0 else volumes[index] / previous_volume - 1.0
868 # Clamped to [-1.0, 20.0] (volume can't fall more than 100%, and a
869 # >2000% single-day jump is a data-feed unit discontinuity, not a
870 # real signal - see BTCUSD 2018-08-14's raw volume jumping ~520,000x
871 # in one day, traced in development/Problems.md). Mirrored exactly
872 # in main.py::_build_model_input() for train/runtime parity.
873 volume_change_1d.append(max(VOLUME_CHANGE_FLOOR, min(VOLUME_CHANGE_CEILING, raw_volume_change)))
875 trailing_closes = closes[: index + 1]
876 rsi_14.append(relative_strength_index(trailing_closes, period=14))
877 atr_pct_14.append(average_true_range_pct(highs[: index + 1], lows[: index + 1], trailing_closes, period=14))
878 bollinger_pctb_20.append(bollinger_pctb(trailing_closes, period=20))
879 volume_zscore_20.append(volume_zscore(volumes[: index + 1], period=20))
881 long_window_start = max(0, index + 1 - LONG_LOOKBACK_WINDOW_BARS)
882 long_trailing_closes = closes[long_window_start : index + 1]
883 macd_histogram_norm.append(macd_histogram_normalized(long_trailing_closes))
884 dist_52w_high.append(distance_from_52w_high(long_trailing_closes, window=LONG_LOOKBACK_WINDOW_BARS))
886 result["close_to_close_return_1d"] = close_to_close_return_1d
887 result["close_to_close_return_5d"] = close_to_close_return_5d
888 result["close_to_close_return_20d"] = close_to_close_return_20d
889 result["rolling_volatility_5d"] = rolling_volatility_5d
890 result["rolling_volatility_20d"] = rolling_volatility_20d
891 result["momentum_5d"] = momentum_5d
892 result["momentum_20d"] = momentum_20d
893 result["high_low_range_pct"] = high_low_range_pct
894 result["open_close_range_pct"] = open_close_range_pct
895 result["volume_change_1d"] = volume_change_1d
896 result["rsi_14"] = rsi_14
897 result["atr_pct_14"] = atr_pct_14
898 result["bollinger_pctb_20"] = bollinger_pctb_20
899 result["volume_zscore_20"] = volume_zscore_20
900 result["macd_histogram_norm"] = macd_histogram_norm
901 result["dist_52w_high"] = dist_52w_high
903 result["target_return_1d"] = result["close"].shift(-1) / result["close"] - 1.0
905 # Label-outlier guard: an unadjusted stock split (AAPL's 2020-08-28
906 # 4-for-1 split shows as a fake -74% "return") or unadjusted reverse
907 # split (USO's 2020-04-28 1-for-8 shows as +745%) produces an
908 # impossible single-day return that corrupts target_direction/
909 # target_return_1d for every trainer reading this column. Bounds are
910 # per security-type since real crypto moves (e.g. XRP's 2021-01-29
911 # +56%) can legitimately exceed any equity-sane threshold. NaN'd out
912 # here so the existing dropna(required_columns) below removes the row
913 # exactly like any other missing-label row - not winsorized, since a
914 # clipped fake -74% is still a fake "down" label, not a smaller real
915 # one. See development/Problems.md for the full incident writeup.
916 return_bounds = max_abs_daily_return or DEFAULT_MAX_ABS_DAILY_RETURN
917 return_bound = float(return_bounds.get(security_type, return_bounds.get("equity", 0.5)))
918 impossible_return = result["target_return_1d"].abs() > return_bound
919 result.loc[impossible_return, "target_return_1d"] = np.nan
921 result["target_direction"] = np.where(
922 result["target_return_1d"].notna(),
923 (result["target_return_1d"] > 0).astype(int),
924 np.nan,
925 )
927 # Multi-horizon targets (5d/20d) - the highest-leverage change this
928 # codebase's root-cause investigation identified: next-day binary
929 # direction on liquid daily bars is close to efficient-market noise;
930 # longer horizons give momentum/mean-reversion more room to show up.
931 # Deliberately NOT added to required_columns below - the trailing
932 # ~5/~20 rows of each asset's history that lack a future close far
933 # enough out stay in the dataset with NaN targets here, handled by
934 # train_multitask.py's/train_sequence.py's masked loss instead of
935 # being dropped outright (dropping would also shrink every per-expert
936 # dataset slice downstream, which only ever needs the 1d target).
937 result["target_return_5d"] = result["close"].shift(-5) / result["close"] - 1.0
938 result["target_return_20d"] = result["close"].shift(-20) / result["close"] - 1.0
940 return_bounds_5d = max_abs_return_5d or DEFAULT_MAX_ABS_RETURN_5D
941 return_bound_5d = float(return_bounds_5d.get(security_type, return_bounds_5d.get("equity", 0.9)))
942 impossible_5d = result["target_return_5d"].abs() > return_bound_5d
943 result.loc[impossible_5d, "target_return_5d"] = np.nan
945 return_bounds_20d = max_abs_return_20d or DEFAULT_MAX_ABS_RETURN_20D
946 return_bound_20d = float(return_bounds_20d.get(security_type, return_bounds_20d.get("equity", 1.5)))
947 impossible_20d = result["target_return_20d"].abs() > return_bound_20d
948 result.loc[impossible_20d, "target_return_20d"] = np.nan
950 # Stays float (NaN-able) - unlike target_direction above, this is never
951 # forced to int since it's not in required_columns's dropna.
952 result["target_direction_5d"] = np.where(
953 result["target_return_5d"].notna(), (result["target_return_5d"] > 0).astype(float), np.nan
954 )
955 result["target_direction_20d"] = np.where(
956 result["target_return_20d"].notna(), (result["target_return_20d"] > 0).astype(float), np.nan
957 )
958 for horizon_days in extra_horizon_days:
959 column = f"target_return_{horizon_days}d"
960 result[column] = result["close"].shift(-horizon_days) / result["close"] - 1.0
961 bound = extra_horizon_return_bound(horizon_days, security_type, max_abs_return_20d or DEFAULT_MAX_ABS_RETURN_20D)
962 result.loc[result[column].abs() > bound, column] = np.nan
964 # Next-day realized-volatility proxy for the multitask model's volatility
965 # head (train_multitask.py): next day's own high_low_range_pct, already
966 # computed above from that day's high/low/close - a genuine one-day-ahead
967 # realized-range measure, NaN only on the same last-per-asset row
968 # target_return_1d is already NaN on (both are shift(-1) of price data),
969 # so it never introduces additional dropped rows beyond what
970 # target_return_1d already drops.
971 result["target_volatility_next_day"] = result["high_low_range_pct"].shift(-1)
972 result["split"] = assign_split_series(result["date"], windows)
973 purge_horizon_rows = int(windows.get("purge_label_horizon_days", 0) or 0)
974 if purge_horizon_rows > 0:
975 result["split"] = purge_label_overlap(result["split"].tolist(), purge_horizon_rows)
976 purge_calendar_days = int(windows.get("purge_label_calendar_days", 0) or 0)
977 if purge_calendar_days > 0:
978 result["split"] = purge_label_overlap_calendar(result["split"].tolist(), result["date"].tolist(), purge_calendar_days)
980 required_columns = feature_names + [
981 "target_return_1d",
982 "target_direction",
983 "target_volatility_next_day",
984 "split",
985 ]
986 result = result.dropna(subset=required_columns).reset_index(drop=True)
987 result["target_direction"] = result["target_direction"].astype(int)
988 return result
991FOREX_CALENDAR_FEATURE_COLUMNS = [
992 "close_to_close_return_1d", "close_to_close_return_5d", "close_to_close_return_20d",
993 "rolling_volatility_5d", "rolling_volatility_20d", "momentum_5d", "momentum_20d",
994 "high_low_range_pct", "open_close_range_pct", "volume_change_1d",
995 "rsi_14", "atr_pct_14", "bollinger_pctb_20", "volume_zscore_20", "macd_histogram_norm", "dist_52w_high",
996 "liquidity_log_dollar_volume", "liquidity_spread_proxy",
997]
1000def fill_forward_forex_frame(frame: pd.DataFrame, holidays: frozenset[int] = frozenset()) -> pd.DataFrame:
1001 """The forex bars Lean delivers: every Sunday-Friday day without a row becomes a flat bar (open=high=low=close =
1002 the previous close, volume 0) - features/cross_asset_timing.py::fill_forward_open_forex_days(), Problems.md #135.
1003 `frame` needs `date` plus the OHLCV columns; extra columns are carried over from the previous bar."""
1004 ordered = frame.sort_values("date").reset_index(drop=True)
1005 ordinals = [day_ordinal(stamp) for stamp in ordered["date"]]
1006 filled_ordinals, _ = fill_forward_open_forex_days(ordinals, ordered["close"].tolist(), holidays)
1007 missing = sorted(set(filled_ordinals) - set(ordinals))
1008 if not missing:
1009 return ordered
1010 fill_dates = pd.to_datetime([pd.Timestamp.fromordinal(ordinal) for ordinal in missing])
1011 previous = ordered.set_index("date").reindex(ordered["date"].tolist() + list(fill_dates)).sort_index().ffill()
1012 fills = previous.loc[fill_dates].reset_index().rename(columns={"index": "date"})
1013 for column in ("open", "high", "low", "close"):
1014 fills[column] = fills["close"]
1015 fills["volume"] = 0.0
1016 if "timestamp" in fills.columns:
1017 fills["timestamp"] = fills["date"]
1018 combined = pd.concat([ordered, fills[ordered.columns]], ignore_index=True)
1019 return combined.sort_values("date").reset_index(drop=True)
1022def drop_lean_holiday_bars(frame: pd.DataFrame, holidays: frozenset[int]) -> pd.DataFrame:
1023 """A zip bar dated on a Lean market holiday never reaches live (Lean drops it), so the dataset drops it too."""
1024 if not holidays or frame.empty:
1025 return frame
1026 keep = [day_ordinal(stamp) not in holidays for stamp in frame["date"]]
1027 return frame.loc[keep].reset_index(drop=True)
1030def engineer_forex_features_on_lean_calendar(
1031 asset_frame: pd.DataFrame, feature_names: list[str], windows: dict, holidays: frozenset[int] = frozenset(), **engineer_kwargs
1032) -> pd.DataFrame:
1033 """Forex rows engineered the way live sees them. Live's forex windows contain Lean's fill-forward bars (flat
1034 Sunday bars, filled gap days), so trailing features (volatility, momentum, RSI, MACD, spread...) are computed on
1035 the filled calendar; the LABELS (forward returns, direction, next-day range) and the row set stay those of the real
1036 bars, so no fake zero-return day enters a target. Returns the same rows as engineer_features() on the raw frame."""
1037 plain = engineer_features(
1038 add_liquidity_features(asset_frame, "forex"), feature_names, windows, security_type="forex", **engineer_kwargs
1039 )
1040 filled = engineer_features(
1041 add_liquidity_features(fill_forward_forex_frame(asset_frame, holidays), "forex"),
1042 feature_names, windows, security_type="forex", **engineer_kwargs,
1043 )
1044 if plain.empty or filled.empty:
1045 return plain
1046 calendar_values = filled.set_index("date")[FOREX_CALENDAR_FEATURE_COLUMNS]
1047 result = plain.copy()
1048 aligned = calendar_values.reindex(result["date"])
1049 for column in FOREX_CALENDAR_FEATURE_COLUMNS:
1050 values = aligned[column].to_numpy()
1051 keep_plain = np.isnan(values) # a row the filled run dropped keeps its plain value
1052 result[column] = np.where(keep_plain, result[column].to_numpy(), values)
1053 return result
1056# ---------------------------------------------------------------------------
1057# Cross-subsystem input features (Phase 1 remainder): regime/liquidity/
1058# topology become genuine model *inputs*, not just downstream consumers of
1059# the model's own output. Mirrors main.py's own runtime computation of each
1060# subsystem exactly (same functions, same config keys) so train/runtime
1061# feature parity holds - see build_feature_dataset()'s orchestration below
1062# and main.py's matching _build_model_input() changes.
1063# ---------------------------------------------------------------------------
1065# Matches main.py's self.symbol_windows (deque(maxlen=25), so up to 24
1066# daily returns) - both the topology returns window and the liquidity
1067# high/low spread-estimation window below reuse this exact size so offline
1068# reconstruction sees the same trailing history depth the live loop does.
1069CROSS_SECTIONAL_WINDOW_BARS = 25
1070CROSS_SECTIONAL_RETURNS_WINDOW = CROSS_SECTIONAL_WINDOW_BARS - 1
1072REGIME_ONEHOT_FEATURE_NAMES = [
1073 "regime_trend_bullish", "regime_trend_bearish", "regime_trend_sideways",
1074 "regime_volatility_low", "regime_volatility_normal", "regime_volatility_high",
1075 "regime_risk_on", "regime_risk_off", "regime_risk_neutral",
1076]
1077REGIME_CONTINUOUS_FEATURE_NAMES = ["regime_signal_confidence", "regime_signal_trend_score", "regime_signal_risk_score"]
1078REGIME_FEATURE_NAMES = REGIME_ONEHOT_FEATURE_NAMES + REGIME_CONTINUOUS_FEATURE_NAMES
1080LIQUIDITY_FEATURE_NAMES = ["liquidity_log_dollar_volume", "liquidity_spread_proxy"]
1082TOPOLOGY_ONEHOT_FEATURE_NAMES = ["topology_risk_normal", "topology_risk_elevated", "topology_risk_isolated"]
1083TOPOLOGY_CONTINUOUS_FEATURE_NAMES = ["topology_correlation_strength"]
1084TOPOLOGY_FEATURE_NAMES = TOPOLOGY_ONEHOT_FEATURE_NAMES + TOPOLOGY_CONTINUOUS_FEATURE_NAMES
1087def _encode_regime_row(row: pd.Series) -> dict:
1088 """Reconstructs the same MarketRegimeVector main.py's
1089 _build_regime_payload() computes at runtime, from this row's own
1090 already-engineered momentum/volatility features.
1092 average_correlation (development/Problems.md #71, Phase 4.12) is now
1093 this row's own real topology_correlation_strength - build_feature_
1094 dataset() moved the add_regime_features() call to run AFTER
1095 build_topology_features_by_date(), specifically so this value is
1096 real, not a placeholder, by the time this function runs. Falls back
1097 to 0.0 only if the column is genuinely absent (a caller bypassing the
1098 normal build_feature_dataset() ordering, e.g. a unit test fixture),
1099 never raises.
1101 portfolio_drawdown=0.0 remains an honest, documented simplification -
1102 no live account-drawdown state exists at offline dataset-build time,
1103 the same simplification train_gating.py::build_gating_training_rows()
1104 still uses for the identical reason. trend_regime/volatility_regime
1105 (the two most-used regime keys) are unaffected by either default."""
1106 features = {
1107 "momentum_5d": row["momentum_5d"],
1108 "momentum_20d": row["momentum_20d"],
1109 "rolling_volatility_5d": row["rolling_volatility_5d"],
1110 "rolling_volatility_20d": row["rolling_volatility_20d"],
1111 }
1112 average_correlation = float(row["topology_correlation_strength"]) if "topology_correlation_strength" in row else 0.0
1113 vector = build_model_input_regime_vector(features, average_correlation=average_correlation)
1114 return {
1115 "regime_trend_bullish": 1.0 if vector.trend_regime == "bullish" else 0.0,
1116 "regime_trend_bearish": 1.0 if vector.trend_regime == "bearish" else 0.0,
1117 "regime_trend_sideways": 1.0 if vector.trend_regime == "sideways" else 0.0,
1118 "regime_volatility_low": 1.0 if vector.volatility_regime == "low_volatility" else 0.0,
1119 "regime_volatility_normal": 1.0 if vector.volatility_regime == "normal_volatility" else 0.0,
1120 "regime_volatility_high": 1.0 if vector.volatility_regime == "high_volatility" else 0.0,
1121 "regime_risk_on": 1.0 if vector.risk_regime == "risk_on" else 0.0,
1122 "regime_risk_off": 1.0 if vector.risk_regime == "risk_off" else 0.0,
1123 "regime_risk_neutral": 1.0 if vector.risk_regime == "risk_neutral" else 0.0,
1124 "regime_signal_confidence": vector.confidence,
1125 "regime_signal_trend_score": vector.trend_score,
1126 "regime_signal_risk_score": vector.risk_score,
1127 }
1130# The regime one-hot / score columns _encode_regime_row() emits. Kept as an
1131# explicit list so add_regime_features() can attach them to an EMPTY frame
1132# without a duplicate-column concat: frame.apply(..., result_type="expand")
1133# on 0 rows returns a copy of the frame's OWN columns (pandas can't infer the
1134# expanded keys with no row to call the function on), so concatenating that
1135# back on axis=1 would duplicate every column - incl. "date" - and later
1136# `frame["date"]` would return a DataFrame, not a Series. Empty asset frames
1137# only arise in a walk-forward sub-window an asset has no data in.
1138REGIME_ENCODED_FEATURE_NAMES = [
1139 "regime_trend_bullish", "regime_trend_bearish", "regime_trend_sideways",
1140 "regime_volatility_low", "regime_volatility_normal", "regime_volatility_high",
1141 "regime_risk_on", "regime_risk_off", "regime_risk_neutral",
1142 "regime_signal_confidence", "regime_signal_trend_score", "regime_signal_risk_score",
1143]
1146def add_regime_features(frame: pd.DataFrame) -> pd.DataFrame:
1147 """Row-wise: every surviving row already has the momentum/volatility
1148 features build_market_regime_vector() needs, so this never drops rows."""
1149 result = frame.reset_index(drop=True)
1150 if result.empty:
1151 for name in REGIME_ENCODED_FEATURE_NAMES:
1152 result[name] = pd.Series(dtype=float)
1153 return result
1154 encoded = result.apply(_encode_regime_row, axis=1, result_type="expand")
1155 return pd.concat([result, encoded.reset_index(drop=True)], axis=1)
1158def add_liquidity_features(frame: pd.DataFrame, security_type: str) -> pd.DataFrame:
1159 """Asset-intrinsic liquidity features only: daily_dollar_volume (log1p-
1160 scaled, since raw values span orders of magnitude) and the Corwin-
1161 Schultz spread_proxy over a trailing CROSS_SECTIONAL_WINDOW_BARS window,
1162 both reusing liquidity/market_liquidity.py's exact runtime functions.
1163 Deliberately excludes participation_rate/estimated_slippage/
1164 adjusted_target_weight from build_liquidity_decision() - those need an
1165 assumed order size (target_weight * portfolio_value), which has no
1166 principled offline value before any sizing decision exists; feeding a
1167 made-up order size in as a "feature" would be circular. This is a
1168 documented adaptation of the original plan text, not an oversight.
1170 Must be called on the RAW per-asset frame, before engineer_features()
1171 drops that asset's first row (its close_to_close_return_1d etc. are
1172 NaN, no previous close to compute from) - main.py's real
1173 self.symbol_windows starts accumulating from that same first raw bar,
1174 so spread_proxy's trailing window must see it too, or the first
1175 ~CROSS_SECTIONAL_WINDOW_BARS rows of every asset's history would be
1176 silently short one bar offline versus what the live loop actually
1177 sees (confirmed via a real train/runtime parity check on ETHUSD's
1178 earliest rows - high/low pairs, unlike returns, are legitimately
1179 available for that first row even though its own return isn't)."""
1180 closes = frame["close"].tolist()
1181 volumes = frame["volume"].tolist()
1182 highs = frame["high"].tolist()
1183 lows = frame["low"].tolist()
1184 fallback_spread = TYPICAL_SPREAD_BY_TYPE.get(str(security_type), 0.001)
1186 log_dollar_volume: list[float] = []
1187 spread_proxy: list[float] = []
1188 for index in range(len(frame)):
1189 log_dollar_volume.append(float(np.log1p(max(closes[index] * volumes[index], 0.0))))
1191 window_start = max(0, index + 1 - CROSS_SECTIONAL_WINDOW_BARS)
1192 window_highs = highs[window_start : index + 1]
1193 window_lows = lows[window_start : index + 1]
1194 estimated = estimate_high_low_spread(window_highs, window_lows) if len(window_highs) >= 2 else None
1195 spread_proxy.append(float(estimated) if estimated is not None else fallback_spread)
1197 result = frame.copy()
1198 result["liquidity_log_dollar_volume"] = log_dollar_volume
1199 result["liquidity_spread_proxy"] = spread_proxy
1200 return result
1203def peer_return_feature_names(top_peers_n: int) -> list[str]:
1204 """Schema-stable peer-return feature names - never ticker-named (peer
1205 identity changes bar to bar and asset to asset), always rank-based:
1206 peer_rank1_return_1d is "this asset's single most-correlated peer's
1207 latest 1-day return", down to peer_rankN_return_1d, plus
1208 peer_mean_return_1d (mean across whichever peers exist). Shared by
1209 build_topology_features_by_date() (offline) and
1210 main.py::_build_model_input() (runtime) so both sides register the
1211 exact same column/feature names."""
1212 return [f"peer_rank{rank}_return_1d" for rank in range(1, top_peers_n + 1)] + ["peer_mean_return_1d"]
1215def build_topology_features_by_date(
1216 asset_frames: dict[str, pd.DataFrame], config: dict, timeline: CrossAssetTimeline | None = None
1217) -> dict[str, pd.DataFrame]:
1218 """Cross-sectional topology + peer-return reconstruction, aligned to what
1219 main.py's `_build_topology_payload()` sees live: the payload is built at the
1220 start of a tick, before that tick's own bars join `symbol_windows`, so a row
1221 sees only the bars that became available strictly before its own
1222 (features/cross_asset_timing.py - Problems.md #135: the earlier same-day
1223 version made live(D) equal the dataset's D-1 on every cross-asset column).
1225 `timeline` carries the RAW (pre-dropna) closes per ticker and their security
1226 types; without it one is derived from the frames' own `date`/`close`
1227 (equity timing). `embedding_iterations=1` is deliberate:
1228 correlation_strength/topology_risk/top_peers/top_peer_returns do not depend
1229 on the SMACOF embedding, so the expensive step is skipped without changing
1230 those values. regime_labels_by_symbol is intentionally omitted: it only
1231 affects cluster/node regime labels this function never reads.
1233 Peer features (peer_rank1_return_1d, ..., peer_mean_return_1d - see
1234 peer_return_feature_names()) are schema-stable, never ticker-named; a missing
1235 peer gets 0.0, identically to main.py::_build_model_input(). Rows without a
1236 computable topology default to build_market_topology()'s own isolated,
1237 zero-correlation fallback - never NaN.
1238 """
1239 topology_config = config.get("phase_v2", {}).get("topology", {})
1240 correlation_threshold = float(topology_config.get("correlation_threshold", 0.6))
1241 link_threshold = float(topology_config.get("link_threshold", 0.5))
1242 min_observations = int(topology_config.get("min_observations", 5))
1243 top_peers_n = int(topology_config.get("top_peers_n", 3))
1244 peer_feature_names = peer_return_feature_names(top_peers_n)
1245 timeline = timeline or CrossAssetTimeline.from_frames(asset_frames)
1246 # Same per-asset-class "elevated" volatility cutoffs main.py resolves (Problems.md #129): without them crypto
1247 # rows were labelled elevated at the global 0.45 here while live called the same node normal below 0.87.
1248 elevated_threshold, elevated_threshold_by_symbol = resolve_elevated_volatility_thresholds(
1249 topology_config.get("elevated_volatility_threshold", ELEVATED_VOLATILITY_THRESHOLD),
1250 {
1251 str(asset.get("ticker")): asset.get("asset_class") or asset.get("security_type")
1252 for asset in config.get("phase1", {}).get("universe", {}).get("assets", [])
1253 },
1254 )
1256 row_keys = {
1257 ticker: [timeline.row_availability(ticker, date) for date in frame["date"]] for ticker, frame in asset_frames.items()
1258 }
1259 tickers_by_key: dict[float, set[str]] = {}
1260 for ticker, keys in row_keys.items():
1261 for key in keys:
1262 tickers_by_key.setdefault(key, set()).add(ticker)
1264 topology_by_key: dict[float, dict[str, tuple[float, str, list[float]]]] = {}
1265 for key in sorted(tickers_by_key):
1266 returns_by_symbol, _ = timeline.inputs_before(key)
1267 if len(returns_by_symbol) < 2:
1268 continue
1269 topology = build_market_topology(
1270 returns_by_symbol=returns_by_symbol,
1271 correlation_threshold=correlation_threshold,
1272 link_threshold=link_threshold,
1273 min_observations=min_observations,
1274 embedding_iterations=1,
1275 top_peers_n=top_peers_n,
1276 elevated_volatility_threshold=elevated_threshold,
1277 elevated_volatility_threshold_by_symbol=elevated_threshold_by_symbol,
1278 )
1279 wanted = tickers_by_key[key]
1280 nodes: dict[str, tuple[float, str, list[float]]] = {}
1281 for node in topology.nodes:
1282 if node.symbol not in wanted:
1283 continue
1284 padded_returns = list(node.top_peer_returns) + [0.0] * (top_peers_n - len(node.top_peer_returns))
1285 mean_peer_return = float(np.mean(node.top_peer_returns)) if node.top_peer_returns else 0.0
1286 nodes[node.symbol] = (node.correlation_strength, node.topology_risk, padded_returns + [mean_peer_return])
1287 topology_by_key[key] = nodes
1289 isolated = (0.0, "isolated", [0.0] * (top_peers_n + 1))
1290 updated_frames: dict[str, pd.DataFrame] = {}
1291 for ticker, frame in asset_frames.items():
1292 result = frame.copy()
1293 rows = [topology_by_key.get(key, {}).get(ticker, isolated) for key in row_keys[ticker]]
1294 result["topology_correlation_strength"] = [row[0] for row in rows]
1295 result["topology_risk_normal"] = [1.0 if row[1] == "normal" else 0.0 for row in rows]
1296 result["topology_risk_elevated"] = [1.0 if row[1] == "elevated" else 0.0 for row in rows]
1297 result["topology_risk_isolated"] = [1.0 if row[1] == "isolated" else 0.0 for row in rows]
1298 for index, feature_name in enumerate(peer_feature_names):
1299 result[feature_name] = [row[2][index] for row in rows]
1300 updated_frames[ticker] = result
1301 return updated_frames
1304DEFAULT_MACRO_REFERENCE_TICKERS = {
1305 "long_duration": "TLT",
1306 "short_duration": "SHY",
1307 "high_yield": "HYG",
1308 "investment_grade": "LQD",
1309 "crypto": "BTCUSD",
1310}
1311MACRO_FEATURE_NAMES = [
1312 "macro_yield_curve_slope_proxy",
1313 "macro_credit_spread_proxy",
1314 "macro_crypto_risk_appetite_proxy",
1315]
1318def build_macro_features_by_date(
1319 asset_frames: dict[str, pd.DataFrame], config: dict, timeline: CrossAssetTimeline | None = None
1320) -> dict[str, pd.DataFrame]:
1321 """Phase 1b cross-asset "macro" features (features/macro_features.py):
1322 TLT-SHY, HYG-LQD and BTCUSD momentum proxies, broadcast to every asset's row.
1323 Each reference ticker contributes its momentum as main.py's
1324 `_build_macro_payload()` reads it live - from the windows BEFORE the row's own
1325 tick (features/cross_asset_timing.py, Problems.md #135) - so a row sees the
1326 latest reference bar that became available strictly before its own.
1328 A reference ticker absent from the universe (or without two bars yet)
1329 neutral-defaults its proxy to 0.0 - never raises, matching
1330 features/macro_features.py. `timeline` as in build_topology_features_by_date().
1331 """
1332 reference_tickers = {
1333 **DEFAULT_MACRO_REFERENCE_TICKERS,
1334 **config.get("phase1", {}).get("features", {}).get("macro_reference_tickers", {}),
1335 }
1336 timeline = timeline or CrossAssetTimeline.from_frames(asset_frames)
1338 row_keys = {
1339 ticker: [timeline.row_availability(ticker, date) for date in frame["date"]] for ticker, frame in asset_frames.items()
1340 }
1341 macro_by_key: dict[float, tuple[float, float, float]] = {}
1342 for key in sorted({key for keys in row_keys.values() for key in keys}):
1343 momentum = timeline.momentum_before(key)
1344 macro_by_key[key] = (
1345 yield_curve_slope_proxy(
1346 momentum.get(reference_tickers["long_duration"]), momentum.get(reference_tickers["short_duration"])
1347 ),
1348 credit_spread_proxy(
1349 momentum.get(reference_tickers["high_yield"]), momentum.get(reference_tickers["investment_grade"])
1350 ),
1351 crypto_risk_appetite_proxy(momentum.get(reference_tickers["crypto"])),
1352 )
1354 updated_frames: dict[str, pd.DataFrame] = {}
1355 for ticker, frame in asset_frames.items():
1356 result = frame.copy()
1357 rows = [macro_by_key[key] for key in row_keys[ticker]]
1358 result["macro_yield_curve_slope_proxy"] = [row[0] for row in rows]
1359 result["macro_credit_spread_proxy"] = [row[1] for row in rows]
1360 result["macro_crypto_risk_appetite_proxy"] = [row[2] for row in rows]
1361 updated_frames[ticker] = result
1362 return updated_frames
1365def build_bond_features_by_date(
1366 asset_frames: dict[str, pd.DataFrame],
1367 config: dict,
1368 fred_series: dict[str, list[dict]],
1369) -> dict[str, pd.DataFrame]:
1370 """Real-data sibling of build_macro_features_by_date() -
1371 features/bond_features.py, backed by data_pipeline/fred_backfill.py's
1372 actual FRED Treasury-yield/credit-spread series rather than
1373 macro_features.py's bond-ETF-price-momentum proxies.
1375 bond_yield_curve_level/slope/curvature and bond_credit_spread_level are
1376 date-only (identical across every asset on a given date) and broadcast
1377 to EVERY asset's row - same "compute once per date, every asset sees
1378 it" shape as build_macro_features_by_date() - this is the concrete
1379 mechanism making real yield-curve/credit-spread signal usable for
1380 equity/crypto/future/option predictions too, not just bonds themselves.
1382 bond_empirical_duration_beta is asset-specific: computed once per
1383 ticker (NOT a true rolling/date-varying value - a single OLS slope over
1384 that asset's whole available history, using
1385 features.empirical_duration_beta()) for assets tagged asset_class ==
1386 "bond" only, and broadcast unchanged to every row of that asset's own
1387 frame; every other asset gets a flat 0.0 (neutral - "no measurable
1388 duration sensitivity", not "unknown"). A bond-tagged asset with fewer
1389 than empirical_duration_beta()'s min_observations valid paired rows
1390 also gets 0.0, same neutral-pad convention as the missing-reference
1391 case above.
1393 bond_analytic_modified_duration/bond_analytic_convexity/bond_dv01
1394 (V4.7) are the offline/training-time counterpart of
1395 main.py::_bond_analytics_for_symbol() - real closed-form bond math
1396 (features.analytic_modified_duration()/analytic_convexity()/
1397 bond_dv01()) using bond_metadata.duration_proxy_years as an assumed
1398 maturity and bond_metadata.assumed_coupon_rate (or, when absent, the
1399 nearest available treasury yield-curve point via
1400 features.nearest_yield_curve_point(), DATE-VARYING per row rather than
1401 a single OLS slope) as an assumed coupon/yield - train/runtime parity
1402 with the live path. Also asset_class == "bond"-only; every other asset
1403 gets flat 0.0 columns, same neutral-pad convention as
1404 bond_empirical_duration_beta.
1406 fred_series is a plain {series_key: [{"date": date, "value": float},
1407 ...]} mapping - load_cached_fred_series()'s return shape, loaded once
1408 by the caller (never fetched live mid-run; Lean backtests are
1409 date-bounded). A series absent from fred_series (fresh clone, backfill
1410 never run) makes every bond feature for every date fall back to its
1411 neutral default - never raises.
1412 """
1413 assets_by_ticker = {asset["ticker"]: asset for asset in config["phase1"]["universe"]["assets"]}
1415 def _series_asof_lookup(series_key: str):
1416 rows = sorted(fred_series.get(series_key, []), key=lambda row: row["date"])
1417 dates = [row["date"] for row in rows]
1418 values = [row["value"] for row in rows]
1420 def _asof(current_date) -> float | None:
1421 target = current_date.date() if hasattr(current_date, "date") else current_date
1422 position = bisect.bisect_right(dates, target)
1423 if position == 0:
1424 return None
1425 return values[position - 1]
1427 return _asof
1429 treasury_3mo_asof = _series_asof_lookup("treasury_3mo")
1430 treasury_2yr_asof = _series_asof_lookup("treasury_2yr")
1431 treasury_5yr_asof = _series_asof_lookup("treasury_5yr")
1432 treasury_10yr_asof = _series_asof_lookup("treasury_10yr")
1433 credit_spread_asof = _series_asof_lookup("credit_spread_baa10y")
1434 beta_mode, beta_lookback = resolve_bond_duration_beta_mode(config.get("phase1", {}).get("features"))
1436 all_dates = sorted({date_value for frame in asset_frames.values() for date_value in frame["date"]})
1438 level_by_date: dict = {}
1439 slope_by_date: dict = {}
1440 curvature_by_date: dict = {}
1441 credit_by_date: dict = {}
1442 treasury_3mo_by_date: dict = {}
1443 treasury_2yr_by_date: dict = {}
1444 treasury_5yr_by_date: dict = {}
1445 treasury_10yr_by_date: dict = {}
1446 for current_date in all_dates:
1447 t3mo = treasury_3mo_asof(current_date)
1448 t2yr = treasury_2yr_asof(current_date)
1449 t5yr = treasury_5yr_asof(current_date)
1450 t10yr = treasury_10yr_asof(current_date)
1451 baa10y = credit_spread_asof(current_date)
1452 level_by_date[current_date] = yield_curve_level(t10yr)
1453 slope_by_date[current_date] = bond_yield_curve_slope(t10yr, t3mo)
1454 curvature_by_date[current_date] = yield_curve_curvature(t2yr, t5yr, t10yr)
1455 credit_by_date[current_date] = credit_spread_level(baa10y)
1456 treasury_3mo_by_date[current_date] = t3mo
1457 treasury_2yr_by_date[current_date] = t2yr
1458 treasury_5yr_by_date[current_date] = t5yr
1459 treasury_10yr_by_date[current_date] = t10yr
1461 updated_frames: dict[str, pd.DataFrame] = {}
1462 for ticker, frame in asset_frames.items():
1463 result = frame.copy()
1464 result["bond_yield_curve_level"] = [level_by_date.get(d, YIELD_CURVE_LEVEL_NEUTRAL) for d in result["date"]]
1465 result["bond_yield_curve_slope"] = [slope_by_date.get(d, 0.0) for d in result["date"]]
1466 result["bond_yield_curve_curvature"] = [
1467 curvature_by_date.get(d, YIELD_CURVE_CURVATURE_NEUTRAL) for d in result["date"]
1468 ]
1469 result["bond_credit_spread_level"] = [
1470 credit_by_date.get(d, CREDIT_SPREAD_LEVEL_NEUTRAL) for d in result["date"]
1471 ]
1473 asset_config = assets_by_ticker.get(ticker, {})
1474 is_bond = (asset_config.get("asset_class") or asset_config.get("security_type")) == "bond"
1475 beta = None
1476 if is_bond and "close_to_close_return_1d" in result.columns:
1477 dates_sorted = result["date"].tolist()
1478 treasury_10yr_sorted = [treasury_10yr_by_date.get(d) for d in dates_sorted]
1479 delta_10yr = [None] * len(treasury_10yr_sorted)
1480 for index in range(1, len(treasury_10yr_sorted)):
1481 previous_value = treasury_10yr_sorted[index - 1]
1482 current_value = treasury_10yr_sorted[index]
1483 if previous_value is not None and current_value is not None:
1484 delta_10yr[index] = current_value - previous_value
1485 beta = empirical_duration_beta(result["close_to_close_return_1d"].tolist(), delta_10yr)
1486 if beta_mode == "rolling":
1487 if is_bond and "close" in result.columns:
1488 treasury_levels = [treasury_10yr_by_date.get(d) for d in result["date"].tolist()]
1489 betas = rolling_duration_beta_series(result["close"].tolist(), treasury_levels, beta_lookback)
1490 result["bond_empirical_duration_beta"] = [value if value is not None else 0.0 for value in betas]
1491 else:
1492 result["bond_empirical_duration_beta"] = 0.0
1493 else:
1494 result["bond_empirical_duration_beta"] = beta if beta is not None else 0.0
1496 bond_metadata = asset_config.get("bond_metadata", {})
1497 years_to_maturity = bond_metadata.get("duration_proxy_years")
1498 assumed_coupon_rate = bond_metadata.get("assumed_coupon_rate")
1499 modified_durations: list[float] = []
1500 convexities: list[float] = []
1501 dv01s: list[float] = []
1502 if is_bond and "close" in result.columns:
1503 dates_sorted = result["date"].tolist()
1504 closes_sorted = result["close"].tolist()
1505 for row_date, close_price in zip(dates_sorted, closes_sorted, strict=False):
1506 coupon_rate = assumed_coupon_rate
1507 if coupon_rate is None:
1508 coupon_rate = nearest_yield_curve_point(
1509 years_to_maturity,
1510 {
1511 0.25: treasury_3mo_by_date.get(row_date),
1512 2.0: treasury_2yr_by_date.get(row_date),
1513 5.0: treasury_5yr_by_date.get(row_date),
1514 10.0: treasury_10yr_by_date.get(row_date),
1515 },
1516 )
1517 yield_to_maturity = coupon_rate # at-par-pricing proxy, matches main.py's runtime convention
1518 modified_duration = analytic_modified_duration(yield_to_maturity, coupon_rate, years_to_maturity)
1519 convexity = analytic_convexity(yield_to_maturity, coupon_rate, years_to_maturity)
1520 dv01 = bond_dv01(close_price, modified_duration)
1521 modified_durations.append(modified_duration if modified_duration is not None else 0.0)
1522 convexities.append(convexity if convexity is not None else 0.0)
1523 dv01s.append(dv01 if dv01 is not None else 0.0)
1524 else:
1525 modified_durations = [0.0] * len(result)
1526 convexities = [0.0] * len(result)
1527 dv01s = [0.0] * len(result)
1528 result["bond_analytic_modified_duration"] = modified_durations
1529 result["bond_analytic_convexity"] = convexities
1530 result["bond_dv01"] = dv01s
1532 updated_frames[ticker] = result
1533 return updated_frames
1536def build_alt_data_features_by_date(
1537 asset_frames: dict[str, pd.DataFrame],
1538 config: dict,
1539 fred_series: dict[str, list[dict]],
1540) -> dict[str, pd.DataFrame]:
1541 """Phase 4.12 (development/Problems.md #71) fourth cross-asset macro
1542 sibling to build_topology_features_by_date()/build_macro_features_by_date()/
1543 build_bond_features_by_date() - features/alt_data_features.py, backed by
1544 the SAME fred_series mapping build_bond_features_by_date() already
1545 receives (load_cached_fred_series() globs the whole cache directory,
1546 so the new implied_volatility_vix/implied_volatility_3m/
1547 financial_conditions_nfci series arrive in that dict with no loader
1548 change needed anywhere).
1550 Date-only, broadcast identically to every asset's row - same shape as
1551 build_bond_features_by_date()'s yield-curve/credit-spread columns,
1552 with no asset-specific branch (unlike that function's
1553 asset_class == "bond" duration/convexity/dv01 computation - these
1554 three features are macro/cross-asset by construction, not tied to any
1555 one asset).
1557 Unlike build_bond_features_by_date()'s inline _series_asof_lookup()
1558 (a bare bisect, correct only for same-day series), lookups here go
1559 through data_pipeline.fred_backfill.series_value_asof()/
1560 series_change_asof() with each series' own
1561 ALT_DATA_PUBLICATION_LAG_DAYS - NFCI is Friday-dated but not released
1562 until the following Wednesday, so a bare bisect would be lookahead.
1563 See those functions' own docstrings for the full reasoning.
1565 A series absent from fred_series (fresh clone, `aq backfill fred
1566 --group alt` never run) neutral-defaults every alt-data feature for
1567 every date via features/alt_data_features.py's own None-handling -
1568 never raises, identical contract to data_pipeline/README.md's existing
1569 FRED-series documentation.
1570 """
1571 financial_conditions_change_periods = int(
1572 config.get("phase1", {}).get("features", {}).get("alt_data_financial_conditions_change_periods", 4)
1573 )
1574 publication_lag = {
1575 **ALT_DATA_PUBLICATION_LAG_DAYS,
1576 **config.get("phase1", {}).get("features", {}).get("alt_data_publication_lag_days", {}),
1577 }
1578 vix_rows = fred_series.get("implied_volatility_vix", [])
1579 vix_3m_rows = fred_series.get("implied_volatility_3m", [])
1580 nfci_rows = fred_series.get("financial_conditions_nfci", [])
1582 all_dates = sorted({date_value for frame in asset_frames.values() for date_value in frame["date"]})
1584 level_by_date: dict = {}
1585 term_structure_by_date: dict = {}
1586 conditions_change_by_date: dict = {}
1587 for current_date in all_dates:
1588 vix_close = series_value_asof(vix_rows, current_date, publication_lag.get("implied_volatility_vix", 0))
1589 vix_3m_close = series_value_asof(vix_3m_rows, current_date, publication_lag.get("implied_volatility_3m", 0))
1590 # series_change_asof() already computes NFCI(t) - NFCI(t -
1591 # periods_back observations), both endpoints lag-adjusted - this
1592 # IS the final feature value, not an intermediate to feed back
1593 # through financial_conditions_change() (which exists as a
1594 # standalone pure utility for callers that already have two
1595 # resolved values in hand, e.g. a direct unit test).
1596 nfci_change = series_change_asof(
1597 nfci_rows,
1598 current_date,
1599 publication_lag.get("financial_conditions_nfci", 7),
1600 financial_conditions_change_periods,
1601 )
1602 level_by_date[current_date] = implied_volatility_level(vix_close)
1603 term_structure_by_date[current_date] = implied_vol_term_structure(vix_close, vix_3m_close)
1604 conditions_change_by_date[current_date] = (
1605 nfci_change if nfci_change is not None else FINANCIAL_CONDITIONS_CHANGE_NEUTRAL
1606 )
1608 updated_frames: dict[str, pd.DataFrame] = {}
1609 for ticker, frame in asset_frames.items():
1610 result = frame.copy()
1611 result["alt_implied_volatility_level"] = [
1612 level_by_date.get(d, IMPLIED_VOLATILITY_LEVEL_NEUTRAL) for d in result["date"]
1613 ]
1614 result["alt_implied_vol_term_structure"] = [
1615 term_structure_by_date.get(d, IMPLIED_VOL_TERM_STRUCTURE_NEUTRAL) for d in result["date"]
1616 ]
1617 result["alt_financial_conditions_change"] = [
1618 conditions_change_by_date.get(d, FINANCIAL_CONDITIONS_CHANGE_NEUTRAL) for d in result["date"]
1619 ]
1620 updated_frames[ticker] = result
1621 return updated_frames
1624def build_fx_carry_features(
1625 asset_frames: dict[str, pd.DataFrame], config: dict, fred_series: dict[str, list[dict]]
1626) -> dict[str, pd.DataFrame]:
1627 """V5.7.0 - adds `fx_carry_3m` (features/fx_carry.py): the 3-month rate differential of each forex pair, looked up
1628 as of the row's own date through the publication-lag-aware FRED helper `main.py` also calls; 0.0 for every other
1629 asset class. Always writes the column so the dataset schema does not depend on whether the feature is in
1630 `phase1.features.input_set` yet (it reaches the model only once a retrain lists it)."""
1631 asset_class_by_ticker = asset_class_by_ticker_from_config(config)
1632 lags = {
1633 **FX_RATE_PUBLICATION_LAG_DAYS,
1634 **config.get("phase1", {}).get("features", {}).get("fx_rate_publication_lag_days", {}),
1635 }
1636 updated: dict[str, pd.DataFrame] = {}
1637 for ticker, frame in asset_frames.items():
1638 result = frame.copy()
1639 asset_class = asset_class_by_ticker.get(ticker)
1640 if asset_class == "forex":
1641 result[FX_CARRY_FEATURE_NAME] = [fx_carry_3m(ticker, asset_class, day, fred_series, lags) for day in result["date"]]
1642 else:
1643 result[FX_CARRY_FEATURE_NAME] = 0.0
1644 updated[ticker] = result
1645 return updated
1648DEFAULT_CROSS_ASSET_SENSITIVITY_LOOKBACK_DAYS = 252
1649DEFAULT_CROSS_ASSET_SENSITIVITY_MIN_OBSERVATIONS = 120
1650DEFAULT_CROSS_ASSET_SENSITIVITY_DRIVERS = {
1651 "vix": "implied_volatility_vix",
1652 "real_rate": "treasury_10yr_real",
1653 "credit": "credit_spread_baa10y",
1654 "dollar": "dollar_index",
1655}
1658def build_cross_asset_sensitivity_features(
1659 asset_frames: dict[str, pd.DataFrame], config: dict, fred_series: dict[str, list[dict]]
1660) -> dict[str, pd.DataFrame]:
1661 """Per-asset macro SENSITIVITY features (V5.1 Phase 2, item 8 / F2) -
1662 features/cross_asset_sensitivity.py, called right after
1663 build_alt_data_features_by_date() (same fred_series input, same
1664 "compute per-date lookup once, then assign per asset" shape).
1666 F2's finding: every macro_*/bond_*/alt_* feature above (except
1667 bond_empirical_duration_beta) broadcasts an IDENTICAL value to every
1668 asset on a date - invisible to a cross-sectional ranker by
1669 construction. This builds the version that varies across the
1670 cross-section instead: for each of 4 drivers (config
1671 phase1.features.cross_asset_sensitivity.drivers, default vix/real_rate/
1672 credit/dollar), a trailing-window OLS beta of each asset's own daily
1673 return on that driver's daily change (features.rolling_sensitivity(),
1674 itself a thin wrapper reusing features.empirical_duration_beta() - no
1675 new OLS implementation), plus the interaction beta_i * delta_macro_t.
1677 Driver friendly names are looked up in the SAME merged fred_series dict
1678 build_bond_features_by_date()/build_alt_data_features_by_date() already
1679 receive (load_cached_fred_series() globs the whole cache directory
1680 regardless of bond/alt/sensitivity distinction). Publication lag per
1681 driver comes from the same phase1.features.alt_data_publication_lag_days
1682 config dict alt-data uses, defaulting 0 (correct for same-day series
1683 like credit_spread_baa10y; VIX/real-rate/dollar are 0 too - see Step
1684 2.4's fred_backfill.py mirror).
1686 enabled defaults to False when the whole cross_asset_sensitivity config
1687 block is absent - a config.json that hasn't been migrated to V5.1 Phase
1688 2 yet must reproduce today's columns byte-for-byte (all-neutral 0.0),
1689 the same "additive, absent-config-is-a-no-op" contract every other
1690 V5.1 config-gated feature in this file already follows. A missing
1691 driver series (fresh clone, `aq backfill fred` never run) neutral-
1692 defaults that driver's beta/interaction columns to 0.0 for every date -
1693 never raises."""
1694 sensitivity_config = config.get("phase1", {}).get("features", {}).get("cross_asset_sensitivity", {})
1695 if not sensitivity_config.get("enabled", False):
1696 updated_frames: dict[str, pd.DataFrame] = {}
1697 for ticker, frame in asset_frames.items():
1698 result = frame.copy()
1699 for feature_name in CROSS_ASSET_SENSITIVITY_FEATURE_NAMES:
1700 result[feature_name] = 0.0
1701 updated_frames[ticker] = result
1702 return updated_frames
1704 lookback = int(sensitivity_config.get("lookback_days", DEFAULT_CROSS_ASSET_SENSITIVITY_LOOKBACK_DAYS))
1705 min_observations = int(sensitivity_config.get("min_observations", DEFAULT_CROSS_ASSET_SENSITIVITY_MIN_OBSERVATIONS))
1706 drivers = sensitivity_config.get("drivers", DEFAULT_CROSS_ASSET_SENSITIVITY_DRIVERS)
1707 publication_lag = {
1708 **ALT_DATA_PUBLICATION_LAG_DAYS,
1709 **config.get("phase1", {}).get("features", {}).get("alt_data_publication_lag_days", {}),
1710 }
1712 all_dates = sorted({date_value for frame in asset_frames.values() for date_value in frame["date"]})
1714 level_by_date_by_driver: dict[str, dict] = {}
1715 for driver_key, friendly_name in drivers.items():
1716 rows = fred_series.get(friendly_name, [])
1717 lag = publication_lag.get(friendly_name, 0)
1718 level_by_date_by_driver[driver_key] = {
1719 current_date: series_value_asof(rows, current_date, lag) for current_date in all_dates
1720 }
1722 updated_frames = {}
1723 for ticker, frame in asset_frames.items():
1724 result = frame.copy()
1725 dates_sorted = result["date"].tolist()
1726 returns_sorted = (
1727 result["close_to_close_return_1d"].tolist()
1728 if "close_to_close_return_1d" in result.columns
1729 else [None] * len(dates_sorted)
1730 )
1732 for driver_key in drivers:
1733 level_by_date = level_by_date_by_driver[driver_key]
1734 levels_sorted = [level_by_date.get(d) for d in dates_sorted]
1735 deltas_sorted: list[float | None] = [None] * len(levels_sorted)
1736 for index in range(1, len(levels_sorted)):
1737 previous_value = levels_sorted[index - 1]
1738 current_value = levels_sorted[index]
1739 if previous_value is not None and current_value is not None:
1740 deltas_sorted[index] = current_value - previous_value
1742 beta_column = []
1743 interaction_column = []
1744 for index in range(len(dates_sorted)):
1745 window_start = max(0, index - lookback + 1) if lookback > 0 else 0
1746 window_returns = returns_sorted[window_start : index + 1]
1747 window_deltas = deltas_sorted[window_start : index + 1]
1748 beta = rolling_sensitivity(
1749 window_returns, window_deltas, lookback=lookback, min_observations=min_observations
1750 )
1751 beta_column.append(beta if beta is not None else 0.0)
1752 interaction_column.append(sensitivity_interaction(beta, deltas_sorted[index]))
1754 result[f"sens_{driver_key}_beta"] = beta_column
1755 result[f"sens_{driver_key}_interaction"] = interaction_column
1757 for feature_name in CROSS_ASSET_SENSITIVITY_FEATURE_NAMES:
1758 if feature_name not in result.columns:
1759 result[feature_name] = 0.0
1761 updated_frames[ticker] = result
1762 return updated_frames
1765def build_derivatives_macro_features_by_date(asset_frames: dict[str, pd.DataFrame], config: dict) -> dict[str, pd.DataFrame]:
1766 """Third cross-asset macro sibling to build_macro_features_by_date()/
1767 build_bond_features_by_date() - features/derivatives_macro_features.py's
1768 futures-term-structure/options-sentiment signals, broadcast identically
1769 to EVERY asset's row (the mechanism making derivatives-derived signal
1770 usable for equity/crypto/bond predictions too, not just futures/options
1771 themselves - generalizing well past any single hardcoded example pair).
1773 Reuses the SAME `aq fetch futures`/`aq fetch options` historical Lean
1774 zips already loaded into `asset_frames` - no separate bulk-fetch
1775 pipeline. Real values require the user to have explicitly fetched
1776 contracts shaped for this:
1778 - Futures term structure: two future-class assets sharing a
1779 `family_ticker` matching `phase1.features.derivatives_reference_tickers
1780 .futures_term_structure` (default "ES") - e.g. `aq fetch futures
1781 --ticker ES_FRONT --family-ticker ES --contract-month <early> --apply`
1782 and `... --ticker ES_NEXT --family-ticker ES --contract-month <later>
1783 --apply`. Ordered by `contract_month` when present (nearest = front),
1784 else by ticker name. Fewer than 2 family members -> neutral (0.0).
1785 - Options sentiment: option-class assets whose `underlying_ticker`
1786 matches `derivatives_reference_tickers.options_sentiment` (default
1787 "SPY"), each carrying `strike`/`expiry`/`right` metadata (written by
1788 `aq fetch options --strike ... --expiry ... --right ...`). Per date,
1789 each contract's IV is solved from that date's close price via
1790 features/options_greeks.py::implied_volatility() (using the
1791 underlying's own close that date as spot, `phase_v2.options_risk
1792 .risk_free_rate`), then delta via compute_greeks() - aggregate
1793 volume for the put/call ratio, nearest-25-delta IV pair for the
1794 skew. No option assets configured for the reference underlying ->
1795 neutral (0.0).
1797 Every lookup neutral-defaults to 0.0 - never raises - the same
1798 "no data configured -> 0.0, indistinguishable from a genuinely neutral
1799 signal" convention as every other cross-asset macro feature here.
1800 Real historical acquisition via IB is inherently a manual, per-contract,
1801 rate-limited process (see data_pipeline/README.md) - this function
1802 just consumes whatever the user has already fetched."""
1803 assets_by_ticker = {
1804 asset["ticker"]: asset
1805 for asset in config.get("phase1", {}).get("universe", {}).get("assets", [])
1806 }
1807 reference_tickers = {
1808 "futures_term_structure": "ES",
1809 "options_sentiment": "SPY",
1810 **config.get("phase1", {}).get("features", {}).get("derivatives_reference_tickers", {}),
1811 }
1812 risk_free_rate = float(config.get("phase_v2", {}).get("options_risk", {}).get("risk_free_rate", 0.045))
1814 def _asset_class(ticker: str) -> str | None:
1815 asset = assets_by_ticker.get(ticker, {})
1816 return asset.get("asset_class") or asset.get("security_type")
1818 # --- Futures term structure: two family members, sorted front-to-next ---
1819 term_structure_by_date: dict = {}
1820 futures_family_ref = reference_tickers.get("futures_term_structure")
1821 futures_members = sorted(
1822 (
1823 ticker for ticker in asset_frames
1824 if _asset_class(ticker) == "future"
1825 and assets_by_ticker.get(ticker, {}).get("family_ticker", ticker) == futures_family_ref
1826 ),
1827 key=lambda ticker: assets_by_ticker[ticker].get("contract_month") or ticker,
1828 )
1829 if len(futures_members) >= 2:
1830 front_by_date = dict(zip(asset_frames[futures_members[0]]["date"], asset_frames[futures_members[0]]["close"], strict=False))
1831 next_by_date = dict(zip(asset_frames[futures_members[1]]["date"], asset_frames[futures_members[1]]["close"], strict=False))
1832 for current_date in set(front_by_date) | set(next_by_date):
1833 term_structure_by_date[current_date] = futures_term_structure_slope(
1834 front_by_date.get(current_date), next_by_date.get(current_date)
1835 )
1837 # --- Options sentiment: every option-class asset for the reference underlying ---
1838 put_call_ratio_by_date: dict = {}
1839 iv_skew_by_date: dict = {}
1840 options_ref = reference_tickers.get("options_sentiment")
1841 option_members = [
1842 ticker for ticker in asset_frames
1843 if _asset_class(ticker) == "option" and assets_by_ticker.get(ticker, {}).get("underlying_ticker") == options_ref
1844 ]
1845 if option_members and options_ref in asset_frames:
1846 underlying_close_by_date = dict(zip(asset_frames[options_ref]["date"], asset_frames[options_ref]["close"], strict=False))
1847 member_rows = {}
1848 for ticker in option_members:
1849 asset = assets_by_ticker[ticker]
1850 right = str(asset.get("right", "")).lower()
1851 strike = float(asset.get("strike", 0.0) or 0.0)
1852 expiry = asset.get("expiry")
1853 if right not in ("call", "put") or strike <= 0 or not expiry:
1854 continue
1855 expiry_date = pd.Timestamp(expiry).date()
1856 frame = asset_frames[ticker]
1857 volume_by_date = dict(zip(frame["date"], frame["volume"], strict=False)) if "volume" in frame.columns else {}
1858 close_by_date = dict(zip(frame["date"], frame["close"], strict=False))
1859 member_rows[ticker] = {"right": right, "strike": strike, "expiry_date": expiry_date, "volume_by_date": volume_by_date, "close_by_date": close_by_date}
1861 all_dates = set(underlying_close_by_date)
1862 for meta in member_rows.values():
1863 all_dates |= set(meta["close_by_date"])
1865 for current_date in all_dates:
1866 spot = underlying_close_by_date.get(current_date)
1867 current_date_only = current_date.date() if hasattr(current_date, "date") else current_date
1868 put_volume = 0.0
1869 call_volume = 0.0
1870 put_candidates: list[tuple[float, float]] = []
1871 call_candidates: list[tuple[float, float]] = []
1872 for meta in member_rows.values():
1873 option_price = meta["close_by_date"].get(current_date)
1874 if spot is None or option_price is None or spot <= 0 or option_price <= 0:
1875 continue
1876 time_to_expiry_years = (meta["expiry_date"] - current_date_only).days / 365.0
1877 if time_to_expiry_years <= 0:
1878 continue
1879 volume = float(meta["volume_by_date"].get(current_date, 0.0) or 0.0)
1880 if meta["right"] == "put":
1881 put_volume += volume
1882 else:
1883 call_volume += volume
1884 iv = implied_volatility(option_price, spot, meta["strike"], time_to_expiry_years, risk_free_rate, 0.0, meta["right"])
1885 if iv is None:
1886 continue
1887 delta = compute_greeks(spot, meta["strike"], time_to_expiry_years, risk_free_rate, iv, 0.0, meta["right"])["delta"]
1888 (put_candidates if meta["right"] == "put" else call_candidates).append((delta, iv))
1890 put_call_ratio_by_date[current_date] = options_put_call_ratio(
1891 put_volume if (put_volume or call_volume) else None, call_volume if (put_volume or call_volume) else None
1892 )
1893 nearest_put_iv = min(put_candidates, key=lambda pair: abs(pair[0] - (-0.25)))[1] if put_candidates else None
1894 nearest_call_iv = min(call_candidates, key=lambda pair: abs(pair[0] - 0.25))[1] if call_candidates else None
1895 iv_skew_by_date[current_date] = options_implied_vol_skew(nearest_put_iv, nearest_call_iv)
1897 updated_frames: dict[str, pd.DataFrame] = {}
1898 for ticker, frame in asset_frames.items():
1899 result = frame.copy()
1900 result["futures_term_structure_slope"] = [term_structure_by_date.get(d, 0.0) for d in result["date"]]
1901 result["options_put_call_ratio"] = [put_call_ratio_by_date.get(d, 0.0) for d in result["date"]]
1902 result["options_implied_vol_skew"] = [iv_skew_by_date.get(d, 0.0) for d in result["date"]]
1903 updated_frames[ticker] = result
1904 return updated_frames
1907# development/Problems.md #71 (Phase 4.12 era-instability fix): raised
1908# 10 -> 20. This universe is bimodal by weekday - equities don't trade on
1909# weekends/holidays, so those dates fall to an 11-12-asset crypto-only
1910# cross-section (verified: 255 of 801 backtest-split dates, 31.8%), vs.
1911# 64-74 assets on a normal business day. A rank computed over 11-12 assets
1912# is a fundamentally different, far noisier statistic than one over the
1913# full universe - ranking 12 assets alone produced 13 of 41 non-overlapping
1914# rank-IC observations at exactly +-1.0, which single-handedly flipped at
1915# least one non-overlapping era's sign (era 9, 2021 Q1: -0.111 with those
1916# dates included, +0.224 without). 20 sits with a wide margin below the
1917# smallest real full-universe date count (64) and well above the largest
1918# degenerate one (12), so this is a clean bimodal split, not a fragile
1919# threshold. Deliberately a SINGLE floor, not a separate lower
1920# training-time / higher evaluation-time pair: a noisy 12-asset rank target
1921# is equally poor training signal for the rank head as it is a poor
1922# evaluation sample, so there is no principled reason to admit it into
1923# training and then exclude it only at evaluation.
1924DEFAULT_RANKING_MIN_UNIVERSE_SIZE = 20
1925DEFAULT_SECTOR_NEUTRAL_MIN_SECTOR_SIZE = 3
1926UNKNOWN_SECTOR_LABEL = "Unknown"
1928# development/Problems.md #71 (Phase 4.12, A4): the default market proxy
1929# for target_beta_neutral_rank_5d/20d's residualization - a highly liquid,
1930# broad-market ETF already present in this project's V1 universe and
1931# already Lean's own default backtest benchmark (see
1932# generate_backtest_report.py's docstring: "main.py/lean.json never call
1933# SetBenchmark(...), so this is Lean's documented default - SPY".
1934DEFAULT_BETA_NEUTRAL_MARKET_TICKER = "SPY"
1935DEFAULT_BETA_NEUTRAL_MIN_OBSERVATIONS = 60
1937# V5.1 Phase 2 (item 5 of the roadmap) - build_residual_rank_targets()'s own
1938# defaults, deliberately mirroring DEFAULT_BETA_NEUTRAL_MARKET_TICKER/
1939# DEFAULT_BETA_NEUTRAL_MIN_OBSERVATIONS above rather than reusing them
1940# directly - this is a genuinely separate config block
1941# (phase1.target.ranking.residual_neutral), not the beta_neutral one, even
1942# though the sensible default VALUES happen to match.
1943DEFAULT_RESIDUAL_MARKET_TICKER = "SPY"
1944DEFAULT_RESIDUAL_MIN_BETA_OBSERVATIONS = 60
1945# No market-cap data exists anywhere in this repo (data/reference/ holds
1946# only sector/forex/futures specs + FRED series) - liquidity_log_dollar_volume
1947# is a LIQUIDITY-based size proxy, not market cap. Deliberate, documented
1948# approximation - see build_residual_rank_targets()'s own docstring.
1949DEFAULT_RESIDUAL_SIZE_PROXY_COLUMN = "liquidity_log_dollar_volume"
1952from features.asof_beta_labels import asof_rolling_beta, cross_sectional_residualize # noqa: E402
1955def _beta_estimation(ranking_config: dict) -> str:
1956 """`phase1.target.ranking.beta_estimation` (V6.4.3): "full_history" (default, one OLS beta per asset over its
1957 whole history of forward returns) or "asof" (a trailing 252-day beta of realised daily returns per date,
1958 features/asof_beta_labels.py - no lookahead into the label)."""
1959 return "asof" if ranking_config.get("beta_estimation", "full_history") == "asof" else "full_history"
1962def _asof_betas(frame: pd.DataFrame, market_daily_by_date: dict) -> list[float]:
1963 """Per-row as-of beta of one asset's frame against the market's daily return (0.0 until enough history)."""
1964 if "close_to_close_return_1d" not in frame.columns:
1965 return [0.0] * len(frame)
1966 market = [market_daily_by_date.get(current_date, np.nan) for current_date in frame["date"]]
1967 betas = asof_rolling_beta(frame["close_to_close_return_1d"].to_numpy(dtype=float), market)
1968 return [0.0 if not np.isfinite(beta) else float(beta) for beta in betas]
1971def _market_daily_by_date(market_frame: pd.DataFrame | None) -> dict:
1972 if market_frame is None or "close_to_close_return_1d" not in market_frame.columns:
1973 return {}
1974 return dict(zip(market_frame["date"], market_frame["close_to_close_return_1d"], strict=False))
1977def load_sector_mapping(config: dict) -> dict[str, str]:
1978 """Phase 5 of the 5/10 -> 9/10 roadmap: ticker -> sector-neutral-ranking
1979 bucket. V5.1 Phase 0 (Problems.md #75): thin delegate to
1980 features/sector_map.py::load_sector_mapping() - main.py cannot import
1981 this module (torch), so the file-read/strip logic now lives in
1982 features/ where both callers can share it. Same signature, same return
1983 shape, same {} (never raises) fallback contract as before this delegate
1984 existed - see the shared implementation's own docstring."""
1985 return _features_load_sector_mapping(config, default_path=SECTOR_MAPPING_PATH)
1988def build_residual_rank_targets(asset_frames: dict[str, pd.DataFrame], config: dict) -> dict[str, pd.DataFrame]:
1989 """V5.1 Phase 2 (item 5 of the roadmap): ONE combined market+sector+size
1990 residualized rank target - `target_residual_rank_5d/20d` - replacing
1991 "outperform the whole universe" (target_rank_Nd, above) with "outperform
1992 your peers after the factors you can't trade." Deliberately a single
1993 combined residualization, not four separate targets stacked on top of
1994 target_rank_Nd/target_sector_neutral_rank_Nd/target_beta_neutral_rank_Nd
1995 above - those three stay exactly as they are (unconsumed by this
1996 function, and target_beta_neutral_rank_Nd's OWN head ships disabled,
1997 see HORIZON_HEAD_SPECS).
1999 Per date, per horizon, the design matrix is
2000 `[intercept, beta_i * market_return_t, sector one-hot dummies (one
2001 dropped as reference), z(size_proxy_column)]`, each column config-gated
2002 by phase1.target.ranking.residual_neutral.{market,sector,size}. The
2003 residual is then ranked cross-sectionally via `.rank(pct=True)` - the
2004 exact same percentile-rank convention target_rank_Nd already uses -
2005 and gated by the same min_universe_size floor (a thin date's residual
2006 cross-section is just as noisy as a thin date's raw-return one).
2008 `beta_i` is a single WHOLE-HISTORY OLS slope per asset
2009 (features.empirical_duration_beta(), reused generically exactly the
2010 way build_cross_sectional_rank_targets()'s own beta_neutral block
2011 above already does - one static beta per asset, not a rolling
2012 per-date one), computed once per horizon, not per date.
2014 SIZE PROXY: no market-cap data exists anywhere in this repo
2015 (data/reference/ holds only sector/forex/futures specs + FRED series).
2016 `size_proxy_column` (default liquidity_log_dollar_volume, already
2017 computed earlier in the per-asset engineer_features() loop) is a
2018 LIQUIDITY-based size proxy, not market cap - a deliberate, documented
2019 approximation. Z-scored CROSS-SECTIONALLY per date (mean 0, std 1
2020 within that date's eligible pool), not as a raw level, so it is
2021 comparable across dates.
2023 With every factor disabled (market=sector=size=False), the design
2024 matrix is just an intercept - OLS with only an intercept fits the
2025 per-date mean, and subtracting a constant from every value never
2026 changes rank ORDER, so target_residual_rank_Nd degenerates to exactly
2027 target_rank_Nd in that configuration - a sensible, well-defined edge
2028 case, not a special-cased branch.
2030 `residual_neutral.enabled: false` (default true) still writes
2031 target_residual_rank_5d/20d, but as an all-NaN column - the same
2032 "config off degrades to no-signal, never a crash or a missing column"
2033 contract every other optional target/head in this codebase follows
2034 (masked_mse_loss()/the per-head disable machinery already treat an
2035 all-NaN column as "no target this row", nothing new to handle)."""
2036 ranking_config = config.get("phase1", {}).get("target", {}).get("ranking", {})
2037 residual_config = ranking_config.get("residual_neutral", {})
2038 enabled = bool(residual_config.get("enabled", True))
2039 updated_frames: dict[str, pd.DataFrame] = dict(asset_frames)
2041 if not enabled:
2042 for ticker, frame in updated_frames.items():
2043 result = frame.copy()
2044 result["target_residual_rank_5d"] = np.nan
2045 result["target_residual_rank_20d"] = np.nan
2046 updated_frames[ticker] = result
2047 return updated_frames
2049 use_market = bool(residual_config.get("market", True))
2050 use_sector = bool(residual_config.get("sector", True))
2051 use_size = bool(residual_config.get("size", True))
2052 size_proxy_column = residual_config.get("size_proxy_column", DEFAULT_RESIDUAL_SIZE_PROXY_COLUMN)
2053 market_ticker = residual_config.get("market_ticker", DEFAULT_RESIDUAL_MARKET_TICKER)
2054 min_universe_size = int(residual_config.get("min_universe_size", DEFAULT_RANKING_MIN_UNIVERSE_SIZE))
2055 min_beta_observations = int(residual_config.get("min_beta_observations", DEFAULT_RESIDUAL_MIN_BETA_OBSERVATIONS))
2057 sector_by_ticker = load_sector_mapping(config) if use_sector else {}
2058 market_frame = updated_frames.get(market_ticker) if use_market else None
2059 asof = _beta_estimation(ranking_config) == "asof"
2060 asof_beta_by_ticker_date: dict = {}
2061 if asof and market_frame is not None:
2062 market_daily = _market_daily_by_date(market_frame)
2063 for ticker, frame in updated_frames.items():
2064 asof_beta_by_ticker_date.update(zip(zip([ticker] * len(frame), frame["date"], strict=False), _asof_betas(frame, market_daily), strict=False))
2066 for horizon_days in (5, 20):
2067 return_column = f"target_return_{horizon_days}d"
2068 residual_rank_column = f"target_residual_rank_{horizon_days}d"
2070 beta_by_ticker: dict[str, float] = {}
2071 market_return_by_date: dict = {}
2072 if use_market and market_frame is not None and return_column in market_frame.columns:
2073 market_return_by_date = dict(zip(market_frame["date"], market_frame[return_column], strict=False))
2074 for ticker, frame in updated_frames.items():
2075 asset_returns = [None if pd.isna(value) else float(value) for value in frame[return_column]]
2076 market_returns = [
2077 None if pd.isna(market_return_by_date.get(current_date)) else float(market_return_by_date[current_date])
2078 for current_date in frame["date"]
2079 ]
2080 beta = empirical_duration_beta(asset_returns, market_returns, min_observations=min_beta_observations)
2081 beta_by_ticker[ticker] = beta if beta is not None else 0.0
2083 long_rows = []
2084 for ticker, frame in updated_frames.items():
2085 for current_date, return_value in zip(frame["date"], frame[return_column], strict=False):
2086 if pd.isna(return_value):
2087 continue
2088 long_rows.append({"ticker": ticker, "date": current_date, "return": float(return_value)})
2090 if not long_rows:
2091 for ticker, frame in updated_frames.items():
2092 result = frame.copy()
2093 result[residual_rank_column] = np.nan
2094 updated_frames[ticker] = result
2095 continue
2097 long_frame = pd.DataFrame(long_rows)
2098 if use_market and asof:
2099 long_frame["beta"] = [asof_beta_by_ticker_date.get(key, 0.0) for key in zip(long_frame["ticker"], long_frame["date"], strict=False)]
2100 else:
2101 long_frame["beta"] = long_frame["ticker"].map(beta_by_ticker).fillna(0.0) if use_market else 0.0
2102 long_frame["market_return"] = (
2103 long_frame["date"].map(market_return_by_date).fillna(0.0) if use_market else 0.0
2104 )
2105 long_frame["market_term"] = long_frame["beta"] * long_frame["market_return"]
2107 if use_sector:
2108 long_frame["sector"] = long_frame["ticker"].map(sector_by_ticker).fillna(UNKNOWN_SECTOR_LABEL)
2110 if use_size:
2111 size_by_ticker_date: dict = {}
2112 for ticker, frame in updated_frames.items():
2113 if size_proxy_column in frame.columns:
2114 for current_date, size_value in zip(frame["date"], frame[size_proxy_column], strict=False):
2115 size_by_ticker_date[(ticker, current_date)] = size_value
2116 long_frame["size_proxy"] = [
2117 size_by_ticker_date.get((ticker, current_date), np.nan)
2118 for ticker, current_date in zip(long_frame["ticker"], long_frame["date"], strict=False)
2119 ]
2120 grouped_size = long_frame.groupby("date")["size_proxy"]
2121 size_std = grouped_size.transform("std").replace(0.0, np.nan)
2122 long_frame["size_z"] = ((long_frame["size_proxy"] - grouped_size.transform("mean")) / size_std).fillna(0.0)
2124 residual_ranks = np.full(len(long_frame), np.nan)
2125 for _current_date, group in long_frame.groupby("date"):
2126 if len(group) < min_universe_size:
2127 continue
2128 design_columns = [np.ones(len(group))]
2129 if use_market:
2130 design_columns.append(group["market_term"].to_numpy())
2131 if use_sector:
2132 sector_dummies = pd.get_dummies(group["sector"], drop_first=True)
2133 if not sector_dummies.empty:
2134 design_columns.append(sector_dummies.to_numpy(dtype=float))
2135 if use_size:
2136 design_columns.append(group["size_z"].to_numpy())
2137 design_matrix = np.column_stack(design_columns)
2139 residuals = cross_sectional_residualize(group["return"].to_numpy(), design_matrix)
2140 residual_ranks[group.index.to_numpy()] = pd.Series(residuals).rank(pct=True).to_numpy()
2142 long_frame["residual_rank"] = residual_ranks
2143 residual_rank_lookup = (
2144 long_frame.dropna(subset=["residual_rank"]).set_index(["ticker", "date"])["residual_rank"].to_dict()
2145 )
2147 for ticker, frame in updated_frames.items():
2148 result = frame.copy() if residual_rank_column not in frame.columns else frame
2149 result[residual_rank_column] = [
2150 residual_rank_lookup.get((ticker, current_date), np.nan) for current_date in result["date"]
2151 ]
2152 updated_frames[ticker] = result
2154 return updated_frames
2157def build_cross_sectional_rank_targets(asset_frames: dict[str, pd.DataFrame], config: dict) -> dict[str, pd.DataFrame]:
2158 """Cross-sectional per-date percentile-rank targets (Phase 4) - the
2159 highest-leverage change this codebase's root-cause investigation
2160 identified: which asset outperforms its peers this period is typically
2161 far more learnable than absolute next-day direction, and maps directly
2162 onto a long/short portfolio (rank the universe, go long the top,
2163 short the bottom), unlike a per-asset direction call.
2165 For each historical date across the whole universe, ranks every
2166 asset's forward target_return_5d/target_return_20d (already computed
2167 by engineer_features(), including that function's own per-horizon
2168 label-outlier guard) into a [0, 1] percentile (ties averaged) among all
2169 assets with a valid forward return on that date - pandas'
2170 `.rank(pct=True)`, the same convention every other rank-based metric in
2171 this codebase would expect.
2173 Must be called after the per-asset engineer_features() loop (needs
2174 target_return_5d/20d already computed) but before build_feature_dataset()'s
2175 final concat/strftime - same ordering constraint as
2176 build_topology_features_by_date(), and deliberately a separate function
2177 from it (no pairwise correlation computation needed here, so none of
2178 that function's O(N^2) machinery applies).
2180 `min_universe_size` (config phase1.target.ranking.min_universe_size,
2181 default 20 as of development/Problems.md #71) guards against thin dates
2182 (e.g. weekends, when only crypto trades) - below that threshold the
2183 rank is NaN, not a near-meaningless percentile over a handful of
2184 assets. This is free: the masked loss (masked_mse_loss()) used by the
2185 rank_5d/20d training heads already treats NaN as "no target this row",
2186 the same convention the direction_5d/20d targets above already
2187 established.
2189 Also adds sibling `target_sector_neutral_rank_5d/20d` columns (Phase 5) -
2190 the SAME per-date percentile rank, but computed WITHIN each asset's
2191 sector bucket (load_sector_mapping()) instead of across the whole
2192 universe: "is this asset outperforming its sector peers," a cleaner
2193 signal than "is this asset outperforming the whole universe" when the
2194 universe's variance is dominated by a systematic tech/market factor.
2195 Purely additive - target_rank_5d/20d and every existing consumer
2196 (rank_sizing_multiplier(), the rank_5d/20d heads) are untouched.
2197 `min_sector_size` (config phase1.target.ranking.sector_neutral.min_sector_size,
2198 default 3) is the same "too few members -> NaN, not a near-meaningless
2199 rank" guard as min_universe_size, applied per (date, sector) instead of
2200 per date. Assets whose sector can't be resolved (load_sector_mapping()
2201 has no entry) get UNKNOWN_SECTOR_LABEL, which naturally NaNs out unless
2202 enough OTHER unmapped assets exist that day to clear min_sector_size.
2204 Also adds sibling `target_beta_neutral_rank_5d/20d` columns
2205 (development/Problems.md #71, Phase 4.12, A4) - unlike sector_neutral
2206 (a within-group RANK, still on raw returns), this residualizes each
2207 asset's forward return against its OWN static market-beta before
2208 ranking: residual_i(date) = target_return_Nd_i(date) - beta_i *
2209 target_return_Nd_market(date), where beta_i is a single whole-history
2210 OLS slope of asset i's forward return against the market ticker's SAME
2211 forward return (features.empirical_duration_beta() - reused as a
2212 generic "OLS slope of series A on series B" helper, exactly the same
2213 simplicity/tractability tradeoff bond_empirical_duration_beta already
2214 established: one static beta per asset, not a rolling per-date one).
2215 market_ticker (config phase1.target.ranking.beta_neutral.market_ticker,
2216 default "SPY") must exist in asset_frames or every beta_neutral rank
2217 for that horizon is NaN (never raises - same degrade-to-missing
2218 convention as an unresolved sector). An asset with too little paired
2219 history for a stable beta estimate (min_observations, default 60)
2220 gets beta=0.0 (residual == raw return - the safe, uninformative
2221 fallback, not a crash). This is currently a computed-but-unwired
2222 target: no model head consumes it yet (a full multitask/sequence head
2223 is a separate, larger change that was not made - see Problems.md
2224 #71 - to avoid stacking two unproven interventions into one retrain
2225 alongside the alt-data features above). The column exists so a head can
2226 be wired and measured on its own.
2227 """
2228 ranking_config = config.get("phase1", {}).get("target", {}).get("ranking", {})
2229 min_universe_size = int(ranking_config.get("min_universe_size", DEFAULT_RANKING_MIN_UNIVERSE_SIZE))
2230 sector_neutral_config = ranking_config.get("sector_neutral", {})
2231 min_sector_size = int(sector_neutral_config.get("min_sector_size", DEFAULT_SECTOR_NEUTRAL_MIN_SECTOR_SIZE))
2232 sector_by_ticker = load_sector_mapping(config)
2233 separate_groups = {str(group): list(classes) for group, classes in ranking_config.get("separate_rank_groups", {}).items()}
2234 separate_group_min_size = int(ranking_config.get("separate_rank_group_min_size", 8))
2235 rank_group_by_ticker: dict[str, str] = {}
2236 if separate_groups:
2237 class_by_ticker = asset_class_by_ticker_from_config(config)
2238 for group, classes in separate_groups.items():
2239 rank_group_by_ticker.update({ticker: group for ticker, kind in class_by_ticker.items() if kind in classes})
2240 beta_neutral_config = ranking_config.get("beta_neutral", {})
2241 market_ticker = beta_neutral_config.get("market_ticker", DEFAULT_BETA_NEUTRAL_MARKET_TICKER)
2242 beta_min_observations = int(beta_neutral_config.get("min_observations", DEFAULT_BETA_NEUTRAL_MIN_OBSERVATIONS))
2243 asof = _beta_estimation(ranking_config) == "asof"
2245 updated_frames: dict[str, pd.DataFrame] = dict(asset_frames)
2246 for horizon_days in (5, 20) + resolve_extra_horizon_days(config):
2247 return_column = f"target_return_{horizon_days}d"
2248 rank_column = f"target_rank_{horizon_days}d"
2249 sector_neutral_rank_column = f"target_sector_neutral_rank_{horizon_days}d"
2250 beta_neutral_rank_column = f"target_beta_neutral_rank_{horizon_days}d"
2252 long_frame = pd.concat(
2253 [
2254 pd.DataFrame({"ticker": ticker, "date": frame["date"], return_column: frame[return_column]})
2255 for ticker, frame in updated_frames.items()
2256 ],
2257 ignore_index=True,
2258 )
2259 eligible = long_frame.dropna(subset=[return_column]).copy()
2260 # V5.7.0: asset classes listed under ranking.separate_rank_groups are ranked AMONG THEMSELVES (forex pairs against
2261 # equities is no cross-section); every other row stays in the "main" pool. Unset = one pool = the old behaviour.
2262 eligible["rank_group"] = eligible["ticker"].map(rank_group_by_ticker).fillna("main")
2263 group_size = eligible.groupby(["date", "rank_group"])[return_column].transform("size")
2264 group_minimum = eligible["rank_group"].map(lambda group: min_universe_size if group == "main" else separate_group_min_size)
2265 eligible = eligible[group_size >= group_minimum].copy()
2266 eligible["rank_value"] = eligible.groupby(["date", "rank_group"])[return_column].rank(pct=True)
2267 rank_lookup = eligible.set_index(["ticker", "date"])["rank_value"].to_dict()
2269 sector_eligible = long_frame.dropna(subset=[return_column]).copy()
2270 sector_eligible["sector"] = sector_eligible["ticker"].map(sector_by_ticker).fillna(UNKNOWN_SECTOR_LABEL)
2271 sector_size = sector_eligible.groupby(["date", "sector"])[return_column].transform("size")
2272 sector_eligible = sector_eligible[sector_size >= min_sector_size].copy()
2273 sector_eligible["sector_rank_value"] = sector_eligible.groupby(["date", "sector"])[return_column].rank(
2274 pct=True
2275 )
2276 sector_rank_lookup = sector_eligible.set_index(["ticker", "date"])["sector_rank_value"].to_dict()
2278 # Beta-neutral: residualize against market_ticker's own SAME-horizon
2279 # forward return, then apply the identical min_universe_size gate
2280 # the plain rank already uses (a residual-return cross-section is
2281 # just as thin/noisy below that bar as a raw-return one).
2282 market_frame = updated_frames.get(market_ticker)
2283 beta_neutral_rank_lookup: dict = {}
2284 if market_frame is not None and return_column in market_frame.columns:
2285 market_return_by_date = dict(zip(market_frame["date"], market_frame[return_column], strict=False))
2286 residual_rows = []
2287 for ticker, frame in updated_frames.items():
2288 dates = frame["date"].tolist()
2289 asset_returns = [None if pd.isna(value) else float(value) for value in frame[return_column]]
2290 market_returns = [
2291 None if pd.isna(market_return_by_date.get(current_date)) else float(market_return_by_date[current_date])
2292 for current_date in dates
2293 ]
2294 if asof:
2295 row_betas = _asof_betas(frame, _market_daily_by_date(market_frame))
2296 else:
2297 beta = empirical_duration_beta(asset_returns, market_returns, min_observations=beta_min_observations)
2298 row_betas = [beta if beta is not None else 0.0] * len(dates)
2299 for current_date, asset_return, market_return, beta in zip(dates, asset_returns, market_returns, row_betas, strict=False):
2300 if asset_return is None or market_return is None:
2301 continue
2302 residual_rows.append(
2303 {"ticker": ticker, "date": current_date, "residual_return": asset_return - beta * market_return}
2304 )
2305 if residual_rows:
2306 residual_frame = pd.DataFrame(residual_rows)
2307 residual_size_by_date = residual_frame.groupby("date")["residual_return"].transform("size")
2308 residual_eligible = residual_frame[residual_size_by_date >= min_universe_size].copy()
2309 residual_eligible["beta_neutral_rank_value"] = residual_eligible.groupby("date")[
2310 "residual_return"
2311 ].rank(pct=True)
2312 beta_neutral_rank_lookup = residual_eligible.set_index(["ticker", "date"])[
2313 "beta_neutral_rank_value"
2314 ].to_dict()
2316 for ticker, frame in updated_frames.items():
2317 result = frame.copy()
2318 result[rank_column] = [rank_lookup.get((ticker, date), np.nan) for date in result["date"]]
2319 result[sector_neutral_rank_column] = [
2320 sector_rank_lookup.get((ticker, date), np.nan) for date in result["date"]
2321 ]
2322 result[beta_neutral_rank_column] = [
2323 beta_neutral_rank_lookup.get((ticker, date), np.nan) for date in result["date"]
2324 ]
2325 updated_frames[ticker] = result
2327 return updated_frames
2330def build_cross_sectional_momentum_rank_features(
2331 asset_frames: dict[str, pd.DataFrame], timeline: CrossAssetTimeline | None = None
2332) -> dict[str, pd.DataFrame]:
2333 """Cross-sectional percentile rank of each asset's momentum_20d (Phase 6),
2334 as main.py computes it live: every symbol's momentum comes from the windows
2335 BEFORE the row's own tick (`_build_topology_payload()` runs ahead of the
2336 per-symbol loop), the pool is every symbol with two bars - including ones
2337 whose latest bar is old - and the rank is the shared
2338 features.cross_sectional_momentum_rank() (Problems.md #135: the earlier
2339 exact-date pool of same-day momentum differed on 85% of rows).
2341 Thin pools default to CROSS_SECTIONAL_MOMENTUM_RANK_NEUTRAL (0.5) through
2342 that same function. `timeline` as in build_topology_features_by_date().
2343 """
2344 timeline = timeline or CrossAssetTimeline.from_frames(asset_frames)
2345 row_keys = {
2346 ticker: [timeline.row_availability(ticker, date) for date in frame["date"]] for ticker, frame in asset_frames.items()
2347 }
2348 tickers_by_key: dict[float, set[str]] = {}
2349 for ticker, keys in row_keys.items():
2350 for key in keys:
2351 tickers_by_key.setdefault(key, set()).add(ticker)
2353 rank_by_key: dict[float, dict[str, float]] = {}
2354 for key in sorted(tickers_by_key):
2355 momentum = timeline.momentum_before(key)
2356 rank_by_key[key] = {ticker: cross_sectional_momentum_rank(momentum, ticker) for ticker in tickers_by_key[key]}
2358 updated_frames: dict[str, pd.DataFrame] = {}
2359 for ticker, frame in asset_frames.items():
2360 result = frame.copy()
2361 result["cs_momentum_rank_20"] = [rank_by_key[key][ticker] for key in row_keys[ticker]]
2362 updated_frames[ticker] = result
2363 return updated_frames
2366# The original phase1.features.input_set - always required for
2367# engineer_features()'s own dropna, computed per-asset before any
2368# cross-sectional (topology) or regime/liquidity feature exists. Kept as an
2369# explicit constant (not read from config) since regime/liquidity features
2370# below are computed from these same names via row-wise .get() lookups -
2371# renaming one of these 10 without updating _encode_regime_row() would be a
2372# silent mismatch, so keeping them fixed here is deliberate.
2373BASE_FEATURE_NAMES = [
2374 "close_to_close_return_1d",
2375 "close_to_close_return_5d",
2376 "close_to_close_return_20d",
2377 "rolling_volatility_5d",
2378 "rolling_volatility_20d",
2379 "momentum_5d",
2380 "momentum_20d",
2381 "high_low_range_pct",
2382 "open_close_range_pct",
2383 "volume_change_1d",
2384 # Phase 6 technical indicators - appended, not inserted among the
2385 # original 10 (the docstring above's "renaming one of these 10" warning
2386 # is about renaming, not appending; _encode_regime_row() looks up its
2387 # own specific names by key via .get(), unaffected by new keys existing
2388 # alongside them).
2389 "rsi_14",
2390 "atr_pct_14",
2391 "bollinger_pctb_20",
2392 "volume_zscore_20",
2393 "macd_histogram_norm",
2394 "dist_52w_high",
2395]
2398def _categorical_feature_names(dataset: pd.DataFrame) -> list[str]:
2399 """Regime/topology one-hot flags present in `dataset` - unscaled model
2400 inputs, same treatment as the asset-context one-hots
2401 add_asset_context_features() produces (already-bounded [0,1] flags, no
2402 StandardScaler needed). Filtered against `dataset.columns` rather than
2403 returned unconditionally so a --candidate/--dataset-only run against an
2404 older dataset without these columns degrades gracefully instead of
2405 KeyError-ing downstream."""
2406 return [name for name in (REGIME_ONEHOT_FEATURE_NAMES + TOPOLOGY_ONEHOT_FEATURE_NAMES) if name in dataset.columns]
2409def build_feature_dataset(config: dict) -> tuple[pd.DataFrame, dict]:
2410 phase1 = config["phase1"]
2411 assets = phase1["universe"]["assets"]
2412 windows = phase1["windows"]
2413 target_config = phase1.get("target", {})
2414 max_abs_daily_return = target_config.get("max_abs_daily_return", DEFAULT_MAX_ABS_DAILY_RETURN)
2415 max_abs_return_5d = target_config.get("max_abs_return_5d", DEFAULT_MAX_ABS_RETURN_5D)
2416 max_abs_return_20d = target_config.get("max_abs_return_20d", DEFAULT_MAX_ABS_RETURN_20D)
2417 extra_horizon_days = resolve_extra_horizon_days(config)
2419 apply_factor_files = bool(phase1["universe"].get("apply_factor_files", True))
2420 asset_frames = {
2421 asset["ticker"]: load_lean_bars(asset, phase1["universe"]["common_window"], apply_factor_files=apply_factor_files)
2422 for asset in assets
2423 }
2424 forex_holidays = resolve_forex_lean_holidays(config)
2425 if forex_holidays:
2426 asset_frames = {
2427 ticker: drop_lean_holiday_bars(frame, forex_holidays) if asset["security_type"] == "forex" else frame
2428 for asset in assets
2429 for ticker, frame in [(asset["ticker"], asset_frames[asset["ticker"]])]
2430 }
2431 union_dates = sorted({date_value for frame in asset_frames.values() for date_value in frame["date"].tolist()})
2432 intersection_dates: set[pd.Timestamp] | None = None
2433 for frame in asset_frames.values():
2434 date_set = set(frame["date"].tolist())
2435 intersection_dates = date_set if intersection_dates is None else intersection_dates & date_set
2437 engineered_frames: dict[str, pd.DataFrame] = {}
2438 asset_summaries = []
2439 raw_frames = {
2440 asset["ticker"]: asset_frames[asset["ticker"]].sort_values("date").reset_index(drop=True) for asset in assets
2441 }
2442 timeline = CrossAssetTimeline.from_frames(
2443 raw_frames, {asset["ticker"]: asset["security_type"] for asset in assets}, forex_holidays=forex_holidays
2444 )
2445 for asset in assets:
2446 ticker = asset["ticker"]
2447 asset_frame = raw_frames[ticker]
2448 if asset["security_type"] == "forex":
2449 engineered = engineer_forex_features_on_lean_calendar(
2450 asset_frame, BASE_FEATURE_NAMES, windows, forex_holidays,
2451 max_abs_daily_return=max_abs_daily_return,
2452 max_abs_return_5d=max_abs_return_5d,
2453 max_abs_return_20d=max_abs_return_20d,
2454 extra_horizon_days=extra_horizon_days,
2455 )
2456 else:
2457 # add_liquidity_features() runs on the RAW frame (before
2458 # engineer_features() drops the first row) so its trailing spread
2459 # window sees the true, undropped bar sequence - see that
2460 # function's docstring for why this ordering is load-bearing, not
2461 # cosmetic.
2462 asset_frame = add_liquidity_features(asset_frame, asset["security_type"])
2463 engineered = engineer_features(
2464 asset_frame,
2465 BASE_FEATURE_NAMES,
2466 windows,
2467 security_type=asset["security_type"],
2468 max_abs_daily_return=max_abs_daily_return,
2469 max_abs_return_5d=max_abs_return_5d,
2470 max_abs_return_20d=max_abs_return_20d,
2471 extra_horizon_days=extra_horizon_days,
2472 )
2473 engineered_frames[ticker] = engineered
2474 asset_summaries.append(
2475 {
2476 "ticker": ticker,
2477 "available_rows": int(len(asset_frame)),
2478 "feature_rows": int(len(engineered)),
2479 "date_start": asset_frame["date"].min().date().isoformat()
2480 if not asset_frame.empty else None,
2481 "date_end": asset_frame["date"].max().date().isoformat()
2482 if not asset_frame.empty else None,
2483 }
2484 )
2486 # Cross-sectional (needs every asset's engineered frame simultaneously) -
2487 # must run after the per-asset loop above, before the final concat.
2488 engineered_frames = build_topology_features_by_date(engineered_frames, config, timeline)
2489 # development/Problems.md #71 (Phase 4.12, A4): add_regime_features()
2490 # moved here, AFTER topology, specifically so _encode_regime_row() can
2491 # read each row's own just-computed topology_correlation_strength as a
2492 # real average_correlation - previously hardcoded to 0.0 because this
2493 # call ran inside the per-asset loop above, before any cross-asset
2494 # correlation data existed for ANY asset. This closes a real gap: the
2495 # risk_off-reinforcing "correlated crash" rule in
2496 # regime/market_regime.py::classify_risk_regime() (correlation >= 0.75
2497 # AND high_volatility) could never fire offline before this change,
2498 # exactly the systemic-correlation-spike signature a genuine market
2499 # crash (e.g. the 2019-12-27..2020-03-25 era) produces.
2500 # portfolio_drawdown stays 0.0 - genuinely no offline analog exists
2501 # (it depends on this run's own live account state, not recoverable
2502 # from historical bars).
2503 engineered_frames = {ticker: add_regime_features(frame) for ticker, frame in engineered_frames.items()}
2504 engineered_frames = build_macro_features_by_date(engineered_frames, config, timeline)
2505 # Hoisted (was inline in the bond call below): both FRED-backed
2506 # builders (bond, alt-data) need the same cache load, and
2507 # load_cached_fred_series() just globs a directory once, so there is
2508 # no reason to pay that I/O twice per build_feature_dataset() call.
2509 fred_cache_dir = phase1["universe"].get("fred_cache_dir")
2510 fred_series = load_cached_fred_series(ROOT / fred_cache_dir) if fred_cache_dir else load_cached_fred_series()
2511 engineered_frames = build_bond_features_by_date(engineered_frames, config, fred_series)
2512 engineered_frames = build_alt_data_features_by_date(engineered_frames, config, fred_series)
2513 # V5.1 Phase 2 (item 8 / F2) - same fred_series input as the alt-data
2514 # call directly above, called right after it per that function's own
2515 # docstring.
2516 engineered_frames = build_cross_asset_sensitivity_features(engineered_frames, config, fred_series)
2517 engineered_frames = build_fx_carry_features(engineered_frames, config, fred_series)
2518 engineered_frames = build_derivatives_macro_features_by_date(engineered_frames, config)
2519 engineered_frames = build_cross_sectional_rank_targets(engineered_frames, config)
2520 # V5.1 Phase 2 (item 5) - same cross-sectional ordering constraint as
2521 # build_cross_sectional_rank_targets() itself (needs every asset's
2522 # target_return_Nd already computed, must run before the final
2523 # concat/strftime below).
2524 engineered_frames = build_residual_rank_targets(engineered_frames, config)
2525 engineered_frames = build_cross_sectional_momentum_rank_features(engineered_frames, timeline)
2527 dataset = pd.concat(list(engineered_frames.values()), ignore_index=True)
2528 dataset = dataset.sort_values(["date", "ticker"]).reset_index(drop=True)
2529 dataset["date"] = dataset["date"].dt.strftime("%Y-%m-%d")
2531 metadata = {
2532 "alignment_mode": "per_asset_window_union",
2533 "union_dates": len(union_dates),
2534 "intersection_dates": len(intersection_dates or set()),
2535 "asset_summaries": asset_summaries,
2536 }
2537 return dataset, metadata
2540def build_asset_quality(config: dict, dataset: pd.DataFrame, metadata: dict) -> dict:
2541 phase9 = config.get("phase9", {})
2542 quality_config = phase9.get("asset_quality", {})
2543 min_total_rows = int(quality_config.get("min_total_feature_rows", 50))
2544 min_training_rows = int(quality_config.get("min_training_rows", 100))
2545 min_backtest_rows = int(quality_config.get("min_backtest_rows", 20))
2547 summary_by_ticker = {item["ticker"]: item for item in metadata.get("asset_summaries", [])}
2548 assets_by_ticker = {asset["ticker"]: asset for asset in config["phase1"]["universe"]["assets"]}
2549 grouped_counts = dataset.groupby(["ticker", "split"]).size().reset_index(name="rows")
2550 split_counts: dict[str, dict[str, int]] = {}
2551 for row in grouped_counts.to_dict(orient="records"):
2552 split_counts.setdefault(row["ticker"], {})
2553 split_counts[row["ticker"]][row["split"]] = int(row["rows"])
2555 quality: dict[str, dict] = {}
2556 for ticker, asset in assets_by_ticker.items():
2557 summary = summary_by_ticker.get(ticker, {})
2558 counts = split_counts.get(ticker, {})
2559 total_rows = int(summary.get("feature_rows", 0))
2560 training_rows = int(counts.get("train", 0))
2561 validation_rows = int(counts.get("validation", 0))
2562 backtest_rows = int(counts.get("backtest", 0))
2564 # `backtest_rows` reads the future: it dropped a name that died before the backtest from all earlier training, which
2565 # is survivorship. V6.6.0's `eligibility_ignores_backtest_rows` removes the clause (default off: installed models keep their recipe).
2566 ignores_backtest_rows = bool(quality_config.get("eligibility_ignores_backtest_rows", False))
2567 training_eligible = (
2568 total_rows >= min_total_rows
2569 and training_rows >= min_training_rows
2570 and (ignores_backtest_rows or backtest_rows >= min_backtest_rows)
2571 )
2572 # V5.7.0: `trading_eligibility_basis: "history"` lets a name with too few TRAIN rows (ETH starts in 2017-09: 54 train
2573 # rows) trade on its validation + backtest history; the pooled model still scores it (its features exist) but its
2574 # rows are never fitted on. Default "train_rows" = the old rule (trading eligible == training eligible).
2575 history_eligible = (
2576 str(quality_config.get("trading_eligibility_basis", "train_rows")) == "history"
2577 and total_rows >= min_total_rows
2578 and validation_rows + backtest_rows >= int(quality_config.get("min_trading_history_rows", 365))
2579 and backtest_rows >= min_backtest_rows
2580 )
2581 trading_eligible = training_eligible or history_eligible
2583 if training_eligible:
2584 quality_tier = "core"
2585 reason = "sufficient_training_and_backtest_history"
2586 role = "model_training_and_trading"
2587 elif history_eligible:
2588 quality_tier = "core"
2589 reason = "scored_by_the_pooled_model_and_tradable_on_validation_and_backtest_history"
2590 role = "trading_without_training_rows"
2591 elif total_rows >= 2:
2592 quality_tier = "thin"
2593 reason = "kept_visible_but_history_is_too_short_for_model_training_or_trading"
2594 role = "observation_only"
2595 else:
2596 quality_tier = "insufficient"
2597 reason = "not_enough_feature_rows_after_engineering"
2598 role = "observation_only"
2600 quality[ticker] = {
2601 "ticker": ticker,
2602 "security_type": asset["security_type"],
2603 "market": asset["market"],
2604 "quality_tier": quality_tier,
2605 "role": role,
2606 "training_eligible": training_eligible,
2607 "trading_eligible": trading_eligible,
2608 "available_rows": int(summary.get("available_rows", 0)),
2609 "feature_rows": total_rows,
2610 "split_rows": {
2611 "train": training_rows,
2612 "validation": validation_rows,
2613 "backtest": backtest_rows,
2614 },
2615 "date_start": summary.get("date_start"),
2616 "date_end": summary.get("date_end"),
2617 "reason": reason,
2618 }
2620 return quality
2623def apply_asset_quality_flags(dataset: pd.DataFrame, asset_quality: dict) -> pd.DataFrame:
2624 result = dataset.copy()
2625 result["quality_tier"] = result["ticker"].map(
2626 lambda ticker: asset_quality.get(ticker, {}).get("quality_tier", "unknown")
2627 )
2628 result["training_eligible"] = result["ticker"].map(
2629 lambda ticker: bool(asset_quality.get(ticker, {}).get("training_eligible", False))
2630 )
2631 result["trading_eligible"] = result["ticker"].map(
2632 lambda ticker: bool(asset_quality.get(ticker, {}).get("trading_eligible", False))
2633 )
2634 return result
2637def fit_and_apply_scaler(
2638 dataset: pd.DataFrame,
2639 feature_names: list[str],
2640 *,
2641 winsorize_quantiles: tuple[float, float] = (0.001, 0.999),
2642 clip_sigma: float = 10.0,
2643) -> tuple[pd.DataFrame, StandardScaler, float]:
2644 train_mask = dataset["split"] == "train"
2645 if "training_eligible" in dataset.columns:
2646 train_mask = train_mask & dataset["training_eligible"]
2647 if int(train_mask.sum()) == 0:
2648 raise ValueError("No training-eligible rows available to fit scaler.")
2650 train_features = dataset.loc[train_mask, feature_names]
2651 # Winsorize a COPY of the train-only slice before fitting so a single
2652 # extreme outlier (e.g. BTCUSD's 2018-08-14 volume-feed discontinuity,
2653 # see development/Problems.md) can't distort the scaler's mean/std
2654 # estimate - only the fit is robustified, every row's real,
2655 # unwinsorized value is still what gets transformed below.
2656 lower_quantile, upper_quantile = winsorize_quantiles
2657 lower_bounds = train_features.quantile(lower_quantile)
2658 upper_bounds = train_features.quantile(upper_quantile)
2659 winsorized_train_features = train_features.clip(lower=lower_bounds, upper=upper_bounds, axis=1)
2661 scaler = StandardScaler()
2662 scaler.fit(winsorized_train_features)
2664 scaled_values = scaler.transform(dataset[feature_names])
2665 # Clip in scaled (sigma) space too - this is the layer that actually
2666 # protects downstream models (especially the sequence encoder, whose
2667 # sliding window replicates a single poisoned row into every subsequent
2668 # window) from a validation/backtest-split outlier the train-only
2669 # winsorized fit above can't see or bound on its own.
2670 scaled_values = np.clip(scaled_values, -clip_sigma, clip_sigma)
2671 for index, feature_name in enumerate(feature_names):
2672 dataset[f"{feature_name}_scaled"] = scaled_values[:, index]
2674 return dataset, scaler, float(clip_sigma)
2677def apply_scaler_stats(dataset: pd.DataFrame, scaler_stats: dict) -> pd.DataFrame:
2678 """Scales `dataset` with an ALREADY FITTED scaler (the active `ml/scaler_stats.json`) instead of fitting a new one:
2679 `(x - mean) / scale` clipped to +-clip_sigma, the identical transform `main.py` applies at runtime. The out-of-window
2680 holdout (V5.7.0) must be scored with the training-window statistics, never with its own."""
2681 names = list(scaler_stats["feature_names"])
2682 mean = np.asarray(scaler_stats["mean"], dtype=float)
2683 scale = np.asarray(scaler_stats["scale"], dtype=float)
2684 scale = np.where(scale == 0.0, 1.0, scale)
2685 clip_sigma = float(scaler_stats.get("clip_sigma", 10.0))
2686 scaled = np.clip((dataset[names].to_numpy(dtype=float) - mean) / scale, -clip_sigma, clip_sigma)
2687 result = dataset.copy()
2688 for index, name in enumerate(names):
2689 result[f"{name}_scaled"] = scaled[:, index]
2690 return result
2693def build_holdout_config(config: dict, holdout_root: str, holdout_start: str, holdout_end: str) -> tuple[dict, list[str]]:
2694 """The config that builds the out-of-window holdout dataset (V5.7.0, todo.md finding 10): every asset reads its zip
2695 from `holdout_root` (same relative path as `data_path`; assets without a zip there are dropped and returned), the
2696 `backtest` window becomes the holdout window, Lean's factor files are not applied (the holdout zips are Yahoo-adjusted)
2697 and the FRED cache comes from the holdout root. Train / validation windows stay the model's own so the features of
2698 those rows (and the scaler statistics) are the ones the model was trained with."""
2699 holdout_config = copy.deepcopy(config)
2700 universe = holdout_config["phase1"]["universe"]
2701 kept, dropped = [], []
2702 for asset in universe["assets"]:
2703 relative = Path(asset["data_path"])
2704 rewritten = Path(holdout_root) / Path(*relative.parts[1:]) if relative.parts and relative.parts[0] == "data" else None
2705 if rewritten is not None and (ROOT / rewritten).exists():
2706 kept.append({**asset, "data_path": rewritten.as_posix()})
2707 else:
2708 dropped.append(asset["ticker"])
2709 universe["assets"] = kept
2710 universe["common_window"] = {**universe["common_window"], "end": holdout_end}
2711 universe["apply_factor_files"] = False
2712 universe["fred_cache_dir"] = (Path(holdout_root) / "reference" / "fred_series").as_posix()
2713 holdout_config["phase1"]["windows"] = {
2714 **holdout_config["phase1"]["windows"],
2715 "backtest": {"start": holdout_start, "end": holdout_end},
2716 }
2717 return holdout_config, dropped
2720def add_asset_context_features(dataset: pd.DataFrame, tickers: list[str]) -> tuple[pd.DataFrame, list[str]]:
2721 context_columns: list[str] = []
2722 for ticker in tickers:
2723 column_name = f"asset_{ticker}"
2724 dataset[column_name] = (dataset["ticker"] == ticker).astype(float)
2725 context_columns.append(column_name)
2726 return dataset, context_columns
2729# V5.7.0: "forex" added - the 15 FX pairs had an all-zero class context, indistinguishable from nothing. main.py fills
2730# `asset_class_<class>` generically from the exported schema, so live needs no change (a retrain lists the new input).
2731ASSET_CLASS_VALUES = ("equity", "crypto", "bond", "future", "option", "forex")
2734def add_asset_class_context_features(dataset: pd.DataFrame, asset_class_by_ticker: dict[str, str]) -> tuple[pd.DataFrame, list[str]]:
2735 """5-column one-hot over ASSET_CLASS_VALUES - additive sibling to
2736 add_asset_context_features()'s per-ticker one-hot, deliberately using
2737 the same "asset_"-prefixed naming convention (asset_class_equity,
2738 asset_class_bond, ...) so build_dataset_manifest()'s existing generic
2739 `column.startswith("asset_")` filter picks these up as
2740 context_feature_names automatically - zero changes needed there. This
2741 is the mechanism letting the model condition on asset class (equity vs
2742 crypto vs bond vs future vs option) inside one shared, unified feature
2743 vector rather than requiring a separate model per asset class - see
2744 train.py's module-level docstring / development/architecture.md for
2745 why a single shared vector was chosen over per-asset-class models
2746 (fragmenting the rank-IC promotion gate and MoE gating architecture
2747 across 5 models, and breaking cross-asset macro-feature sharing).
2749 A ticker missing from asset_class_by_ticker (shouldn't happen -
2750 callers always build it from the full configured universe, but
2751 defensive) falls back to "equity", the least-surprising default and
2752 this codebase's existing Lean security_type default everywhere else."""
2753 ticker_classes = dataset["ticker"].map(lambda ticker: asset_class_by_ticker.get(ticker, "equity"))
2754 context_columns: list[str] = []
2755 for asset_class in ASSET_CLASS_VALUES:
2756 column_name = f"asset_class_{asset_class}"
2757 dataset[column_name] = (ticker_classes == asset_class).astype(float)
2758 context_columns.append(column_name)
2759 return dataset, context_columns
2762def select_model_context_columns(dataset_columns) -> list[str]:
2763 """The one place that decides which "asset_"-prefixed dataset columns
2764 become actual model inputs - used by build_dataset_manifest() (what
2765 gets exported as feature_schema.json's context_feature_names, which
2766 main.py reads at runtime) AND by every trainer's own feature_names
2767 construction, so the exported schema and the actually-trained model
2768 input vector can never drift apart (same predicate, same column order,
2769 computed from the same dataset object).
2771 Selects only the 5 asset_class_* columns (add_asset_class_context_features()),
2772 not the per-ticker asset_<TICKER> ones (add_asset_context_features()) -
2773 35 of this model's 85 inputs used to be static per-ticker identity
2774 flags (development/Problems.md), which can only encode each ticker's
2775 own base rate and pushes the net toward a constant per-asset output.
2776 Collapsing to 5 class-level flags keeps the "which kind of asset is
2777 this" context signal (needed for the macro/bond/crypto feature blocks
2778 to mean the right thing per asset class) without the per-ticker
2779 memorization capacity. add_asset_context_features() itself is
2780 unchanged and still runs (other, non-model-input consumers may still
2781 want the per-ticker columns in the dataset) - this only changes which
2782 columns get SELECTED as model inputs.
2784 Safe on the runtime side without further plumbing: main.py's
2785 context_values dict (main.py::_build_model_input()) is built generically
2786 from whatever names feature_schema.json's context_feature_names lists,
2787 filling asset_<ticker>/asset_class_<class> keys only "if key in
2788 context_values" - a per-ticker key simply won't exist post-collapse,
2789 exactly like an older exported model's schema missing the (newer)
2790 asset_class_ keys entirely already degrades gracefully today."""
2791 return [column for column in dataset_columns if str(column).startswith("asset_class_")]
2794def asset_class_by_ticker_from_config(config: dict) -> dict[str, str]:
2795 return {
2796 asset["ticker"]: asset.get("asset_class") or asset.get("security_type")
2797 for asset in config["phase1"]["universe"]["assets"]
2798 }
2801# Structural/bookkeeping columns that persist in the final dataset but are
2802# neither features (input_set/scaled/categorical/context) nor target_*
2803# columns - RAW_COLUMNS (the raw OHLCV+timestamp columns read straight off
2804# the Lean bars, train.py:122) plus the asset-identity/quality columns
2805# added later in build_feature_dataset() (security_type/market at
2806# load_lean_bars() time; quality_tier/trading_eligible/training_eligible
2807# from the asset-quality pass). "date"/"ticker"/"split" are the row-identity
2808# columns added by the final concat.
2809_NON_FEATURE_DATASET_COLUMNS = {
2810 "date", "ticker", "split",
2811 *RAW_COLUMNS,
2812 "security_type", "market", "quality_tier", "trading_eligible", "training_eligible",
2813}
2816def _computed_but_unused_feature_columns(
2817 dataset_columns,
2818 base_feature_names: list[str],
2819 scaled_feature_names: list[str],
2820 categorical_feature_names: list[str],
2821 context_feature_names: list[str],
2822) -> list[str]:
2823 """Dataset columns that are neither in phase1.features.input_set
2824 (base_feature_names, or its scaled/categorical/context siblings) nor a
2825 target_*/bookkeeping column - i.e. genuinely computed, genuinely never
2826 trained on. V5.1 Phase 2 (item 8, Step 2.5): makes the class of silent
2827 waste this session found (the 3 derivatives-macro features - constant
2828 0.0 with no futures/options contract subscribed, yet fully computed
2829 every dataset build) impossible to repeat unnoticed - any future
2830 feature builder that gets wired into build_feature_dataset() but
2831 forgotten in input_set now shows up here automatically, with zero
2832 manual bookkeeping.
2834 GUARDRAIL (found via CODESPACE RUN 1's first real dataset build,
2835 Problems.md): the dataset passed in here is POST-scaling, so it
2836 carries BOTH each raw base_feature_names column AND its "_scaled"
2837 sibling as separate columns - omitting scaled_feature_names from the
2838 exclusion set flags every single scaled feature as "unused". Same for
2839 categorical_feature_names (the regime_*/topology_risk_* one-hots) and
2840 the raw OHLCV/asset-identity bookkeeping columns
2841 (_NON_FEATURE_DATASET_COLUMNS) - a small synthetic unit-test fixture
2842 never exercises these, only a real end-to-end dataset build does.
2844 Excludes "asset_"-prefixed columns (both add_asset_context_features()'s
2845 per-ticker asset_<TICKER> one-hots and add_asset_class_context_features()'s
2846 asset_class_<class> ones) - these are deliberately dataset-only/context,
2847 not "computed but forgotten" features, the same distinction
2848 select_model_context_columns()'s own docstring draws."""
2849 known = (
2850 set(base_feature_names)
2851 | set(scaled_feature_names)
2852 | set(categorical_feature_names)
2853 | set(context_feature_names)
2854 | _NON_FEATURE_DATASET_COLUMNS
2855 )
2856 return sorted(
2857 str(column)
2858 for column in dataset_columns
2859 if column not in known and not str(column).startswith("target_") and not str(column).startswith("asset_")
2860 )
2863def build_dataset_manifest(
2864 config: dict,
2865 dataset: pd.DataFrame,
2866 inventory: dict,
2867 metadata: dict,
2868 asset_quality: dict,
2869) -> dict:
2870 base_feature_names = config["phase1"]["features"]["input_set"]
2871 context_feature_names = select_model_context_columns(dataset.columns)
2872 categorical_feature_names = _categorical_feature_names(dataset)
2873 scaled_feature_names = [f"{feature_name}_scaled" for feature_name in base_feature_names]
2874 model_input_names = scaled_feature_names + categorical_feature_names + context_feature_names
2876 split_counts = {split: int(count) for split, count in dataset["split"].value_counts().sort_index().items()}
2877 per_asset_split = {}
2878 grouped = dataset.groupby(["ticker", "split"]).size().reset_index(name="rows")
2879 for row in grouped.to_dict(orient="records"):
2880 ticker = row["ticker"]
2881 per_asset_split.setdefault(ticker, {})
2882 per_asset_split[ticker][row["split"]] = int(row["rows"])
2884 return {
2885 "project": config["name"],
2886 "phase": 2,
2887 "created_at": datetime.now(timezone.utc).isoformat(),
2888 "dataset_rows": int(len(dataset)),
2889 "feature_count": len(base_feature_names),
2890 "feature_names": base_feature_names,
2891 "scaled_feature_names": scaled_feature_names,
2892 "categorical_feature_names": categorical_feature_names,
2893 "context_feature_names": context_feature_names,
2894 "model_input_names": model_input_names,
2895 "model_input_count": len(model_input_names),
2896 "target_column": "target_direction",
2897 "aux_target_column": "target_return_1d",
2898 # Additive head->column map for the multi-horizon/ranking heads
2899 # (train_multitask.py/train_sequence.py) - never replaces
2900 # target_column/aux_target_column above, which every existing
2901 # consumer (experts/expert_datasets.py, feature_schema.json)
2902 # still reads unchanged.
2903 "target_columns": {
2904 "direction": "target_direction",
2905 "magnitude": "target_return_1d",
2906 "volatility": "target_volatility_next_day",
2907 "direction_5d": "target_direction_5d",
2908 "direction_20d": "target_direction_20d",
2909 "rank_5d": "target_rank_5d",
2910 "rank_20d": "target_rank_20d",
2911 "sector_neutral_rank_20d": "target_sector_neutral_rank_20d",
2912 "residual_rank_5d": "target_residual_rank_5d",
2913 "residual_rank_20d": "target_residual_rank_20d",
2914 "beta_neutral_rank_20d": "target_beta_neutral_rank_20d",
2915 },
2916 # V5.1 Phase 2, Step 2.5 - see _computed_but_unused_feature_columns()'s
2917 # own docstring.
2918 "computed_but_unused_features": _computed_but_unused_feature_columns(
2919 dataset.columns, base_feature_names, scaled_feature_names, categorical_feature_names, context_feature_names
2920 ),
2921 "split_counts": split_counts,
2922 "per_asset_split_counts": per_asset_split,
2923 "asset_quality": asset_quality,
2924 "training_eligible_assets": [
2925 ticker for ticker, quality in asset_quality.items() if quality["training_eligible"]
2926 ],
2927 "trading_eligible_assets": [
2928 ticker for ticker, quality in asset_quality.items() if quality["trading_eligible"]
2929 ],
2930 "observation_only_assets": [
2931 ticker for ticker, quality in asset_quality.items() if not quality["trading_eligible"]
2932 ],
2933 "date_range": {
2934 "start": str(dataset["date"].min()) if not dataset.empty else None,
2935 "end": str(dataset["date"].max()) if not dataset.empty else None,
2936 },
2937 "alignment": metadata,
2938 # _run_walk_forward() passes an empty inventory ({}) per window - the
2939 # data-coverage snapshot is identical across windows and not worth
2940 # recomputing per fold - so tolerate a missing key rather than
2941 # KeyError (the main, non-walk-forward path always passes a real one).
2942 "inventory_snapshot": inventory.get("coverage_checks", {}),
2943 }
2946def write_inventory_file(inventory: dict) -> None:
2947 INVENTORY_PATH.write_text(json.dumps(inventory, indent=2), encoding="utf-8")
2950def write_scaler_artifacts(
2951 scaler: StandardScaler,
2952 manifest: dict,
2953 *,
2954 scaler_path: Path | None = None,
2955 scaler_stats_path: Path | None = None,
2956 clip_sigma: float = 10.0,
2957) -> None:
2958 """Persists the fitted scaler as both the joblib pickle (training-only)
2959 and the JSON mean/scale arrays main.py actually loads for inference.
2960 `clip_sigma` (the scaled-value clip bound fit_and_apply_scaler() already
2961 applied offline) is carried along so main.py can apply the identical
2962 bound at runtime - see main.py::_build_model_input()'s matching clamp,
2963 with a safe default of 10.0 for scaler_stats.json files written before
2964 this field existed.
2966 Extracted out of write_dataset_artifacts() so candidate training (V2-17)
2967 can write into ml/versions/<id>/ without touching the active scaler.
2968 """
2969 # Resolved here, not bound as defaults: a default captured at import time keeps pointing at the real ml/ after a test
2970 # moves the module's constants, which is how the installed scaler was rewritten under unchanged models (#382).
2971 scaler_path = SCALER_PATH if scaler_path is None else scaler_path
2972 scaler_stats_path = SCALER_STATS_PATH if scaler_stats_path is None else scaler_stats_path
2973 scaler_path.parent.mkdir(parents=True, exist_ok=True)
2974 joblib.dump(scaler, scaler_path)
2975 scaler_stats_path.write_text(
2976 json.dumps(
2977 {
2978 "feature_names": manifest["feature_names"],
2979 "mean": [float(value) for value in scaler.mean_.tolist()],
2980 "scale": [float(value) for value in scaler.scale_.tolist()],
2981 "clip_sigma": float(clip_sigma),
2982 },
2983 indent=2,
2984 ),
2985 encoding="utf-8",
2986 )
2989def build_feature_schema_payload(manifest: dict) -> dict:
2990 """Pure extraction of the feature-schema JSON shape from a dataset
2991 manifest (V5.1 Phase 4, Step 4.1). Shared by write_dataset_artifacts()
2992 (writes to the active ml/feature_schema.json) and _run_walk_forward()
2993 (writes one per window) so the two call sites can never drift apart -
2994 previously only write_dataset_artifacts() built this dict inline and
2995 _run_walk_forward() never wrote a schema file at all, which meant a
2996 per-window train_multitask.py/train_sequence.py subprocess had no
2997 feature schema to read (see --feature-schema-path's docstring)."""
2998 return {
2999 "project": manifest["project"],
3000 "phase": 2,
3001 "feature_names": manifest["feature_names"],
3002 "scaled_feature_names": manifest["scaled_feature_names"],
3003 "categorical_feature_names": manifest["categorical_feature_names"],
3004 "context_feature_names": manifest["context_feature_names"],
3005 "model_input_names": manifest["model_input_names"],
3006 "target_column": manifest["target_column"],
3007 "split_column": "split",
3008 "asset_quality": manifest["asset_quality"],
3009 "training_eligible_assets": manifest["training_eligible_assets"],
3010 "trading_eligible_assets": manifest["trading_eligible_assets"],
3011 "observation_only_assets": manifest["observation_only_assets"],
3012 }
3015def write_dataset_artifacts(
3016 dataset: pd.DataFrame,
3017 manifest: dict,
3018 scaler: StandardScaler,
3019 config: dict | None = None,
3020 clip_sigma: float = 10.0,
3021) -> None:
3022 dataset.to_csv(FULL_DATASET_PATH, index=False)
3023 dataset[dataset["split"] == "train"].to_csv(TRAIN_DATASET_PATH, index=False)
3024 dataset[dataset["split"] == "validation"].to_csv(VALIDATION_DATASET_PATH, index=False)
3025 dataset[dataset["split"] == "backtest"].to_csv(BACKTEST_DATASET_PATH, index=False)
3027 DATASET_MANIFEST_PATH.write_text(json.dumps(manifest, indent=2), encoding="utf-8")
3028 FEATURE_SCHEMA_PATH.write_text(json.dumps(build_feature_schema_payload(manifest), indent=2), encoding="utf-8")
3029 write_scaler_artifacts(scaler, manifest, clip_sigma=clip_sigma)
3031 expert_dataset, expert_manifest = build_expert_dataset_manifest(dataset, manifest, config)
3032 write_expert_dataset_artifacts(
3033 expert_dataset,
3034 expert_manifest,
3035 EXPERT_DATASET_DIR,
3036 EXPERT_DATASET_MANIFEST_PATH,
3037 )
3042def build_sequence_tensor_dataset(
3043 dataset: pd.DataFrame, model_input_names: list[str], window_size: int, row_mask: np.ndarray | None = None
3044) -> np.ndarray:
3045 """Builds a (rows, window_size, features) tensor, row-order-aligned
3046 with `dataset` itself (sequences[i] corresponds to dataset.iloc[i]),
3047 using each ticker's own trailing window of already-computed
3048 model_input columns - the exact same 48-dim vector AetherNetMultiTask's
3049 flat trunk already consumes per row. Phase 2 needs no new feature
3050 engineering, only windowing over what Phase 1 already computes per bar
3051 - `dataset` must already be sorted the way build_feature_dataset()
3052 leaves it (by date within each ticker's own rows, in chronological
3053 order).
3055 Rows with fewer than `window_size` preceding rows (including itself)
3056 for their ticker are LEFT-PADDED with zeros - main.py's runtime
3057 rolling buffer (main.py::_build_sequence_model_input()) starts empty
3058 and fills up bar by bar the same way, so this is the correct offline
3059 mirror of that behavior, not an approximation.
3061 `row_mask` (V5.8.0): build only the masked rows (in dataset order), still windowing over each ticker's FULL
3062 history - a validation row's window reaches back into train rows exactly as before. Per-split tensors built this
3063 way never materialise the full (rows, window, features) array, which with the 2014-2021 train window is ~2 GB."""
3064 feature_matrix = dataset[model_input_names].to_numpy(dtype=np.float32)
3065 tickers = dataset["ticker"].to_numpy()
3067 output_row_by_position: np.ndarray | None = None
3068 if row_mask is not None:
3069 row_mask = np.asarray(row_mask, dtype=bool)
3070 output_row_by_position = np.full(len(dataset), -1, dtype=np.int64)
3071 output_row_by_position[row_mask] = np.arange(int(row_mask.sum()))
3072 output_rows = len(dataset) if row_mask is None else int(row_mask.sum())
3073 sequences = np.zeros((output_rows, window_size, len(model_input_names)), dtype=np.float32)
3074 positions_by_ticker: dict[str, list[int]] = {}
3075 for position, ticker in enumerate(tickers):
3076 positions_by_ticker.setdefault(ticker, []).append(position)
3078 for positions in positions_by_ticker.values():
3079 for index_within_ticker, position in enumerate(positions):
3080 output_row = position if output_row_by_position is None else output_row_by_position[position]
3081 if output_row < 0:
3082 continue
3083 window_start = max(0, index_within_ticker + 1 - window_size)
3084 window_positions = positions[window_start : index_within_ticker + 1]
3085 window_values = feature_matrix[window_positions]
3086 sequences[output_row, -len(window_values):, :] = window_values
3088 return sequences
3093def split_frame(dataset: pd.DataFrame, split_name: str) -> pd.DataFrame:
3094 return dataset[dataset["split"] == split_name].reset_index(drop=True)
3097def frame_to_tensors(frame: pd.DataFrame, feature_names: list[str]) -> tuple[torch.Tensor, torch.Tensor]:
3098 features = torch.tensor(frame[feature_names].to_numpy(dtype=np.float32), dtype=torch.float32)
3099 targets = torch.tensor(frame["target_direction"].to_numpy(dtype=np.float32), dtype=torch.float32)
3100 return features, targets
3103def compute_binary_metrics(
3104 logits: torch.Tensor,
3105 targets: torch.Tensor,
3106 criterion: nn.Module,
3107 threshold: float,
3108) -> dict:
3109 loss = float(criterion(logits, targets).item())
3110 probabilities = torch.sigmoid(logits)
3111 predictions = (probabilities >= threshold).float()
3113 targets_np = targets.detach().cpu().numpy()
3114 predictions_np = predictions.detach().cpu().numpy()
3115 probabilities_np = probabilities.detach().cpu().numpy()
3117 tp = int(((predictions_np == 1) & (targets_np == 1)).sum())
3118 tn = int(((predictions_np == 0) & (targets_np == 0)).sum())
3119 fp = int(((predictions_np == 1) & (targets_np == 0)).sum())
3120 fn = int(((predictions_np == 0) & (targets_np == 1)).sum())
3122 total = max(len(targets_np), 1)
3123 accuracy = (tp + tn) / total
3124 precision = tp / max(tp + fp, 1)
3125 recall = tp / max(tp + fn, 1)
3126 specificity = tn / max(tn + fp, 1)
3127 balanced_accuracy = (recall + specificity) / 2.0
3128 f1 = 2 * precision * recall / max(precision + recall, 1e-12)
3129 denominator = max(((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn)) ** 0.5, 1e-12)
3130 matthews_corrcoef = ((tp * tn) - (fp * fn)) / denominator
3132 return {
3133 "loss": loss,
3134 "accuracy": accuracy,
3135 "balanced_accuracy": balanced_accuracy,
3136 "precision": precision,
3137 "recall": recall,
3138 "specificity": specificity,
3139 "f1": f1,
3140 "mcc": matthews_corrcoef,
3141 "threshold": threshold,
3142 "positive_rate": float(predictions_np.mean()) if len(predictions_np) else 0.0,
3143 "average_probability": float(probabilities_np.mean()) if len(probabilities_np) else 0.0,
3144 "confusion_matrix": {
3145 "tp": tp,
3146 "tn": tn,
3147 "fp": fp,
3148 "fn": fn,
3149 },
3150 }
3155def compute_regression_metrics(predictions: torch.Tensor, targets: torch.Tensor) -> dict:
3156 """Plain regression metrics (MAE/RMSE + bias) for the magnitude/volatility
3157 heads - compute_binary_metrics() above stays direction-only, since MCC/
3158 F1/precision-recall are meaningless for a continuous target."""
3159 predictions_np = predictions.detach().cpu().numpy()
3160 targets_np = targets.detach().cpu().numpy()
3161 errors = predictions_np - targets_np
3162 mae = float(np.abs(errors).mean()) if len(errors) else 0.0
3163 rmse = float(np.sqrt((errors ** 2).mean())) if len(errors) else 0.0
3164 bias = float(errors.mean()) if len(errors) else 0.0
3165 return {
3166 "mae": mae,
3167 "rmse": rmse,
3168 "bias": bias,
3169 "mean_prediction": float(predictions_np.mean()) if len(predictions_np) else 0.0,
3170 "mean_target": float(targets_np.mean()) if len(targets_np) else 0.0,
3171 }
3176# V5.2.8 (development/Problems.md #94) - a small, real, calibrated floor
3177# (never exactly 0.0 - a date must always contribute SOME gradient,
3178# same "never let one exotic input silently kill a whole term" reasoning
3179# risk_off_override_min_severity's own None-sentinel design already
3180# established for the live analyzer).
3181_GATE_FRIENDLINESS_WEIGHT_FLOOR = 0.1
3184def compute_gate_friendliness_weight_by_date(frame: pd.DataFrame, risk_off_override_min_severity: float = 0.0) -> dict:
3185 """V5.2.8 (development/Problems.md #94) - per-date scalar weight in
3186 (0, 1] approximating what fraction of that date's cross-section would
3187 have cleared the SAME two STATELESS, asset-level gates
3188 analyzer/market_analyzer.py::build_market_analysis_decision() applies
3189 at Priority 2 (regime risk_off override) and Priority 3 (topology
3190 elevated/isolated override). risk_off_override_min_severity should be
3191 the caller's already-resolved phase_v2.regime_detection.
3192 risk_off_override_min_severity value (the same V5.2.6-calibrated
3193 number the live analyzer uses, default 0.55 in config.json) - this
3194 function takes it as a plain float rather than a config dict, matching
3195 this codebase's convention of pure functions taking already-resolved
3196 scalars (e.g. risk_controls.py::assess_drawdown_lock()) rather than
3197 reaching into config themselves.
3199 Deliberately narrower than the full live decision chain - the
3200 liquidity block/thin gate is NOT included here: build_liquidity_decision()'s
3201 real classification needs raw daily-dollar-volume history plus an
3202 order-size assumption that isn't stored in this dataset in the needed
3203 shape (only the already-log-scaled liquidity_log_dollar_volume
3204 column exists), and approximating it with a newly-guessed percentile
3205 threshold would repeat exactly the "guessed constant" mistake this
3206 codebase has already found and fixed more than once (development/
3207 Problems.md #89/#90) - better to model two real gates precisely than
3208 three gates including one built on a shaky proxy. The portfolio-level
3209 kill-switch/drawdown-lock is excluded for the same reason
3210 evaluation/kill_switch_replay.py excludes it from ITS approximation:
3211 no per-row training-dataset equivalent exists (it's path-dependent on
3212 the actual book's own realized history, not a per-asset market
3213 condition). Keeping both sides of this round's gate-awareness work
3214 (evaluation and training) scoped to the same excluded set is
3215 deliberate, for consistency and honesty about what neither attempts.
3217 A frame missing every needed column degrades to
3218 weight 1.0 (today's exact uniform behavior for that date) rather than
3219 raising - this function must never be able to crash a training run."""
3220 required_columns = {"date", "topology_risk_elevated", "topology_risk_isolated", "regime_risk_off", "regime_signal_risk_score"}
3221 if not required_columns.issubset(frame.columns):
3222 return {str(date): 1.0 for date in frame["date"].unique()} if "date" in frame.columns else {}
3224 risk_off_override_min_severity = float(risk_off_override_min_severity or 0.0)
3226 weights: dict = {}
3227 for date, group in frame.groupby("date"):
3228 topology_gated = (group["topology_risk_elevated"] == 1) | (group["topology_risk_isolated"] == 1)
3229 risk_off_active = group["regime_risk_off"] == 1
3230 severity = group["regime_signal_risk_score"].abs()
3231 regime_gated = risk_off_active & (severity >= risk_off_override_min_severity)
3232 eligible_fraction = float((~(topology_gated | regime_gated)).mean())
3233 weights[str(date)] = max(eligible_fraction, _GATE_FRIENDLINESS_WEIGHT_FLOOR)
3234 return weights
3239def compute_masked_binary_metrics(
3240 logits: torch.Tensor,
3241 targets: torch.Tensor,
3242 criterion: nn.Module,
3243 threshold: float,
3244) -> dict | None:
3245 """compute_binary_metrics(), restricted to rows where `targets` is not
3246 NaN - compute_binary_metrics() itself has no NaN-awareness (a NaN
3247 target would silently miscount as a negative in its ==1/==0
3248 comparisons), so this must filter first. Returns None when a split has
3249 zero valid rows for this head (e.g. an unrealistically short backtest
3250 window shorter than the horizon itself) rather than reporting
3251 meaningless all-zero metrics."""
3252 mask = ~torch.isnan(targets)
3253 if not torch.any(mask):
3254 return None
3255 return compute_binary_metrics(logits[mask], targets[mask], criterion, threshold)
3258def compute_masked_regression_metrics(predictions: torch.Tensor, targets: torch.Tensor) -> dict | None:
3259 """compute_regression_metrics(), restricted to rows where `targets` is
3260 not NaN - same masking convention as compute_masked_binary_metrics()
3261 above, for the rank_5d/20d heads."""
3262 mask = ~torch.isnan(targets)
3263 if not torch.any(mask):
3264 return None
3265 return compute_regression_metrics(predictions[mask], targets[mask])
3268def _rank_ic_from_arrays(
3269 predictions: np.ndarray,
3270 targets: np.ndarray,
3271 dates: np.ndarray,
3272 non_overlapping_stride: int = 1,
3273) -> dict:
3274 """V5.3.5 (development/Problems.md #102) - thin re-export.
3275 The actual implementation now lives in
3276 evaluation/rank_ic_core.py::rank_ic_from_arrays() (moved, not
3277 duplicated) so main.py's live decision path can import the torch-free
3278 IC core directly without pulling in this module's heavy torch/sklearn
3279 imports (development/Problems.md #16 - the Lean 90-second isolator
3280 timeout this exact class of import risk already caused once). This
3281 alias exists purely so every existing internal call site in this file
3282 (compute_rank_ic(), bootstrap_ic_confidence_interval(), era-stability
3283 checks) keeps working unchanged. See the real docstring there."""
3284 return rank_ic_from_arrays(predictions, targets, dates, non_overlapping_stride)
3287def compute_rank_ic(
3288 predictions: torch.Tensor,
3289 targets: torch.Tensor,
3290 dates,
3291 *,
3292 non_overlapping_stride: int = 1,
3293) -> dict:
3294 """Training-time wrapper over _rank_ic_from_arrays() - converts torch
3295 tensors to numpy, then defers entirely to the shared core. See
3296 _rank_ic_from_arrays()'s docstring for the actual algorithm."""
3297 predictions_np = predictions.detach().cpu().numpy()
3298 targets_np = targets.detach().cpu().numpy()
3299 return _rank_ic_from_arrays(predictions_np, targets_np, np.asarray(dates), non_overlapping_stride)
3302def bootstrap_ic_confidence_interval(
3303 ic_values: list[float],
3304 n_resamples: int = 2000,
3305 confidence: float = 0.95,
3306 seed: int = 42,
3307) -> dict:
3308 """Phase 2 of the 5/10 -> 9/10 roadmap: a resample-with-replacement
3309 bootstrap confidence interval over compute_rank_ic()'s raw per-date IC
3310 series, the most direct way to answer this codebase's own promotion
3311 question ("mean rank-IC > 0.02, t-stat > 2, non-overlapping dates,
3312 stable across reruns" - see development/Changelog.md's "frontier-model
3313 edge investigation" entry) with an actual interval instead of a single
3314 point estimate that a single unlucky/lucky rerun could shift.
3316 Deterministic (fixed `seed`) so repeated calls on the same ic_values
3317 reproduce the exact same interval - this codebase's other
3318 randomness-touching code (e.g. topology warm-start) is deliberately
3319 seeded the same way. Returns a degenerate all-zero interval (never
3320 raises) when fewer than 2 IC values are available - a bootstrap over 0
3321 or 1 observations is undefined, not "wide," and callers (e.g.
3322 assess_ranking_quality() below) must treat that as a failure to
3323 demonstrate significance, not a passing near-zero interval."""
3324 if len(ic_values) < 2:
3325 return {
3326 "lower_bound": 0.0,
3327 "upper_bound": 0.0,
3328 "mean_ic": 0.0,
3329 "confidence": confidence,
3330 "n_resamples": 0,
3331 "num_observations": len(ic_values),
3332 }
3334 rng = np.random.default_rng(seed)
3335 ic_array = np.asarray(ic_values, dtype=float)
3336 resample_means = np.empty(n_resamples, dtype=float)
3337 for index in range(n_resamples):
3338 sample = rng.choice(ic_array, size=len(ic_array), replace=True)
3339 resample_means[index] = sample.mean()
3341 alpha = 1.0 - confidence
3342 lower_bound = float(np.quantile(resample_means, alpha / 2.0))
3343 upper_bound = float(np.quantile(resample_means, 1.0 - alpha / 2.0))
3344 return {
3345 "lower_bound": lower_bound,
3346 "upper_bound": upper_bound,
3347 "mean_ic": float(ic_array.mean()),
3348 "confidence": confidence,
3349 "n_resamples": n_resamples,
3350 "num_observations": len(ic_values),
3351 }
3354def average_ensemble_predictions(predictions_by_seed: list[torch.Tensor]) -> torch.Tensor:
3355 """Stage 4 of the rank-pivot roadmap (development/Problems.md#43):
3356 combines the SAME model architecture's predictions from independently-
3357 seeded training runs (see train_multitask.py/train_sequence.py's
3358 `ensemble_seeds` config) into one steadier signal for a given head
3359 (typically rank_20d).
3361 Deliberately PREDICTION averaging, not weight averaging: two networks
3362 trained from different random initializations generally land in
3363 different (but equally valid) regions of a non-convex loss landscape -
3364 their hidden units are not aligned to the same "meaning" (permutation
3365 symmetry), so averaging their raw weights elementwise produces a
3366 network that doesn't correspond to either optimum and is not
3367 guaranteed to be sensible, let alone better. Averaging their OUTPUTS
3368 instead is always well-defined regardless of internal alignment, is
3369 the standard neural-net ensembling technique in the literature, and
3370 matches this codebase's existing ensembling precedent (moe/gating.py's
3371 build_gating_decision() blends multiple experts' PROBABILITY outputs,
3372 never their weights).
3374 Deterministic (a plain elementwise mean) - same inputs always produce
3375 the same output, matching this codebase's other seeded-determinism
3376 conventions (set_seed()). Requires at least one prediction tensor, all
3377 the same shape (one entry per seed, each already evaluated on the same
3378 rows in the same order)."""
3379 if not predictions_by_seed:
3380 raise ValueError("average_ensemble_predictions() requires at least one prediction tensor")
3381 stacked = torch.stack(list(predictions_by_seed), dim=0)
3382 return stacked.mean(dim=0)
3385def aggregate_seed_ensemble_rank_ic(
3386 predictions_by_seed: dict[int, torch.Tensor],
3387 targets: torch.Tensor,
3388 dates,
3389 non_overlapping_stride: int = 20,
3390) -> dict:
3391 """Stage 4 of the rank-pivot roadmap (development/Problems.md#43): the
3392 evaluation half of seed-ensembling, pairing with
3393 average_ensemble_predictions() above and train_multitask.py/
3394 train_sequence.py's `--seed` CLI override.
3396 Workflow: train the same trainer once per seed (e.g. `--seed 42/43/44`,
3397 each its own --version-id, isolated under ml/versions/ exactly like any
3398 other --candidate run), reload each seed's exported backtest rank_20d
3399 predictions on the SAME rows/order (e.g. via
3400 inference/exported_model.py against the shared backtest split), then
3401 call this function once to get both the per-seed rank-IC (did any
3402 individual seed happen to get lucky/unlucky) and the ensembled rank-IC
3403 (does averaging across seeds actually produce a steadier signal - the
3404 entire point of ensembling). `dates` and `non_overlapping_stride`
3405 forward directly to compute_rank_ic() - default stride 20 matches
3406 rank_20d's own horizon (see compute_rank_ic()'s docstring on why the
3407 naive daily series overstates significance for a 20-day-forward
3408 target).
3410 Requires at least one seed. Returns a dict shaped for direct JSON
3411 serialization into an ensemble_summary.json-style artifact."""
3412 if not predictions_by_seed:
3413 raise ValueError("aggregate_seed_ensemble_rank_ic() requires at least one seed's predictions")
3415 per_seed_ic = {
3416 str(seed): compute_rank_ic(predictions, targets, dates, non_overlapping_stride=non_overlapping_stride)
3417 for seed, predictions in predictions_by_seed.items()
3418 }
3419 ensembled_predictions = average_ensemble_predictions(list(predictions_by_seed.values()))
3420 ensemble_ic = compute_rank_ic(ensembled_predictions, targets, dates, non_overlapping_stride=non_overlapping_stride)
3422 return {
3423 "seeds": sorted(predictions_by_seed.keys()),
3424 "per_seed_rank_ic": per_seed_ic,
3425 "ensemble_rank_ic": ensemble_ic,
3426 }
3429def compute_purged_cv_rank_ic_diagnostic(
3430 predictions: torch.Tensor,
3431 targets: torch.Tensor,
3432 dates,
3433 n_folds: int,
3434 horizon_days: int,
3435 embargo_days: int = 0,
3436) -> dict:
3437 """Stage 5 of the rank-pivot roadmap (development/Problems.md#43): the
3438 actual executed diagnostic behind phase1.target.ranking.purged_cv.enabled -
3439 purged_embargoed_folds() above existed as a tested, standalone utility
3440 with ZERO call sites in the actual training pipeline (config.json's flag
3441 was pure dead configuration, verified by grep - no production code path
3442 ever read it). This function is what train_multitask.py/train_sequence.py
3443 now call when that flag is true.
3445 Evaluates the model ALREADY trained on the full fixed train window's own
3446 rank_20d predictions against each purged/embargoed fold's held-out row
3447 subset - no extra training, no separately-trained per-fold models. This
3448 is a robustness check of one model's in-sample IC stability across
3449 sub-periods of its own training data, distinct from (and complementary
3450 to) assess_ranking_quality()'s non-overlapping-era check on the
3451 BACKTEST split: that asks "is the OOS edge concentrated in one regime?";
3452 this asks "is the model's fit itself concentrated in one training
3453 sub-period, or does it generalize evenly across the whole train
3454 window?" A per-fold IC that flips sign, or an aggregate far below the
3455 full-train IC, is evidence of exactly that overfit-to-one-sub-period
3456 failure mode.
3458 Requires `predictions`/`targets` aligned 1:1 with `dates` (same row
3459 order - typically the TRAIN split's own rows, since purging/embargoing
3460 is layered *inside* that split, never across the train/validation/
3461 backtest wall - see purged_embargoed_folds()'s docstring)."""
3462 folds = purged_embargoed_folds(dates, n_folds, horizon_days, embargo_days)
3463 dates_array = np.asarray(dates)
3464 per_fold = []
3465 for fold_index, (_train_indices, validation_indices) in enumerate(folds):
3466 fold_ic = compute_rank_ic(predictions[validation_indices], targets[validation_indices], dates_array[validation_indices])
3467 per_fold.append({"fold": fold_index, **fold_ic})
3469 folds_with_data = [fold for fold in per_fold if fold["num_dates"] > 0]
3470 mean_ics = [fold["mean_ic"] for fold in folds_with_data]
3471 return {
3472 "n_folds_requested": n_folds,
3473 "n_folds_with_data": len(folds_with_data),
3474 "per_fold": per_fold,
3475 "mean_ic_across_folds": float(np.mean(mean_ics)) if mean_ics else 0.0,
3476 "any_fold_opposite_sign": bool(mean_ics and min(mean_ics) < 0 < max(mean_ics)),
3477 # V5.7.0: the model scored here was TRAINED on these rows, so the fold ICs (0.40-0.49 on the V5.6.0 models)
3478 # measure how evenly the fit spreads over the train window, never generalization. Out-of-sample evidence is
3479 # the validation split (HAC t) and the walk-forward windows.
3480 "scope": "in_sample_fold_stability_not_out_of_sample",
3481 }
3484def split_into_non_overlapping_eras(dates, era_length_days: int) -> list[tuple]:
3485 """Phase 2 of the 5/10 -> 9/10 roadmap: chops the date range covered by
3486 `dates` (any array-like of orderable date values) into consecutive,
3487 non-overlapping eras of `era_length_days` each - e.g. quarterly eras
3488 over the existing 2019-2021 backtest window - so
3489 compute_rank_ic()/assess_ranking_quality() can be run independently per
3490 era instead of only ever producing one aggregate number. Turns the
3491 single "28 independent 20-day windows" analysis
3492 (development/Changelog.md) into a distribution across eras: was the
3493 edge concentrated in one regime (e.g. 2020 volatility), or stable?
3495 Returns a list of (era_start, era_end) date tuples spanning the full
3496 range of `dates` (inclusive on both ends, last era may be shorter than
3497 `era_length_days` if the range doesn't divide evenly - never dropped,
3498 since silently discarding the tail would bias eras away from the most
3499 recent data). Returns [] (never raises) when `dates` is empty."""
3500 # pd.to_datetime(), not np.asarray(): see purged_embargoed_folds()'s
3501 # identical comment - `dates` in every real caller is a plain string
3502 # array (build_feature_dataset() stringifies the date column), and
3503 # `era_start + era_length` below would raise on raw strings.
3504 dates_array = pd.to_datetime(np.asarray(dates))
3505 if len(dates_array) == 0:
3506 return []
3508 # np.unique(), not sorted(set(dates_array.tolist())) - see
3509 # purged_embargoed_folds()'s identical comment on why raw datetime64[ns]
3510 # numpy arrays need this, unlike a pandas Series.
3511 unique_dates = np.unique(dates_array)
3512 range_start = unique_dates[0]
3513 range_end = unique_dates[-1]
3514 era_length = pd.Timedelta(era_length_days, unit="D")
3516 eras: list[tuple] = []
3517 era_start = range_start
3518 while era_start <= range_end:
3519 era_end = min(era_start + era_length - pd.Timedelta(1, unit="D"), range_end)
3520 eras.append((era_start, era_end))
3521 era_start = era_end + pd.Timedelta(1, unit="D")
3523 return eras
3526def evaluate_split(
3527 model: nn.Module,
3528 frame: pd.DataFrame,
3529 feature_names: list[str],
3530 criterion: nn.Module,
3531 threshold: float,
3532 device: torch.device,
3533) -> dict:
3534 features, targets = frame_to_tensors(frame, feature_names)
3535 features = features.to(device)
3536 targets = targets.to(device)
3538 model.eval()
3539 with torch.no_grad():
3540 logits = model(features)
3541 return compute_binary_metrics(logits, targets, criterion, threshold)
3544def predict_probabilities(
3545 model: nn.Module,
3546 frame: pd.DataFrame,
3547 feature_names: list[str],
3548 device: torch.device,
3549) -> np.ndarray:
3550 features, _ = frame_to_tensors(frame, feature_names)
3551 features = features.to(device)
3553 model.eval()
3554 with torch.no_grad():
3555 logits = model(features)
3556 probabilities = torch.sigmoid(logits)
3557 return probabilities.detach().cpu().numpy()
3560def compute_strategy_metrics(
3561 frame: pd.DataFrame,
3562 probability_column: str,
3563 buy_threshold: float,
3564 sell_threshold: float,
3565 trading_days_per_year: int,
3566) -> tuple[dict, pd.DataFrame]:
3567 report_frame = frame.copy()
3568 report_frame["probability_up"] = report_frame[probability_column].astype(float)
3569 report_frame["position"] = np.where(report_frame["probability_up"] >= buy_threshold, 1.0, 0.0)
3570 report_frame["strategy_return"] = report_frame["position"] * report_frame["target_return_1d"]
3571 report_frame["baseline_return"] = report_frame["target_return_1d"]
3573 # Compound per ticker, not across the whole frame: `frame` may hold every
3574 # traded asset interleaved by (date, ticker) (see build_strategy_report's
3575 # per-split call), and a plain .cumprod() over that would compound one
3576 # ticker's return into the next ticker's running total.
3577 report_frame["cumulative_strategy"] = report_frame.groupby("ticker")["strategy_return"].transform(
3578 lambda returns: (1.0 + returns).cumprod()
3579 )
3580 report_frame["cumulative_baseline"] = report_frame.groupby("ticker")["baseline_return"].transform(
3581 lambda returns: (1.0 + returns).cumprod()
3582 )
3583 report_frame["strategy_drawdown"] = report_frame.groupby("ticker")["cumulative_strategy"].transform(
3584 lambda cumulative: cumulative / cumulative.cummax() - 1.0
3585 )
3586 report_frame["baseline_drawdown"] = report_frame.groupby("ticker")["cumulative_baseline"].transform(
3587 lambda cumulative: cumulative / cumulative.cummax() - 1.0
3588 )
3590 strategy_returns = report_frame["strategy_return"].to_numpy(dtype=float)
3591 baseline_returns = report_frame["baseline_return"].to_numpy(dtype=float)
3592 positions = report_frame["position"].to_numpy(dtype=float)
3593 position_changes = np.abs(np.diff(np.concatenate(([0.0], positions))))
3595 # Aggregate total-return/drawdown as an equal-weighted portfolio across
3596 # tickers per date (not per-ticker's own cumprod, which has no single
3597 # "last row" once multiple assets are present) - reduces to the same
3598 # single-ticker curve above when `frame` only holds one ticker.
3599 portfolio_by_date = report_frame.groupby("date")[["strategy_return", "baseline_return"]].mean().sort_index()
3600 portfolio_cumulative_strategy = (1.0 + portfolio_by_date["strategy_return"]).cumprod()
3601 portfolio_cumulative_baseline = (1.0 + portfolio_by_date["baseline_return"]).cumprod()
3603 strategy_total_return = (
3604 float(portfolio_cumulative_strategy.iloc[-1] - 1.0) if len(portfolio_cumulative_strategy) else 0.0
3605 )
3606 baseline_total_return = (
3607 float(portfolio_cumulative_baseline.iloc[-1] - 1.0) if len(portfolio_cumulative_baseline) else 0.0
3608 )
3610 strategy_mean = float(strategy_returns.mean()) if len(strategy_returns) else 0.0
3611 baseline_mean = float(baseline_returns.mean()) if len(baseline_returns) else 0.0
3612 strategy_vol = float(strategy_returns.std(ddof=1)) if len(strategy_returns) > 1 else 0.0
3613 baseline_vol = float(baseline_returns.std(ddof=1)) if len(baseline_returns) > 1 else 0.0
3615 annual_factor = math.sqrt(trading_days_per_year)
3616 strategy_sharpe = (strategy_mean / strategy_vol) * annual_factor if strategy_vol > 0 else 0.0
3617 baseline_sharpe = (baseline_mean / baseline_vol) * annual_factor if baseline_vol > 0 else 0.0
3619 strategy_max_drawdown = (
3620 float((portfolio_cumulative_strategy / portfolio_cumulative_strategy.cummax() - 1.0).min())
3621 if len(portfolio_cumulative_strategy)
3622 else 0.0
3623 )
3624 baseline_max_drawdown = (
3625 float((portfolio_cumulative_baseline / portfolio_cumulative_baseline.cummax() - 1.0).min())
3626 if len(portfolio_cumulative_baseline)
3627 else 0.0
3628 )
3629 strategy_hit_rate = float((strategy_returns > 0).mean()) if len(strategy_returns) else 0.0
3630 baseline_hit_rate = float((baseline_returns > 0).mean()) if len(baseline_returns) else 0.0
3632 return (
3633 {
3634 "rows": int(len(report_frame)),
3635 "buy_threshold": buy_threshold,
3636 "sell_threshold": sell_threshold,
3637 "exposure_rate": float(positions.mean()) if len(positions) else 0.0,
3638 "trade_count": int((position_changes > 0).sum()),
3639 "turnover": float(position_changes.sum()),
3640 "strategy": {
3641 "total_return": strategy_total_return,
3642 "annualized_return": float((1.0 + strategy_total_return) ** (trading_days_per_year / max(len(report_frame), 1)) - 1.0)
3643 if len(report_frame) else 0.0,
3644 "annualized_volatility": strategy_vol * annual_factor,
3645 "sharpe": strategy_sharpe,
3646 "max_drawdown": strategy_max_drawdown,
3647 "hit_rate": strategy_hit_rate,
3648 "average_daily_return": strategy_mean,
3649 },
3650 "buy_and_hold": {
3651 "total_return": baseline_total_return,
3652 "annualized_return": float((1.0 + baseline_total_return) ** (trading_days_per_year / max(len(report_frame), 1)) - 1.0)
3653 if len(report_frame) else 0.0,
3654 "annualized_volatility": baseline_vol * annual_factor,
3655 "sharpe": baseline_sharpe,
3656 "max_drawdown": baseline_max_drawdown,
3657 "hit_rate": baseline_hit_rate,
3658 "average_daily_return": baseline_mean,
3659 },
3660 "excess_return_vs_buy_and_hold": strategy_total_return - baseline_total_return,
3661 },
3662 report_frame,
3663 )
3666def build_strategy_report(
3667 config: dict,
3668 model: nn.Module,
3669 dataset: pd.DataFrame,
3670 feature_names: list[str],
3671 threshold: float,
3672 device: torch.device,
3673) -> tuple[dict, pd.DataFrame]:
3674 backtest_config = config["phase5"]["backtest"]
3675 threshold_offset_buy = float(backtest_config.get("buy_threshold_offset", 0.08))
3676 threshold_offset_sell = float(backtest_config.get("sell_threshold_offset", 0.08))
3677 buy_threshold = min(0.95, threshold + threshold_offset_buy)
3678 sell_threshold = max(0.05, threshold - threshold_offset_sell)
3679 trading_days_per_year = int(backtest_config.get("trading_days_per_year", 252))
3681 split_reports = {}
3682 curve_frames = []
3684 for split_name in ("validation", "backtest"):
3685 split_frame_df = split_frame(dataset, split_name).copy()
3686 split_frame_df["probability_up"] = predict_probabilities(model, split_frame_df, feature_names, device)
3687 split_report, split_curve = compute_strategy_metrics(
3688 split_frame_df,
3689 probability_column="probability_up",
3690 buy_threshold=buy_threshold,
3691 sell_threshold=sell_threshold,
3692 trading_days_per_year=trading_days_per_year,
3693 )
3694 split_reports[split_name] = split_report
3695 split_curve["split"] = split_name
3696 curve_frames.append(
3697 split_curve[
3698 [
3699 "date",
3700 "ticker",
3701 "split",
3702 "probability_up",
3703 "position",
3704 "strategy_return",
3705 "baseline_return",
3706 "cumulative_strategy",
3707 "cumulative_baseline",
3708 "strategy_drawdown",
3709 "baseline_drawdown",
3710 ]
3711 ]
3712 )
3714 per_asset_report = {}
3715 backtest_frame_df = split_frame(dataset, "backtest").copy()
3716 backtest_frame_df["probability_up"] = predict_probabilities(model, backtest_frame_df, feature_names, device)
3717 for ticker in sorted(backtest_frame_df["ticker"].unique()):
3718 asset_frame = backtest_frame_df[backtest_frame_df["ticker"] == ticker].reset_index(drop=True)
3719 asset_report, _ = compute_strategy_metrics(
3720 asset_frame,
3721 probability_column="probability_up",
3722 buy_threshold=buy_threshold,
3723 sell_threshold=sell_threshold,
3724 trading_days_per_year=trading_days_per_year,
3725 )
3726 per_asset_report[ticker] = asset_report
3728 report = {
3729 "project": config["name"],
3730 "phase": 5,
3731 "created_at": datetime.now(timezone.utc).isoformat(),
3732 "strategy_mode": backtest_config.get("strategy_mode", "long_flat"),
3733 "buy_threshold": buy_threshold,
3734 "sell_threshold": sell_threshold,
3735 "trading_days_per_year": trading_days_per_year,
3736 "validation": split_reports["validation"],
3737 "backtest": split_reports["backtest"],
3738 "backtest_per_asset": per_asset_report,
3739 }
3741 combined_curves = pd.concat(curve_frames, ignore_index=True)
3742 return report, combined_curves
3745def find_optimal_threshold(
3746 logits: torch.Tensor,
3747 targets: torch.Tensor,
3748 criterion: nn.Module,
3749 metric_name: str,
3750 threshold_min: float,
3751 threshold_max: float,
3752 threshold_steps: int,
3753 min_positive_rate: float = 0.15,
3754 max_positive_rate: float = 0.85,
3755) -> tuple[float, dict]:
3756 """MCC (or whatever metric_name is) is nearly flat when logits carry
3757 little discriminative signal, so its weak maximum tends to sit at a
3758 near-degenerate corner - an operating point that calls almost
3759 everything positive (or almost everything negative). Confirmed live:
3760 the shipped baseline model picked threshold 0.46 -> positive_rate 0.91,
3761 the sequence model's threshold picked 0.545 -> positive_rate 0.0004
3762 (development/Problems.md). Neither is a useful trading signal even
3763 though each was the metric-optimal point in its unconstrained search.
3765 `min_positive_rate`/`max_positive_rate` restrict SELECTION to
3766 thresholds whose predicted positive rate falls in a non-degenerate
3767 band (every candidate is still scored, so the metric surface is swept
3768 faithfully). If every candidate in the sweep is degenerate, falls back
3769 to the plain best-scoring threshold from the unconstrained sweep rather
3770 than silently returning the never-searched default 0.5 - callers can
3771 tell which happened via best_metrics['positive_rate'] sitting outside
3772 the band."""
3773 best_threshold = 0.5
3774 best_metrics = compute_binary_metrics(logits, targets, criterion, best_threshold)
3775 best_score = best_metrics.get(metric_name, best_metrics["f1"])
3776 best_threshold_unconstrained = best_threshold
3777 best_metrics_unconstrained = best_metrics
3778 best_score_unconstrained = best_score
3780 def _within_band(metrics: dict) -> bool:
3781 positive_rate = float(metrics.get("positive_rate", 0.5))
3782 return min_positive_rate <= positive_rate <= max_positive_rate
3784 found_non_degenerate = _within_band(best_metrics)
3786 for threshold in np.linspace(threshold_min, threshold_max, threshold_steps):
3787 threshold = float(round(float(threshold), 4))
3788 metrics = compute_binary_metrics(logits, targets, criterion, threshold)
3789 score = metrics.get(metric_name, metrics["f1"])
3791 if score > best_score_unconstrained or (
3792 abs(score - best_score_unconstrained) < 1e-12 and abs(threshold - 0.5) < abs(best_threshold_unconstrained - 0.5)
3793 ):
3794 best_threshold_unconstrained = threshold
3795 best_metrics_unconstrained = metrics
3796 best_score_unconstrained = score
3798 if _within_band(metrics) and (
3799 score > best_score or (abs(score - best_score) < 1e-12 and abs(threshold - 0.5) < abs(best_threshold - 0.5))
3800 ):
3801 best_threshold = threshold
3802 best_metrics = metrics
3803 best_score = score
3804 found_non_degenerate = True
3806 if found_non_degenerate:
3807 return best_threshold, best_metrics
3808 return best_threshold_unconstrained, best_metrics_unconstrained
3811def find_optimal_masked_threshold(
3812 logits: torch.Tensor,
3813 targets: torch.Tensor,
3814 criterion: nn.Module,
3815 metric_name: str,
3816 threshold_min: float,
3817 threshold_max: float,
3818 threshold_steps: int,
3819) -> tuple[float, dict] | tuple[None, None]:
3820 """find_optimal_threshold(), restricted to non-NaN rows first - a
3821 horizon-direction head's own probability distribution is unrelated to
3822 the primary "direction" head's, so it needs its own tuned threshold
3823 (reusing the primary head's threshold verbatim was observed to
3824 silently collapse a horizon head to always-predict-positive, since a
3825 threshold tuned for one head's logit distribution is meaningless
3826 applied to another's - see development/Problems.md). Shared by
3827 train_multitask.py/train_sequence.py, both of which train
3828 AetherNetMultiTaskHorizons/AetherNetSequenceMultiTaskHorizons's
3829 identically-named horizon heads."""
3830 mask = ~torch.isnan(targets)
3831 if not torch.any(mask):
3832 return None, None
3833 return find_optimal_threshold(logits[mask], targets[mask], criterion, metric_name, threshold_min, threshold_max, threshold_steps)
3842def train_model(
3843 config: dict,
3844 dataset: pd.DataFrame,
3845 *,
3846 checkpoint_path: Path = MODEL_CHECKPOINT_PATH,
3847 metrics_path: Path = TRAINING_METRICS_PATH,
3848 strategy_report_path: Path = STRATEGY_REPORT_PATH,
3849 equity_curves_path: Path = EQUITY_CURVES_PATH,
3850) -> dict:
3851 """Trains the baseline model and writes its artifacts.
3853 Output paths default to the active ml//backtests locations so every
3854 existing call site is unaffected; candidate training (V2-17) passes
3855 ml/versions/<id>/... paths instead, keeping the active model untouched.
3856 """
3857 phase3 = config["phase3"]
3858 training_config = phase3["training"]
3859 model_config = phase3["model"]
3860 feature_names = [f"{name}_scaled" for name in config["phase1"]["features"]["input_set"]]
3861 feature_names += _categorical_feature_names(dataset)
3862 if bool(model_config.get("use_asset_context", False)):
3863 feature_names += select_model_context_columns(dataset.columns)
3865 set_seed(int(training_config["seed"]))
3866 device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
3868 training_dataset = dataset
3869 if "training_eligible" in dataset.columns:
3870 training_dataset = dataset[dataset["training_eligible"]].copy()
3871 if training_dataset.empty:
3872 raise ValueError("No training-eligible assets available for model training.")
3874 train_frame = split_frame(training_dataset, "train")
3875 validation_frame = split_frame(training_dataset, "validation")
3876 backtest_frame = split_frame(training_dataset, "backtest")
3877 if train_frame.empty or validation_frame.empty or backtest_frame.empty:
3878 raise ValueError("Training, validation and backtest splits must all contain eligible rows.")
3880 train_features, train_targets = frame_to_tensors(train_frame, feature_names)
3881 validation_features, validation_targets = frame_to_tensors(validation_frame, feature_names)
3883 train_loader = DataLoader(
3884 TensorDataset(train_features, train_targets),
3885 batch_size=int(training_config["batch_size"]),
3886 shuffle=True,
3887 )
3889 model = AetherNet(
3890 input_dim=len(feature_names),
3891 hidden_layers=list(model_config["hidden_layers"]),
3892 dropout=float(model_config["dropout"]),
3893 activation=str(model_config.get("activation", "relu")),
3894 normalization=str(model_config.get("normalization", "none")),
3895 ).to(device)
3897 optimizer = torch.optim.Adam(
3898 model.parameters(),
3899 lr=float(training_config["learning_rate"]),
3900 weight_decay=float(training_config["weight_decay"]),
3901 )
3902 positive_count = max(float(train_frame["target_direction"].sum()), 1.0)
3903 negative_count = max(float(len(train_frame) - train_frame["target_direction"].sum()), 1.0)
3904 pos_weight = torch.tensor(negative_count / positive_count, dtype=torch.float32, device=device)
3905 criterion = nn.BCEWithLogitsLoss(pos_weight=pos_weight)
3906 threshold = float(training_config["decision_threshold"])
3907 patience = int(training_config["patience"])
3908 max_epochs = int(training_config["epochs"])
3909 threshold_metric = str(training_config.get("optimize_threshold_metric", "f1"))
3910 threshold_min = float(training_config.get("threshold_search_min", 0.35))
3911 threshold_max = float(training_config.get("threshold_search_max", 0.65))
3912 threshold_steps = int(training_config.get("threshold_search_steps", 61))
3914 best_state = None
3915 best_epoch = 0
3916 best_validation_balanced_accuracy = float("-inf")
3917 epochs_without_improvement = 0
3918 history: list[dict] = []
3919 min_best_epoch = int(training_config.get("min_best_epoch", 3))
3921 validation_features = validation_features.to(device)
3922 validation_targets = validation_targets.to(device)
3924 for epoch in range(1, max_epochs + 1):
3925 model.train()
3926 running_loss = 0.0
3927 sample_count = 0
3929 for batch_features, batch_targets in train_loader:
3930 batch_features = batch_features.to(device)
3931 batch_targets = batch_targets.to(device)
3933 optimizer.zero_grad()
3934 logits = model(batch_features)
3935 loss = criterion(logits, batch_targets)
3936 loss.backward()
3937 optimizer.step()
3939 running_loss += float(loss.item()) * len(batch_targets)
3940 sample_count += len(batch_targets)
3942 train_epoch_loss = running_loss / max(sample_count, 1)
3944 model.eval()
3945 with torch.no_grad():
3946 validation_logits = model(validation_features)
3947 validation_metrics = compute_binary_metrics(validation_logits, validation_targets, criterion, threshold)
3949 history.append(
3950 {
3951 "epoch": epoch,
3952 "train_loss": train_epoch_loss,
3953 "validation_loss": validation_metrics["loss"],
3954 "validation_accuracy": validation_metrics["accuracy"],
3955 "validation_balanced_accuracy": validation_metrics["balanced_accuracy"],
3956 "validation_f1": validation_metrics["f1"],
3957 }
3958 )
3960 # Monitors validation balanced-accuracy (a skill metric), not raw
3961 # loss - see is_new_best_epoch()'s docstring for why (Problems.md:
3962 # loss-monitoring shipped best_epoch=1, essentially the untrained
3963 # initialization, for baseline/multitask/sequence alike).
3964 if is_new_best_epoch(validation_metrics["balanced_accuracy"], best_validation_balanced_accuracy, epoch, min_best_epoch):
3965 best_validation_balanced_accuracy = validation_metrics["balanced_accuracy"]
3966 best_epoch = epoch
3967 best_state = copy.deepcopy(model.state_dict())
3968 epochs_without_improvement = 0
3969 else:
3970 epochs_without_improvement += 1
3972 if epoch >= min_best_epoch and epochs_without_improvement >= patience:
3973 break
3975 if best_state is None:
3976 best_state = copy.deepcopy(model.state_dict())
3977 best_epoch = len(history)
3979 model.load_state_dict(best_state)
3980 checkpoint_path.parent.mkdir(parents=True, exist_ok=True)
3981 torch.save(best_state, checkpoint_path)
3983 model.eval()
3984 with torch.no_grad():
3985 validation_logits = model(validation_features)
3986 tuned_threshold, tuned_validation_metrics = find_optimal_threshold(
3987 validation_logits,
3988 validation_targets,
3989 criterion,
3990 threshold_metric,
3991 threshold_min,
3992 threshold_max,
3993 threshold_steps,
3994 )
3996 metrics = {
3997 "project": config["name"],
3998 "phase": 3,
3999 "created_at": datetime.now(timezone.utc).isoformat(),
4000 "device": str(device),
4001 "best_epoch": best_epoch,
4002 "epochs_ran": len(history),
4003 "threshold_optimization": {
4004 "metric": threshold_metric,
4005 "default_threshold": threshold,
4006 "selected_threshold": tuned_threshold,
4007 "selected_validation_metrics": tuned_validation_metrics,
4008 },
4009 "train": evaluate_split(model, train_frame, feature_names, criterion, tuned_threshold, device),
4010 "validation": evaluate_split(model, validation_frame, feature_names, criterion, tuned_threshold, device),
4011 "backtest": evaluate_split(model, backtest_frame, feature_names, criterion, tuned_threshold, device),
4012 "asset_quality": {
4013 "training_eligible_assets": sorted(training_dataset["ticker"].unique().tolist()),
4014 "observation_only_assets": sorted(
4015 dataset.loc[~dataset.get("training_eligible", pd.Series(True, index=dataset.index)), "ticker"]
4016 .unique()
4017 .tolist()
4018 ) if "training_eligible" in dataset.columns else [],
4019 },
4020 "history": history,
4021 }
4022 metrics_path.parent.mkdir(parents=True, exist_ok=True)
4023 metrics_path.write_text(json.dumps(metrics, indent=2), encoding="utf-8")
4025 strategy_report, equity_curves = build_strategy_report(
4026 config=config,
4027 model=model,
4028 dataset=training_dataset,
4029 feature_names=feature_names,
4030 threshold=tuned_threshold,
4031 device=device,
4032 )
4033 strategy_report_path.parent.mkdir(parents=True, exist_ok=True)
4034 strategy_report_path.write_text(json.dumps(strategy_report, indent=2), encoding="utf-8")
4035 equity_curves.to_csv(equity_curves_path, index=False)
4037 return {
4038 "model": model,
4039 "metrics": metrics,
4040 "strategy_report": strategy_report,
4041 "scaled_feature_names": feature_names,
4042 "threshold": tuned_threshold,
4043 "model_config": model_config,
4044 "training_config": training_config,
4045 }
4048def _feature_names_for_model(config: dict, dataset: pd.DataFrame) -> list[str]:
4049 model_config = config["phase3"]["model"]
4050 feature_names = [f"{name}_scaled" for name in config["phase1"]["features"]["input_set"]]
4051 feature_names += _categorical_feature_names(dataset)
4052 if bool(model_config.get("use_asset_context", False)):
4053 feature_names += select_model_context_columns(dataset.columns)
4054 return feature_names
4057def _expert_training_config(config: dict) -> tuple[dict, dict]:
4058 expert_config = config.get("phase_v2", {}).get("expert_models", {})
4059 model_config = copy.deepcopy(config["phase3"]["model"])
4060 model_config["hidden_layers"] = [24]
4061 model_config["dropout"] = 0.30
4062 model_config["normalization"] = "layernorm"
4063 model_config.update(expert_config.get("model", {}))
4065 training_config = copy.deepcopy(config["phase3"]["training"])
4066 training_config["epochs"] = min(int(training_config.get("epochs", 120)), 60)
4067 training_config["patience"] = min(int(training_config.get("patience", 18)), 8)
4068 training_config["weight_decay"] = max(float(training_config.get("weight_decay", 0.0)), 0.001)
4069 training_config["learning_rate"] = min(float(training_config.get("learning_rate", 0.0007)), 0.0005)
4070 training_overrides = expert_config.get("training", {})
4071 training_config.update(training_overrides)
4072 training_config["epochs"] = int(training_config.get("epochs", 60))
4073 training_config["patience"] = int(training_config.get("patience", 8))
4074 training_config["min_train_rows"] = int(training_overrides.get("min_train_rows", 50))
4075 training_config["min_validation_rows"] = int(training_overrides.get("min_validation_rows", 10))
4076 training_config["min_backtest_rows"] = int(training_overrides.get("min_backtest_rows", 10))
4077 training_config["quality_gate"] = {
4078 # Raised to coin-flip-or-better (development/Problems.md): these
4079 # used to default BELOW random (0.48 balanced-accuracy, -0.05 MCC),
4080 # so every expert this codebase ever trained cleared the gate
4081 # automatically regardless of whether it had learned anything -
4082 # confirmed live, every shipped expert's validation MCC was 0.02-0.11
4083 # and still passed. moe/gating.py's _performance_score() applies the
4084 # matching 0.0-below-coin-flip floor at inference time; this is the
4085 # training-time gate that should have caught it first.
4086 "min_validation_balanced_accuracy": float(training_overrides.get("min_validation_balanced_accuracy", 0.50)),
4087 "min_backtest_balanced_accuracy": float(training_overrides.get("min_backtest_balanced_accuracy", 0.50)),
4088 "min_backtest_mcc": float(training_overrides.get("min_backtest_mcc", 0.0)),
4089 "max_train_backtest_balanced_accuracy_gap": float(
4090 training_overrides.get("max_train_backtest_balanced_accuracy_gap", 0.20)
4091 ),
4092 "watchlist_margin": float(training_overrides.get("watchlist_margin", 0.03)),
4093 }
4094 return model_config, training_config
4097def assess_expert_quality(metrics: dict, training_config: dict) -> dict:
4098 gate = training_config.get("quality_gate", {})
4099 min_validation_balanced_accuracy = float(gate.get("min_validation_balanced_accuracy", 0.50))
4100 min_backtest_balanced_accuracy = float(gate.get("min_backtest_balanced_accuracy", 0.50))
4101 min_backtest_mcc = float(gate.get("min_backtest_mcc", 0.0))
4102 max_gap = float(gate.get("max_train_backtest_balanced_accuracy_gap", 0.20))
4103 watchlist_margin = float(gate.get("watchlist_margin", 0.03))
4105 train_balanced_accuracy = float(metrics.get("train", {}).get("balanced_accuracy", 0.0) or 0.0)
4106 validation_balanced_accuracy = float(metrics.get("validation", {}).get("balanced_accuracy", 0.0) or 0.0)
4107 backtest_balanced_accuracy = float(metrics.get("backtest", {}).get("balanced_accuracy", 0.0) or 0.0)
4108 backtest_mcc = float(metrics.get("backtest", {}).get("mcc", 0.0) or 0.0)
4109 train_backtest_gap = train_balanced_accuracy - backtest_balanced_accuracy
4111 failures = []
4112 near_misses = []
4113 if validation_balanced_accuracy < min_validation_balanced_accuracy:
4114 failures.append("validation_balanced_accuracy_below_gate")
4115 elif validation_balanced_accuracy < min_validation_balanced_accuracy + watchlist_margin:
4116 near_misses.append("validation_balanced_accuracy_near_gate")
4118 if backtest_balanced_accuracy < min_backtest_balanced_accuracy:
4119 failures.append("backtest_balanced_accuracy_below_gate")
4120 elif backtest_balanced_accuracy < min_backtest_balanced_accuracy + watchlist_margin:
4121 near_misses.append("backtest_balanced_accuracy_near_gate")
4123 if backtest_mcc < min_backtest_mcc:
4124 failures.append("backtest_mcc_below_gate")
4125 elif backtest_mcc < min_backtest_mcc + watchlist_margin:
4126 near_misses.append("backtest_mcc_near_gate")
4128 if train_backtest_gap > max_gap:
4129 failures.append("train_backtest_gap_too_large")
4130 elif train_backtest_gap > max_gap - watchlist_margin:
4131 near_misses.append("train_backtest_gap_near_limit")
4133 if failures:
4134 quality_status = "disabled_for_gating"
4135 elif near_misses:
4136 quality_status = "watchlist"
4137 else:
4138 quality_status = "stable"
4140 return {
4141 "quality_status": quality_status,
4142 "gating_eligible": quality_status in {"stable", "watchlist"},
4143 "failures": failures,
4144 "near_misses": near_misses,
4145 "thresholds": {
4146 "min_validation_balanced_accuracy": min_validation_balanced_accuracy,
4147 "min_backtest_balanced_accuracy": min_backtest_balanced_accuracy,
4148 "min_backtest_mcc": min_backtest_mcc,
4149 "max_train_backtest_balanced_accuracy_gap": max_gap,
4150 "watchlist_margin": watchlist_margin,
4151 },
4152 "observed": {
4153 "train_balanced_accuracy": train_balanced_accuracy,
4154 "validation_balanced_accuracy": validation_balanced_accuracy,
4155 "backtest_balanced_accuracy": backtest_balanced_accuracy,
4156 "backtest_mcc": backtest_mcc,
4157 "train_backtest_balanced_accuracy_gap": train_backtest_gap,
4158 },
4159 }
4162def assess_regression_quality(regression_metrics_by_split: dict, training_config: dict) -> dict:
4163 """Direction models get assess_expert_quality()'s MCC/balanced-accuracy
4164 gate above; magnitude/volatility regression heads (train_multitask.py,
4165 train_sequence.py) had no equivalent gate at all until now - the
4166 sequence encoder's real backtest RMSE 2.09 vs MAE 0.068 (~31x, every
4167 other model's ratio is ~1.5-3x) shipped silently because nothing ever
4168 inspected it (root cause: a single poisoned feature row replicated
4169 into 30 consecutive sliding-window predictions - see
4170 development/Problems.md). Mirrors assess_expert_quality()'s
4171 failures/near_misses/quality_status shape so callers can treat both
4172 gates the same way.
4174 regression_metrics_by_split must be {"train": {...}, "validation":
4175 {...}, "backtest": {...}}, each a compute_regression_metrics() output
4176 (mae/rmse/bias/...) for ONE head (magnitude or volatility) - callers
4177 with multiple heads call this once per head.
4178 """
4179 gate = training_config.get("quality_gate", {})
4180 max_rmse_mae_ratio = float(gate.get("max_rmse_mae_ratio", 4.0))
4181 max_backtest_train_rmse_ratio = float(gate.get("max_backtest_train_rmse_ratio", 3.0))
4182 watchlist_margin = float(gate.get("regression_watchlist_margin", 0.5))
4184 train_rmse = float(regression_metrics_by_split.get("train", {}).get("rmse", 0.0) or 0.0)
4185 backtest_rmse = float(regression_metrics_by_split.get("backtest", {}).get("rmse", 0.0) or 0.0)
4186 backtest_mae = float(regression_metrics_by_split.get("backtest", {}).get("mae", 0.0) or 0.0)
4188 # A zero-valued denominator means "can't compute" (e.g. an empty
4189 # split), not "infinitely bad" - ratio stays 0.0 so it's never
4190 # spuriously flagged as a gate failure.
4191 rmse_mae_ratio = backtest_rmse / backtest_mae if backtest_mae > 0 else 0.0
4192 backtest_train_rmse_ratio = backtest_rmse / train_rmse if train_rmse > 0 else 0.0
4194 failures = []
4195 near_misses = []
4196 if rmse_mae_ratio > max_rmse_mae_ratio:
4197 failures.append("rmse_mae_ratio_above_gate")
4198 elif rmse_mae_ratio > max_rmse_mae_ratio - watchlist_margin:
4199 near_misses.append("rmse_mae_ratio_near_gate")
4201 if backtest_train_rmse_ratio > max_backtest_train_rmse_ratio:
4202 failures.append("backtest_train_rmse_ratio_above_gate")
4203 elif backtest_train_rmse_ratio > max_backtest_train_rmse_ratio - watchlist_margin:
4204 near_misses.append("backtest_train_rmse_ratio_near_gate")
4206 if failures:
4207 quality_status = "disabled_for_gating"
4208 elif near_misses:
4209 quality_status = "watchlist"
4210 else:
4211 quality_status = "stable"
4213 return {
4214 "quality_status": quality_status,
4215 "gating_eligible": quality_status in {"stable", "watchlist"},
4216 "failures": failures,
4217 "near_misses": near_misses,
4218 "thresholds": {
4219 "max_rmse_mae_ratio": max_rmse_mae_ratio,
4220 "max_backtest_train_rmse_ratio": max_backtest_train_rmse_ratio,
4221 "watchlist_margin": watchlist_margin,
4222 },
4223 "observed": {
4224 "backtest_rmse_mae_ratio": rmse_mae_ratio,
4225 "backtest_train_rmse_ratio": backtest_train_rmse_ratio,
4226 "train_rmse": train_rmse,
4227 "backtest_rmse": backtest_rmse,
4228 "backtest_mae": backtest_mae,
4229 },
4230 }
4233def assess_ranking_quality(
4234 non_overlapping_rank_ic: dict,
4235 bootstrap_result: dict,
4236 per_era: list[dict],
4237 training_config: dict,
4238) -> dict:
4239 """Phase 2 of the 5/10 -> 9/10 roadmap: the code-enforced version of
4240 the promotion criterion this codebase's own prior investigation
4241 documented but never actually implemented in code (see
4242 development/Changelog.md's "frontier-model edge investigation" entry:
4243 "promote when backtest mean rank-IC > 0.02, t-stat > 2, on
4244 non-overlapping dates" - and risk/README.md's rank_sizing_multiplier()
4245 docstring, which explains why rank_sizing_enabled shipped off by
4246 default: the non-overlapping subsample's t-stat was only 1.20, not the
4247 4.40 the full autocorrelated series showed). Mirrors
4248 assess_regression_quality()'s failures/near_misses/quality_status shape
4249 so callers can treat every quality gate in this codebase the same way.
4251 Callers compute each input via the already-existing building blocks
4252 rather than this function re-deriving them:
4253 - `non_overlapping_rank_ic`: a compute_rank_ic() result computed WITH
4254 non_overlapping_stride > 1 (the honest, non-autocorrelated series -
4255 never pass the full daily series here, that's exactly the inflated
4256 number this gate exists to not be fooled by).
4257 - `bootstrap_result`: bootstrap_ic_confidence_interval() run over that
4258 SAME non-overlapping series' "ic_values".
4259 - `per_era`: one dict per era from assess_ranking_quality_from_predictions()
4260 (each {"era_index", "era_start", "era_end", "num_dates", "mean_ic",
4261 "t_stat"}) - was the edge concentrated in one regime, or stable? Kept
4262 as full dicts, not bare floats (development/Problems.md #71): a
4263 promotion-gate failure can then be traced back to WHICH era and WHEN,
4264 not just a count - the count alone made "an era mean of -0.001 from 4
4265 dates" indistinguishable from "a real regime inversion."
4267 era_sign_min_abs_ic / era_min_observations (config
4268 phase1.target.ranking.promotion_gate, both default 0.0/0 - i.e. a
4269 byte-identical no-op unless explicitly set): an era only counts as a
4270 sign-instability failure if BOTH its |mean_ic| clears the noise floor
4271 AND it has enough contributing dates to be a meaningful estimate at
4272 all. Without these, a razor-thin era mean (a handful of observations
4273 averaging to something indistinguishable from zero) fails this gate
4274 exactly as hard as a genuine regime inversion - see Problems.md #71 for
4275 the calibration data (a real COVID-era inversion of -0.171 vs. a noise
4276 era of -0.001, both previously counted as one "opposite_sign_eras"
4277 entry each). Eras below era_min_observations are reported separately
4278 as `num_insufficient_data_eras`, never silently dropped.
4279 """
4280 gate = training_config.get("phase1", {}).get("target", {}).get("ranking", {}).get("promotion_gate", {})
4281 min_non_overlapping_t_stat = float(gate.get("min_non_overlapping_t_stat", 2.0))
4282 min_bootstrap_ci_lower = float(gate.get("min_bootstrap_ci_lower", 0.0))
4283 watchlist_margin = float(gate.get("ranking_watchlist_margin", 0.3))
4284 era_sign_min_abs_ic = float(gate.get("era_sign_min_abs_ic", 0.0))
4285 era_min_observations = int(gate.get("era_min_observations", 0))
4286 # V5.3.7 (development/Problems.md #107) - era promotion rule selector.
4287 # "legacy" (default, byte-identical): ANY opposite-sign era fails
4288 # ("era_sign_instability") - the historical behavior.
4289 # "flip_fraction": the any-flip hard failure is skipped; blocking comes
4290 # solely from max_era_sign_flip_fraction below. Rationale: a 400-perm
4291 # null study under this exact criterion (90-day eras,
4292 # |mean_ic| >= era_sign_min_abs_ic floor) produced ZERO opposite-sign
4293 # eras for skill-free models while the real rank signal showed
4294 # 2/9 eras at fraction 0.22 - so flip counts with the magnitude floor
4295 # are already noise-robust, and the calibrated question becomes
4296 # "what INSTABILITY FRACTION is tolerable", answered by the knob.
4297 era_rule = str(gate.get("era_rule", "legacy"))
4298 # V5.1 Phase 4 (item 4) - multi-regime stability, one level up from the
4299 # existing era-sign-instability check above: that check fails on ANY
4300 # single opposite-sign era, however small a fraction of the total. This
4301 # pair is a proportional generalization on top of it - both default to
4302 # a byte-identical no-op (min_stable_eras=0 always satisfied;
4303 # max_era_sign_flip_fraction=1.0 can never be exceeded since a fraction
4304 # is bounded at 1.0), same convention as era_sign_min_abs_ic/
4305 # era_min_observations above.
4306 min_stable_eras = int(gate.get("min_stable_eras", 0))
4307 max_era_sign_flip_fraction = float(gate.get("max_era_sign_flip_fraction", 1.0))
4309 non_overlapping_t_stat = float(non_overlapping_rank_ic.get("t_stat", 0.0) or 0.0)
4310 non_overlapping_mean_ic = float(non_overlapping_rank_ic.get("mean_ic", 0.0) or 0.0)
4311 bootstrap_lower_bound = float(bootstrap_result.get("lower_bound", 0.0) or 0.0)
4313 eligible_eras = [era for era in per_era if int(era.get("num_dates", 0)) >= era_min_observations]
4314 insufficient_data_eras = [era for era in per_era if int(era.get("num_dates", 0)) < era_min_observations]
4315 opposite_sign_eras = [
4316 era
4317 for era in eligible_eras
4318 if abs(float(era.get("mean_ic", 0.0))) >= era_sign_min_abs_ic
4319 and (
4320 (non_overlapping_mean_ic > 0 and era["mean_ic"] < 0)
4321 or (non_overlapping_mean_ic < 0 and era["mean_ic"] > 0)
4322 )
4323 ]
4325 era_sign_flip_fraction = len(opposite_sign_eras) / len(eligible_eras) if eligible_eras else 0.0
4327 failures = []
4328 near_misses = []
4329 if non_overlapping_t_stat < min_non_overlapping_t_stat:
4330 failures.append("non_overlapping_t_stat_below_gate")
4331 elif non_overlapping_t_stat < min_non_overlapping_t_stat + watchlist_margin:
4332 near_misses.append("non_overlapping_t_stat_near_gate")
4334 if bootstrap_lower_bound < min_bootstrap_ci_lower:
4335 failures.append("bootstrap_ci_lower_bound_below_gate")
4337 if opposite_sign_eras and era_rule == "legacy":
4338 failures.append("era_sign_instability")
4339 elif opposite_sign_eras:
4340 # flip_fraction mode: recorded as a near-miss diagnostic, never a
4341 # hard failure - the calibrated fraction knob below owns blocking.
4342 near_misses.append("era_sign_instability_flip_fraction_mode")
4344 if len(eligible_eras) < min_stable_eras:
4345 failures.append("insufficient_eras_for_stability")
4347 if era_sign_flip_fraction > max_era_sign_flip_fraction:
4348 failures.append("era_sign_flip_fraction_above_gate")
4350 if failures:
4351 quality_status = "not_promotable"
4352 elif near_misses:
4353 quality_status = "watchlist"
4354 else:
4355 quality_status = "promotable"
4357 return {
4358 "quality_status": quality_status,
4359 # Matches assess_regression_quality()'s "gating_eligible" convention:
4360 # "watchlist" (a near-miss, not an outright failure) still counts as
4361 # eligible, same treatment every other quality gate in this codebase
4362 # gives a near-gate-but-passing result.
4363 "promotion_eligible": quality_status in {"promotable", "watchlist"},
4364 "failures": failures,
4365 "near_misses": near_misses,
4366 "thresholds": {
4367 "min_non_overlapping_t_stat": min_non_overlapping_t_stat,
4368 "min_bootstrap_ci_lower": min_bootstrap_ci_lower,
4369 "watchlist_margin": watchlist_margin,
4370 "era_rule": era_rule,
4371 "era_sign_min_abs_ic": era_sign_min_abs_ic,
4372 "era_min_observations": era_min_observations,
4373 "min_stable_eras": min_stable_eras,
4374 "max_era_sign_flip_fraction": max_era_sign_flip_fraction,
4375 },
4376 "observed": {
4377 "non_overlapping_t_stat": non_overlapping_t_stat,
4378 "non_overlapping_mean_ic": non_overlapping_mean_ic,
4379 "bootstrap_ci_lower_bound": bootstrap_lower_bound,
4380 "bootstrap_ci_upper_bound": float(bootstrap_result.get("upper_bound", 0.0) or 0.0),
4381 "num_eras": len(per_era),
4382 "num_eligible_eras": len(eligible_eras),
4383 "num_opposite_sign_eras": len(opposite_sign_eras),
4384 "num_insufficient_data_eras": len(insufficient_data_eras),
4385 "era_sign_flip_fraction": era_sign_flip_fraction,
4386 "per_era": per_era,
4387 },
4388 }
4391def assess_net_performance_quality(
4392 simulation_result: dict, capacity_result: dict, stress_results: list[dict], config: dict
4393) -> dict:
4394 """V5.1 Phase 4 (items 7, 12): the code-enforced version of "does this
4395 edge survive costs, capacity, and stress" - mirrors assess_ranking_quality()'s
4396 EXACT {quality_status, promotion_eligible, failures, near_misses,
4397 thresholds, observed} shape so every quality gate in this repo stays
4398 consumable identically by retraining/validation_gate.py and the webui.
4400 Inputs are already-computed evaluation/rank_book_simulator.py results
4401 (RankBookSimulationResult.to_dict(), capacity_curve(), stress_test_costs())
4402 - this function only assesses them, it never runs a simulation itself,
4403 so callers control exactly which head/config the simulation used.
4405 Checks: net_sharpe >= min_net_sharpe (watchlist within
4406 net_performance_watchlist_margin of the gate); annualized_turnover <=
4407 max_annualized_turnover; capacity_usd >= min_capacity_usd; the 2x cost
4408 stress run's net_sharpe > 0 (the edge must survive DOUBLE costs, not
4409 just the calibrated estimate - a stress_results list missing a 2.0
4410 multiplier entry simply skips this check rather than failing on an
4411 absent input)."""
4412 gate = config.get("phase1", {}).get("target", {}).get("ranking", {}).get("promotion_gate", {})
4413 min_net_sharpe = float(gate.get("min_net_sharpe", 0.0))
4414 max_annualized_turnover = float(gate.get("max_annualized_turnover", 1e9))
4415 min_capacity_usd = float(gate.get("min_capacity_usd", 0.0))
4416 watchlist_margin = float(gate.get("net_performance_watchlist_margin", 0.1))
4418 net_sharpe = float(simulation_result.get("net_sharpe", 0.0) or 0.0)
4419 annualized_turnover = float(simulation_result.get("annualized_turnover", 0.0) or 0.0)
4420 capacity_usd = float(capacity_result.get("capacity_usd", 0.0) or 0.0)
4421 double_cost_result = next(
4422 (entry for entry in stress_results if abs(float(entry.get("cost_multiplier", 0.0)) - 2.0) < 1e-9), None
4423 )
4424 double_cost_net_sharpe = float(double_cost_result["net_sharpe"]) if double_cost_result is not None else None
4426 failures: list[str] = []
4427 near_misses: list[str] = []
4429 if net_sharpe < min_net_sharpe:
4430 failures.append("net_sharpe_below_gate")
4431 elif net_sharpe < min_net_sharpe + watchlist_margin:
4432 near_misses.append("net_sharpe_near_gate")
4434 if annualized_turnover > max_annualized_turnover:
4435 failures.append("annualized_turnover_above_gate")
4437 if capacity_usd < min_capacity_usd:
4438 failures.append("capacity_usd_below_gate")
4440 if double_cost_net_sharpe is not None and double_cost_net_sharpe <= 0.0:
4441 failures.append("net_sharpe_does_not_survive_double_costs")
4443 if failures:
4444 quality_status = "not_promotable"
4445 elif near_misses:
4446 quality_status = "watchlist"
4447 else:
4448 quality_status = "promotable"
4450 return {
4451 "quality_status": quality_status,
4452 "promotion_eligible": quality_status in {"promotable", "watchlist"},
4453 "failures": failures,
4454 "near_misses": near_misses,
4455 "thresholds": {
4456 "min_net_sharpe": min_net_sharpe,
4457 "max_annualized_turnover": max_annualized_turnover,
4458 "min_capacity_usd": min_capacity_usd,
4459 "watchlist_margin": watchlist_margin,
4460 },
4461 "observed": {
4462 "net_sharpe": net_sharpe,
4463 "annualized_turnover": annualized_turnover,
4464 "capacity_usd": capacity_usd,
4465 "double_cost_net_sharpe": double_cost_net_sharpe,
4466 },
4467 }
4470def assess_ranking_quality_from_predictions(
4471 predictions: torch.Tensor,
4472 targets: torch.Tensor,
4473 dates,
4474 non_overlapping_stride: int,
4475 config: dict,
4476) -> dict:
4477 """Phase 2 of the 5/10 -> 9/10 roadmap: orchestrates
4478 compute_rank_ic()/bootstrap_ic_confidence_interval()/
4479 split_into_non_overlapping_eras()/assess_ranking_quality() into one
4480 call, so train_multitask.py/train_sequence.py's main() gets the full
4481 promotion-gate verdict for one rank head's BACKTEST split from a single
4482 call, the same way assess_regression_quality() is already called
4483 directly on an already-assembled metrics dict.
4485 Unlike assess_regression_quality() (which reads a narrow, per-model
4486 training_config), this reads `config` as the FULL config.json (same
4487 convention as build_cross_sectional_rank_targets()/
4488 build_macro_features_by_date() above) - the ranking promotion gate
4489 (phase1.target.ranking.promotion_gate) is a property of the ranking
4490 TARGET itself, not a per-model training hyperparameter, so it lives in
4491 one place shared by every model with a rank head, not duplicated under
4492 each model's own training config block.
4493 """
4494 non_overlapping_ic = compute_rank_ic(predictions, targets, dates, non_overlapping_stride=non_overlapping_stride)
4495 bootstrap_result = bootstrap_ic_confidence_interval(non_overlapping_ic["ic_values"])
4497 promotion_gate_config = config.get("phase1", {}).get("target", {}).get("ranking", {}).get("promotion_gate", {})
4498 era_length_days = int(promotion_gate_config.get("era_length_days", 90))
4500 # pd.to_datetime(), not np.asarray(): `dates` here is a plain string
4501 # array in every real caller (train_multitask.py/train_sequence.py
4502 # pass frame["date"], stringified by build_feature_dataset() before
4503 # any trainer reads it) - comparing raw strings against
4504 # split_into_non_overlapping_eras()'s Timestamp era boundaries below
4505 # would raise. See that function's own identical fix/comment.
4506 dates_array = pd.to_datetime(np.asarray(dates))
4507 per_era: list[dict] = []
4508 for era_index, (era_start, era_end) in enumerate(split_into_non_overlapping_eras(dates_array, era_length_days)):
4509 era_mask = (dates_array >= era_start) & (dates_array <= era_end)
4510 if not era_mask.any():
4511 continue
4512 era_mask_tensor = torch.as_tensor(era_mask)
4513 era_result = compute_rank_ic(
4514 predictions[era_mask_tensor],
4515 targets[era_mask_tensor],
4516 dates_array[era_mask],
4517 non_overlapping_stride=non_overlapping_stride,
4518 )
4519 if era_result["num_dates"] > 0:
4520 per_era.append(
4521 {
4522 "era_index": era_index,
4523 # pd.Timestamp(), not era_start.date(): split_into_non_
4524 # overlapping_eras() returns numpy.datetime64 scalars
4525 # (np.unique() on the dates array strips the pandas
4526 # Timestamp wrapper), which has no .date() method.
4527 "era_start": pd.Timestamp(era_start).date().isoformat(),
4528 "era_end": pd.Timestamp(era_end).date().isoformat(),
4529 "num_dates": era_result["num_dates"],
4530 "mean_ic": era_result["mean_ic"],
4531 "t_stat": era_result["t_stat"],
4532 }
4533 )
4535 return assess_ranking_quality(non_overlapping_ic, bootstrap_result, per_era, config)
4538def generate_walk_forward_windows(
4539 common_window: dict,
4540 train_span_days: int,
4541 validation_span_days: int,
4542 backtest_span_days: int,
4543 step_days: int,
4544 mode: str = "rolling",
4545) -> list[dict]:
4546 """Phase 4 of the 5/10 -> 9/10 roadmap: generates a sequence of
4547 {"training": {...}, "validation": {...}, "backtest": {...}} window
4548 dicts spanning `common_window` - each one has the EXACT shape of
4549 today's single phase1.windows, so every existing consumer
4550 (assign_split(), build_feature_dataset(), build_dataset_manifest())
4551 needs zero changes to accept a walk-forward window instead of the
4552 fixed one. Walk-forward is achieved by calling the existing pipeline
4553 once per generated window, not by changing what "a window" means.
4555 `mode="rolling"`: a fixed-length training window slides forward by
4556 `step_days` each iteration (window i's train_start = common_window's
4557 start + i*step_days). `mode="expanding"`: the training window's start
4558 stays fixed at common_window's start and only its END grows by
4559 step_days each iteration (train_end = start + train_span_days - 1 +
4560 i*step_days) - each window sees strictly more history than the last,
4561 never less.
4563 Validation and backtest immediately follow training with no gap
4564 (validation_start = train_end + 1 day, etc.) and never overlap between
4565 consecutive windows' training data and a later window's backtest data
4566 within the SAME window - each window's own three sub-ranges are
4567 contiguous and disjoint by construction.
4569 Returns [] (never raises) once a window's backtest_end would exceed
4570 common_window's end - including immediately, on the very first
4571 iteration, if `common_window` is too short for even one full window to
4572 fit. This is the same "guard against thin data" convention
4573 build_cross_sectional_rank_targets()'s min_universe_size gate and
4574 every other thin-data guard in this file already follow.
4575 """
4576 range_start = pd.Timestamp(common_window["start"])
4577 range_end = pd.Timestamp(common_window["end"])
4579 windows: list[dict] = []
4580 index = 0
4581 while True:
4582 if mode == "expanding":
4583 train_start = range_start
4584 train_end = range_start + pd.Timedelta(train_span_days - 1 + step_days * index, unit="D")
4585 else:
4586 train_start = range_start + pd.Timedelta(step_days * index, unit="D")
4587 train_end = train_start + pd.Timedelta(train_span_days - 1, unit="D")
4589 validation_start = train_end + pd.Timedelta(1, unit="D")
4590 validation_end = validation_start + pd.Timedelta(validation_span_days - 1, unit="D")
4591 backtest_start = validation_end + pd.Timedelta(1, unit="D")
4592 backtest_end = backtest_start + pd.Timedelta(backtest_span_days - 1, unit="D")
4594 if backtest_end > range_end:
4595 break
4597 windows.append(
4598 {
4599 "training": {"start": train_start.strftime("%Y-%m-%d"), "end": train_end.strftime("%Y-%m-%d")},
4600 "validation": {
4601 "start": validation_start.strftime("%Y-%m-%d"),
4602 "end": validation_end.strftime("%Y-%m-%d"),
4603 },
4604 "backtest": {"start": backtest_start.strftime("%Y-%m-%d"), "end": backtest_end.strftime("%Y-%m-%d")},
4605 }
4606 )
4607 index += 1
4609 return windows
4612def summarize_walk_forward_run(per_window_metric_values: list[float]) -> dict:
4613 """Phase 4 of the 5/10 -> 9/10 roadmap: cross-window stability summary
4614 for a walk-forward run - turns a single "trained once on one fixed
4615 window" number into a distribution across windows (was performance
4616 concentrated in one window, or stable across the whole walk-forward
4617 run?), the direct generalization of Phase 2's "single non-overlapping
4618 IC number" -> "distribution across eras" upgrade
4619 (split_into_non_overlapping_eras()/assess_ranking_quality()) applied
4620 one level up, across whole retrain windows instead of within one.
4622 Deliberately takes a plain `list[float]` (whatever numeric metric the
4623 caller cares about per window - rank-IC mean, MCC, Sharpe - already
4624 extracted from that window's own training_metrics.json) rather than
4625 assuming any particular metrics-JSON shape, so this composes with any
4626 current or future trainer's own metrics without modification. Reuses
4627 bootstrap_ic_confidence_interval() for the cross-window confidence
4628 interval rather than reimplementing the same bootstrap logic - despite
4629 the "_ic" in that function's name, it is a plain bootstrap-mean-CI over
4630 any float series, not IC-specific in what it actually computes.
4631 """
4632 bootstrap_result = bootstrap_ic_confidence_interval(per_window_metric_values)
4633 return {
4634 "num_windows": len(per_window_metric_values),
4635 "per_window_metric_values": list(per_window_metric_values),
4636 "cross_window_bootstrap": bootstrap_result,
4637 }
4640def extract_metric_by_path(metrics: dict | None, dotted_path: str) -> float | None:
4641 """V5.1 Phase 4 (item 4) - pure. Walks a dotted key path (e.g.
4642 "backtest.rank_20d_ic_non_overlapping.mean_ic") through a metrics dict;
4643 a missing key, a None value anywhere along the path, or a non-numeric
4644 leaf all return None rather than raising. Replaces
4645 _run_walk_forward()'s previous hardcoded
4646 training_result["metrics"]["backtest"].get("mcc", 0.0) extraction with
4647 a generic one driven by walk_forward.tracked_metrics config, so the
4648 walk-forward loop can track any trainer's any metric without new code
4649 per metric."""
4650 if not isinstance(metrics, dict):
4651 return None
4652 current: object = metrics
4653 for key in dotted_path.split("."):
4654 if not isinstance(current, dict) or key not in current:
4655 return None
4656 current = current[key]
4657 if current is None:
4658 return None
4659 try:
4660 return float(current)
4661 except (TypeError, ValueError):
4662 return None
4665def _train_expert_classifier(
4666 expert_name: str,
4667 expert_frame: pd.DataFrame,
4668 feature_names: list[str],
4669 model_config: dict,
4670 training_config: dict,
4671 device: torch.device,
4672) -> dict:
4673 train_frame = split_frame(expert_frame, "train")
4674 validation_frame = split_frame(expert_frame, "validation")
4675 backtest_frame = split_frame(expert_frame, "backtest")
4677 min_train_rows = int(training_config.get("min_train_rows", 50))
4678 min_validation_rows = int(training_config.get("min_validation_rows", 10))
4679 min_backtest_rows = int(training_config.get("min_backtest_rows", 10))
4680 if len(train_frame) < min_train_rows or len(validation_frame) < min_validation_rows or len(backtest_frame) < min_backtest_rows:
4681 return {
4682 "expert": expert_name,
4683 "status": "skipped",
4684 "reason": "not_enough_rows_for_expert_training",
4685 "rows": int(len(expert_frame)),
4686 "split_rows": {
4687 "train": int(len(train_frame)),
4688 "validation": int(len(validation_frame)),
4689 "backtest": int(len(backtest_frame)),
4690 },
4691 "minimums": {
4692 "train": min_train_rows,
4693 "validation": min_validation_rows,
4694 "backtest": min_backtest_rows,
4695 },
4696 }
4698 seed = int(training_config["seed"]) + sum(ord(character) for character in expert_name)
4699 set_seed(seed)
4701 train_features, train_targets = frame_to_tensors(train_frame, feature_names)
4702 validation_features, validation_targets = frame_to_tensors(validation_frame, feature_names)
4703 train_loader = DataLoader(
4704 TensorDataset(train_features, train_targets),
4705 batch_size=int(training_config["batch_size"]),
4706 shuffle=True,
4707 )
4709 model = AetherNet(
4710 input_dim=len(feature_names),
4711 hidden_layers=list(model_config["hidden_layers"]),
4712 dropout=float(model_config["dropout"]),
4713 activation=str(model_config.get("activation", "relu")),
4714 normalization=str(model_config.get("normalization", "none")),
4715 ).to(device)
4717 optimizer = torch.optim.Adam(
4718 model.parameters(),
4719 lr=float(training_config["learning_rate"]),
4720 weight_decay=float(training_config["weight_decay"]),
4721 )
4722 positive_count = max(float(train_frame["target_direction"].sum()), 1.0)
4723 negative_count = max(float(len(train_frame) - train_frame["target_direction"].sum()), 1.0)
4724 pos_weight = torch.tensor(negative_count / positive_count, dtype=torch.float32, device=device)
4725 criterion = nn.BCEWithLogitsLoss(pos_weight=pos_weight)
4727 threshold = float(training_config["decision_threshold"])
4728 threshold_metric = str(training_config.get("optimize_threshold_metric", "f1"))
4729 threshold_min = float(training_config.get("threshold_search_min", 0.35))
4730 threshold_max = float(training_config.get("threshold_search_max", 0.65))
4731 threshold_steps = int(training_config.get("threshold_search_steps", 61))
4732 max_epochs = int(training_config["epochs"])
4733 patience = int(training_config["patience"])
4735 best_state = None
4736 best_epoch = 0
4737 best_validation_balanced_accuracy = float("-inf")
4738 epochs_without_improvement = 0
4739 history: list[dict] = []
4740 min_best_epoch = int(training_config.get("min_best_epoch", 3))
4742 validation_features = validation_features.to(device)
4743 validation_targets = validation_targets.to(device)
4745 for epoch in range(1, max_epochs + 1):
4746 model.train()
4747 running_loss = 0.0
4748 sample_count = 0
4750 for batch_features, batch_targets in train_loader:
4751 batch_features = batch_features.to(device)
4752 batch_targets = batch_targets.to(device)
4754 optimizer.zero_grad()
4755 logits = model(batch_features)
4756 loss = criterion(logits, batch_targets)
4757 loss.backward()
4758 optimizer.step()
4760 running_loss += float(loss.item()) * len(batch_targets)
4761 sample_count += len(batch_targets)
4763 model.eval()
4764 with torch.no_grad():
4765 validation_logits = model(validation_features)
4766 validation_metrics = compute_binary_metrics(validation_logits, validation_targets, criterion, threshold)
4767 train_epoch_loss = running_loss / max(sample_count, 1)
4768 history.append(
4769 {
4770 "epoch": epoch,
4771 "train_loss": train_epoch_loss,
4772 "validation_loss": validation_metrics["loss"],
4773 "validation_accuracy": validation_metrics["accuracy"],
4774 "validation_balanced_accuracy": validation_metrics["balanced_accuracy"],
4775 "validation_f1": validation_metrics["f1"],
4776 }
4777 )
4779 if is_new_best_epoch(validation_metrics["balanced_accuracy"], best_validation_balanced_accuracy, epoch, min_best_epoch):
4780 best_validation_balanced_accuracy = validation_metrics["balanced_accuracy"]
4781 best_epoch = epoch
4782 best_state = copy.deepcopy(model.state_dict())
4783 epochs_without_improvement = 0
4784 else:
4785 epochs_without_improvement += 1
4787 if epoch >= min_best_epoch and epochs_without_improvement >= patience:
4788 break
4790 if best_state is None:
4791 best_state = copy.deepcopy(model.state_dict())
4792 best_epoch = len(history)
4794 model.load_state_dict(best_state)
4795 model.eval()
4796 with torch.no_grad():
4797 validation_logits = model(validation_features)
4798 tuned_threshold, tuned_validation_metrics = find_optimal_threshold(
4799 validation_logits,
4800 validation_targets,
4801 criterion,
4802 threshold_metric,
4803 threshold_min,
4804 threshold_max,
4805 threshold_steps,
4806 )
4808 metrics = {
4809 "expert": expert_name,
4810 "status": "trained",
4811 "rows": int(len(expert_frame)),
4812 "split_rows": {
4813 "train": int(len(train_frame)),
4814 "validation": int(len(validation_frame)),
4815 "backtest": int(len(backtest_frame)),
4816 },
4817 "best_epoch": best_epoch,
4818 "epochs_ran": len(history),
4819 "threshold_optimization": {
4820 "metric": threshold_metric,
4821 "default_threshold": threshold,
4822 "selected_threshold": tuned_threshold,
4823 "selected_validation_metrics": tuned_validation_metrics,
4824 },
4825 "train": evaluate_split(model, train_frame, feature_names, criterion, tuned_threshold, device),
4826 "validation": evaluate_split(model, validation_frame, feature_names, criterion, tuned_threshold, device),
4827 "backtest": evaluate_split(model, backtest_frame, feature_names, criterion, tuned_threshold, device),
4828 "tickers": sorted(expert_frame["ticker"].unique().tolist()) if "ticker" in expert_frame.columns else [],
4829 "history": history,
4830 }
4831 metrics["quality_gate"] = assess_expert_quality(metrics, training_config)
4832 return {
4833 "expert": expert_name,
4834 "status": "trained",
4835 "quality_status": metrics["quality_gate"]["quality_status"],
4836 "gating_eligible": metrics["quality_gate"]["gating_eligible"],
4837 "model": model,
4838 "state_dict": best_state,
4839 "threshold": tuned_threshold,
4840 "metrics": metrics,
4841 }
4844def _write_expert_model_export(
4845 expert_name: str,
4846 result: dict,
4847 model_config: dict,
4848 training_config: dict,
4849 feature_names: list[str],
4850 output_dir: Path,
4851) -> dict:
4852 def artifact_path(path: Path) -> str:
4853 try:
4854 return str(path.relative_to(ROOT))
4855 except ValueError:
4856 return str(path)
4858 expert_dir = output_dir / expert_name
4859 expert_dir.mkdir(parents=True, exist_ok=True)
4860 checkpoint_path = expert_dir / "model.pt"
4861 weights_path = expert_dir / "model_weights.json"
4862 metrics_path = expert_dir / "metrics.json"
4864 torch.save(result["state_dict"], checkpoint_path)
4865 metrics_path.write_text(json.dumps(result["metrics"], indent=2), encoding="utf-8")
4866 payload = {
4867 "project": "Aether Quant",
4868 "phase": "v2_expert_model",
4869 "expert": expert_name,
4870 "status": "trained",
4871 "created_at": datetime.now(timezone.utc).isoformat(),
4872 "model": {
4873 "type": model_config["type"],
4874 "model_input_features": feature_names,
4875 "hidden_layers": model_config["hidden_layers"],
4876 "dropout": model_config["dropout"],
4877 "activation": model_config.get("activation", "relu"),
4878 "normalization": model_config.get("normalization", "none"),
4879 "use_asset_context": model_config.get("use_asset_context", False),
4880 "output_activation": model_config.get("output_activation", "sigmoid"),
4881 },
4882 "training": {
4883 "decision_threshold": result["threshold"],
4884 "threshold_metric": training_config.get("optimize_threshold_metric", "f1"),
4885 "best_epoch": result["metrics"]["best_epoch"],
4886 "epochs_ran": result["metrics"]["epochs_ran"],
4887 "quality_status": result["metrics"]["quality_gate"]["quality_status"],
4888 "gating_eligible": result["metrics"]["quality_gate"]["gating_eligible"],
4889 },
4890 "quality_gate": result["metrics"]["quality_gate"],
4891 "metrics_path": artifact_path(metrics_path),
4892 "checkpoint_path": artifact_path(checkpoint_path),
4893 "export": {
4894 "architecture": export_architecture(result["model"]),
4895 "state_dict": export_state_dict(result["model"]),
4896 },
4897 }
4898 weights_path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
4899 return {
4900 "weights_path": artifact_path(weights_path),
4901 "metrics_path": artifact_path(metrics_path),
4902 "checkpoint_path": artifact_path(checkpoint_path),
4903 }
4906def _expert_multitask_tensors(
4907 frame: pd.DataFrame, feature_names: list[str]
4908) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
4909 features = torch.tensor(frame[feature_names].to_numpy(dtype=np.float32), dtype=torch.float32)
4910 direction = torch.tensor(frame["target_direction"].to_numpy(dtype=np.float32), dtype=torch.float32)
4911 magnitude = torch.tensor(frame["target_return_1d"].to_numpy(dtype=np.float32), dtype=torch.float32)
4912 volatility = torch.tensor(frame["target_volatility_next_day"].to_numpy(dtype=np.float32), dtype=torch.float32)
4913 return features, direction, magnitude, volatility
4916def _train_expert_multitask(
4917 expert_name: str,
4918 expert_frame: pd.DataFrame,
4919 feature_names: list[str],
4920 model_config: dict,
4921 training_config: dict,
4922 device: torch.device,
4923) -> dict:
4924 """Per-expert multitask (direction+magnitude+volatility) trainer -
4925 mirrors _train_expert_classifier()'s exact shape (split -> loader ->
4926 model -> Adam -> epoch loop with early stopping on validation loss ->
4927 best-state reload -> threshold tuning) but trains AetherNetMultiTask
4928 with the same combined BCE+MSE+MSE loss train_multitask.py's main()
4929 uses, over the SAME regime-filtered per-expert dataset slice
4930 _train_expert_classifier() already trains its direction-only
4931 classifier on. This is what lets moe/gating.py blend per-expert
4932 magnitude/volatility the same weighted-average way it already blends
4933 expert_probability_up (see moe/README.md's scope note on this)."""
4934 required_target_columns = {"target_return_1d", "target_volatility_next_day"}
4935 if not required_target_columns.issubset(expert_frame.columns):
4936 # Older/synthetic datasets (e.g. built before the multitask targets
4937 # existed, or hand-constructed test fixtures) simply don't have
4938 # these columns - best-effort skip, never a hard failure, matching
4939 # every other optional stage in this pipeline.
4940 return {
4941 "expert": expert_name,
4942 "status": "skipped",
4943 "reason": "dataset_missing_multitask_target_columns",
4944 }
4946 train_frame = split_frame(expert_frame, "train")
4947 validation_frame = split_frame(expert_frame, "validation")
4948 backtest_frame = split_frame(expert_frame, "backtest")
4950 min_train_rows = int(training_config.get("min_train_rows", 50))
4951 min_validation_rows = int(training_config.get("min_validation_rows", 10))
4952 min_backtest_rows = int(training_config.get("min_backtest_rows", 10))
4953 if len(train_frame) < min_train_rows or len(validation_frame) < min_validation_rows or len(backtest_frame) < min_backtest_rows:
4954 return {
4955 "expert": expert_name,
4956 "status": "skipped",
4957 "reason": "not_enough_rows_for_expert_multitask_training",
4958 }
4960 # +1 vs _train_expert_classifier()'s own seed formula, so the two
4961 # models' random initialization/batch shuffling are decorrelated
4962 # rather than accidentally identical.
4963 seed = int(training_config["seed"]) + sum(ord(character) for character in expert_name) + 1
4964 set_seed(seed)
4966 magnitude_loss_weight = float(training_config.get("magnitude_loss_weight", 1.0))
4967 volatility_loss_weight = float(training_config.get("volatility_loss_weight", 1.0))
4969 train_features, train_direction, train_magnitude, train_volatility = _expert_multitask_tensors(train_frame, feature_names)
4970 validation_features, validation_direction, validation_magnitude, validation_volatility = _expert_multitask_tensors(
4971 validation_frame, feature_names
4972 )
4973 validation_features = validation_features.to(device)
4974 validation_direction = validation_direction.to(device)
4975 validation_magnitude = validation_magnitude.to(device)
4976 validation_volatility = validation_volatility.to(device)
4978 train_loader = DataLoader(
4979 TensorDataset(train_features, train_direction, train_magnitude, train_volatility),
4980 batch_size=int(training_config["batch_size"]),
4981 shuffle=True,
4982 )
4984 model = AetherNetMultiTask(
4985 input_dim=len(feature_names),
4986 hidden_layers=list(model_config["hidden_layers"]),
4987 dropout=float(model_config["dropout"]),
4988 activation=str(model_config.get("activation", "relu")),
4989 normalization=str(model_config.get("normalization", "none")),
4990 ).to(device)
4992 optimizer = torch.optim.Adam(
4993 model.parameters(),
4994 lr=float(training_config["learning_rate"]),
4995 weight_decay=float(training_config["weight_decay"]),
4996 )
4997 positive_count = max(float(train_frame["target_direction"].sum()), 1.0)
4998 negative_count = max(float(len(train_frame) - train_frame["target_direction"].sum()), 1.0)
4999 pos_weight = torch.tensor(negative_count / positive_count, dtype=torch.float32, device=device)
5000 direction_criterion = nn.BCEWithLogitsLoss(pos_weight=pos_weight)
5001 magnitude_criterion = nn.MSELoss()
5002 volatility_criterion = nn.MSELoss()
5004 threshold = float(training_config["decision_threshold"])
5005 threshold_metric = str(training_config.get("optimize_threshold_metric", "f1"))
5006 threshold_min = float(training_config.get("threshold_search_min", 0.35))
5007 threshold_max = float(training_config.get("threshold_search_max", 0.65))
5008 threshold_steps = int(training_config.get("threshold_search_steps", 61))
5009 max_epochs = int(training_config["epochs"])
5010 patience = int(training_config["patience"])
5012 best_state = None
5013 best_epoch = 0
5014 best_validation_loss = float("inf")
5015 epochs_without_improvement = 0
5016 history: list[dict] = []
5018 for epoch in range(1, max_epochs + 1):
5019 model.train()
5020 running_loss = 0.0
5021 sample_count = 0
5023 for batch_features, batch_direction, batch_magnitude, batch_volatility in train_loader:
5024 batch_features = batch_features.to(device)
5025 batch_direction = batch_direction.to(device)
5026 batch_magnitude = batch_magnitude.to(device)
5027 batch_volatility = batch_volatility.to(device)
5029 optimizer.zero_grad()
5030 direction_logits, magnitude_predictions, volatility_predictions = model(batch_features)
5031 loss = (
5032 direction_criterion(direction_logits, batch_direction)
5033 + magnitude_loss_weight * magnitude_criterion(magnitude_predictions, batch_magnitude)
5034 + volatility_loss_weight * volatility_criterion(volatility_predictions, batch_volatility)
5035 )
5036 loss.backward()
5037 optimizer.step()
5039 running_loss += float(loss.item()) * len(batch_direction)
5040 sample_count += len(batch_direction)
5042 model.eval()
5043 with torch.no_grad():
5044 validation_direction_logits, validation_magnitude_predictions, validation_volatility_predictions = model(
5045 validation_features
5046 )
5047 validation_loss = (
5048 direction_criterion(validation_direction_logits, validation_direction)
5049 + magnitude_loss_weight * magnitude_criterion(validation_magnitude_predictions, validation_magnitude)
5050 + volatility_loss_weight * volatility_criterion(validation_volatility_predictions, validation_volatility)
5051 )
5052 history.append(
5053 {
5054 "epoch": epoch,
5055 "train_loss": running_loss / max(sample_count, 1),
5056 "validation_loss": float(validation_loss.item()),
5057 }
5058 )
5060 if float(validation_loss.item()) < best_validation_loss:
5061 best_validation_loss = float(validation_loss.item())
5062 best_epoch = epoch
5063 best_state = copy.deepcopy(model.state_dict())
5064 epochs_without_improvement = 0
5065 else:
5066 epochs_without_improvement += 1
5068 if epochs_without_improvement >= patience:
5069 break
5071 if best_state is None:
5072 best_state = copy.deepcopy(model.state_dict())
5073 best_epoch = len(history)
5075 model.load_state_dict(best_state)
5076 model.eval()
5077 with torch.no_grad():
5078 validation_direction_logits, _, _ = model(validation_features)
5079 tuned_threshold, tuned_validation_metrics = find_optimal_threshold(
5080 validation_direction_logits,
5081 validation_direction,
5082 direction_criterion,
5083 threshold_metric,
5084 threshold_min,
5085 threshold_max,
5086 threshold_steps,
5087 )
5089 def compute_split_metrics(features, direction, magnitude, volatility) -> dict:
5090 model.eval()
5091 with torch.no_grad():
5092 direction_logits, magnitude_predictions, volatility_predictions = model(features)
5093 return {
5094 "direction": compute_binary_metrics(direction_logits, direction, direction_criterion, tuned_threshold),
5095 "magnitude": compute_regression_metrics(magnitude_predictions, magnitude),
5096 "volatility": compute_regression_metrics(volatility_predictions, volatility),
5097 }
5099 backtest_features, backtest_direction, backtest_magnitude, backtest_volatility = _expert_multitask_tensors(
5100 backtest_frame, feature_names
5101 )
5102 backtest_features = backtest_features.to(device)
5103 backtest_direction = backtest_direction.to(device)
5104 backtest_magnitude = backtest_magnitude.to(device)
5105 backtest_volatility = backtest_volatility.to(device)
5107 metrics = {
5108 "expert": expert_name,
5109 "status": "trained",
5110 "rows": int(len(expert_frame)),
5111 "split_rows": {
5112 "train": int(len(train_frame)),
5113 "validation": int(len(validation_frame)),
5114 "backtest": int(len(backtest_frame)),
5115 },
5116 "best_epoch": best_epoch,
5117 "epochs_ran": len(history),
5118 "loss_weights": {
5119 "magnitude_loss_weight": magnitude_loss_weight,
5120 "volatility_loss_weight": volatility_loss_weight,
5121 },
5122 "threshold_optimization": {
5123 "metric": threshold_metric,
5124 "default_threshold": threshold,
5125 "selected_threshold": tuned_threshold,
5126 "selected_validation_metrics": tuned_validation_metrics,
5127 },
5128 "train": compute_split_metrics(
5129 train_features.to(device), train_direction.to(device), train_magnitude.to(device), train_volatility.to(device)
5130 ),
5131 "validation": compute_split_metrics(validation_features, validation_direction, validation_magnitude, validation_volatility),
5132 "backtest": compute_split_metrics(backtest_features, backtest_direction, backtest_magnitude, backtest_volatility),
5133 "history": history,
5134 }
5135 return {
5136 "expert": expert_name,
5137 "status": "trained",
5138 "model": model,
5139 "threshold": tuned_threshold,
5140 "metrics": metrics,
5141 }
5144def _write_expert_multitask_export(
5145 expert_name: str,
5146 result: dict,
5147 model_config: dict,
5148 feature_names: list[str],
5149 output_dir: Path,
5150) -> dict:
5151 def artifact_path(path: Path) -> str:
5152 try:
5153 return str(path.relative_to(ROOT))
5154 except ValueError:
5155 return str(path)
5157 expert_dir = output_dir / expert_name
5158 expert_dir.mkdir(parents=True, exist_ok=True)
5159 weights_path = expert_dir / "multitask_model.json"
5160 metrics_path = expert_dir / "multitask_training_metrics.json"
5162 metrics_path.write_text(json.dumps(result["metrics"], indent=2), encoding="utf-8")
5163 payload = {
5164 "project": "Aether Quant",
5165 "phase": "v2_expert_multitask_model",
5166 "expert": expert_name,
5167 "status": "trained",
5168 "created_at": datetime.now(timezone.utc).isoformat(),
5169 "model": {
5170 "type": "multitask_direction_magnitude_volatility",
5171 "model_input_features": feature_names,
5172 "hidden_layers": model_config["hidden_layers"],
5173 "dropout": model_config["dropout"],
5174 "activation": model_config.get("activation", "relu"),
5175 "normalization": model_config.get("normalization", "none"),
5176 "decision_threshold": result["threshold"],
5177 },
5178 "export": export_multitask_architecture(result["model"]) | {"state_dict": export_state_dict(result["model"])},
5179 }
5180 weights_path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
5181 return {
5182 "weights_path": artifact_path(weights_path),
5183 "metrics_path": artifact_path(metrics_path),
5184 }
5187def train_expert_models(
5188 config: dict,
5189 dataset: pd.DataFrame,
5190 dataset_manifest: dict,
5191 output_dir: Path = EXPERT_MODEL_DIR,
5192 metrics_path: Path = EXPERT_TRAINING_METRICS_PATH,
5193) -> dict:
5194 annotated_dataset, expert_dataset_manifest = build_expert_dataset_manifest(dataset, dataset_manifest, config)
5195 eligible = annotated_dataset
5196 if "training_eligible" in eligible.columns:
5197 eligible = eligible[eligible["training_eligible"]].copy()
5199 model_config, training_config = _expert_training_config(config)
5200 feature_names = _feature_names_for_model(config, annotated_dataset)
5201 device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
5203 # Per-expert multitask (direction+magnitude+volatility) training config -
5204 # reuses phase_v2.retraining.multitask_training's magnitude_loss_weight/
5205 # volatility_loss_weight (train_multitask.py's own config block) layered
5206 # onto the expert classifier's own training_config, so both loss weights
5207 # and the classifier's regularization/epoch/patience settings apply.
5208 multitask_overrides = config.get("phase_v2", {}).get("retraining", {}).get("multitask_training", {})
5209 expert_multitask_training_config = dict(training_config)
5210 expert_multitask_training_config["magnitude_loss_weight"] = float(multitask_overrides.get("magnitude_loss_weight", 1.0))
5211 expert_multitask_training_config["volatility_loss_weight"] = float(multitask_overrides.get("volatility_loss_weight", 1.0))
5213 summary = {
5214 "project": config["name"],
5215 "phase": "v2_expert_models_stabilized",
5216 "created_at": datetime.now(timezone.utc).isoformat(),
5217 "device": str(device),
5218 "feature_names": feature_names,
5219 "model_config": model_config,
5220 "training_config": {
5221 key: value for key, value in training_config.items() if key != "seed"
5222 },
5223 "source_dataset_rows": int(len(dataset)),
5224 "eligible_dataset_rows": int(len(eligible)),
5225 "expert_dataset_manifest": expert_dataset_manifest,
5226 "experts": {},
5227 }
5229 output_dir.mkdir(parents=True, exist_ok=True)
5230 for expert_name, expert_summary in expert_dataset_manifest["experts"].items():
5231 definition = EXPERT_DEFINITIONS[expert_name]
5232 expert_frame = eligible.copy()
5233 for column, allowed_values in definition["filter"].items():
5234 expert_frame = expert_frame[expert_frame[f"regime_{column}"].isin(allowed_values)].copy()
5236 result = _train_expert_classifier(
5237 expert_name,
5238 expert_frame,
5239 feature_names,
5240 model_config,
5241 training_config,
5242 device,
5243 )
5244 if result["status"] == "trained":
5245 artifacts = _write_expert_model_export(
5246 expert_name,
5247 result,
5248 model_config,
5249 training_config,
5250 feature_names,
5251 output_dir,
5252 )
5254 # Best-effort per-expert multitask head - a failure/skip here
5255 # never affects the classifier's own "trained" status above;
5256 # this only adds an optional multitask_model.json sibling file
5257 # moe/gating.py's per-expert magnitude/volatility blend
5258 # consumes when present (see moe/README.md).
5259 multitask_result = _train_expert_multitask(
5260 expert_name,
5261 expert_frame,
5262 feature_names,
5263 model_config,
5264 expert_multitask_training_config,
5265 device,
5266 )
5267 multitask_summary: dict = dict(multitask_result)
5268 multitask_summary.pop("model", None)
5269 if multitask_result["status"] == "trained":
5270 multitask_artifacts = _write_expert_multitask_export(
5271 expert_name,
5272 multitask_result,
5273 model_config,
5274 feature_names,
5275 output_dir,
5276 )
5277 multitask_summary["artifacts"] = multitask_artifacts
5279 summary["experts"][expert_name] = {
5280 **result["metrics"],
5281 "description": expert_summary["description"],
5282 "artifacts": artifacts,
5283 "multitask": multitask_summary,
5284 }
5285 else:
5286 summary["experts"][expert_name] = {
5287 **result,
5288 "description": expert_summary["description"],
5289 }
5291 summary["trained_experts"] = [
5292 expert for expert, payload in summary["experts"].items() if payload.get("status") == "trained"
5293 ]
5294 summary["skipped_experts"] = [
5295 expert for expert, payload in summary["experts"].items() if payload.get("status") != "trained"
5296 ]
5297 summary["gating_eligible_experts"] = [
5298 expert for expert, payload in summary["experts"].items() if payload.get("quality_gate", {}).get("gating_eligible")
5299 ]
5300 summary["disabled_for_gating_experts"] = [
5301 expert
5302 for expert, payload in summary["experts"].items()
5303 if payload.get("status") == "trained" and not payload.get("quality_gate", {}).get("gating_eligible", False)
5304 ]
5305 summary["quality_status_counts"] = dict(
5306 Counter(
5307 payload.get("quality_gate", {}).get("quality_status", payload.get("status", "unknown"))
5308 for payload in summary["experts"].values()
5309 )
5310 )
5311 metrics_path.write_text(json.dumps(summary, indent=2), encoding="utf-8")
5312 return summary
5315def write_model_export(
5316 config: dict,
5317 data_summary: dict,
5318 dataset_manifest: dict | None = None,
5319 training_result: dict | None = None,
5320 *,
5321 weights_path: Path = MODEL_WEIGHTS_PATH,
5322 dataset_manifest_path: Path = DATASET_MANIFEST_PATH,
5323 scaler_path: Path = SCALER_PATH,
5324 scaler_stats_path: Path = SCALER_STATS_PATH,
5325 checkpoint_path: Path = MODEL_CHECKPOINT_PATH,
5326 metrics_path: Path = TRAINING_METRICS_PATH,
5327 strategy_report_path: Path = STRATEGY_REPORT_PATH,
5328) -> None:
5329 """Writes the Lean-readable model export.
5331 All *_path kwargs default to the active ml/ locations so every existing
5332 call site is unaffected; candidate training (V2-17) passes
5333 ml/versions/<id>/... paths so the export's own path fields describe the
5334 candidate, not the active model.
5335 """
5336 phase1 = config["phase1"]
5337 payload = {
5338 "project": config["name"],
5339 "phase": 3,
5340 "status": "trained" if training_result else ("dataset_ready" if dataset_manifest else "placeholder"),
5341 "created_at": datetime.now(timezone.utc).isoformat(),
5342 "model": {
5343 "type": config["phase3"]["model"]["type"],
5344 "input_features": phase1["features"]["input_set"],
5345 "scaled_input_features": [f"{name}_scaled" for name in phase1["features"]["input_set"]],
5346 "context_input_features": dataset_manifest["context_feature_names"] if dataset_manifest else [],
5347 "model_input_features": dataset_manifest["model_input_names"] if dataset_manifest else [],
5348 "output_schema": phase1["target"]["type"],
5349 },
5350 "data_summary": data_summary,
5351 "v1_universe": phase1["universe"],
5352 "training_windows": phase1["windows"],
5353 "dataset_manifest_path": str(dataset_manifest_path.relative_to(ROOT)) if dataset_manifest else None,
5354 "scaler_path": str(scaler_path.relative_to(ROOT)) if dataset_manifest else None,
5355 "scaler_stats_path": str(scaler_stats_path.relative_to(ROOT)) if dataset_manifest else None,
5356 "checkpoint_path": str(checkpoint_path.relative_to(ROOT)) if training_result else None,
5357 "metrics_path": str(metrics_path.relative_to(ROOT)) if training_result else None,
5358 "strategy_report_path": str(strategy_report_path.relative_to(ROOT)) if training_result else None,
5359 "notes": [
5360 "Phase 3 trains a first MLP classifier on the synchronized daily dataset.",
5361 "The exported state_dict is JSON-based so Lean-side inference can be added in Phase 4.",
5362 "Keep ml/model.pt local-only for the binary PyTorch checkpoint.",
5363 ],
5364 }
5366 if training_result:
5367 model_config = training_result["model_config"]
5368 metrics = training_result["metrics"]
5369 payload["model"].update(
5370 {
5371 "hidden_layers": model_config["hidden_layers"],
5372 "dropout": model_config["dropout"],
5373 "activation": model_config["activation"],
5374 "normalization": model_config.get("normalization", "none"),
5375 "use_asset_context": model_config.get("use_asset_context", False),
5376 "output_activation": model_config["output_activation"],
5377 }
5378 )
5379 payload["training"] = {
5380 "best_epoch": metrics["best_epoch"],
5381 "epochs_ran": metrics["epochs_ran"],
5382 "decision_threshold": training_result["threshold"],
5383 "threshold_metric": training_result["training_config"].get("optimize_threshold_metric", "f1"),
5384 "validation_accuracy": metrics["validation"]["accuracy"],
5385 "validation_balanced_accuracy": metrics["validation"]["balanced_accuracy"],
5386 "validation_f1": metrics["validation"]["f1"],
5387 "backtest_accuracy": metrics["backtest"]["accuracy"],
5388 "backtest_balanced_accuracy": metrics["backtest"]["balanced_accuracy"],
5389 "backtest_f1": metrics["backtest"]["f1"],
5390 }
5391 payload["backtest"] = training_result["strategy_report"]
5392 payload["export"] = {
5393 "architecture": export_architecture(training_result["model"]),
5394 "state_dict": export_state_dict(training_result["model"]),
5395 }
5397 weights_path.parent.mkdir(parents=True, exist_ok=True)
5398 weights_path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
5401def load_existing_training_context() -> dict | None:
5402 if not TRAINING_METRICS_PATH.exists() or not STRATEGY_REPORT_PATH.exists():
5403 return None
5405 metrics = json.loads(TRAINING_METRICS_PATH.read_text(encoding="utf-8"))
5406 strategy_report = json.loads(STRATEGY_REPORT_PATH.read_text(encoding="utf-8"))
5407 feature_schema = json.loads(FEATURE_SCHEMA_PATH.read_text(encoding="utf-8")) if FEATURE_SCHEMA_PATH.exists() else {}
5408 model_export = json.loads(MODEL_WEIGHTS_PATH.read_text(encoding="utf-8")) if MODEL_WEIGHTS_PATH.exists() else {}
5409 threshold = metrics.get("threshold_optimization", {}).get(
5410 "selected_threshold",
5411 model_export.get("training", {}).get("decision_threshold", 0.5),
5412 )
5414 return {
5415 "metrics": metrics,
5416 "strategy_report": strategy_report,
5417 "threshold": threshold,
5418 "scaled_feature_names": list(feature_schema.get("model_input_names", [])),
5419 }
5422def build_phase8_asset_heatmap(strategy_report: dict | None) -> list[dict]:
5423 if not strategy_report:
5424 return []
5426 heatmap = []
5427 per_asset = strategy_report.get("backtest_per_asset", {})
5428 for ticker, asset_report in sorted(per_asset.items()):
5429 strategy = asset_report["strategy"]
5430 heatmap.append(
5431 {
5432 "ticker": ticker,
5433 "strategy_return": strategy["total_return"],
5434 "excess_return": asset_report["excess_return_vs_buy_and_hold"],
5435 "sharpe": strategy["sharpe"],
5436 "max_drawdown": strategy["max_drawdown"],
5437 "exposure_rate": asset_report["exposure_rate"],
5438 "trade_count": asset_report["trade_count"],
5439 "signal_bias": "positive" if asset_report["excess_return_vs_buy_and_hold"] >= 0 else "negative",
5440 }
5441 )
5442 return heatmap
5445def build_phase8_scene_payload(
5446 universe_assets: list[dict],
5447 strategy_report: dict | None,
5448 total_portfolio_value: float,
5449) -> dict:
5450 nodes = [
5451 {
5452 "id": "portfolio_core",
5453 "label": "Portfolio Core",
5454 "kind": "portfolio",
5455 "x": 50,
5456 "y": 52,
5457 "z": 0.95,
5458 "intensity": 0.82,
5459 "value": total_portfolio_value,
5460 "detail": "Central portfolio state",
5461 }
5462 ]
5463 links = []
5464 per_asset = strategy_report.get("backtest_per_asset", {}) if strategy_report else {}
5465 asset_count = max(len(universe_assets), 1)
5467 for index, asset in enumerate(universe_assets):
5468 ticker = asset["ticker"]
5469 asset_report = per_asset.get(ticker)
5470 angle = (2 * math.pi * index) / asset_count
5471 x = 50 + math.cos(angle) * 32
5472 y = 50 + math.sin(angle) * 22
5473 z = 0.45 + ((index % 4) * 0.12)
5474 excess_return = asset_report["excess_return_vs_buy_and_hold"] if asset_report else 0.0
5475 intensity = 0.5 + max(min(excess_return, 0.6), -0.6) / 1.5
5476 nodes.append(
5477 {
5478 "id": ticker,
5479 "label": ticker,
5480 "kind": "asset",
5481 "x": x,
5482 "y": y,
5483 "z": z,
5484 "intensity": max(0.12, min(0.96, intensity)),
5485 "value": asset_report["strategy"]["total_return"] if asset_report else 0.0,
5486 "detail": asset["security_type"],
5487 }
5488 )
5489 links.append(
5490 {
5491 "source": "portfolio_core",
5492 "target": ticker,
5493 "strength": asset_report["exposure_rate"] if asset_report else 0.25,
5494 }
5495 )
5497 return {
5498 "layout": "portfolio_star",
5499 "nodes": nodes,
5500 "links": links,
5501 "dimensions": {"width": 100, "height": 100, "depth": 1},
5502 }
5505def build_phase8_scorecards(
5506 config: dict,
5507 training_context: dict | None,
5508 total_portfolio_value: float,
5509) -> list[dict]:
5510 cards = [
5511 {
5512 "key": "portfolio_value",
5513 "label": "Portfolio Value",
5514 "value": total_portfolio_value,
5515 "format": "currency",
5516 }
5517 ]
5519 if not training_context:
5520 return cards
5522 metrics = training_context["metrics"]
5523 strategy_report = training_context["strategy_report"]
5524 cards.extend(
5525 [
5526 {
5527 "key": "validation_accuracy",
5528 "label": "Validation Accuracy",
5529 "value": metrics["validation"]["accuracy"],
5530 "format": "percent",
5531 },
5532 {
5533 "key": "backtest_return",
5534 "label": "Backtest Return",
5535 "value": strategy_report["backtest"]["strategy"]["total_return"],
5536 "format": "percent",
5537 },
5538 {
5539 "key": "backtest_sharpe",
5540 "label": "Backtest Sharpe",
5541 "value": strategy_report["backtest"]["strategy"]["sharpe"],
5542 "format": "number",
5543 },
5544 {
5545 "key": "max_drawdown",
5546 "label": "Max Drawdown",
5547 "value": strategy_report["backtest"]["strategy"]["max_drawdown"],
5548 "format": "percent",
5549 },
5550 ]
5551 )
5552 return cards
5555def write_phase8_exports(
5556 config: dict,
5557 training_context: dict | None,
5558 scene_payload: dict,
5559 scorecards: list[dict],
5560 asset_heatmap: list[dict],
5561) -> None:
5562 metrics_snapshot = {
5563 "project": config["name"],
5564 "phase": 8,
5565 "updated_at": datetime.now(timezone.utc).isoformat(),
5566 "scorecards": scorecards,
5567 "asset_heatmap": asset_heatmap,
5568 "feed_files": {
5569 "state": str(STATE_PATH.relative_to(ROOT)),
5570 "scene": str(SCENE_PATH.relative_to(ROOT)),
5571 "equity_curves": str(GRAFANA_EQUITY_CURVES_PATH.relative_to(ROOT)),
5572 "asset_performance": str(GRAFANA_ASSET_PERFORMANCE_PATH.relative_to(ROOT)),
5573 },
5574 }
5576 if training_context:
5577 metrics_snapshot["training"] = {
5578 "best_epoch": training_context["metrics"]["best_epoch"],
5579 "validation_accuracy": training_context["metrics"]["validation"]["accuracy"],
5580 "validation_balanced_accuracy": training_context["metrics"]["validation"]["balanced_accuracy"],
5581 "backtest_accuracy": training_context["metrics"]["backtest"]["accuracy"],
5582 "decision_threshold": training_context["threshold"],
5583 }
5584 metrics_snapshot["strategy"] = training_context["strategy_report"]["backtest"]
5586 GRAFANA_METRICS_PATH.write_text(json.dumps(metrics_snapshot, indent=2), encoding="utf-8")
5587 SCENE_PATH.write_text(json.dumps(scene_payload, indent=2), encoding="utf-8")
5589 if EQUITY_CURVES_PATH.exists():
5590 GRAFANA_EQUITY_CURVES_PATH.write_text(EQUITY_CURVES_PATH.read_text(encoding="utf-8"), encoding="utf-8")
5592 asset_frame = pd.DataFrame(asset_heatmap)
5593 if not asset_frame.empty:
5594 asset_frame.to_csv(GRAFANA_ASSET_PERFORMANCE_PATH, index=False)
5597def write_visualization_state(
5598 config: dict,
5599 inventory: dict,
5600 data_summary: dict,
5601 dataset_manifest: dict | None = None,
5602 training_context: dict | None = None,
5603) -> None:
5604 phase1 = config["phase1"]
5605 training_state = {
5606 "status": "trained" if training_context else ("dataset_ready" if dataset_manifest else "not_started"),
5607 "dataset_available": data_summary["available"],
5608 "asset_groups": data_summary["asset_groups"],
5609 "selected_universe": [asset["ticker"] for asset in phase1["universe"]["assets"]],
5610 "resolution": phase1["universe"]["resolution"],
5611 "windows": phase1["windows"],
5612 }
5614 if dataset_manifest:
5615 training_state["dataset_rows"] = dataset_manifest["dataset_rows"]
5616 training_state["feature_count"] = dataset_manifest["feature_count"]
5617 training_state["split_counts"] = dataset_manifest["split_counts"]
5618 training_state["alignment_mode"] = dataset_manifest["alignment"]["alignment_mode"]
5619 training_state["asset_quality"] = dataset_manifest.get("asset_quality", {})
5620 training_state["training_eligible_assets"] = dataset_manifest.get("training_eligible_assets", [])
5621 training_state["trading_eligible_assets"] = dataset_manifest.get("trading_eligible_assets", [])
5622 training_state["observation_only_assets"] = dataset_manifest.get("observation_only_assets", [])
5624 if training_context:
5625 metrics = training_context["metrics"]
5626 strategy_report = training_context["strategy_report"]
5627 training_state["model_type"] = config["phase3"]["model"]["type"]
5628 training_state["best_epoch"] = metrics["best_epoch"]
5629 training_state["model_input_count"] = len(training_context["scaled_feature_names"])
5630 training_state["validation_accuracy"] = metrics["validation"]["accuracy"]
5631 training_state["validation_balanced_accuracy"] = metrics["validation"]["balanced_accuracy"]
5632 training_state["validation_f1"] = metrics["validation"]["f1"]
5633 training_state["backtest_accuracy"] = metrics["backtest"]["accuracy"]
5634 training_state["backtest_balanced_accuracy"] = metrics["backtest"]["balanced_accuracy"]
5635 training_state["backtest_f1"] = metrics["backtest"]["f1"]
5636 training_state["decision_threshold"] = training_context["threshold"]
5637 training_state["strategy_total_return"] = strategy_report["backtest"]["strategy"]["total_return"]
5638 training_state["strategy_sharpe"] = strategy_report["backtest"]["strategy"]["sharpe"]
5639 training_state["strategy_max_drawdown"] = strategy_report["backtest"]["strategy"]["max_drawdown"]
5640 training_state["buy_and_hold_return"] = strategy_report["backtest"]["buy_and_hold"]["total_return"]
5642 total_portfolio_value = float(config["runtime"]["initial_cash"])
5643 asset_heatmap = build_phase8_asset_heatmap(training_context["strategy_report"] if training_context else None)
5644 scene_payload = build_phase8_scene_payload(
5645 phase1["universe"]["assets"],
5646 training_context["strategy_report"] if training_context else None,
5647 total_portfolio_value,
5648 )
5649 scorecards = build_phase8_scorecards(config, training_context, total_portfolio_value)
5651 payload = {
5652 "project": config["name"],
5653 "mode": "idle",
5654 "updated_at": datetime.now(timezone.utc).isoformat(),
5655 "insight": "Phase 8 visualization exports ready" if training_context else ("Phase 2 dataset pipeline ready" if dataset_manifest else "Inventory ready"),
5656 "portfolio": {
5657 "cash": total_portfolio_value,
5658 "total_portfolio_value": total_portfolio_value,
5659 },
5660 "positions": [],
5661 "signals": {},
5662 "training": training_state,
5663 "dashboard": {
5664 "scorecards": scorecards,
5665 "asset_heatmap": asset_heatmap,
5666 "strategy_snapshot": training_context["strategy_report"]["backtest"] if training_context else None,
5667 "visualization_stage": "phase8",
5668 },
5669 "monitoring": {
5670 "feeds": {
5671 "metrics_snapshot": str(GRAFANA_METRICS_PATH.relative_to(ROOT)),
5672 "equity_curves": str(GRAFANA_EQUITY_CURVES_PATH.relative_to(ROOT)),
5673 "asset_performance": str(GRAFANA_ASSET_PERFORMANCE_PATH.relative_to(ROOT)),
5674 "scene": str(SCENE_PATH.relative_to(ROOT)),
5675 }
5676 },
5677 "scene": scene_payload,
5678 "inventory_snapshot": inventory["coverage_checks"],
5679 }
5680 STATE_PATH.write_text(json.dumps(payload, indent=2), encoding="utf-8")
5681 write_phase8_exports(config, training_context, scene_payload, scorecards, asset_heatmap)
5684def run_net_performance_simulation(
5685 frame: pd.DataFrame, prediction_column: str, net_performance_config: dict, sector_by_ticker: dict[str, str],
5686 full_config: dict | None = None,
5687) -> dict | None:
5688 """V5.1 Phase 4 (items 7, 12) - shared by _run_walk_forward_net_performance()
5689 (one call per walk-forward window) and train_multitask.py/
5690 train_sequence.py's compute_*_metrics() (one call per regular
5691 backtest-split evaluation), so both call sites run the identical
5692 simulate_rank_book()/capacity_curve()/stress_test_costs() pipeline with
5693 identical config-reading rather than two independently-drifting copies.
5695 `frame` must already be filtered to the split being evaluated
5696 (typically backtest) and contain `prediction_column` (an
5697 already-predicted, unbounded rank score - a raw model output, not yet
5698 normalized) alongside ticker/date/target_return_1d. Returns None (never
5699 raises) when `frame` has no usable, non-NaN predictions in that column
5700 - the caller then simply omits the net-performance result rather than
5701 recording a fabricated one."""
5702 if prediction_column not in frame.columns or frame[prediction_column].dropna().empty:
5703 return None
5704 base_kwargs = {
5705 "prediction_column": prediction_column,
5706 "top_n": int(net_performance_config.get("top_n", 6)),
5707 "bottom_n": int(net_performance_config.get("bottom_n", 6)),
5708 "rebalance_every_bars": int(net_performance_config.get("rebalance_every_bars", 10)),
5709 "cost_bps_per_side": float(net_performance_config.get("cost_bps_per_side", 5.0)),
5710 "commission_bps": float(net_performance_config.get("commission_bps", 1.0)),
5711 "gross_exposure": float(net_performance_config.get("gross_exposure", 1.0)),
5712 "dollar_neutral": bool(net_performance_config.get("dollar_neutral", True)),
5713 "sector_neutral": bool(net_performance_config.get("sector_neutral", True)),
5714 "sector_by_ticker": sector_by_ticker,
5715 "hysteresis_rank_margin": float(net_performance_config.get("hysteresis_rank_margin", 0.05)),
5716 "max_weight_per_name": float(net_performance_config.get("max_weight_per_name", 0.12)),
5717 # V5.2.1 (development/Problems.md) - both no-op by default,
5718 # matching simulate_rank_book()'s own defaults exactly - see
5719 # aq_cli.py::cmd_evaluate()'s identical wiring for the full
5720 # rationale.
5721 "entry_lag_bars": int(net_performance_config.get("entry_lag_bars", 0)),
5722 "min_commission_usd": float(net_performance_config.get("min_commission_usd", 0.0)),
5723 "assumed_portfolio_value_usd": float(net_performance_config.get("assumed_portfolio_value_usd", 0.0)),
5724 # Per-class exchange fees (phase_v2.costs.fee_by_type), so the offline book pays what the live gate assumes.
5725 "commission_bps_by_ticker": commission_bps_by_ticker(
5726 (full_config or {}).get("phase_v2", {}).get("costs", {}),
5727 {
5728 str(asset.get("ticker")): str(asset.get("security_type"))
5729 for asset in (full_config or {}).get("phase1", {}).get("universe", {}).get("assets", [])
5730 },
5731 )
5732 or None,
5733 }
5734 simulation_result = simulate_rank_book(frame, **base_kwargs)
5735 capacity_result = capacity_curve(
5736 frame,
5737 participation_cap=float(net_performance_config.get("capacity_participation_cap", 0.01)),
5738 base_kwargs=base_kwargs,
5739 top_n_sweep=list(net_performance_config.get("capacity_top_n_sweep", [3, 6, 10, 15])),
5740 )
5741 stress_results = stress_test_costs(
5742 frame,
5743 base_kwargs=base_kwargs,
5744 cost_multipliers=tuple(net_performance_config.get("stress_cost_multipliers", (1.0, 2.0, 3.0))),
5745 )
5746 return {"simulation": simulation_result.to_dict(), "capacity": capacity_result, "stress": stress_results}
5749def _run_walk_forward_trainer(
5750 script_name: str,
5751 version_id: str,
5752 dataset_path: Path,
5753 feature_schema_path: Path,
5754 config_path: Path,
5755 timeout_seconds: int,
5756 memory_profile: str = "standard",
5757 resume: bool = False,
5758) -> dict | None:
5759 """V5.1 Phase 4 (Step 4.2) - best-effort per-window subprocess call to
5760 train_multitask.py/train_sequence.py, same never-fatal contract as
5761 retraining/orchestrator.py::train_multitask()/train_sequence(): a
5762 failure here never aborts the walk-forward run, it just means that
5763 window contributes no tracked-metric value for that trainer. Passes
5764 --dataset-path/--feature-schema-path/--config-path so each subprocess
5765 trains against THIS window's own data, not the active ml/ artifacts
5766 (see train_multitask.py::parse_args()'s --feature-schema-path
5767 docstring, added in this same phase). Returns the written
5768 *_training_metrics.json dict, or None on any failure (launch error,
5769 nonzero exit, or a "skipped, no artifacts written" run - e.g. too few
5770 rows in a short window).
5772 V6.6.10, `resume` (a resumed walk-forward): a trainer that already finished in this window (its metrics file is written last) is
5773 not run again, and the sequence trainer continues from its per-epoch checkpoint (`--resume`, written under the low profile)."""
5774 metrics_name = "multitask_training_metrics.json" if "multitask" in script_name else "sequence_training_metrics.json"
5775 metrics_path = ML_DIR / "versions" / version_id / metrics_name
5776 if resume and metrics_path.exists():
5777 LOGGER.info("walk-forward: %s already finished for %s - reusing its metrics.", script_name, version_id)
5778 return json.loads(metrics_path.read_text(encoding="utf-8"))
5779 continue_checkpoint = resume and "sequence" in script_name and memory_profile != "standard"
5780 script_path = ROOT / script_name
5781 failed_marker = metrics_path.parent / f"{Path(script_name).stem}{WALK_FORWARD_TRAINER_FAILED_SUFFIX}"
5782 try:
5783 result = subprocess.run(
5784 [
5785 sys.executable, str(script_path),
5786 "--version-id", version_id,
5787 "--dataset-path", str(dataset_path),
5788 "--feature-schema-path", str(feature_schema_path),
5789 "--config-path", str(config_path),
5790 *(["--memory-profile", memory_profile] if memory_profile != "standard" else []),
5791 *(["--resume"] if continue_checkpoint else []),
5792 ],
5793 cwd=str(ROOT),
5794 capture_output=True,
5795 text=True,
5796 timeout=timeout_seconds, check=False,
5797 )
5798 except Exception as exc: # never let a best-effort subprocess crash the walk-forward run (a timeout lands here too)
5799 LOGGER.warning("walk-forward: %s subprocess failed for %s - %s", script_name, version_id, exc)
5800 _mark_trainer_failed(failed_marker, f"{type(exc).__name__}: {exc}")
5801 return None
5802 if result.returncode != 0:
5803 LOGGER.warning(
5804 "walk-forward: %s failed for %s (rc=%d) - %s",
5805 script_name, version_id, result.returncode, result.stderr[-2000:],
5806 )
5807 _mark_trainer_failed(failed_marker, f"exit {result.returncode}")
5808 return None
5809 failed_marker.unlink(missing_ok=True)
5811 if not metrics_path.exists():
5812 LOGGER.info("walk-forward: %s skipped writing artifacts for %s (insufficient rows).", script_name, version_id)
5813 return None
5814 return json.loads(metrics_path.read_text(encoding="utf-8"))
5817def _run_walk_forward_net_performance(
5818 dataset: pd.DataFrame,
5819 feature_names: list[str],
5820 model_export: dict,
5821 model_kind: str,
5822 sequence_feature_schema: dict | None,
5823 configured_window_size: int,
5824 head: str,
5825 net_performance_config: dict,
5826 sector_by_ticker: dict[str, str],
5827 full_config: dict | None = None,
5828) -> dict | None:
5829 """V5.1 Phase 4 (Step 4.2) - runs simulate_rank_book()/capacity_curve()/
5830 stress_test_costs() against ONE window's own backtest-split
5831 predictions, via evaluation.predict_head() - the SAME torch-free
5832 interpreter `aq evaluate --rank-book` uses, so a window's net
5833 performance is computed identically to the offline evaluator, not a
5834 re-derived approximation. Returns None (never raises) when the
5835 backtest split is empty or the head produced no usable predictions -
5836 net_performance_by_window simply omits that window rather than
5837 recording a fabricated zero."""
5838 eligible = dataset[dataset["training_eligible"]].copy() if "training_eligible" in dataset.columns else dataset.copy()
5839 backtest_frame = eligible[eligible["split"] == "backtest"].reset_index(drop=True)
5840 if backtest_frame.empty:
5841 return None
5843 predictions = predict_head(
5844 backtest_frame, model_export, feature_names, head,
5845 model_kind=model_kind, sequence_feature_schema=sequence_feature_schema,
5846 configured_window_size=configured_window_size,
5847 )
5848 backtest_frame = backtest_frame.copy()
5849 backtest_frame["_walk_forward_predicted_head"] = predictions
5851 result = run_net_performance_simulation(
5852 backtest_frame, "_walk_forward_predicted_head", net_performance_config, sector_by_ticker, full_config
5853 )
5854 if result is None:
5855 return None
5856 return {"head": head, "model_kind": model_kind, **result}
5859WALK_FORWARD_WINDOW_RESULT_FILENAME = "window_result.json"
5860WALK_FORWARD_TRAINER_FAILED_SUFFIX = ".failed"
5863def _mark_trainer_failed(marker: Path, reason: str) -> None:
5864 """V6.6.10 (#408): a window trainer that failed or timed out leaves `<trainer>.failed` beside its version, so a resumed walk-forward
5865 retries that window (its dataset, baseline and finished trainers are reused) instead of keeping it as complete."""
5866 marker.parent.mkdir(parents=True, exist_ok=True)
5867 marker.write_text(reason + "\n", encoding="utf-8")
5870WALK_FORWARD_DATASET_DONE_FILENAME = "dataset_complete.json"
5871WALK_FORWARD_BASELINE_DONE_FILENAME = "baseline_complete.json"
5874def _reusable_window_parts(paths: dict) -> dict:
5875 """V6.6.10: what a resumed walk-forward window can take from its earlier attempt. The dataset counts only with its completion marker
5876 (written after the CSV, scaler, manifest and schema), the baseline only with its own (written after its export): anything torn reruns."""
5877 parts: dict = {}
5878 version_dir = paths["version_dir"]
5879 manifest = load_json_lenient(paths["dataset_manifest"])
5880 if (version_dir / WALK_FORWARD_DATASET_DONE_FILENAME).exists() and isinstance(manifest, dict) and paths["full_dataset"].exists():
5881 parts["dataset_manifest"] = manifest
5882 baseline = load_json_lenient(version_dir / WALK_FORWARD_BASELINE_DONE_FILENAME)
5883 if isinstance(baseline, dict) and isinstance(baseline.get("metrics"), dict):
5884 parts["metrics"] = baseline["metrics"]
5885 return parts
5888def _read_window_dataset(path: Path, memory_profile: str) -> pd.DataFrame:
5889 """A window's own dataset, read back for a resumed window or for its net-performance step (float32 under the low profile)."""
5890 if memory_profile == "low":
5891 from retraining.slicing import read_csv_float32
5893 return read_csv_float32(path)
5894 return pd.read_csv(path)
5897def _load_walk_forward_window_result(run_id: str, window_index: int) -> dict | None:
5898 """The saved outcome of a COMPLETED walk-forward window (written as that window's last step), else None -
5899 a missing or torn file means the window reruns, never that it is trusted."""
5900 path = ML_DIR / "versions" / run_id / f"window_{window_index}" / WALK_FORWARD_WINDOW_RESULT_FILENAME
5901 if any(path.parent.glob(f"*{WALK_FORWARD_TRAINER_FAILED_SUFFIX}")):
5902 return None # a trainer failed in it: the window is retried (#408)
5903 payload = load_json_lenient(path)
5904 if not isinstance(payload, dict) or not isinstance(payload.get("window_result"), dict) or "backtest_mcc" not in payload:
5905 return None
5906 return payload
5909def _run_walk_forward(
5910 config: dict, data_summary: dict, step_days: int, mode: str, resume_run_id: str | None = None, memory_profile: str = "standard",
5911 run_id_file: str | None = None,
5912) -> dict:
5913 """Phase 4 of the 5/10 -> 9/10 roadmap: `python train.py --walk-forward`'s
5914 implementation - runs the baseline model's existing dataset-build +
5915 training pipeline once per generate_walk_forward_windows() window,
5916 writing each window to ml/versions/<run_id>/window_<i>/ (extends
5917 candidate_output_paths()'s directory convention: this deliberately
5918 duplicates the same handful of calls the `--candidate` branch below
5919 already makes, in a loop, rather than refactoring that already-tested
5920 branch to share code - zero regression risk to it as a result).
5922 Never touches active ml/ - same as --candidate. Returns a summary dict
5923 with per-window results and, for every entry in
5924 walk_forward.tracked_metrics (default: the single backtest.mcc entry,
5925 reproducing today's behavior exactly), a cross-window
5926 summarize_walk_forward_run() stability readout under
5927 summary_by_metric/stability_by_metric (V5.1 Phase 4, item 4).
5929 V5.1 Phase 4 (items 4, 7, 12) additions, all config-gated under
5930 walk_forward and all OFF by default (byte-identical to pre-Phase-4
5931 behavior when unset): walk_forward.train_multitask/train_sequence run
5932 those trainers per window against that window's own data (needs Step
5933 4.1's per-window full_dataset.csv/feature_schema.json, written below);
5934 walk_forward.net_performance runs the offline rank-book simulator
5935 against whichever of those two models trained (sequence preferred,
5936 matching phase_v2.rank_signal.model_priority's own precedent),
5937 producing net_performance_by_window.
5938 """
5939 walk_forward_config = config.get("phase_v2", {}).get("retraining", {}).get("walk_forward", {})
5940 train_span_days = int(walk_forward_config.get("train_span_days", 1095))
5941 validation_span_days = int(walk_forward_config.get("validation_span_days", 365))
5942 backtest_span_days = int(walk_forward_config.get("backtest_span_days", 365))
5943 train_multitask_enabled = bool(walk_forward_config.get("train_multitask", False))
5944 train_sequence_enabled = bool(walk_forward_config.get("train_sequence", False))
5945 net_performance_enabled = bool(walk_forward_config.get("net_performance", False))
5946 net_performance_head = str(walk_forward_config.get("net_performance_head", "rank_20d"))
5947 from retraining.slicing import memory_profile as _memory_profile
5949 timeout_factor = _memory_profile(memory_profile).timeout_factor
5950 multitask_timeout_seconds = int(int(walk_forward_config.get("multitask_timeout_seconds", 2400)) * timeout_factor)
5951 sequence_timeout_seconds = int(int(walk_forward_config.get("sequence_timeout_seconds", 2400)) * timeout_factor)
5952 tracked_metrics_config = list(
5953 walk_forward_config.get(
5954 "tracked_metrics", [{"name": "backtest_mcc", "artifact": "training_metrics.json", "path": "backtest.mcc"}]
5955 )
5956 )
5958 windows = generate_walk_forward_windows(
5959 config["phase1"]["universe"]["common_window"],
5960 train_span_days=train_span_days,
5961 validation_span_days=validation_span_days,
5962 backtest_span_days=backtest_span_days,
5963 step_days=step_days,
5964 mode=mode,
5965 )
5966 if not windows:
5967 LOGGER.warning(
5968 "walk-forward: no windows fit inside common_window with train=%s/validation=%s/backtest=%s/step=%s days.",
5969 train_span_days, validation_span_days, backtest_span_days, step_days,
5970 )
5971 return {
5972 "run_id": None, "num_windows": 0, "window_results": [],
5973 "summary": summarize_walk_forward_run([]),
5974 "summary_by_metric": {}, "stability_by_metric": {}, "net_performance_by_window": [],
5975 }
5977 run_id = resume_run_id or f"walk-forward-{uuid.uuid4()}"
5978 LOGGER.info("walk-forward run id: %s", run_id)
5979 if run_id_file:
5980 Path(run_id_file).parent.mkdir(parents=True, exist_ok=True)
5981 Path(run_id_file).write_text(run_id + "\n", encoding="utf-8")
5982 feature_names = config["phase1"]["features"]["input_set"]
5983 window_results: list[dict] = []
5984 backtest_mcc_by_window: list[float] = []
5985 tracked_values_by_metric: dict[str, list[float]] = {entry["name"]: [] for entry in tracked_metrics_config}
5986 net_performance_by_window: list[dict] = []
5987 sector_by_ticker = load_sector_mapping(config) if net_performance_enabled else {}
5989 for window_index, window in enumerate(windows):
5990 saved_result = _load_walk_forward_window_result(run_id, window_index) if resume_run_id else None
5991 if saved_result is not None:
5992 LOGGER.info("walk-forward window %s/%s already complete - resuming past it.", window_index + 1, len(windows))
5993 window_results.append(saved_result["window_result"])
5994 backtest_mcc_by_window.append(float(saved_result["backtest_mcc"]))
5995 for name, value in saved_result.get("tracked_values", {}).items():
5996 tracked_values_by_metric.setdefault(name, []).append(float(value))
5997 if saved_result.get("net_performance") is not None:
5998 net_performance_by_window.append(saved_result["net_performance"])
5999 continue
6001 window_config = copy.deepcopy(config)
6002 window_config["phase1"]["windows"] = {
6003 **window,
6004 **{
6005 key: config["phase1"]["windows"][key]
6006 for key in ("purge_label_horizon_days",)
6007 if key in config["phase1"].get("windows", {})
6008 },
6009 }
6010 LOGGER.info(
6011 "walk-forward window %s/%s: train=%s..%s validation=%s..%s backtest=%s..%s",
6012 window_index + 1, len(windows),
6013 window["training"]["start"], window["training"]["end"],
6014 window["validation"]["start"], window["validation"]["end"],
6015 window["backtest"]["start"], window["backtest"]["end"],
6016 )
6018 version_id = f"{run_id}/window_{window_index}"
6019 paths = candidate_output_paths(version_id)
6020 reused = _reusable_window_parts(paths) if resume_run_id else {}
6021 dataset = None
6022 if "dataset_manifest" in reused:
6023 dataset_manifest = reused["dataset_manifest"]
6024 LOGGER.info("walk-forward window %s/%s: its dataset was written completely before - reusing it.", window_index + 1, len(windows))
6025 else:
6026 dataset, metadata = build_feature_dataset(window_config)
6027 asset_quality = build_asset_quality(window_config, dataset, metadata)
6028 dataset = apply_asset_quality_flags(dataset, asset_quality)
6030 feature_config = window_config["phase1"]["features"]
6031 winsorize_quantiles = tuple(feature_config.get("winsorize_quantiles", (0.001, 0.999)))
6032 clip_sigma = float(feature_config.get("scaled_feature_clip_sigma", 10.0))
6033 dataset, scaler, clip_sigma = fit_and_apply_scaler(
6034 dataset, feature_names, winsorize_quantiles=winsorize_quantiles, clip_sigma=clip_sigma,
6035 )
6036 dataset, _ = add_asset_context_features(
6037 dataset, [asset["ticker"] for asset in window_config["phase1"]["universe"]["assets"]],
6038 )
6039 dataset, _ = add_asset_class_context_features(dataset, asset_class_by_ticker_from_config(window_config))
6040 dataset_manifest = build_dataset_manifest(window_config, dataset, {}, metadata, asset_quality)
6042 paths["version_dir"].mkdir(parents=True, exist_ok=True)
6043 write_scaler_artifacts(
6044 scaler, dataset_manifest, scaler_path=paths["scaler"], scaler_stats_path=paths["scaler_stats"],
6045 clip_sigma=clip_sigma,
6046 )
6047 paths["dataset_manifest"].write_text(json.dumps(dataset_manifest, indent=2), encoding="utf-8")
6048 # Per-window dataset + schema for the multitask/sequence subprocesses below (the active schema does not match this window).
6049 # Written beside its name and renamed, then marked complete: a resumed window reuses only a dataset written to its end.
6050 partial = paths["full_dataset"].with_name(paths["full_dataset"].name + ".partial")
6051 dataset.to_csv(partial, index=False)
6052 partial.replace(paths["full_dataset"])
6053 paths["feature_schema"].write_text(
6054 json.dumps(build_feature_schema_payload(dataset_manifest), indent=2), encoding="utf-8"
6055 )
6056 atomic_write_json(paths["version_dir"] / WALK_FORWARD_DATASET_DONE_FILENAME, {"rows": len(dataset)})
6058 if "metrics" in reused:
6059 training_metrics = reused["metrics"]
6060 LOGGER.info("walk-forward window %s/%s: its baseline finished before - reusing it.", window_index + 1, len(windows))
6061 else:
6062 if dataset is None:
6063 dataset = _read_window_dataset(paths["full_dataset"], memory_profile)
6064 if memory_profile == "low":
6065 dataset = compact_dataset_for_training(dataset) # after the CSV is written: the trainers' inputs are float32 anyway
6066 training_result = train_model(
6067 window_config, dataset,
6068 checkpoint_path=paths["model_checkpoint"], metrics_path=paths["training_metrics"],
6069 strategy_report_path=paths["strategy_report"], equity_curves_path=paths["equity_curves"],
6070 )
6071 write_model_export(
6072 window_config, data_summary, dataset_manifest=dataset_manifest, training_result=training_result,
6073 weights_path=paths["model_weights"], dataset_manifest_path=paths["dataset_manifest"],
6074 scaler_path=paths["scaler"], scaler_stats_path=paths["scaler_stats"],
6075 checkpoint_path=paths["model_checkpoint"], metrics_path=paths["training_metrics"],
6076 strategy_report_path=paths["strategy_report"],
6077 )
6078 training_metrics = training_result["metrics"]
6079 atomic_write_json(paths["version_dir"] / WALK_FORWARD_BASELINE_DONE_FILENAME, {"metrics": training_metrics})
6081 backtest_mcc = float(training_metrics["backtest"].get("mcc", 0.0) or 0.0)
6082 backtest_mcc_by_window.append(backtest_mcc)
6084 # V5.1 Phase 4 memory fix - the parent process's own `dataset`
6085 # (already written to paths["full_dataset"] above) is no longer
6086 # needed until the net-performance block far below, but the
6087 # multitask/sequence subprocess calls immediately after this point
6088 # each load their OWN full copy of that same window's dataset from
6089 # disk into a SEPARATE process's memory - while the parent is
6090 # BLOCKED waiting on subprocess.run(), the parent's already-resident
6091 # `dataset` and the child's freshly-loaded copy (plus the child's
6092 # own dense (rows, window, features) sequence-tensor allocation)
6093 # are concurrently resident on the SAME machine. On a 7.8GB/no-swap
6094 # Codespace this externally SIGTERM'd the sequence subprocess for
6095 # every window whose row count grew past ~130k (windows 2-5 of a
6096 # real 6-window run all failed here, rc=-15, mid tensor-build,
6097 # windows 0-1's smaller row counts succeeded). Freeing it here and
6098 # re-reading only if/when net-performance actually needs it removes
6099 # the parent's contribution to that peak, at the cost of one extra
6100 # CSV read per window (cheap relative to a subprocess retrain).
6101 dataset = None
6102 gc.collect()
6104 # V5.1 Phase 4, Step 4.2 - config-gated multi-model walk-forward.
6105 window_config_path = paths["version_dir"] / "config.json"
6106 window_config_path.write_text(json.dumps(window_config, indent=2), encoding="utf-8")
6108 multitask_metrics = (
6109 _run_walk_forward_trainer(
6110 "train_multitask.py", version_id, paths["full_dataset"], paths["feature_schema"],
6111 window_config_path, timeout_seconds=multitask_timeout_seconds, memory_profile=memory_profile, resume=resume_run_id is not None,
6112 )
6113 if train_multitask_enabled else None
6114 )
6115 sequence_metrics = (
6116 _run_walk_forward_trainer(
6117 "train_sequence.py", version_id, paths["full_dataset"], paths["feature_schema"],
6118 window_config_path, timeout_seconds=sequence_timeout_seconds, memory_profile=memory_profile, resume=resume_run_id is not None,
6119 )
6120 if train_sequence_enabled else None
6121 )
6123 window_metrics_artifacts: dict[str, dict] = {"training_metrics.json": training_metrics}
6124 if multitask_metrics is not None:
6125 window_metrics_artifacts["multitask_training_metrics.json"] = multitask_metrics
6126 if sequence_metrics is not None:
6127 window_metrics_artifacts["sequence_training_metrics.json"] = sequence_metrics
6129 window_tracked_values: dict[str, float] = {}
6130 for entry in tracked_metrics_config:
6131 value = extract_metric_by_path(window_metrics_artifacts.get(entry["artifact"]), entry["path"])
6132 if value is not None:
6133 tracked_values_by_metric.setdefault(entry["name"], []).append(value)
6134 window_tracked_values[entry["name"]] = value
6135 window_net_performance = None
6137 if net_performance_enabled:
6138 # Re-read from the CSV written earlier this iteration - see the
6139 # `del dataset` comment above for why the parent doesn't hold
6140 # this in memory continuously through the subprocess calls.
6141 dataset = _read_window_dataset(paths["full_dataset"], memory_profile)
6142 # V5.1 Phase 4 bugfix - must use THIS window's own
6143 # model_input_names (dataset_manifest["model_input_names"],
6144 # 66 columns including scaled/categorical/context features),
6145 # NOT the outer `feature_names` (= phase1.features.input_set,
6146 # the 49 raw pre-scaling names) - train_multitask.py/
6147 # train_sequence.py train against model_input_names via their
6148 # own feature_schema.json, so predicting with the raw input_set
6149 # list feeds the wrong column count into the exported model's
6150 # interpreter (crashed with a real in_channels mismatch,
6151 # 49 vs the trained weight's 66, the first time this ran).
6152 net_performance_feature_names = dataset_manifest["model_input_names"]
6153 net_result = None
6154 if sequence_metrics is not None:
6155 sequence_model_path = paths["version_dir"] / "sequence_model.json"
6156 sequence_schema_path = paths["version_dir"] / "sequence_feature_schema.json"
6157 if sequence_model_path.exists() and sequence_schema_path.exists():
6158 net_result = _run_walk_forward_net_performance(
6159 dataset, net_performance_feature_names,
6160 json.loads(sequence_model_path.read_text(encoding="utf-8")), "sequence",
6161 json.loads(sequence_schema_path.read_text(encoding="utf-8")), 30,
6162 net_performance_head,
6163 window_config.get("phase1", {}).get("target", {}).get("ranking", {}).get("net_performance", {}),
6164 sector_by_ticker,
6165 full_config=window_config,
6166 )
6167 if net_result is None and multitask_metrics is not None:
6168 multitask_model_path = paths["version_dir"] / "multitask_model.json"
6169 if multitask_model_path.exists():
6170 net_result = _run_walk_forward_net_performance(
6171 dataset, net_performance_feature_names,
6172 json.loads(multitask_model_path.read_text(encoding="utf-8")), "multitask",
6173 None, 30, net_performance_head,
6174 window_config.get("phase1", {}).get("target", {}).get("ranking", {}).get("net_performance", {}),
6175 sector_by_ticker,
6176 full_config=window_config,
6177 )
6178 if net_result is not None:
6179 window_net_performance = {"window_index": window_index, **net_result}
6180 net_performance_by_window.append(window_net_performance)
6182 window_result = {"window": window, "version_id": version_id, "backtest_mcc": backtest_mcc}
6183 window_results.append(window_result)
6184 atomic_write_json(
6185 ML_DIR / "versions" / run_id / f"window_{window_index}" / WALK_FORWARD_WINDOW_RESULT_FILENAME,
6186 {
6187 "window_result": window_result,
6188 "backtest_mcc": backtest_mcc,
6189 "tracked_values": window_tracked_values,
6190 "net_performance": window_net_performance,
6191 },
6192 )
6193 LOGGER.info("walk-forward window %s/%s backtest MCC: %.4f", window_index + 1, len(windows), backtest_mcc)
6195 summary = summarize_walk_forward_run(backtest_mcc_by_window)
6196 summary_by_metric = {name: summarize_walk_forward_run(values) for name, values in tracked_values_by_metric.items()}
6197 stability_by_metric = {
6198 name: summarize_metric_stability(
6199 values,
6200 min_windows=int(walk_forward_config.get("min_stable_windows", 3)),
6201 max_sign_flip_fraction=float(walk_forward_config.get("max_window_sign_flip_fraction", 0.34)),
6202 )
6203 for name, values in tracked_values_by_metric.items()
6204 }
6205 run_summary = {
6206 "run_id": run_id,
6207 "num_windows": len(windows),
6208 "window_results": window_results,
6209 "summary": summary,
6210 "summary_by_metric": summary_by_metric,
6211 "stability_by_metric": stability_by_metric,
6212 "net_performance_by_window": net_performance_by_window,
6213 }
6214 (ML_DIR / "versions" / run_id / "walk_forward_summary.json").parent.mkdir(parents=True, exist_ok=True)
6215 (ML_DIR / "versions" / run_id / "walk_forward_summary.json").write_text(
6216 json.dumps(run_summary, indent=2), encoding="utf-8"
6217 )
6218 return run_summary
6221def main() -> int:
6222 install_sigterm_witness(LOGGER)
6223 setup_logging()
6224 args = parse_args()
6225 if args.candidate and not args.version_id:
6226 raise SystemExit("--candidate requires --version-id")
6227 ensure_directories()
6228 config = load_project_config()
6229 LOGGER.info("Starting Aether Quant training pipeline.")
6230 raise_if_validation_failed(validate_training_inputs(config))
6231 ensure_derived_crypto_daily_series(config)
6232 data_summary = summarize_data_tree()
6233 inventory = build_phase_inventory(config, data_summary)
6234 write_inventory_file(inventory)
6236 if args.init_only:
6237 existing_context = load_existing_training_context()
6238 if existing_context is None and not MODEL_WEIGHTS_PATH.exists():
6239 write_model_export(config, data_summary)
6240 write_visualization_state(config, inventory, data_summary, training_context=existing_context)
6241 LOGGER.info("Inventory refreshed.")
6242 print("Phase 5 inventory refreshed.")
6243 return 0
6245 if args.walk_forward:
6246 walk_forward_config = config.get("phase_v2", {}).get("retraining", {}).get("walk_forward", {})
6247 step_days = args.step_days if args.step_days is not None else int(walk_forward_config.get("step_days", 90))
6248 mode = args.mode if args.mode is not None else str(walk_forward_config.get("mode", "expanding"))
6249 # V5.1 Phase 4 (item 4) - --include-multitask/--include-sequence/--metrics
6250 # override config.json's walk_forward block IN MEMORY ONLY for this
6251 # invocation (never written to disk), same one-run-override
6252 # precedent as --seed/--ranking-objective elsewhere in this project.
6253 if args.include_multitask or args.include_sequence or args.metrics is not None:
6254 config = copy.deepcopy(config)
6255 walk_forward_config = config["phase_v2"]["retraining"]["walk_forward"]
6256 if args.include_multitask:
6257 walk_forward_config["train_multitask"] = True
6258 if args.include_sequence:
6259 walk_forward_config["train_sequence"] = True
6260 if args.metrics is not None:
6261 requested_names = {name.strip() for name in args.metrics.split(",") if name.strip()}
6262 existing_tracked = walk_forward_config.get(
6263 "tracked_metrics",
6264 [{"name": "backtest_mcc", "artifact": "training_metrics.json", "path": "backtest.mcc"}],
6265 )
6266 walk_forward_config["tracked_metrics"] = [
6267 entry for entry in existing_tracked if entry.get("name") in requested_names
6268 ]
6269 run_summary = _run_walk_forward(
6270 config, data_summary, step_days=step_days, mode=mode, resume_run_id=args.resume_run_id, memory_profile=args.memory_profile,
6271 run_id_file=args.run_id_file,
6272 )
6273 if run_summary["num_windows"] == 0:
6274 print("Walk-forward run produced no windows - common_window too short for the configured spans.")
6275 return 0
6276 print(
6277 f"Walk-forward run {run_summary['run_id']}: {run_summary['num_windows']} windows trained into "
6278 f"ml/versions/{run_summary['run_id']}/window_*/.",
6279 f"Cross-window backtest MCC: mean={run_summary['summary']['cross_window_bootstrap']['mean_ic']:.4f}, "
6280 f"95% CI=[{run_summary['summary']['cross_window_bootstrap']['lower_bound']:.4f}, "
6281 f"{run_summary['summary']['cross_window_bootstrap']['upper_bound']:.4f}].",
6282 )
6283 LOGGER.info("Walk-forward run finished — active ml/ artifacts untouched.")
6284 return 0
6286 dataset, metadata = build_feature_dataset(config)
6287 log_resident_memory("after build_feature_dataset")
6288 feature_names = config["phase1"]["features"]["input_set"]
6289 asset_quality = build_asset_quality(config, dataset, metadata)
6290 dataset = apply_asset_quality_flags(dataset, asset_quality)
6291 log_resident_memory("after asset-quality flags")
6292 LOGGER.info(
6293 "Built dataset with %s rows across %s assets.",
6294 len(dataset),
6295 len(asset_quality),
6296 )
6297 LOGGER.info(
6298 "Training-eligible assets: %s",
6299 ", ".join(ticker for ticker, quality in asset_quality.items() if quality["training_eligible"]),
6300 )
6301 observation_only = [ticker for ticker, quality in asset_quality.items() if not quality["trading_eligible"]]
6302 if observation_only:
6303 LOGGER.info("Observation-only assets: %s", ", ".join(observation_only))
6305 feature_config = config["phase1"]["features"]
6306 winsorize_quantiles = tuple(feature_config.get("winsorize_quantiles", (0.001, 0.999)))
6307 clip_sigma = float(feature_config.get("scaled_feature_clip_sigma", 10.0))
6308 dataset, scaler, clip_sigma = fit_and_apply_scaler(
6309 dataset,
6310 feature_names,
6311 winsorize_quantiles=winsorize_quantiles,
6312 clip_sigma=clip_sigma,
6313 )
6314 log_resident_memory("after scaler")
6315 dataset, _ = add_asset_context_features(
6316 dataset,
6317 [asset["ticker"] for asset in config["phase1"]["universe"]["assets"]],
6318 )
6319 dataset, _ = add_asset_class_context_features(dataset, asset_class_by_ticker_from_config(config))
6320 log_resident_memory("after context features")
6321 dataset_manifest = build_dataset_manifest(config, dataset, inventory, metadata, asset_quality)
6323 if args.candidate:
6324 paths = candidate_output_paths(args.version_id)
6325 paths["version_dir"].mkdir(parents=True, exist_ok=True)
6327 write_scaler_artifacts(
6328 scaler,
6329 dataset_manifest,
6330 scaler_path=paths["scaler"],
6331 scaler_stats_path=paths["scaler_stats"],
6332 clip_sigma=clip_sigma,
6333 )
6334 paths["feature_schema"].write_text(
6335 json.dumps(
6336 {
6337 "project": dataset_manifest["project"],
6338 "phase": 2,
6339 "feature_names": dataset_manifest["feature_names"],
6340 "scaled_feature_names": dataset_manifest["scaled_feature_names"],
6341 "categorical_feature_names": dataset_manifest["categorical_feature_names"],
6342 "context_feature_names": dataset_manifest["context_feature_names"],
6343 "model_input_names": dataset_manifest["model_input_names"],
6344 "target_column": dataset_manifest["target_column"],
6345 "split_column": "split",
6346 "asset_quality": dataset_manifest["asset_quality"],
6347 "training_eligible_assets": dataset_manifest["training_eligible_assets"],
6348 "trading_eligible_assets": dataset_manifest["trading_eligible_assets"],
6349 "observation_only_assets": dataset_manifest["observation_only_assets"],
6350 },
6351 indent=2,
6352 ),
6353 encoding="utf-8",
6354 )
6355 paths["dataset_manifest"].write_text(json.dumps(dataset_manifest, indent=2), encoding="utf-8")
6356 if args.write_dataset:
6357 # V6.6.10: the stack's later trainers read this run's own dataset, built from today's universe, not the installed one
6358 dataset.to_csv(paths["full_dataset"], index=False)
6360 LOGGER.info("Training candidate model %s.", args.version_id)
6361 if args.memory_profile == "low":
6362 dataset = compact_dataset_for_training(dataset)
6363 training_result = train_model(
6364 config,
6365 dataset,
6366 checkpoint_path=paths["model_checkpoint"],
6367 metrics_path=paths["training_metrics"],
6368 strategy_report_path=paths["strategy_report"],
6369 equity_curves_path=paths["equity_curves"],
6370 )
6371 write_model_export(
6372 config,
6373 data_summary,
6374 dataset_manifest=dataset_manifest,
6375 training_result=training_result,
6376 weights_path=paths["model_weights"],
6377 dataset_manifest_path=paths["dataset_manifest"],
6378 scaler_path=paths["scaler"],
6379 scaler_stats_path=paths["scaler_stats"],
6380 checkpoint_path=paths["model_checkpoint"],
6381 metrics_path=paths["training_metrics"],
6382 strategy_report_path=paths["strategy_report"],
6383 )
6384 print(
6385 f"Candidate {args.version_id} trained into {paths['version_dir']}.",
6386 f"Backtest sharpe: {training_result['strategy_report']['backtest']['strategy']['sharpe']:.4f}.",
6387 f"Backtest max drawdown: {training_result['strategy_report']['backtest']['strategy']['max_drawdown']:.4f}.",
6388 )
6389 LOGGER.info("Candidate training finished — active ml/ artifacts untouched.")
6390 return 0
6392 write_dataset_artifacts(dataset, dataset_manifest, scaler, config=config, clip_sigma=clip_sigma)
6393 log_resident_memory("after dataset artifacts")
6395 if args.dataset_only:
6396 existing_context = load_existing_training_context()
6397 if existing_context is None:
6398 write_model_export(config, data_summary, dataset_manifest=dataset_manifest)
6399 write_visualization_state(
6400 config,
6401 inventory,
6402 data_summary,
6403 dataset_manifest=dataset_manifest,
6404 training_context=existing_context,
6405 )
6406 print(
6407 "Phase 5 dataset built without training.",
6408 f"Rows: {dataset_manifest['dataset_rows']}.",
6409 f"Splits: {dataset_manifest['split_counts']}.",
6410 )
6411 return 0
6413 if args.experts_only:
6414 LOGGER.info("Training expert models.")
6415 expert_training_result = train_expert_models(config, dataset, dataset_manifest)
6416 write_visualization_state(
6417 config,
6418 inventory,
6419 data_summary,
6420 dataset_manifest=dataset_manifest,
6421 training_context=load_existing_training_context(),
6422 )
6423 print(
6424 "Phase V2-8.5 stabilized expert models trained.",
6425 f"Trained: {', '.join(expert_training_result['trained_experts']) or 'none'}.",
6426 f"Skipped: {', '.join(expert_training_result['skipped_experts']) or 'none'}.",
6427 f"Gating eligible: {', '.join(expert_training_result['gating_eligible_experts']) or 'none'}.",
6428 f"Disabled for gating: {', '.join(expert_training_result['disabled_for_gating_experts']) or 'none'}.",
6429 )
6430 return 0
6432 dataset = compact_dataset_for_training(dataset)
6433 log_resident_memory("before baseline training")
6434 LOGGER.info("Training model.")
6435 training_result = train_model(config, dataset)
6436 log_resident_memory("after baseline training")
6437 LOGGER.info("Training expert models.")
6438 expert_training_result = train_expert_models(config, dataset, dataset_manifest)
6439 log_resident_memory("after expert training")
6440 write_model_export(
6441 config,
6442 data_summary,
6443 dataset_manifest=dataset_manifest,
6444 training_result=training_result,
6445 )
6446 write_visualization_state(
6447 config,
6448 inventory,
6449 data_summary,
6450 dataset_manifest=dataset_manifest,
6451 training_context=training_result,
6452 )
6454 print(
6455 "Phase 5 model and strategy validation complete.",
6456 f"Best epoch: {training_result['metrics']['best_epoch']}.",
6457 f"Validation accuracy: {training_result['metrics']['validation']['accuracy']:.4f}.",
6458 f"Backtest strategy return: {training_result['strategy_report']['backtest']['strategy']['total_return']:.4f}.",
6459 f"Expert models trained: {', '.join(expert_training_result['trained_experts']) or 'none'}.",
6460 f"Gating eligible experts: {', '.join(expert_training_result['gating_eligible_experts']) or 'none'}.",
6461 )
6462 LOGGER.info("Training pipeline finished.")
6463 return 0
6466if __name__ == "__main__":
6467 raise SystemExit(main())