Coverage for evaluation/signal_tools.py: 100%
71 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"""From prices to the inputs `evaluation.research_harness.evaluate_signal` reads, plus two quick looks at any signal
2(V6.6.5, #345): returns by score quantile and the information coefficient by horizon.
4A score dated D may use what was known at D's close; its targets are the returns from D's close to D+h's close.
5"""
7from __future__ import annotations
9from collections.abc import Sequence
11import numpy as np
12import pandas as pd
14__all__ = ["forward_returns", "forward_rank_targets", "quantile_returns", "ic_decay", "validate_signal_frame"]
17def forward_returns(prices: pd.DataFrame, horizon: int) -> pd.DataFrame:
18 """`price[t + h] / price[t] - 1` (dates x tickers), NaN where either price is missing or non-positive."""
19 clean = prices.astype(float).where(lambda frame: frame > 0.0)
20 return clean.shift(-int(horizon)) / clean - 1.0
23def forward_rank_targets(prices: pd.DataFrame, horizons: Sequence[int] = (5, 20), *, split: str = "validation") -> pd.DataFrame:
24 """Long format with `date, ticker, split, target_return_1d` and, per horizon, `target_return_{h}d` and
25 `target_rank_{h}d` (the cross-sectional percentile of the forward return on that date). Rows without a 1-day target drop."""
26 pieces = {"target_return_1d": forward_returns(prices, 1)}
27 for horizon in horizons:
28 future = forward_returns(prices, int(horizon))
29 pieces[f"target_return_{int(horizon)}d"] = future
30 pieces[f"target_rank_{int(horizon)}d"] = future.rank(axis=1, pct=True)
31 parts = [
32 frame.rename_axis(index="date", columns="ticker").reset_index().melt(id_vars="date", var_name="ticker", value_name=name)
33 for name, frame in pieces.items()
34 ]
35 long = parts[0]
36 for part in parts[1:]:
37 long = long.merge(part, on=["date", "ticker"], how="outer")
38 long["date"] = long["date"].astype(str)
39 long["ticker"] = long["ticker"].astype(str)
40 long.insert(2, "split", split)
41 return long.dropna(subset=["target_return_1d"]).sort_values(["date", "ticker"]).reset_index(drop=True)
44def quantile_returns(scores: pd.DataFrame, forward_returns_frame: pd.DataFrame, *, n_quantiles: int = 5) -> pd.DataFrame:
45 """Per date, the mean forward return of each score quantile (columns 1..n, 1 = lowest scores). Dates with fewer names
46 than quantiles are skipped."""
47 rows: dict[str, dict[int, float]] = {}
48 aligned = forward_returns_frame.reindex(index=scores.index, columns=scores.columns)
49 for day in scores.index:
50 pair = pd.DataFrame({"s": scores.loc[day], "r": aligned.loc[day]}).replace([np.inf, -np.inf], np.nan).dropna()
51 if len(pair) < int(n_quantiles):
52 continue
53 buckets = pd.qcut(pair["s"].rank(method="first"), int(n_quantiles), labels=False) + 1
54 rows[str(day)] = pair.groupby(buckets)["r"].mean().to_dict()
55 return pd.DataFrame.from_dict(rows, orient="index").reindex(columns=range(1, int(n_quantiles) + 1))
58def ic_decay(scores: pd.DataFrame, prices: pd.DataFrame, horizons: Sequence[int] = (1, 5, 10, 20, 60), *, min_names: int = 3) -> pd.Series:
59 """Mean daily Spearman correlation between the scores and each horizon's forward return; NaN when no date has
60 `min_names` names with both."""
61 out: dict[int, float] = {}
62 for horizon in horizons:
63 future = forward_returns(prices, int(horizon)).reindex(index=scores.index, columns=scores.columns)
64 values = []
65 for day in scores.index:
66 pair = pd.DataFrame({"s": scores.loc[day], "r": future.loc[day]}).replace([np.inf, -np.inf], np.nan).dropna()
67 if len(pair) < int(min_names) or pair["s"].nunique() < 2 or pair["r"].nunique() < 2:
68 continue
69 values.append(float(pair["s"].rank().corr(pair["r"].rank())))
70 out[int(horizon)] = float(np.mean(values)) if values else float("nan")
71 return pd.Series(out, name="mean_ic", dtype=float)
74def validate_signal_frame(frame: pd.DataFrame, *, min_names: int = 2) -> dict[str, list[str]]:
75 """What is wrong with a (date, ticker, score) signal table before anything scores it: {"errors": [...], "warnings": [...]}.
76 Errors: a missing column, an unparseable date, a duplicate (date, ticker), a non-finite score. Warnings: rows out of date
77 order, dates with fewer than `min_names` scored names, a score that never varies within a date."""
78 errors: list[str] = []
79 warnings: list[str] = []
80 missing = [column for column in ("date", "ticker", "score") if column not in frame.columns]
81 if missing:
82 return {"errors": [f"missing column(s): {', '.join(missing)} (a signal is date, ticker, score)"], "warnings": []}
83 dates = pd.to_datetime(frame["date"], errors="coerce")
84 if dates.isna().any():
85 bad = frame.loc[dates.isna(), "date"].astype(str).head(3).tolist()
86 errors.append(f"{int(dates.isna().sum())} unparseable date(s), e.g. {bad}")
87 duplicated = frame.duplicated(subset=["date", "ticker"], keep=False)
88 if duplicated.any():
89 errors.append(f"{int(duplicated.sum())} rows share a (date, ticker) with another row, e.g. {frame.loc[duplicated, ['date', 'ticker']].head(2).to_dict('records')}")
90 scores = pd.to_numeric(frame["score"], errors="coerce")
91 nonfinite = ~np.isfinite(scores.to_numpy(dtype=float))
92 if nonfinite.any():
93 errors.append(f"{int(nonfinite.sum())} score(s) are missing, NaN or infinite")
94 if dates.notna().all() and not dates.is_monotonic_increasing:
95 warnings.append("rows are not in date order (scoring sorts them; check the file was written as intended)")
96 counts = frame.assign(_finite=~nonfinite).loc[lambda data: data["_finite"]].groupby("date")["ticker"].nunique()
97 thin = counts[counts < int(min_names)]
98 if len(thin):
99 warnings.append(f"{len(thin)} date(s) score fewer than {int(min_names)} names: a cross-sectional rank needs several")
100 flat = frame.assign(_score=scores).groupby("date")["_score"].nunique()
101 if len(flat) and (flat <= 1).all():
102 warnings.append("the score never varies within a date: it ranks nothing")
103 return {"errors": errors, "warnings": warnings}