Coverage for scripts/model_candidate_research.py: 100%
132 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"""Rule R-MODEL9 / R-HEAD2 inputs (V6.1.0): rank IC of every retrained candidate, single seeds and seed ensembles.
3A candidate is a set of member version directories per model kind (`ml/versions/<id>` as `train_multitask.py` /
4`train_sequence.py` write them). Each member's heads are scored on the validation, backtest and holdout rows; an
5ensemble averages the members' raw head outputs (`evaluation.model_predictions.predict_heads_ensemble`, the rule live
6uses). The decision score is the live blend (`phase_v2.rank_signal.heads`, sequence before multitask per head), also with the
7priority swapped (`decision_rank_20d_swapped_priority`). IC is
8taken inside the main rank group (equity + crypto, the book's pool) against each head's own target: daily mean, HAC t,
9and the non-overlapping mean / t at the head's horizon. The holdout is reported, never used to select.
11 python scripts/model_candidate_research.py --dataset ml/datasets/v610_full_dataset.csv \\
12 --candidate ctl=multitask:ml/versions/v610_mt_ctl_s1,...;sequence:ml/versions/v610_seq_ctl_s1,... \\
13 [--each-member] [--out ml/evaluation/v610/model_ic.json]
15`--each-member` also scores every member alone (the seed spread R-MODEL9 clause 1 needs).
16`--bootstrap NAME` (V6.2.0, R-MODEL10) resamples that candidate's members with replacement (`--bootstrap-n` times, the
17same ensemble size per kind) and reports the spread of the resampled ensembles' validation decision IC: the noise of a
18seed ENSEMBLE, which is what an ensemble candidate has to beat (a single member's range overstates it).
19"""
21from __future__ import annotations
23import argparse
24import json
25import sys
26from pathlib import Path
28import numpy as np
29import pandas as pd
31ROOT_DIR = Path(__file__).resolve().parents[1]
32sys.path.insert(0, str(ROOT_DIR))
34HEADS = {
35 "rank_5d": ("target_rank_5d", 5), "rank_20d": ("target_rank_20d", 20),
36 "sector_neutral_rank_20d": ("target_sector_neutral_rank_20d", 20),
37 "residual_rank_5d": ("target_residual_rank_5d", 5), "residual_rank_20d": ("target_residual_rank_20d", 20),
38}
39SPLITS = ("validation", "backtest", "holdout")
40MODEL_FILES = {"multitask": ("multitask_model.json", "multitask_feature_schema.json"),
41 "sequence": ("sequence_model.json", "sequence_feature_schema.json")}
42CONTEXT_START = "2021-09-01" # the sequence windows of the first validation rows need earlier bars
45def parse_candidate(text: str) -> tuple[str, dict[str, list[str]]]:
46 """`name=multitask:dir1,dir2;sequence:dir3` -> (name, {"multitask": [...], "sequence": [...]})."""
47 name, _, rest = text.partition("=")
48 members: dict[str, list[str]] = {}
49 for part in filter(None, rest.split(";")):
50 kind, _, dirs = part.partition(":")
51 if kind not in MODEL_FILES or not dirs:
52 raise ValueError(f"bad --candidate part {part!r}")
53 members[kind] = [item for item in dirs.split(",") if item]
54 if not name or not members:
55 raise ValueError(f"bad --candidate {text!r}")
56 return name, members
59def ic_stats(frame: pd.DataFrame, prediction: np.ndarray, target: str, horizon: int) -> dict:
60 from evaluation.rank_ic_core import newey_west_t_stat, rank_ic_from_arrays
62 mask = ~np.isnan(prediction) & frame[target].notna().to_numpy()
63 if mask.sum() < 50:
64 return {"daily_mean_ic": None, "hac_t": None, "non_overlapping_mean_ic": None, "non_overlapping_t": None, "dates": 0}
65 values, targets, dates = prediction[mask], frame[target].to_numpy()[mask], frame["date"].to_numpy()[mask]
66 daily = rank_ic_from_arrays(values, targets, dates, min_names_per_date=10)
67 non_overlapping = rank_ic_from_arrays(values, targets, dates, non_overlapping_stride=horizon, min_names_per_date=10)
68 return {
69 "daily_mean_ic": daily["mean_ic"], "hac_t": newey_west_t_stat(daily["ic_values"], horizon - 1),
70 "non_overlapping_mean_ic": non_overlapping["mean_ic"], "non_overlapping_t": non_overlapping["t_stat"],
71 "dates": daily["num_dates"],
72 }
75def blend_decision_score(predictions: dict[str, dict[str, np.ndarray]], policy_heads: dict[str, float],
76 model_priority: list[str]) -> np.ndarray:
77 """Per row: each configured head from the first model in `model_priority` that has a finite value, weighted by the
78 configured blend (portfolio.rank_signal.select_raw_rank_score, vectorised)."""
79 length = len(next(iter(next(iter(predictions.values())).values())))
80 weighted, weights = np.zeros(length), np.zeros(length)
81 for head, weight in policy_heads.items():
82 if weight <= 0:
83 continue
84 value = np.full(length, np.nan)
85 for kind in model_priority:
86 if kind in predictions and head in predictions[kind]:
87 value = np.where(np.isnan(value), predictions[kind][head], value)
88 finite = ~np.isnan(value)
89 weighted[finite] += weight * value[finite]
90 weights[finite] += weight
91 with np.errstate(invalid="ignore", divide="ignore"):
92 return np.where(weights > 0, weighted / np.where(weights > 0, weights, 1.0), np.nan)
95def predict_kind(frame: pd.DataFrame, member_dirs: list[str], kind: str, window: int) -> dict[str, np.ndarray]:
96 from evaluation.model_predictions import predict_heads_ensemble
98 model_file, schema_file = MODEL_FILES[kind]
99 schema = json.loads((ROOT_DIR / member_dirs[0] / schema_file).read_text(encoding="utf-8"))
100 exports = [json.loads((ROOT_DIR / directory / model_file).read_text(encoding="utf-8")) for directory in member_dirs]
101 return predict_heads_ensemble(
102 frame, exports, schema["model_input_names"], list(HEADS), model_kind=kind,
103 sequence_feature_schema=schema if kind == "sequence" else None, configured_window_size=window, batched=True,
104 )
107def score(frame: pd.DataFrame, predictions: dict[str, dict[str, np.ndarray]], config: dict) -> dict:
108 rank_signal = config["phase_v2"]["rank_signal"]
109 decision = blend_decision_score(predictions, rank_signal["heads"], list(rank_signal["model_priority"]))
110 # The same heads with the other model served first: live's priority is sequence first, which hides every
111 # multitask-only change (a variant that differs only in the multitask model scores identically); R-HEAD2 may flip it.
112 swapped = blend_decision_score(predictions, rank_signal["heads"], list(reversed(rank_signal["model_priority"])))
113 out: dict = {}
114 for split in SPLITS:
115 rows = (frame["split"] == split).to_numpy() & frame["in_main_group"].to_numpy() & frame["training_eligible"].astype(bool).to_numpy()
116 part = frame.loc[rows]
117 entry = {
118 "decision_rank_20d": ic_stats(part, decision[rows], "target_rank_20d", 20),
119 "decision_rank_20d_swapped_priority": ic_stats(part, swapped[rows], "target_rank_20d", 20),
120 }
121 for kind, heads in predictions.items():
122 for head, (target, horizon) in HEADS.items():
123 if target in part.columns:
124 entry[f"{kind}.{head}"] = ic_stats(part, heads[head][rows], target, horizon)
125 out[split] = entry
126 return out
129def bootstrap_decision_ic(frame: pd.DataFrame, member_predictions: dict[str, list[dict[str, np.ndarray]]], config: dict,
130 *, runs: int = 200, seed: int = 7) -> dict:
131 """Validation decision IC (both priorities) of `runs` ensembles drawn with replacement from each kind's members, and
132 the R-MODEL10 yardstick per key: max(0.02, 2 x their standard deviation)."""
133 rank_signal = config["phase_v2"]["rank_signal"]
134 rows = (frame["split"] == "validation").to_numpy() & frame["in_main_group"].to_numpy() & frame["training_eligible"].astype(bool).to_numpy()
135 part = frame.loc[rows]
136 rng = np.random.default_rng(seed)
137 values: dict[str, list[float]] = {"decision_rank_20d": [], "decision_rank_20d_swapped_priority": []}
138 for _ in range(int(runs)):
139 drawn = {}
140 for kind, members in member_predictions.items():
141 picks = rng.integers(0, len(members), size=len(members))
142 drawn[kind] = {head: np.mean(np.stack([members[i][head] for i in picks]), axis=0) for head in members[0]}
143 for key, priority in (("decision_rank_20d", list(rank_signal["model_priority"])),
144 ("decision_rank_20d_swapped_priority", list(reversed(rank_signal["model_priority"])))):
145 decision = blend_decision_score(drawn, rank_signal["heads"], priority)
146 ic = ic_stats(part, decision[rows], "target_rank_20d", 20)["non_overlapping_mean_ic"]
147 if ic is not None:
148 values[key].append(float(ic))
149 out = {}
150 for key, series in values.items():
151 std = float(np.std(series, ddof=1)) if len(series) > 1 else 0.0
152 out[key] = {"runs": len(series), "mean": float(np.mean(series)) if series else None, "std": std,
153 "yardstick": max(0.02, 2.0 * std)}
154 return out
157def main() -> int:
158 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
159 parser.add_argument("--dataset", default=str(ROOT_DIR / "ml" / "datasets" / "full_dataset.csv"))
160 parser.add_argument("--candidate", action="append", required=True)
161 parser.add_argument("--each-member", action="store_true")
162 parser.add_argument("--bootstrap", default=None, help="V6.2.0: candidate whose members are resampled (R-MODEL10 noise)")
163 parser.add_argument("--bootstrap-n", type=int, default=200)
164 parser.add_argument("--out", default=str(ROOT_DIR / "ml" / "evaluation" / "v610" / "model_ic.json"))
165 args = parser.parse_args()
166 config = json.loads((ROOT_DIR / "config.json").read_text(encoding="utf-8"))
167 window = int(config.get("phase_v2", {}).get("sequence_model", {}).get("window_size", 30))
168 parts = [chunk[chunk["date"].astype(str) >= CONTEXT_START] for chunk in pd.read_csv(args.dataset, chunksize=40_000)]
169 frame = pd.concat(parts, ignore_index=True).sort_values(["ticker", "date"]).reset_index(drop=True)
170 classes = {a["ticker"]: a.get("asset_class") or a.get("security_type") for a in config["phase1"]["universe"]["assets"]}
171 separate = {kind for kinds in (config["phase1"]["target"]["ranking"].get("separate_rank_groups") or {}).values() for kind in kinds}
172 frame["in_main_group"] = ~frame["ticker"].map(classes).isin(separate)
173 report: dict = {"dataset": args.dataset, "candidates": {}}
174 for text in args.candidate:
175 name, members = parse_candidate(text)
176 predictions = {kind: predict_kind(frame, dirs, kind, window) for kind, dirs in members.items()}
177 report["candidates"][name] = {"members": members, "ensemble": score(frame, predictions, config)}
178 print(name, "validation decision IC:", json.dumps(report["candidates"][name]["ensemble"]["validation"]["decision_rank_20d"]), flush=True)
179 if args.each_member:
180 singles = {}
181 for kind, dirs in members.items():
182 for directory in dirs:
183 single = {kind: predict_kind(frame, [directory], kind, window)}
184 # a member is scored with the other kind's ensemble as the fallback, as live would serve it
185 for other in members:
186 if other != kind:
187 single[other] = predictions[other]
188 singles[directory] = score(frame, single, config)
189 report["candidates"][name]["members_scored"] = singles
190 if args.bootstrap == name:
191 per_member = {kind: [predict_kind(frame, [directory], kind, window) for directory in dirs] for kind, dirs in members.items()}
192 report["bootstrap"] = {"candidate": name, **bootstrap_decision_ic(frame, per_member, config, runs=args.bootstrap_n)}
193 print("bootstrap", json.dumps(report["bootstrap"]), flush=True)
194 Path(args.out).parent.mkdir(parents=True, exist_ok=True)
195 Path(args.out).write_text(json.dumps(report, indent=1, default=float), encoding="utf-8")
196 print(f"written {args.out}")
197 return 0
200if __name__ == "__main__":
201 raise SystemExit(main())