Coverage for features/asof_beta_labels.py: 100%

77 statements  

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

1"""As-of beta for the beta-neutral and residual rank labels (V6.4.3). 

2 

3train.py's `target_beta_neutral_rank_Nd` / `target_residual_rank_Nd` residualise each forward return against ONE 

4whole-history beta per asset, an OLS slope fitted on forward returns that include the label's own future (Problems #238). 

5Here the beta at date t is a trailing OLS slope of the asset's realised daily returns on the market's, over the 

6`window` days up to and including t, so a label row only depends on what was known at t plus its own forward window. 

7The rest of each label (market term, sector dummies, cross-sectional size z-score, the min universe floor, the 

8percentile rank) is train.py's definition unchanged. Pure numpy/pandas. 

9""" 

10 

11from __future__ import annotations 

12 

13from typing import TYPE_CHECKING 

14 

15import numpy as np 

16import pandas as pd 

17 

18if TYPE_CHECKING: 

19 from collections.abc import Sequence 

20 

21 from numpy.typing import ArrayLike 

22 

23DEFAULT_WINDOW = 252 

24DEFAULT_MIN_PERIODS = 126 

25 

26 

27def cross_sectional_residualize(returns: np.ndarray, design_matrix: np.ndarray) -> np.ndarray: 

28 """Residuals of one date's `returns ~ design_matrix` least-squares fit; a degenerate fit (fewer rows than columns, a 

29 LinAlgError, rank 0, a non-finite residual) returns `returns` unchanged. Never raises. train.py uses this one.""" 

30 n_rows, n_columns = design_matrix.shape 

31 if n_rows == 0 or n_rows < n_columns: 

32 return returns 

33 try: 

34 coefficients, _residual_sum, rank, _singular_values = np.linalg.lstsq(design_matrix, returns, rcond=None) 

35 except np.linalg.LinAlgError: 

36 return returns 

37 if rank < 1: 

38 return returns 

39 residuals = returns - design_matrix @ coefficients 

40 if not np.all(np.isfinite(residuals)): 

41 return returns 

42 return residuals 

43 

44 

45def asof_rolling_beta(asset_returns: ArrayLike, market_returns: ArrayLike, *, window: int = DEFAULT_WINDOW, min_periods: int = DEFAULT_MIN_PERIODS) -> np.ndarray: 

46 """Trailing OLS slope of `asset_returns` on `market_returns` (aligned arrays, NaN = missing) over the last `window` 

47 paired observations up to and including each position; NaN until `min_periods` pairs exist.""" 

48 asset = pd.Series(np.asarray(asset_returns, dtype=float)) 

49 market = pd.Series(np.asarray(market_returns, dtype=float)) 

50 paired = asset.notna() & market.notna() 

51 asset, market = asset.where(paired), market.where(paired) 

52 covariance = asset.rolling(window, min_periods=min_periods).cov(market) 

53 variance = market.rolling(window, min_periods=min_periods).var() 

54 beta = covariance / variance.where(variance > 0.0) 

55 return beta.to_numpy() 

56 

57 

58def asof_residual_forward_return(fwd_asset: ArrayLike, fwd_market: ArrayLike, beta_t: ArrayLike) -> np.ndarray: 

59 """fwd_asset - beta_t * fwd_market; a missing beta counts as 0 (train.py's fallback for a short history).""" 

60 beta = np.nan_to_num(np.asarray(beta_t, dtype=float), nan=0.0) 

61 return np.asarray(fwd_asset, dtype=float) - beta * np.asarray(fwd_market, dtype=float) 

62 

63 

64def asof_beta_by_row(frame: pd.DataFrame, *, market_ticker: str, return_column: str = "close_to_close_return_1d", 

65 window: int = DEFAULT_WINDOW, min_periods: int = DEFAULT_MIN_PERIODS) -> pd.Series: 

66 """The as-of beta of every row of a long (date, ticker) frame, aligned to `frame.index`. The market's daily return 

67 is matched by date, so each asset pairs only on the dates both traded.""" 

