Coverage for evaluation/factor_neutralization_check.py: 100%
86 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"""V5.4.3 - factor-neutralization check: decomposes the offline rank book's
2realized returns into systematic (market/sector/momentum) and residual
3(pure alpha) components, answering "how much of the claimed Sharpe is
4actually skill vs. factor exposure?"
6Pure: numpy/pandas only, no I/O, no torch."""
8from __future__ import annotations
10import numpy as np
11import pandas as pd
14def compute_factor_exposure(
15 book_returns: pd.Series,
16 market_returns: pd.Series,
17 *,
18 momentum_factor: pd.Series | None = None,
19 sector_returns: dict[str, pd.Series] | None = None,
20) -> dict:
21 """Regresses book returns onto factor columns and reports loadings,
22 R², residual Sharpe, and % of variance explained by each factor.
24 All input series must be aligned by date (same index or positional).
25 Missing values are forward-filled then dropped.
27 Returns:
28 {"alpha_sharpe": float, "total_sharpe": float, "r_squared": float,
29 "loadings": {factor: beta}, "alpha_annualized_return_pct": float,
30 "factor_contribution_pct": {factor: pct_of_variance},
31 "n_obs": int}
32 """
33 book = _align(book_returns)
34 market = _align(market_returns)
35 n = min(len(book), len(market))
36 book, market = book[:n], market[:n]
38 factors = {"market": market}
39 if momentum_factor is not None:
40 mom = _align(momentum_factor)[:n]
41 if len(mom) == n:
42 factors["momentum"] = mom
43 if sector_returns:
44 for name, series in sector_returns.items():
45 s = _align(series)
46 if len(s) >= n:
47 factors[f"sector_{name}"] = s[:n]
49 # Build design matrix [1, factor_1, ..., factor_k]
50 names = list(factors.keys())
51 X = np.column_stack([np.ones(n)] + [factors[name] for name in names])
52 y = book
54 # OLS: beta = (X'X)^-1 X'y
55 XtX = X.T @ X
56 Xty = X.T @ y
57 try:
58 betas = np.linalg.solve(XtX, Xty)
59 except np.linalg.LinAlgError:
60 return {"error": "singular design matrix", "n_obs": n}
62 residuals = y - X @ betas
63 ss_total = float(np.sum((y - y.mean()) ** 2))
64 ss_resid = float(np.sum(residuals ** 2))
65 r_squared = 1.0 - ss_resid / ss_total if ss_total > 1e-12 * n else 0.0 # constant returns carry float noise
67 # Alpha = the part of the book's return the factors do NOT explain: the
68 # regression INTERCEPT plus the residuals. V5.5.0 (found when the first
69 # caller shipped): this used mean(residuals) alone, which is identically ~0
70 # for an OLS fit that includes an intercept, so alpha_sharpe and
71 # alpha_annualized_return_pct were always 0.0 whatever the book earned.
72 alpha_series = residuals + betas[0]
73 resid_std = np.std(alpha_series, ddof=1) if len(alpha_series) > 1 else 1e-12
74 alpha_sharpe = float(np.mean(alpha_series) / max(resid_std, 1e-12) * np.sqrt(252))
75 total_sharpe = float(np.mean(y) / max(np.std(y, ddof=1), 1e-12) * np.sqrt(252))
77 # Factor contribution: variance explained by each factor alone
78 contributions = {}
79 for i, name in enumerate(names):
80 col = X[:, i + 1]
81 ss_factor = float(np.sum((col - col.mean()) ** 2))
82 beta_i = betas[i + 1]
83 contribution = beta_i ** 2 * ss_factor
84 contributions[name] = round(float(contribution / ss_total * 100), 2) if ss_total > 1e-12 * n else 0.0
86 return {
87 "alpha_sharpe": round(alpha_sharpe, 4),
88 "total_sharpe": round(total_sharpe, 4),
89 "r_squared": round(r_squared, 4),
90 "loadings": {name: round(float(betas[i + 1]), 6) for i, name in enumerate(names)},
91 "alpha_annualized_return_pct": round(float(np.mean(alpha_series) * 252 * 100), 4),
92 "factor_contribution_pct": contributions,
93 "n_obs": n,
94 }
97def _align(series: pd.Series) -> np.ndarray:
98 values = pd.Series(series).ffill().dropna().to_numpy(dtype=float)
99 return values
102# ---------------------------------------------------------------------------
103# V5.5.0 - the missing caller. compute_factor_exposure() shipped in V5.4.3 but
104# nothing produced its inputs, so "how much of the book's Sharpe is market or
105# momentum exposure rather than ranking skill" was never answered. These
106# helpers build the factor series from the dataset's own close pivot, on the
107# SAME dating convention rank_book_simulator uses: a return booked on date d is
108# the FORWARD return d -> d+1 of weights decided with information up to d.
109# ---------------------------------------------------------------------------
112def _forward_returns(close_pivot: pd.DataFrame) -> pd.DataFrame:
113 return close_pivot.shift(-1) / close_pivot - 1.0
116def market_forward_returns(close_pivot: pd.DataFrame, market_ticker: str = "SPY") -> pd.Series:
117 """Forward 1-day return of `market_ticker`, indexed by decision date.
118 Empty series when the ticker is absent (callers report SKIPPED)."""
119 if market_ticker not in close_pivot.columns:
120 return pd.Series(dtype=float)
121 return _forward_returns(close_pivot)[market_ticker]
124def momentum_factor_forward_returns(
125 close_pivot: pd.DataFrame, *, lookback: int = 20, quantile: float = 0.2
126) -> pd.Series:
127 """Long-short momentum factor: per date, the mean forward return of the
128 top `quantile` of names by trailing `lookback`-day return minus the
129 bottom `quantile`'s. The signal at d uses closes up to d only, so the
130 factor has no lookahead against the book it is regressed on."""
131 momentum = close_pivot / close_pivot.shift(lookback) - 1.0
132 forward = _forward_returns(close_pivot)
133 values: dict = {}
134 for date in close_pivot.index:
135 signal = momentum.loc[date].dropna()
136 outcome = forward.loc[date]
137 bucket = max(1, int(len(signal) * quantile))
138 if len(signal) < 2 * bucket:
139 continue
140 ranked = signal.sort_values()
141 short_leg = outcome.reindex(ranked.index[:bucket]).dropna()
142 long_leg = outcome.reindex(ranked.index[-bucket:]).dropna()
143 if short_leg.empty or long_leg.empty:
144 continue
145 values[date] = float(long_leg.mean() - short_leg.mean())
146 return pd.Series(values, dtype=float)
149def compute_book_factor_exposure(
150 per_date: list[str],
151 per_date_net_return: list[float],
152 close_pivot: pd.DataFrame,
153 *,
154 market_ticker: str = "SPY",
155 momentum_lookback: int = 20,
156) -> dict:
157 """Regress a simulated book's daily net returns on the market and
158 momentum factors. Dates are inner-joined first so the positional OLS in
159 compute_factor_exposure() sees aligned, NaN-free series."""
160 if close_pivot.empty:
161 return {"status": "SKIPPED", "reason": "no close column in dataset"}
162 book = pd.Series(per_date_net_return, index=[str(date) for date in per_date], dtype=float)
163 market = market_forward_returns(close_pivot, market_ticker)
164 if market.empty:
165 return {"status": "SKIPPED", "reason": f"{market_ticker} not in dataset"}
166 market.index = [str(date) for date in market.index]
167 momentum = momentum_factor_forward_returns(close_pivot, lookback=momentum_lookback)
168 momentum.index = [str(date) for date in momentum.index]
169 joined = pd.concat({"book": book, "market": market, "momentum": momentum}, axis=1, join="inner").dropna()
170 if len(joined) < 30:
171 return {"status": "SKIPPED", "reason": f"only {len(joined)} aligned dates (need >= 30)"}
172 result = compute_factor_exposure(joined["book"], joined["market"], momentum_factor=joined["momentum"])
173 result["status"] = "OK"
174 result["market_ticker"] = market_ticker
175 return result