Coverage for features/cross_sectional_inputs.py: 100%

100 statements  

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

1"""Cross-sectionally ranked model inputs (V6.4.4, Problems.md #247). 

2 

3A scaled feature's level across assets is mostly asset identity (the installed model ranked worse than an asset-class 

4prior); its percentile rank among the assets of the same class on the same bar is the comparable part. With 

5`phase1.features.cross_sectional_inputs.enabled`, every `*_scaled` model input is replaced by ("replace") or joined by 

6("append", as `<name>_csr`) its rank within (bar, asset class), centred to [-0.5, 0.5]. 

7 

8Groups are asset classes because each class's bars reach live on their own tick (equities and bonds at the close, crypto 

9at midnight UTC, forex on its own calendar): a rank across classes could not be reproduced live. 

10 

11One definition, two forms with identical values: `rank_input_matrix` (lists, `main.py` on the tick's pending symbols) and 

12`rank_input_frame` (pandas, the trainer and the offline scorer per dataset date). A value that is not finite, or a group 

13with fewer than `min_group_size` finite values, becomes 0.0 (the centre) - never NaN into a model. 

14""" 

15 

16from __future__ import annotations 

17 

18import math 

19from collections.abc import Mapping, Sequence 

20from typing import TYPE_CHECKING, Any 

21 

22if TYPE_CHECKING: 

23 import pandas as pd 

24 

25CSR_SUFFIX = "_csr" 

26RANKED_SUFFIX = "_scaled" 

27MODES = ("replace", "append") 

28GROUPS = ("asset_class",) 

29 

30 

31def resolve_cross_sectional_inputs(raw: Mapping[str, Any] | None) -> dict[str, Any] | None: 

32 """`phase1.features.cross_sectional_inputs` -> settings, or None when absent / disabled (today's behaviour).""" 

33 if not isinstance(raw, Mapping) or not bool(raw.get("enabled", False)): 

34 return None 

35 group = str(raw.get("group", "asset_class")) 

36 mode = str(raw.get("mode", "replace")) 

37 try: 

38 min_group_size = int(raw.get("min_group_size", 5)) 

39 except (TypeError, ValueError): 

40 min_group_size = 5 

41 return { 

42 "group": group if group in GROUPS else "asset_class", 

43 "mode": mode if mode in MODES else "replace", 

44 "min_group_size": max(2, min_group_size), 

45 } 

46 

47 

48def settings_from_config(config: Mapping[str, Any] | None) -> dict[str, Any] | None: 

49 """The resolved cross-sectional input settings from `phase1.features.cross_sectional_inputs`, or None when off.""" 

50 return resolve_cross_sectional_inputs(((config or {}).get("phase1") or {}).get("features", {}).get("cross_sectional_inputs")) 

51 

52 

53def ranked_input_names(names: Sequence[str]) -> list[str]: 

54 """The inputs that get ranked: the scaled features (categorical / class context inputs stay as they are).""" 

55 return [str(name) for name in names if str(name).endswith(RANKED_SUFFIX)] 

56 

57 

58def expand_input_names(names: Sequence[str], settings: Mapping[str, Any] | None) -> list[str]: 

59 """Model input names after the transform: unchanged for "replace", `<name>_csr` appended for "append".""" 

60 names = [str(name) for name in names] 

61 if not settings or settings.get("mode") != "append": 

62 return names 

63 extra = [name + CSR_SUFFIX for name in ranked_input_names(names) if name + CSR_SUFFIX not in names] 

64 return names + extra 

65 

66 

67def asset_class_of(asset: Mapping[str, Any] | None) -> str: 

68 """The class main.py's _class_raw_scores uses: asset_class, else security_type (bond ETFs are equity / bond).""" 

69 asset = asset or {} 

70 return str(asset.get("asset_class") or asset.get("security_type") or "unknown") 

71 

72 

73def asset_class_by_ticker(config: Mapping[str, Any] | None) -> dict[str, str]: 

74 """{ticker: asset class} for every asset in the config's universe.""" 

75 assets = (((config or {}).get("phase1") or {}).get("universe") or {}).get("assets") or [] 

76 return {str(asset.get("ticker")): asset_class_of(asset) for asset in assets} 

77 

78 

79def _finite(value) -> float | None: 

80 try: 

81 number = float(value) 

82 except (TypeError, ValueError): 

83 return None 

84 return number if math.isfinite(number) else None 

85 

86 

