Coverage for scripts/v664_crypto_gbm.py: 100%

78 statements  

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

1"""Round 4C's x13: a walk-forward gradient-boosted ranker over crypto features (V6.6.4). 

2 

3Features are the cross-sectional ranks of x01-x08 and the c1, c2 tables; the label is the rank of the next 20 days' return. Refit each 1 January and 1 July on rows whose label ended before the 

4refit date, scored for the half-year after it, from 2019-01-01. Reads cell CS only. Writes `ml/evaluation/v664/scores/x13.csv` (`date,ticker,score`), which round 4C's x13 reads as a 

5`score_file`. Deterministic: fixed seeds, so two runs give identical bytes. 

6 

7 python scripts/v664_crypto_gbm.py 

8""" 

9 

10from __future__ import annotations 

11 

12import json 

13import sys 

14from collections.abc import Mapping 

15from pathlib import Path 

16 

17import numpy as np 

18import pandas as pd 

19 

20ROOT = Path(__file__).resolve().parents[1] 

21sys.path.insert(0, str(ROOT)) 

22 

23from portfolio import crypto_signals as cs # noqa: E402 

24 

25HORIZON = 20 

26FIRST_SCORED = "2019-01-01" 

27FEATURES = ("x01", "x02", "x03", "x04", "x05", "x06", "x07", "x08", "c1", "c2") 

28OUTPUT = ROOT / "ml" / "evaluation" / "v664" / "scores" / "x13.csv" 

29PARAMETERS = {"max_depth": 3, "learning_rate": 0.05, "max_iter": 200, "random_state": 0} 

30 

31 

32def feature_tables(known: pd.DataFrame, volume: pd.DataFrame, member: pd.DataFrame, c_tables: Mapping[str, pd.DataFrame]) -> dict[str, pd.DataFrame]: 

33 """The ten inputs as session x coin tables, ranked within each session among members.""" 

34 raw = { 

35 "x01": cs.low_vol(known), "x02": cs.lottery_max(known), "x03": cs.amihud(known, volume), "x04": cs.volume_trend(volume.reindex(columns=known.columns)), 

36 "x05": cs.high_proximity(known), "x06": cs.short_reversal(known), "x07": cs.low_beta(known), "x08": cs.idio_vol(known), "c1": c_tables["c1"], "c2": c_tables["c2"], 

37 } 

38 return {name: table.where(member).rank(axis=1, pct=True) for name, table in raw.items()} 

39 

40 

41def label_rank(known: pd.DataFrame, member: pd.DataFrame, horizon: int = HORIZON) -> pd.DataFrame: 

42 """The rank of each coin's next-`horizon`-days return. A training label only; it is never a feature.""" 

43 ahead = (known.shift(-horizon) / known - 1.0).replace([np.inf, -np.inf], np.nan) 

44 return ahead.where(member).rank(axis=1, pct=True) 

45 

46 

47def refit_dates(index: pd.Index, first: str = FIRST_SCORED) -> list[str]: 

48 """Each 1 January and 1 July from `first`, as the first session on or after it.""" 

49 sessions = [str(day) for day in index] 

50 out = [] 

51 for stamp in pd.date_range(first, sessions[-1], freq="6MS"): 

52 later = [day for day in sessions if day >= stamp.strftime("%Y-%m-%d")] 

53 if later: 

54 out.append(later[0]) 

55 return out 

56 

57 

58def walk_forward(features: Mapping[str, pd.DataFrame], label: pd.DataFrame, index: pd.Index, *, horizon: int = HORIZON, fit=None) -> pd.DataFrame: 

59 """Scores for every session from the first refit, each half-year by a model fitted only on rows whose label had ended before that refit.""" 

60 from sklearn.ensemble import HistGradientBoostingRegressor 

61 

62 names = list(features) 

63 sessions = [str(day) for day in index] 

64 refits = refit_dates(index) 

65 scores = pd.DataFrame(np.nan, index=index, columns=label.columns) 

66 stack = np.stack([features[name].reindex(index=index, columns=label.columns).to_numpy(dtype=float) for name in names], axis=-1) 

67 for position, start in enumerate(refits): 

68 end = refits[position + 1] if position + 1 < len(refits) else None 

69 cut = sessions.index(start) - horizon # the last row whose label ended before this refit 

70 if cut <= 0: 

71 continue 

72 rows = stack[:cut] 

73 target = label.to_numpy(dtype=float)[:cut] 

74 x, y = rows.reshape(-1, len(names)), target.reshape(-1) 

75 keep = np.isfinite(y) & np.isfinite(x).all(axis=1) 

76 if keep.sum() < 500: 

77 continue 

78 model = fit() if fit else HistGradientBoostingRegressor(**PARAMETERS) 

79 model.fit(x[keep], y[keep]) 

80 first = sessions.index(start) 

81 last = sessions.index(end) if end else len(sessions) 

82 block = stack[first:last] 

83 flat = block.reshape(-1, len(names)) 

84 ok = np.isfinite(flat).all(axis=1) 

85 predicted = np.full(len(flat), np.nan) 

86 if ok.any(): 

87 predicted[ok] = model.predict(flat[ok]) 

88 scores.iloc[first:last] = predicted.reshape(block.shape[0], block.shape[1]) 

89 return scores 

90 

91 

92def main() -> int: 

93 from evaluation.research_cells import CELLS 

94 from evaluation.wide_context import crypto_cell 

95 

96 base = json.loads((ROOT / "config.json").read_text(encoding="utf-8")) 

97 cell = crypto_cell(ROOT, base, "CS") 

98 if cell.cell.name != "CS" or cell.cell.end != CELLS["CS"].end: 

99 raise SystemExit("x13 reads cell CS only") 

100 known = cell.context.panel.known 

101 features = feature_tables(known, cell.features["quote_volume"], cell.member, cell.tables) 

102 scores = walk_forward(features, label_rank(known, cell.member), known.index) 

103 scores = scores[scores.index <= cell.cell.end].where(cell.member) 

104 frame = scores.stack().rename("score").reset_index() 

105 frame.columns = ["date", "ticker", "score"] 

106 OUTPUT.parent.mkdir(parents=True, exist_ok=True) 

107 frame.to_csv(OUTPUT, index=False, lineterminator="\n", float_format="%.10g") 

108 print(f"wrote {OUTPUT}: {len(frame)} rows, {frame['date'].nunique()} sessions, refits {len(refit_dates(known.index))}") 

109 return 0 

110 

111 

112if __name__ == "__main__": 

113 raise SystemExit(main())