Coverage for evaluation/overfit_diagnostics.py: 100%
46 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"""Overfitting diagnostics (V6.4.3): how much of a model's in-sample rank IC survives out of sample, and how the
2out-of-sample IC moves with the length of the training window. Pure; reads only the JSON files it is given."""
4from __future__ import annotations
6import json
7from collections.abc import Callable
8from pathlib import Path
9from typing import TYPE_CHECKING, Any
11import pandas as pd
13if TYPE_CHECKING:
14 from collections.abc import Sequence
16RANK_HEADS = ("rank_5d", "rank_20d", "sector_neutral_rank_20d", "residual_rank_5d", "residual_rank_20d")
19def head_ic(metrics: dict[str, Any], split: str, head: str) -> float | None:
20 """`<split>.<head>_ic_non_overlapping.mean_ic` of a training-metrics file (the daily `<head>_ic` as a fallback)."""
21 node = metrics.get(split) or {}
22 for key in (f"{head}_ic_non_overlapping", f"{head}_ic"):
23 value = (node.get(key) or {}).get("mean_ic")
24 if isinstance(value, (int, float)):
25 return float(value)
26 return None
29def training_gap_report(metrics_paths: dict[str, Path], heads: Sequence[str]=RANK_HEADS, splits: Sequence[str]=("train", "validation", "backtest")) -> dict[str, Any]:
30 """{model: {head: {split: ic, "train_minus_validation": gap, "retained": validation / train}}} from
31 ml/<model>_training_metrics.json files."""
32 report: dict = {}
33 for model, path in metrics_paths.items():
34 try:
35 metrics = json.loads(Path(path).read_text(encoding="utf-8"))
36 except (OSError, ValueError):
37 report[model] = {"error": f"unreadable {path}"}
38 continue
39 entry: dict = {}
40 for head in heads:
41 values: dict = {split: head_ic(metrics, split, head) for split in splits}
42 if all(value is None for value in values.values()):
43 continue
44 train, validation = values.get("train"), values.get("validation")
45 if train is not None and validation is not None:
46 values["train_minus_validation"] = train - validation
47 values["retained"] = validation / train if train else None
48 entry[head] = values
49 report[model] = entry
50 return report
53def learning_curve(fit_and_score: Callable[[pd.DataFrame, pd.DataFrame], float], frame: pd.DataFrame, *, train_years: Sequence[int]=(1, 2, 4, 7),
54 train_end: str = "2021-12-31", eval_split: str = "validation", date_column: str = "date",
55 split_column: str = "split") -> list[dict]:
56 """Out-of-sample score for training windows of `train_years` years ending at `train_end`; `fit_and_score(train,
57 evaluation)` fits on the first frame and returns a score (e.g. mean rank IC) on the second."""
58 dates = pd.to_datetime(frame[date_column])
59 evaluation = frame[frame[split_column] == eval_split]
60 end = pd.Timestamp(train_end)
61 curve = []
62 for years in train_years:
63 start = end - pd.DateOffset(years=int(years))
64 train = frame[(frame[split_column] == "train") & (dates > start) & (dates <= end)]
65 if train.empty:
66 continue
67 curve.append({"train_years": int(years), "train_rows": int(len(train)), "score": float(fit_and_score(train, evaluation))})
68 return curve