Coverage for lab/explain.py: 100%
81 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"""What a lab model uses and how stable it is: permutation importance per feature and group (`aq lab explain`), the IC
2lost when a feature group is removed and the model retrained (`aq lab ablate`), and the spread of out-of-sample IC
3across seeds (`aq lab seeds`).
4"""
6from __future__ import annotations
8import json
9from collections.abc import Callable, Mapping, Sequence
10from pathlib import Path
11from typing import Any
13import numpy as np
14import pandas as pd
16from features import feature_registry
17from lab import lab_dataset, run_registry, trainer
18from lab.trainer import progress
21def run_predictor(run_dir: Path, frame: pd.DataFrame) -> Callable[[pd.DataFrame], np.ndarray]:
22 """A function scoring a dataset frame with the run's first seed's model of its last fold (what `explain` permutes)."""
23 record = run_registry.read_run(run_dir)
24 features = record["features"]
25 seed = record["seeds"][0]
26 if record["template"] == "linear":
27 path = sorted(run_dir.glob(f"linear_*_seed_{seed}.json"))[-1]
28 coefficients = np.asarray(json.loads(path.read_text(encoding="utf-8"))["coefficients"])
29 return lambda data: trainer.predict_linear(lab_dataset.rank_features(data, features), coefficients)
30 torch = trainer.require_torch()
31 module = trainer.load_model_module(run_dir.parent.parent / "models" / record["model"])
32 spec = json.loads((run_dir / "config.json").read_text(encoding="utf-8"))
33 head = trainer.head_of(record["target"])
34 hparams = {key: value for key, value in spec["model"].items() if key not in {"template", "name"}}
35 model = module.build(len(features), [head], **hparams)
36 model.load_state_dict(torch.load(sorted(run_dir.glob(f"model_*_seed_{seed}.pt"))[-1], weights_only=True))
37 window = int(spec["model"]["window"]) if record["template"] == "tcn" else None
39 def predict(data: pd.DataFrame) -> np.ndarray:
40 # the rows `data` holds (perhaps with a feature shuffled) inside the whole dataset, so a sequence window reaches back into
41 # the rows before them exactly as in training
42 full = frame.copy()
43 full.loc[data.index, features] = data[features].to_numpy()
44 ordered = full.sort_values(["ticker", "date"])
45 x = lab_dataset.rank_features(ordered, features)
46 windows = None
47 if window is not None:
48 from retraining.slicing import sequence_window_index
50 windows = sequence_window_index(ordered["ticker"].to_numpy(), window)
51 scores = trainer.predict_torch(model, x, np.arange(len(ordered)), windows, head)
52 return pd.Series(scores, index=ordered.index).reindex(data.index).to_numpy()
54 return predict
57def explain_run(run_dir: Path, *, dataset: pd.DataFrame | None = None, seed: int = 7) -> dict[str, Any]:
58 """Out-of-sample permutation importance (IC drop) per feature, summed per feature group, and each feature's own IC."""
59 from evaluation.feature_quality_audit import permutation_ic_drop
60 from lab.run_evaluation import daily_ic
62 record = run_registry.read_run(run_dir)
63 full = (dataset if dataset is not None else lab_dataset.load_dataset(Path(record["dataset"]))).reset_index(drop=True)
64 frame = full[full["split"].isin(["validation", "backtest"])]
65 features = record["features"]
66 drops = permutation_ic_drop(frame, features, run_predictor(run_dir, full), target=record["target"], min_names=3, seed=seed)
67 groups: dict[str, float] = {}
68 for group, names in feature_registry.groups_of(features).items():
69 values = [drops[name] for name in names if drops.get(name) is not None]
70 groups[group] = float(np.sum(values)) if values else None
71 own = {name: float(daily_ic(frame[name], frame[record["target"]], frame["date"]).mean()) for name in features}
72 return {"run": run_dir.name, "importance": dict(sorted(drops.items(), key=lambda item: -(item[1] or 0.0))), "groups": groups, "feature_ic": own}
75def ablate_run(lab_dir: Path, run_dir: Path, *, groups: Mapping[str, Sequence[str]] | None = None, train: Callable[..., dict] = trainer.train_run,
76 log: Callable[[str], None] = progress) -> dict[str, Any]:
77 """Retrain the run's model once per feature group with that group removed; the change in out-of-sample IC per group."""
78 record = run_registry.read_run(run_dir)
79 features = record["features"]
80 groups = dict(groups or feature_registry.groups_of(features))
81 base = (record.get("metrics") or {}).get("oof_ic_mean")
82 rows = {}
83 for group, names in groups.items():
84 kept = [name for name in features if name not in set(names)]
85 if not kept:
86 rows[group] = {"removed": list(names), "oof_ic": None, "change": None, "note": "nothing left to train on"}
87 continue
88 log(f"without {group} ({', '.join(names)})")
89 result = train(lab_dir, record["model"], overrides={"data": {"features": kept}}, seeds=record["seeds"], log=log)
90 ic = (result.get("metrics") or {}).get("oof_ic_mean")
91 rows[group] = {"removed": list(names), "run": result["id"], "oof_ic": ic, "change": None if ic is None or base is None else ic - base}
92 return {"run": run_dir.name, "base_oof_ic": base, "groups": rows}
95def seed_stability(lab_dir: Path, run_dir: Path, *, seeds: int, train: Callable[..., dict] = trainer.train_run, log: Callable[[str], None] = progress) -> dict[str, Any]:
96 """Retrain with `seeds` seeds; the IC mean, spread and range, flagged unstable when the spread is over half the mean."""
97 record = run_registry.read_run(run_dir)
98 result = train(lab_dir, record["model"], seeds=list(range(1, seeds + 1)), log=log)
99 per_seed = list(((result.get("metrics") or {}).get("per_seed_ic") or {}).values())
100 values = np.asarray([value for value in per_seed if value is not None], dtype=float)
101 mean = float(values.mean()) if len(values) else None
102 spread = float(values.std(ddof=1)) if len(values) > 1 else None
103 return {"run": result["id"], "seeds": seeds, "per_seed_ic": per_seed, "mean": mean, "std": spread,
104 "range": [float(values.min()), float(values.max())] if len(values) else None,
105 "unstable": bool(mean is not None and spread is not None and spread > abs(mean) / 2.0)}
108def render_mapping(title: str, values: Mapping[str, Any], digits: int = 4) -> str:
109 """A titled list of `name: value` lines in the mapping's order (floats signed, None as -)."""
110 lines = [title]
111 for key, value in values.items():
112 lines.append(f" {key}: {'-' if value is None else f'{value:+.{digits}f}' if isinstance(value, float) else value}")
113 return "\n".join(lines)