Coverage for features/cross_asset_sensitivity.py: 100%

35 statements  

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

1"""Per-asset macro sensitivities (V5.1 Phase 2, item 8 / F2 of the plan) - 

2additive sibling to features/bond_features.py, features/macro_features.py, 

3features/alt_data_features.py. 

4 

5F2's finding: every existing macro_*/bond_*/alt_* feature (except 

6bond_empirical_duration_beta) is written IDENTICALLY to every asset's row 

7on a date - a per-date constant that shifts every asset's score equally, 

8which a cross-sectional ranker is by construction invariant to (Spearman/ 

9ListNet ignore any transform that preserves relative order within a date). 

10"Add more macro features," taken literally, is near-worthless for a rank 

11model. The version that works is a per-asset SENSITIVITY: how much does 

12THIS asset's return move per unit of macro change - a quantity that varies 

13across the cross-section, plus the interaction term (sensitivity x today's 

14macro move), which is the closest thing to a forward-looking macro-driven 

15return prediction that stays scale-consistent asset to asset. 

16 

17Imported by BOTH train.py (offline, per-date/per-asset rolling regression 

18over the full history) and main.py (runtime, once per symbol per bar using 

19the same rolling-deque pattern main.py's 

20_bond_empirical_duration_beta_for_symbol() already established) for 

21train/inference parity by construction - same convention as every other 

22features/ module. main.py cannot import train.py (torch), which is the 

23whole reason this module lives here rather than in train.py alongside 

24build_cross_asset_sensitivity_features(). 

25""" 

26 

27from __future__ import annotations 

28 

29from features.bond_features import empirical_duration_beta 

30 

31CROSS_ASSET_SENSITIVITY_FEATURE_NAMES = [ 

32 "sens_vix_beta", 

33 "sens_vix_interaction", 

34 "sens_real_rate_beta", 

35 "sens_real_rate_interaction", 

36 "sens_credit_beta", 

37 "sens_credit_interaction", 

38 "sens_dollar_beta", 

39 "sens_dollar_interaction", 

40] 

41 

42 

43def rolling_sensitivity( 

44 asset_returns: list[float | None], 

45 macro_changes: list[float | None], 

46 *, 

47 lookback: int, 

48 min_observations: int, 

49) -> float | None: 

50 """Trailing-window OLS slope of asset_returns on macro_changes, 

51 restricted to the last `lookback` positions of each series (positionally 

52 paired - callers are responsible for date alignment, the same contract 

53 empirical_duration_beta() itself already documents). A thin wrapper - 

54 REUSES empirical_duration_beta() rather than reimplementing OLS, exactly 

55 as bond_empirical_duration_beta already does for a whole-history 

56 (non-rolling) beta. 

57 

58 lookback <= 0 disables windowing (uses the full series - a whole-history 

59 beta, matching bond_empirical_duration_beta's convention). Returns None 

60 (not 0.0) when fewer than min_observations valid pairs exist in the 

61 window - a missing/insufficient-history sensitivity must stay 

62 distinguishable from a genuinely-zero one, same as 

63 empirical_duration_beta()'s own return contract.""" 

64 if lookback > 0: 

65 asset_returns = asset_returns[-lookback:] 

66 macro_changes = macro_changes[-lookback:] 

67 return empirical_duration_beta(asset_returns, macro_changes, min_observations=min_observations) 

68 

69 

70def sensitivity_interaction(sensitivity: float | None, macro_change: float | None) -> float: 

71 """beta_i * delta_macro_t - the interaction term that turns a per-date 

72 constant macro move into a per-asset-varying signal a cross-sectional 

73 ranker can actually use. Neutral 0.0 on any missing input, the same 

74 "None input -> 0.0 neutral output" convention every features/*.py 

75 interaction/composite function already follows (e.g. 

76 features/alt_data_features.py's own neutral defaults).""" 

77 if sensitivity is None or macro_change is None: 

78 return 0.0 

79 return float(sensitivity) * float(macro_change) 

80 

81 

82def sensitivity_features_vector( 

83 closes: list[float], 

84 levels_by_driver: dict[str, list[float | None]], 

85 *, 

86 lookback: int, 

87 min_observations: int, 

88) -> dict[str, float]: 

89 """All 8 sensitivity features of one symbol from its trailing closes and each driver's aligned level history, built as 

90 float64 arrays (V6.0.0, latency: the list-and-loop version was ~55% of `main.py::_build_model_input`). 

91 

92 The same definition as the list path: returns[i] = closes[i] / closes[i-1] - 1 (missing when the previous close is 0), 

93 deltas[i] = level[i] - level[i-1] (missing when either level is), the last `lookback` of each paired positionally, 

94 beta = OLS slope, interaction = beta x the latest delta, neutral 0.0 where a value is missing. Equal to the list path 

95 to rounding level (`tests/test_v600_sensitivity_vector.py`).""" 

96 import numpy as np 

97 

98 from features.bond_features import duration_beta_from_arrays 

99 

100 tail = lookback + 1 if lookback > 0 else None 

101 prices = np.asarray(closes[-tail:] if tail is not None else closes, dtype=float) 

102 returns = np.full(len(prices), np.nan) 

103 if len(prices) > 1: 

104 previous = prices[:-1] 

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

106 returns[1:] = np.where(previous != 0.0, prices[1:] / previous - 1.0, np.nan) 

107 window_returns = returns[-lookback:] if lookback > 0 else returns 

108 result: dict[str, float] = {} 

109 for driver_key, levels in levels_by_driver.items(): 

110 series = np.array(levels[-tail:] if tail is not None else levels, dtype=float) # None becomes nan 

111 deltas = np.full(len(series), np.nan) 

112 if len(series) > 1: 

113 deltas[1:] = series[1:] - series[:-1] 

114 window_deltas = deltas[-lookback:] if lookback > 0 else deltas 

115 beta = duration_beta_from_arrays(window_returns, window_deltas, min_observations) 

116 latest = float(deltas[-1]) if len(deltas) and not np.isnan(deltas[-1]) else None 

117 result[f"sens_{driver_key}_beta"] = beta if beta is not None else 0.0 

118 result[f"sens_{driver_key}_interaction"] = sensitivity_interaction(beta, latest) 

119 return result 

120