68 market = frame.loc[frame["ticker"] == market_ticker, ["date", return_column]].drop_duplicates("date") 

69 market_by_date = dict(zip(market["date"], market[return_column], strict=False)) 

70 out = pd.Series(np.nan, index=frame.index, dtype=float) 

71 for _ticker, rows in frame.sort_values("date").groupby("ticker", sort=False): 

72 market_returns = rows["date"].map(market_by_date).to_numpy(dtype=float) 

73 out.loc[rows.index] = asof_rolling_beta(rows[return_column].to_numpy(dtype=float), market_returns, window=window, 

74 min_periods=min_periods) 

75 return out 

76 

77 

78def build_asof_rank_labels(frame: pd.DataFrame, *, horizons: Sequence[int]=(5, 20), market_ticker: str = "SPY", window: int = DEFAULT_WINDOW, 

79 min_periods: int = DEFAULT_MIN_PERIODS, min_universe_size: int = 20, 

80 sector_by_ticker: dict[str, str] | None = None, size_column: str | None = "liquidity_log_dollar_volume", 

81 use_market: bool = True, use_sector: bool = True, use_size: bool = True) -> pd.DataFrame: 

82 """`target_beta_neutral_rank_{h}d_asof` and `target_residual_rank_{h}d_asof` for a long frame holding `date`, 

83 `ticker`, `close_to_close_return_1d`, `target_return_{h}d` (and `size_column`). Same index as `frame`.""" 

84 beta = asof_beta_by_row(frame, market_ticker=market_ticker, window=window, min_periods=min_periods) 

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

86 sectors = frame["ticker"].map(sector_by_ticker or {}).fillna("Unknown") if use_sector else None 

87 for horizon in horizons: 

88 return_column = f"target_return_{horizon}d" 

89 market = frame.loc[frame["ticker"] == market_ticker, ["date", return_column]].drop_duplicates("date") 

90 market_fwd = frame["date"].map(dict(zip(market["date"], market[return_column], strict=False))) 

91 valid = frame[return_column].notna() & market_fwd.notna() 

92 

93 residual = pd.Series(asof_residual_forward_return(frame[return_column], market_fwd, beta), index=frame.index).where(valid) 

94 size_by_date = residual.groupby(frame["date"]).transform("count") 

95 eligible = residual.where(size_by_date >= min_universe_size) 

96 out[f"target_beta_neutral_rank_{horizon}d_asof"] = eligible.groupby(frame["date"]).rank(pct=True) 

97 

98 ranks = pd.Series(np.nan, index=frame.index, dtype=float) 

99 has_return = frame[return_column].notna() 

100 long_frame = frame.loc[has_return, ["date", return_column]].copy() 

101 long_frame["market_term"] = (np.nan_to_num(beta[has_return].to_numpy(), nan=0.0) 

102 * market_fwd[has_return].fillna(0.0).to_numpy()) if use_market else 0.0 

103 if use_size and size_column and size_column in frame.columns: 

104 size = frame.loc[has_return, size_column] 

105 grouped = size.groupby(long_frame["date"]) 

106 long_frame["size_z"] = ((size - grouped.transform("mean")) / grouped.transform("std").replace(0.0, np.nan)).fillna(0.0) 

107 for _date, group in long_frame.groupby("date", sort=False): 

108 if len(group) < min_universe_size: 

109 continue 

110 columns = [np.ones(len(group))] 

111 if use_market: 

112 columns.append(group["market_term"].to_numpy()) 

113 if use_sector: 

114 dummies = pd.get_dummies(sectors.loc[group.index], drop_first=True) 

115 if not dummies.empty: 

116 columns.append(dummies.to_numpy(dtype=float)) 

117 if "size_z" in group: 

118 columns.append(group["size_z"].to_numpy()) 

119 residuals = cross_sectional_residualize(group[return_column].to_numpy(dtype=float), np.column_stack(columns)) 

120 ranks.loc[group.index] = pd.Series(residuals).rank(pct=True).to_numpy() 

121 out[f"target_residual_rank_{horizon}d_asof"] = ranks 

122 return out