Coverage for evaluation/round_builders.py: 100%

47 statements  

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

1"""Table builders a research round's rule file can name (V6.6.4): `"builder": "low_vol", "params": {...}` instead of a recipe over stored features. 

2 

3Each builder is a pure function of the cell (its prices, its membership mask, the features the cell holds, and the reference files under its data root) and returns a session x name 

4table, higher is better. The set is closed: a round names a builder from `BUILDERS`, and a name that isn't there is an error, so a rule file can't reach code by name. A builder whose 

5input file is absent raises `MissingInput`, which the runner reads as "this trial did not run" (it still counts in N). 

6""" 

7 

8from __future__ import annotations 

9 

10from collections.abc import Callable, Mapping 

11from pathlib import Path 

12from typing import TYPE_CHECKING, Any 

13 

14import pandas as pd 

15 

16from portfolio import crypto_signals, filing_signals 

17 

18if TYPE_CHECKING: 

19 from evaluation.wide_context import WideCell 

20 

21 

22class MissingInput(FileNotFoundError): 

23 """A builder's input isn't on this host.""" 

24 

25 

26def _reference_rows(cell, name: str) -> pd.DataFrame: 

27 if cell.root is None: 

28 raise MissingInput("this cell was built without a data root") 

29 path = Path(cell.root) / str(cell.data_dir) / "reference" / name 

30 if not path.exists(): 

31 raise MissingInput(f"{path} is not here (build it with scripts/build_filing_signals.py)") 

32 return pd.read_csv(path, dtype=str) 

33 

34 

35def _known(cell) -> pd.DataFrame: 

36 return cell.context.panel.known 

37 

38 

39def _feature(cell, name: str) -> pd.DataFrame: 

40 if name not in cell.features: 

41 raise MissingInput(f"the cell holds no {name!r} feature") 

42 return cell.features[name] 

43 

44 

45def _fundamentals(cell) -> pd.DataFrame: 

46 frames = [_reference_rows(cell, "edgar_fundamentals.csv.gz"), _reference_rows(cell, "edgar_fundamentals_ext.csv.gz")] 

47 return pd.concat(frames, ignore_index=True) 

48 

49 

50def _fred_known(cell) -> pd.DataFrame: 

51 """The 10-year, 3-month and Baa-spread series from the cell's own root, as a session knows them (one session late).""" 

52 from data_pipeline.fred_backfill import load_cached_fred_series 

53 from portfolio.premia_signals import fred_series_table 

54 

55 if cell.root is None: 

56 raise MissingInput("this cell was built without a data root") 

57 directory = Path(cell.root) / str(cell.data_dir) / "reference" / "fred_series" 

58 if not directory.exists(): 

59 raise MissingInput(f"{directory} is not here") 

60 keys = ("treasury_10yr", "treasury_3mo", "credit_spread_baa10y") 

61 return filing_signals.fred_as_known(fred_series_table(load_cached_fred_series(directory), keys), _known(cell).index, keys=keys) 

62 

63 

64BUILDERS: dict[str, Callable[[object, Mapping], pd.DataFrame]] = { 

65 "low_vol": lambda cell, p: crypto_signals.low_vol(_known(cell), **p), 

66 "lottery_max": lambda cell, p: crypto_signals.lottery_max(_known(cell), **p), 

67 "amihud": lambda cell, p: crypto_signals.amihud(_known(cell), _feature(cell, "quote_volume"), **p), 

68 "volume_trend": lambda cell, p: crypto_signals.volume_trend(_feature(cell, "quote_volume").reindex(columns=_known(cell).columns), **p), 

69 "high_proximity": lambda cell, p: crypto_signals.high_proximity(_known(cell), **p), 

70 "short_reversal": lambda cell, p: crypto_signals.short_reversal(_known(cell), **p), 

71 "low_beta": lambda cell, p: crypto_signals.low_beta(_known(cell), **p), 

72 "idio_vol": lambda cell, p: crypto_signals.idio_vol(_known(cell), **p), 

73 "trend_votes": lambda cell, p: crypto_signals.trend_votes(_known(cell), **p), 

74 "funding_filtered_trend": lambda cell, p: crypto_signals.funding_filtered_trend(_known(cell), cell.features.get("funding"), **p), 

75 "breadth_timing": lambda cell, p: crypto_signals.breadth_timing(_known(cell), _feature(cell, "liquid"), **p), 

76 "core_constant": lambda cell, p: crypto_signals.core_constant(_known(cell), **p), 

77 "similarity_table": lambda cell, p: filing_signals.similarity_table(_reference_rows(cell, "filing_similarity.csv.gz").assign(similarity=lambda f: f["similarity"].astype(float)), _known(cell).index, _known(cell).columns, **p), 

78 "announcement_proximity": lambda cell, p: filing_signals.announcement_proximity(_reference_rows(cell, "earnings_dates.csv.gz"), _known(cell).index, _known(cell).columns, **p), 

79 "announcement_return": lambda cell, p: filing_signals.announcement_return(_reference_rows(cell, "earnings_dates.csv.gz"), _known(cell), **p), 

80 "same_month_seasonality": lambda cell, p: filing_signals.same_month_seasonality(_known(cell), **p), 

81 "opportunistic_buying": lambda cell, p: filing_signals.opportunistic_buying(_reference_rows(cell, "insider_trades.csv.gz"), _known(cell).index, _known(cell).columns, **p), 

82 "cash_profitability": lambda cell, p: filing_signals.cash_profitability(_fundamentals(cell).assign(value=lambda f: f["value"].astype(float)), _known(cell).index, _known(cell).columns, **p), 

83 "term_credit_timing": lambda cell, p: filing_signals.term_credit_timing(_fred_known(cell), _known(cell), **p), 

84 "cross_asset_trend": lambda cell, p: filing_signals.cross_asset_trend(_known(cell), **p), 

85} 

86 

87 

88def build_trial_table(builder: str, params: Mapping[str, Any] | None, cell: WideCell) -> pd.DataFrame: 

89 """One builder's table on this cell. `cross_asset_trend` takes its `tickers` from the params.""" 

90 if builder not in BUILDERS: 

91 raise KeyError(f"unknown builder {builder!r}; expected one of {sorted(BUILDERS)}") 

92 arguments = dict(params or {}) 

93 if builder == "cross_asset_trend" and "tickers" in arguments: 

94 arguments["tickers"] = tuple(arguments["tickers"]) 

95 return BUILDERS[builder](cell, arguments) 

96 

97 

98def apply_gate(table: pd.DataFrame, gate: str | None, cell: WideCell) -> pd.DataFrame: 

99 """An optional gate on the finished table. `regime`: no signal while BTC is below its 120-session average.""" 

100 if not gate: 

101 return table 

102 if gate == "regime": 

103 return crypto_signals.regime_gate(table, _known(cell)) 

104 raise KeyError(f"unknown gate {gate!r}")