Coverage for evaluation/factor_spanning.py: 100%

60 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""Factor baselines and spanning regressions (V6.4.3): does a signal add anything over plain, untrained factors? 

2 

3`build_factor_scores` derives five classic cross-sectional factor scores from columns every dataset row already has 

4(as of the row's date, no lookahead); `build_factor_returns` turns any score into a daily top-minus-bottom quantile 

5return; `factor_spanning` regresses a signal's long/short return on the factor returns with Newey-West errors - the 

6intercept (alpha) is what the signal earns beyond the factors. Pure numpy/pandas. 

7""" 

8 

9from __future__ import annotations 

10 

11from typing import TYPE_CHECKING, Any 

12 

13import numpy as np 

14import pandas as pd 

15 

16if TYPE_CHECKING: 

17 from collections.abc import Sequence 

18 

19FACTOR_COLUMNS = ("f_mom_12_1", "f_mom_20", "f_rev_5", "f_lowvol", "f_high52") 

20 

21 

22def build_factor_scores(frame: pd.DataFrame, *, ticker_column: str = "ticker", date_column: str = "date") -> pd.DataFrame: 

23 """f_mom_12_1 (sum of daily returns from t-252 to t-21), f_mom_20 (momentum_20d), f_rev_5 (-5-day return), 

24 f_lowvol (-rolling_volatility_20d), f_high52 (dist_52w_high: higher = nearer the 52-week high) and f_composite 

25 (mean of the per-date ranks of mom_12_1, high52, lowvol and rev_5). Same index as `frame`.""" 

26 out = pd.DataFrame(index=frame.index) 

27 ordered = frame.sort_values([ticker_column, date_column]) 

28 daily = ordered.groupby(ticker_column)["close_to_close_return_1d"] 

29 momentum = daily.transform(lambda s: s.shift(21).rolling(231, min_periods=231).sum()) 

30 out["f_mom_12_1"] = momentum.reindex(frame.index) 

31 out["f_mom_20"] = frame.get("momentum_20d", np.nan) 

32 out["f_rev_5"] = -frame["close_to_close_return_5d"] if "close_to_close_return_5d" in frame else np.nan 

33 out["f_lowvol"] = -frame["rolling_volatility_20d"] if "rolling_volatility_20d" in frame else np.nan 

34 out["f_high52"] = frame.get("dist_52w_high", np.nan) 

35 ranks = out[["f_mom_12_1", "f_high52", "f_lowvol", "f_rev_5"]].groupby(frame[date_column]).rank(pct=True) 

36 out["f_composite"] = ranks.mean(axis=1, skipna=True) 

37 return out 

38 

39 

40def build_factor_returns(frame: pd.DataFrame, factor_columns: Sequence[str], *, date_column: str = "date", 

41 forward_return_column: str = "target_return_1d", quantile: float = 0.2, min_names: int = 20) -> pd.DataFrame: 

42 """Daily equal-weight top-quantile minus bottom-quantile return of each score column; NaN on dates with fewer than 

43 `min_names` scored names. `forward_return_column` at t is the t -> t+1 return (the simulator's convention).""" 

44 result = {} 

45 for column in factor_columns: 

46 data = frame[[date_column, column, forward_return_column]].dropna() 

47 returns = {} 

48 for date, day in data.groupby(date_column, sort=True): 

49 if len(day) < min_names: 

50 continue 

51 k = max(1, int(round(len(day) * quantile))) 

52 ordered = day.sort_values(column) 

53 returns[date] = float(ordered[forward_return_column].iloc[-k:].mean() - ordered[forward_return_column].iloc[:k].mean()) 

54 result[column] = pd.Series(returns, dtype=float) 

55 return pd.DataFrame(result).sort_index() 

56 

57 

58def _newey_west_cov(x: np.ndarray, residuals: np.ndarray, lags: int) -> np.ndarray: 

59 n = len(residuals) 

60 scores = x * residuals[:, None] 

61 meat = scores.T @ scores / n 

62 for lag in range(1, min(lags, n - 1) + 1): 

63 weight = 1.0 - lag / (lags + 1.0) 

64 gamma = scores[lag:].T @ scores[:-lag] / n 

65 meat += weight * (gamma + gamma.T) 

66 bread = np.linalg.pinv(x.T @ x / n) 

67 return bread @ meat @ bread / n 

68 

69 

70def factor_alpha(series: pd.Series, factors: pd.DataFrame, *, hac_lags: int = 5, periods_per_year: int = 252) -> dict[str, Any]: 

71 """What a sleeve earns beyond published factors (French's five and momentum, AQR's QMJ and BAB). A return all explained here may be real and 

72 still only a premium anyone can buy, so this labels a result; it never blocks one. `RF` isn't a factor. Rows a factor hasn't reached are dropped, and 

73 `num_dates` shows how many remain.""" 

74 columns = [name for name in factors.columns if name != "RF"] 

75 return factor_spanning(series, factors[columns], hac_lags=hac_lags, periods_per_year=periods_per_year) 

76 

77 

78def factor_spanning(signal_returns: pd.Series, factor_returns: pd.DataFrame, *, hac_lags: int = 19, periods_per_year: int = 252) -> dict[str, Any]: 

79 """OLS of the signal's daily return on the factors' (dates present in both, rows with a NaN dropped).""" 

80 joined = pd.concat([signal_returns.rename("_signal"), factor_returns], axis=1, join="inner") 

81 joined = joined.dropna(axis=1, how="all").dropna() # a factor with no history at all (e.g. 12-1 momentum) is left out 

82 factors = [c for c in factor_returns.columns if c in joined.columns] 

83 if len(joined) <= len(factors) + 2: 

84 return {"num_dates": int(len(joined)), "alpha_daily": None, "alpha_t": None} 

85 y = joined["_signal"].to_numpy(dtype=float) 

86 x = np.column_stack([np.ones(len(joined)), joined[factors].to_numpy(dtype=float)]) 

87 coefficients, *_ = np.linalg.lstsq(x, y, rcond=None) 

88 residuals = y - x @ coefficients 

89 covariance = _newey_west_cov(x, residuals, hac_lags) 

90 standard_errors = np.sqrt(np.maximum(np.diag(covariance), 0.0)) 

91 with np.errstate(divide="ignore", invalid="ignore"): 

92 t_stats = np.where(standard_errors > 0, coefficients / standard_errors, 0.0) 

93 total = float(((y - y.mean()) ** 2).sum()) 

94 return { 

95 "num_dates": int(len(joined)), 

96 "alpha_daily": float(coefficients[0]), 

97 "alpha_annual": float(coefficients[0] * periods_per_year), 

98 "alpha_t": float(t_stats[0]), 

99 "betas": {name: float(value) for name, value in zip(factors, coefficients[1:], strict=False)}, 

100 "betas_t": {name: float(value) for name, value in zip(factors, t_stats[1:], strict=False)}, 

101 "r2": float(1.0 - (residuals**2).sum() / total) if total > 0 else 0.0, 

102 }