87def _centred_ranks(values: Sequence[float | None], min_group_size: int) -> list[float]: 

88 """Average-rank percentile minus 0.5 over the finite values (pandas rank(pct=True) - 0.5); 0.0 elsewhere.""" 

89 finite = [(value, index) for index, value in enumerate(values) if value is not None] 

90 out = [0.0] * len(values) 

91 count = len(finite) 

92 if count < min_group_size: 

93 return out 

94 finite.sort(key=lambda pair: pair[0]) 

95 position = 0 

96 while position < count: 

97 end = position 

98 while end + 1 < count and finite[end + 1][0] == finite[position][0]: 

99 end += 1 

100 average_rank = (position + 1 + end + 1) / 2.0 

101 for _, index in finite[position:end + 1]: 

102 out[index] = average_rank / count - 0.5 

103 position = end + 1 

104 return out 

105 

106 

107def rank_input_matrix( 

108 rows: Sequence[Sequence[float]], names: Sequence[str], groups: Sequence[str], settings: Mapping[str, Any] 

109) -> tuple[list[list[float]], list[str]]: 

110 """Live form: `rows` are the model input vectors (in `names` order) of the symbols of ONE bar, `groups` their asset 

111 classes. Returns (new rows, new names) - new lists, the inputs are never mutated.""" 

112 names = [str(name) for name in names] 

113 out_names = expand_input_names(names, settings) 

114 out_rows = [list(row) + [0.0] * (len(out_names) - len(names)) for row in rows] 

115 min_group_size = int(settings.get("min_group_size", 5)) 

116 append = settings.get("mode") == "append" 

117 members: dict[str, list[int]] = {} 

118 for index, group in enumerate(groups): 

119 members.setdefault(str(group), []).append(index) 

120 for name in ranked_input_names(names): 

121 source = names.index(name) 

122 target = out_names.index(name + CSR_SUFFIX) if append else source 

123 for indexes in members.values(): 

124 ranks = _centred_ranks([_finite(rows[i][source]) for i in indexes], min_group_size) 

125 for i, rank in zip(indexes, ranks, strict=False): 

126 out_rows[i][target] = rank 

127 return out_rows, out_names 

128 

129 

130def rank_input_frame(frame: pd.DataFrame, names: Sequence[str], groups: Sequence[Any] | pd.Series, settings: Mapping[str, Any], *, date_column: str = "date") -> pd.DataFrame: 

131 """Offline form, same values as rank_input_matrix per (date, group): returns a copy of `frame` with the scaled 

132 inputs replaced (or `<name>_csr` columns added). `groups` is aligned to `frame` (a Series or a sequence).""" 

133 import numpy as np 

134 import pandas as pd 

135 

136 names = [str(name) for name in names] 

137 ranked = [name for name in ranked_input_names(names) if name in frame.columns] 

138 out = frame.copy() 

139 if out.empty or not ranked: 

140 return out 

141 min_group_size = int(settings.get("min_group_size", 5)) 

142 keys = [out[date_column].astype(str).str[:10].to_numpy(), np.asarray(list(groups), dtype=object)] 

143 values = out[ranked].apply(pd.to_numeric, errors="coerce").replace([np.inf, -np.inf], np.nan) 

144 grouped = values.groupby(keys, sort=False) 

145 ranks = grouped.rank(pct=True, method="average") - 0.5 

146 counts = grouped.transform("count") 

147 ranks = ranks.where(counts >= min_group_size).fillna(0.0) 

148 append = settings.get("mode") == "append" 

149 for name in ranked: 

150 out[name + CSR_SUFFIX if append else name] = ranks[name].to_numpy(dtype=float) 

151 return out 

152 

153 

154def apply_cross_sectional_inputs(frame: pd.DataFrame, config: Mapping[str, Any] | None, names: Sequence[str], *, ticker_column: str = "ticker", 

155 date_column: str = "date") -> pd.DataFrame: 

156 """The trainer's / offline scorer's one call: `frame` unchanged when the setting is off, else ranked per (date, class) 

157 with each row's class from the config universe (the same mapping main.py uses).""" 

158 settings = settings_from_config(config) 

159 if settings is None: 

160 return frame 

161 classes = asset_class_by_ticker(config) 

162 groups = [classes.get(str(ticker), "unknown") for ticker in frame[ticker_column].tolist()] 

163 return rank_input_frame(frame, names, groups, settings, date_column=date_column)