Coverage for lab/run_evaluation.py: 100%
173 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"""Judging lab runs by the project's own statistics: `aq lab eval`, `aq lab compare` and `aq lab card`.
3Every number is computed on the run's out-of-sample scores (`scores.csv`), never on rows a model was fitted on, and
4every Sharpe is shown next to the deflated-Sharpe hurdle at the lab's trial count N.
5"""
7from __future__ import annotations
9import itertools
10import json
11from collections.abc import Mapping, Sequence
12from pathlib import Path
13from typing import Any
15import numpy as np
16import pandas as pd
18from evaluation.rank_ic_core import newey_west_t_stat
19from evaluation.research_harness import block_bootstrap_mean_ci
20from lab import lab_dataset, run_registry
21from lab import report_html as rh
24def daily_ic(scores: pd.Series, target: pd.Series, dates: pd.Series, *, min_names: int = 3) -> pd.Series:
25 """Per-date Spearman correlation of score and target (dates with fewer than `min_names` names, or no spread, skipped)."""
26 frame = pd.DataFrame({"date": dates.to_numpy(), "s": scores.to_numpy(), "t": target.to_numpy()}).dropna()
27 out = {}
28 for date, group in frame.groupby("date"):
29 if len(group) < min_names or group["s"].nunique() < 2 or group["t"].nunique() < 2:
30 continue
31 out[date] = float(group["s"].rank().corr(group["t"].rank()))
32 return pd.Series(out, dtype=float).sort_index()
35def ic_stats(series: pd.Series, *, horizon: int) -> dict[str, Any]:
36 """Mean daily IC, its HAC t-statistic, a bootstrap interval and the number of days."""
37 values = series.dropna().to_numpy()
38 return {"mean": float(values.mean()) if len(values) else None, "days": int(len(values)),
39 "t_hac": newey_west_t_stat(values, max(horizon - 1, 0)) if len(values) > 1 else None,
40 "ci95": block_bootstrap_mean_ci(values, block=max(horizon, 1)) if len(values) > 1 else None}
43def half_life(decay: Mapping[int, float]) -> float | None:
44 """Sessions until the IC falls to half its shortest-horizon value (linear between horizons), None if it never does."""
45 points = sorted((int(horizon), value) for horizon, value in decay.items() if value is not None and np.isfinite(value))
46 if not points or points[0][1] <= 0:
47 return None
48 half = points[0][1] / 2.0
49 for (h0, v0), (h1, v1) in itertools.pairwise(points):
50 if v1 <= half:
51 return float(h0 + (v0 - half) / (v0 - v1) * (h1 - h0)) if v0 != v1 else float(h1)
52 return None
55def load_run_frame(run_dir: Path, dataset: pd.DataFrame | None = None) -> tuple[pd.DataFrame, str, dict]:
56 """The run's scores joined to its dataset rows, the score column, and the run record."""
57 record = run_registry.read_run(run_dir)
58 scores = pd.read_csv(run_dir / "scores.csv", dtype={"date": str, "ticker": str})
59 column = next(name for name in scores.columns if name.startswith("score_"))
60 if dataset is None:
61 dataset = lab_dataset.load_dataset(Path(record["dataset"]))
62 frame = scores.merge(dataset.drop(columns=["split"], errors="ignore"), on=["date", "ticker"], how="left")
63 return frame, column, record
66def spread_returns(frame: pd.DataFrame, column: str, *, quantile: float = 0.2, cost_bps: float = 0.0) -> pd.Series:
67 """Daily top-minus-bottom quintile return on target_return_1d, less `cost_bps` on the day's turnover of the two legs."""
68 out, previous = {}, None
69 for date, group in frame.dropna(subset=[column, "target_return_1d"]).groupby("date"):
70 if len(group) < 4:
71 continue
72 ranked = group[column].rank(pct=True)
73 long, short = set(group.loc[ranked > 1 - quantile, "ticker"]), set(group.loc[ranked <= quantile, "ticker"])
74 gross = group.loc[group["ticker"].isin(long), "target_return_1d"].mean() - group.loc[group["ticker"].isin(short), "target_return_1d"].mean()
75 if previous is None:
76 turnover = 1.0
77 else:
78 turnover = (len(long ^ previous[0]) / max(len(long), 1) + len(short ^ previous[1]) / max(len(short), 1)) / 2.0
79 out[date] = gross - turnover * 2.0 * cost_bps / 1e4
80 previous = (long, short)
81 return pd.Series(out, dtype=float).sort_index()
84def sharpe_block(returns: pd.Series, *, trials_n: int, trial_variance: float | None) -> dict[str, Any]:
85 """Sharpe, PSR, DSR at N (with a variance floor) and the minimum track record, annualised by the calendar."""
86 from evaluation.alpha_proof import deflated_sharpe_from_inputs
87 from evaluation.backtest_statistics import expected_max_sharpe, probabilistic_sharpe_ratio
88 from evaluation.overfitting import minimum_track_record_length
90 values = returns.dropna()
91 if len(values) < 3 or float(values.std(ddof=1)) == 0.0:
92 return {"days": int(len(values)), "sharpe": None}
93 weekends = pd.to_datetime(pd.Index(values.index)).day_of_week.max() >= 5
94 periods = 365.0 if weekends else 252.0
95 sharpe = float(values.mean() / values.std(ddof=1) * np.sqrt(periods))
96 variance = trial_variance if trial_variance is not None and trial_variance > 0 else 0.25
97 psr = probabilistic_sharpe_ratio(values.to_numpy())
98 block = {"days": int(len(values)), "sharpe": sharpe, "annual_return": float(values.mean() * periods), "psr": None if psr is None else float(psr),
99 "trials_n": int(trials_n), "hurdle_sharpe": expected_max_sharpe(max(trials_n, 1), variance) or 0.0}
100 block["dsr"] = deflated_sharpe_from_inputs(values.to_numpy(), num_trials=max(trials_n, 1), trial_variance=variance, annualization=periods).get("value")
101 block["min_track_record_days"] = float(minimum_track_record_length(values.to_numpy(), periods_per_year=int(periods)))
102 return block
105def trial_variance(ledger: Path) -> float | None:
106 """The variance of the lab's trial Sharpe ratios (the deflated Sharpe's input), or None below two trials."""
107 from evaluation.trial_ledger import read_ledger
109 if not ledger.exists():
110 return None
111 sharpes = [entry["annualised_sharpe"] for entry in read_ledger(ledger) if entry.get("role") == "candidate" and entry.get("annualised_sharpe") is not None]
112 return float(np.var(sharpes, ddof=1)) if len(sharpes) > 1 else None
115def evaluate_run(run_dir: Path, *, lab_dir: Path, book: bool = False, cost_bps: float = 10.0, horizons: Sequence[int] = (1, 5, 20),
116 dataset: pd.DataFrame | None = None) -> dict[str, Any]:
117 """IC (overall, by split, by year), its decay and half-life, quintile spreads, the train-to-OOS gap and, with `book`,
118 a cost-aware quintile book judged at the lab's N."""
119 frame, column, record = load_run_frame(run_dir, dataset)
120 target = record.get("target", "target_rank_20d")
121 horizon = int("".join(ch for ch in target.split("_")[-1] if ch.isdigit()) or 20)
122 report: dict[str, Any] = {"run": run_dir.name, "model": record.get("model"), "template": record.get("template"), "target": target}
123 ic = daily_ic(frame[column], frame[target], frame["date"])
124 report["ic"] = ic_stats(ic, horizon=horizon)
125 report["ic_by_split"] = {split: ic_stats(daily_ic(part[column], part[target], part["date"]), horizon=horizon) for split, part in frame.groupby("split")}
126 report["ic_by_year"] = {year: float(values.mean()) for year, values in ic.groupby(pd.Index(ic.index).str[:4])}
127 decay = {}
128 for h in horizons:
129 column_h = f"target_return_{h}d"
130 if column_h in frame.columns:
131 decay[int(h)] = float(daily_ic(frame[column], frame[column_h], frame["date"]).mean())
132 report["decay"] = decay
133 report["half_life_sessions"] = half_life(decay)
134 quintiles = {}
135 for _, group in frame.dropna(subset=[column, "target_return_1d"]).groupby("date"):
136 if len(group) >= 5:
137 buckets = pd.qcut(group[column].rank(method="first"), 5, labels=False) + 1
138 for bucket, value in group.groupby(buckets)["target_return_1d"].mean().items():
139 quintiles.setdefault(int(bucket), []).append(float(value))
140 report["quintile_mean_return_1d"] = {bucket: float(np.mean(values)) for bucket, values in sorted(quintiles.items())}
141 folds = (record.get("metrics") or {}).get("folds") or []
142 validation = [row["best_validation_ic"] for row in folds if row.get("best_validation_ic") is not None]
143 report["overfit_gap"] = {"best_validation_ic": float(np.mean(validation)) if validation else None, "oos_ic": report["ic"]["mean"],
144 "gap": (float(np.mean(validation)) - report["ic"]["mean"]) if validation and report["ic"]["mean"] is not None else None}
145 from lab.trainer import ledger_count
147 trials_n = max(ledger_count(lab_dir), int(record.get("trials_n") or 1)) # N as it stands now: every later trial counts against this run too
148 variance = trial_variance(lab_dir / "trials.jsonl")
149 report["book"] = sharpe_block(spread_returns(frame, column, cost_bps=cost_bps), trials_n=trials_n, trial_variance=variance) if book else None
150 report["trials_n"] = trials_n
151 return report
154def render_eval(report: Mapping[str, Any]) -> str:
155 """`aq lab eval`'s text report."""
156 ic = report["ic"]
157 lines = [f"{report['run']} ({report['model']}, {report['template']}) on {report['target']}",
158 f"out-of-sample IC {rh.fmt(ic['mean'], 4)} over {ic['days']} days, HAC t {rh.fmt(ic['t_hac'], 2)}, 95% CI {ic['ci95'] and [round(v, 4) for v in ic['ci95']]}"]
159 lines += [f" {split}: IC {rh.fmt(stats['mean'], 4)} ({stats['days']} days, t {rh.fmt(stats['t_hac'], 2)})" for split, stats in report["ic_by_split"].items()]
160 lines.append("by year: " + ", ".join(f"{year} {value:+.4f}" for year, value in report["ic_by_year"].items()))
161 lines.append("decay: " + ", ".join(f"{h}d {value:+.4f}" for h, value in report["decay"].items()) + f"; half-life {rh.fmt(report['half_life_sessions'], 1)} sessions")
162 lines.append("quintiles (1d return): " + ", ".join(f"Q{bucket} {value:+.5f}" for bucket, value in report["quintile_mean_return_1d"].items()))
163 gap = report["overfit_gap"]
164 lines.append(f"best validation IC {rh.fmt(gap['best_validation_ic'], 4)} vs out-of-sample {rh.fmt(gap['oos_ic'], 4)} (gap {rh.fmt(gap['gap'], 4)})")
165 if report.get("book"):
166 book = report["book"]
167 lines.append(f"quintile book after costs: Sharpe {rh.fmt(book.get('sharpe'), 2)}, PSR {rh.fmt(book.get('psr'), 3)}, DSR at N={book.get('trials_n')} "
168 f"{rh.fmt(book.get('dsr'), 3)} (a winner of N trials must beat Sharpe {rh.fmt(book.get('hurdle_sharpe'), 2)})")
169 return "\n".join(lines)
172def render_eval_html(report: Mapping[str, Any]) -> str:
173 """`aq lab eval --html`: the report as one self-contained page."""
174 rows = [[split, stats["mean"], stats["days"], stats["t_hac"]] for split, stats in report["ic_by_split"].items()]
175 sections = [("Out-of-sample IC", rh.table([["all", report["ic"]["mean"], report["ic"]["days"], report["ic"]["t_hac"]], *rows], ["split", "mean IC", "days", "HAC t"])),
176 ("IC by year", rh.svg_bars(report["ic_by_year"], label="IC by year")),
177 ("Decay", rh.table([[f"{h} sessions", value] for h, value in report["decay"].items()], ["horizon", "IC"])),
178 ("Quintiles", rh.svg_bars({f"Q{bucket}": value for bucket, value in report["quintile_mean_return_1d"].items()}, label="Quintile returns"))]
179 if report.get("book"):
180 book = report["book"]
181 sections.append(("Quintile book after costs", rh.table([[key, value] for key, value in book.items()], ["statistic", "value"])))
182 return rh.page(f"Lab run {report['run']}", sections, subtitle=f"{report['model']} ({report['template']}) on {report['target']}, out-of-sample rows only",
183 footer=f"N = {report['trials_n']} trials in this lab: judge any Sharpe against the hurdle, not against zero.")
186def baseline_scores(frame: pd.DataFrame, name: str) -> pd.Series:
187 """A simple baseline on the same rows: `momentum_20` (20-session return) or `reversal_5`, from the dataset's columns."""
188 if name in frame.columns:
189 return frame[name]
190 mapping = {"momentum_20": "ret_20", "momentum_60": "ret_60", "reversal_5": "rev_5"}
191 if mapping.get(name) in frame.columns:
192 return frame[mapping[name]]
193 raise KeyError(f"no baseline {name!r}: use a feature column of the dataset or one of {', '.join(mapping)}")
196def compare_runs(run_dirs: Sequence[Path], *, baseline: str | None = None) -> dict[str, Any]:
197 """A leaderboard by mean out-of-sample IC on the rows every run scored, with each run's IC difference to the best one
198 tested by a HAC t and a block-bootstrap CI."""
199 frames = [load_run_frame(path) for path in run_dirs]
200 target = frames[0][2].get("target", "target_rank_20d")
201 common = None
202 for frame, _, _ in frames:
203 keys = set(zip(frame["date"], frame["ticker"], strict=False))
204 common = keys if common is None else common & keys
205 series: dict[str, pd.Series] = {}
206 for (frame, column, _), path in zip(frames, run_dirs, strict=False):
207 mask = [key in common for key in zip(frame["date"], frame["ticker"], strict=False)]
208 part = frame[mask]
209 series[path.name] = daily_ic(part[column], part[target], part["date"])
210 if baseline and baseline not in series:
211 series[baseline] = daily_ic(baseline_scores(part, baseline), part[target], part["date"])
212 table = sorted(({"run": name, "ic": float(values.mean()), "days": int(len(values))} for name, values in series.items()), key=lambda row: -row["ic"])
213 best = table[0]["run"]
214 horizon = int("".join(ch for ch in target.split("_")[-1] if ch.isdigit()) or 20)
215 for row in table:
216 if row["run"] == best:
217 row.update(diff=0.0, t_hac=None, ci95=None)
218 continue
219 joined = pd.concat([series[row["run"]], series[best]], axis=1, join="inner").dropna()
220 difference = (joined.iloc[:, 0] - joined.iloc[:, 1]).to_numpy()
221 row.update(diff=float(difference.mean()) if len(difference) else None, t_hac=newey_west_t_stat(difference, max(horizon - 1, 0)) if len(difference) > 1 else None,
222 ci95=block_bootstrap_mean_ci(difference, block=horizon) if len(difference) > 1 else None)
223 return {"target": target, "rows": len(common or []), "leaderboard": table}
226def render_compare(report: Mapping[str, Any]) -> str:
227 """`aq lab compare`'s text: the leaderboard, each run against the best."""
228 lines = [f"{report['rows']} common rows, target {report['target']}"]
229 for row in report["leaderboard"]:
230 test = "" if row["t_hac"] is None else f" vs best {row['diff']:+.4f} (HAC t {row['t_hac']:.2f}, CI {[round(v, 4) for v in row['ci95']] if row['ci95'] else '-'})"
231 lines.append(f"{row['ic']:+.4f} {row['run']} ({row['days']} days){test}")
232 return "\n".join(lines)
235def model_card(run_dir: Path, report: Mapping[str, Any] | None = None) -> str:
236 """A Markdown model card from the run's own numbers."""
237 record = run_registry.read_run(run_dir)
238 report = report or evaluate_run(run_dir, lab_dir=run_dir.parent.parent, book=True)
239 metrics = record.get("metrics") or {}
240 book = report.get("book") or {}
241 ic = report["ic"]
242 return "\n".join([
243 f"# Model card: {record.get('model')} ({run_dir.name})", "",
244 f"- **Template:** {record.get('template')}; loss {record.get('loss')}; folds {record.get('folds')}; seeds {record.get('seeds')}",
245 f"- **Data:** {record.get('dataset')} ({record.get('rows')} rows); target `{record.get('target')}`",
246 f"- **Features ({len(record.get('features', []))}):** {', '.join(record.get('features', []))}",
247 f"- **Out-of-sample IC:** {rh.fmt(ic['mean'], 4)} over {ic['days']} days (HAC t {rh.fmt(ic['t_hac'], 2)}, 95% CI {ic['ci95'] and [round(v, 4) for v in ic['ci95']]})",
248 f"- **Seed stability:** IC spread across seeds {rh.fmt(metrics.get('oof_ic_seed_std'), 4)} (per seed: {metrics.get('per_seed_ic')})",
249 f"- **Half-life:** {rh.fmt(report.get('half_life_sessions'), 1)} sessions; decay {report.get('decay')}",
250 f"- **Quintile book after costs:** Sharpe {rh.fmt(book.get('sharpe'), 2)}, PSR {rh.fmt(book.get('psr'), 3)}, DSR {rh.fmt(book.get('dsr'), 3)} at N = {report.get('trials_n')}"
251 f" (hurdle {rh.fmt(book.get('hurdle_sharpe'), 2)})",
252 "- **Intended use:** research. A lab result is a candidate, not a verified edge: it needs a pre-registered round and an unread holdout.",
253 f"- **Limits:** {len(report.get('ic_by_year', {}))} years of out-of-sample dates; the IC by year is {report.get('ic_by_year')}.",
254 f"- **Pins:** {json.dumps(record.get('pins', {}))}",
255 ]) + "\n"