Coverage for evaluation/audit_runners.py: 100%
99 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"""Orchestration for the V5.8.0 `aq evaluate` audit flags (--ic-by-class, --audit-gates, --audit-data, --audit-heads,
2--audit-features). The analysis lives in the pure modules (class_ic_audit, gate_audit, data_audit, head_audit,
3feature_quality_audit); this module only loads the inputs the way the live path sees them and returns JSON-ready dicts.
4Heavy imports stay inside the functions so `aq` starts fast.
5"""
7from __future__ import annotations
9import json
10import sys
11from pathlib import Path
13ROOT_DIR = Path(__file__).resolve().parents[1]
14ML_DIR = ROOT_DIR / "ml"
17def _harness(split: str, dataset_path: str | None):
18 scripts_dir = str(ROOT_DIR / "scripts")
19 if scripts_dir not in sys.path:
20 sys.path.insert(0, scripts_dir)
21 from as_live_levers import AsLiveHarness
23 return AsLiveHarness(split, dataset_path=dataset_path)
26def run_ic_by_class(config: dict, *, split: str, dataset_path: str | None = None) -> dict:
27 """Within/between-class decomposition of the LIVE blended score against the realized 5- and 20-day returns."""
28 from evaluation.class_ic_audit import class_ic_decomposition
30 harness = _harness(split, dataset_path)
31 frame = harness.frame.copy()
32 frame["asset_class"] = frame["ticker"].map(harness.asset_class_by_ticker)
33 report = {"split": split, "rows": int(len(frame)), "heads": {}}
34 for target, horizon in (("target_return_20d", 20), ("target_return_5d", 5)):
35 if target not in frame.columns:
36 continue
37 report["heads"][target] = class_ic_decomposition(
38 frame, prediction="live_rank_score", target=target, horizon=horizon, min_names_per_class=5
39 )
40 return report
43def run_audit_gates(config: dict, *, split: str, dataset_path: str | None = None) -> dict:
44 """The rolling-IC gate's own reading next to the fully resolved IC on every date of the split."""
45 from evaluation.gate_audit import audit_rolling_ic_gate, daily_rank_ic
46 from evaluation.live_parity import main_group_tickers
48 harness = _harness(split, dataset_path)
49 frame = harness.lagged_frame
50 gate_fn = harness.gate_for(frame)
51 state_fn = next(iter(harness._states.values()))
52 ic_config = harness.ic_config
53 horizon = int(ic_config.get("horizon_days", 20))
54 window = int(ic_config.get("rolling_window_days", 40))
55 main_tickers = main_group_tickers(harness.rank_groups, frame["ticker"].unique())
56 scored = frame if main_tickers is None else frame[frame["ticker"].astype(str).isin(main_tickers)]
57 target = f"target_return_{horizon}d" if f"target_return_{horizon}d" in scored.columns else "target_rank_20d"
58 daily = daily_rank_ic(scored, score_column="live_rank_score", target_column=target,
59 min_names_per_date=int(ic_config.get("min_names_per_date", 10)))
60 equity_dates = sorted(
61 frame.loc[frame["ticker"].map(harness.asset_class_by_ticker).isin({"equity", "bond"}), "date"].astype(str).unique()
62 )
63 report = audit_rolling_ic_gate(
64 decision_dates=equity_dates, gate_fn=gate_fn, state_fn=state_fn, daily_ic=daily, trading_dates=equity_dates,
65 horizon=horizon, window=window,
66 )
67 report.update({"split": split, "gate_config": ic_config, "target": target,
68 "grouped_main_pool_only": main_tickers is not None})
69 return report
72def run_audit_data(config: dict, *, data_root: Path, start: str | None = None, end: str | None = None,
73 write_manifest: bool = True) -> dict:
74 from data_pipeline.data_audit import audit_non_daily_files, audit_universe, build_data_manifest
76 report = audit_universe(config, data_root, start=start, end=end)
77 report["non_daily_files"] = audit_non_daily_files(config, data_root)
78 if write_manifest:
79 manifest = build_data_manifest(data_root)
80 manifest_path = Path(data_root) / "manifest_v580.json"
81 with manifest_path.open("w", encoding="utf-8", newline="\n") as handle: # LF everywhere: same bytes on Windows and Linux
82 handle.write(json.dumps(manifest, indent=1, sort_keys=True))
83 report["manifest"] = {"path": str(manifest_path), "num_files": len(manifest)}
84 return report
87def live_consumers(config: dict) -> set[str]:
88 """Components the live decision path reads, from the config: the blended rank heads of every model in
89 `rank_signal.model_priority`, the gating network when enabled, the experts (MoE path), RL when enabled."""
90 phase_v2 = config.get("phase_v2", {})
91 rank_signal = phase_v2.get("rank_signal", {})
92 consumers = {
93 f"{model}.{head}"
94 for model in rank_signal.get("model_priority", ["sequence", "multitask"])
95 for head, weight in (rank_signal.get("heads") or {"rank_20d": 1.0}).items()
96 if float(weight) > 0.0 and head not in set(rank_signal.get("demoted", []))
97 }
98 if phase_v2.get("gating_network", {}).get("learned_model_enabled", False):
99 consumers.add("gating")
100 consumers.update({f"expert.{name}" for name in ("bullish", "bearish", "sideways", "volatility")})
101 consumers.update({"multitask.direction", "sequence.direction", "baseline.direction"})
102 if phase_v2.get("dynamic_risk", {}).get("rl_sizing_enabled", False):
103 consumers.add("rl_sizing")
104 if phase_v2.get("forex_sleeve", {}).get("rl_sizing_enabled", False):
105 consumers.add("rl_sizing_forex")
106 return consumers
109def run_audit_heads(config: dict, *, ml_dir: Path = ML_DIR) -> dict:
110 from evaluation.head_audit import audit_heads, load_head_metrics
111 from portfolio.rank_signal import resolve_rank_signal_policy
113 report = audit_heads(load_head_metrics(ml_dir), consumers=live_consumers(config))
114 report["consumers"] = sorted(live_consumers(config))
115 metrics_by_model = {}
116 for model_name in ("sequence", "multitask"):
117 path = ml_dir / f"{model_name}_training_metrics.json"
118 try:
119 metrics_by_model[model_name] = json.loads(path.read_text(encoding="utf-8")) if path.exists() else None
120 except (OSError, ValueError):
121 metrics_by_model[model_name] = None
122 # The policy main.py resolves at Initialize(): shows when every decision head failed and live fell back to the blend.
123 report["rank_signal_policy"] = resolve_rank_signal_policy(metrics_by_model, config)
124 return report
127def run_audit_features(config: dict, *, dataset_path: str | None = None, permutation: bool = False) -> dict:
128 """Feature quality over every split of the dataset (column-pruned read), optionally with the multitask model's
129 permutation IC drop on the validation split."""
130 import numpy as np
131 import pandas as pd
133 from evaluation.feature_quality_audit import feature_quality, permutation_ic_drop
135 schema = json.loads((ML_DIR / "multitask_feature_schema.json").read_text(encoding="utf-8"))
136 features = list(schema["model_input_names"])
137 path = Path(dataset_path) if dataset_path else ML_DIR / "datasets" / "full_dataset.csv"
138 wanted = set(features) | {"date", "ticker", "split", "target_rank_20d", "training_eligible"}
139 frame = pd.concat(
140 list(pd.read_csv(path, usecols=lambda name: name in wanted, chunksize=50_000)), ignore_index=True
141 )
142 asset_class = {a["ticker"]: a.get("asset_class") or a.get("security_type") for a in config["phase1"]["universe"]["assets"]}
143 frame["asset_class"] = frame["ticker"].map(asset_class)
144 report = feature_quality(frame, features)
145 if permutation:
146 from evaluation.model_predictions import predict_multitask_head
148 model = json.loads((ML_DIR / "multitask_model.json").read_text(encoding="utf-8"))
149 validation = frame[frame["split"] == "validation"].reset_index(drop=True)
151 def predict(data):
152 return np.asarray(predict_multitask_head(data, model, features, "rank_20d"))
154 report["permutation_ic_drop"] = permutation_ic_drop(validation, features, predict)
155 return report