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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""ML overlay on the PASSing Donchian long-only trend strategy.
|
| 2 |
+
|
| 3 |
+
Design (leakage-controlled):
|
| 4 |
+
- Features at day t use ONLY data through t-1.
|
| 5 |
+
- Target: next-20d return > 0 (binary), label window [t, t+20].
|
| 6 |
+
- Walk-forward: expanding train window, refit every 60 days,
|
| 7 |
+
PURGE = 20 days gap between train end and t (label horizon).
|
| 8 |
+
- Position = Donchian20_long_only signal (0/1) MODULATED by the model:
|
| 9 |
+
filter : position = donch if p > 0.5 else 0
|
| 10 |
+
scale : position = donch * clip(2*(p-0.25), 0, 1)
|
| 11 |
+
- Model: HistGradientBoostingClassifier (sklearn), tiny configs only.
|
| 12 |
+
|
| 13 |
+
Every ML variant is a counted trial. The verdict is the ML variant's
|
| 14 |
+
purged-CPCV OOS Sharpe vs the Donchian baseline's (1.48 from sweep2).
|
| 15 |
+
"""
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import json
|
| 19 |
+
import sys
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
import pandas as pd
|
| 24 |
+
from sklearn.ensemble import HistGradientBoostingClassifier
|
| 25 |
+
|
| 26 |
+
from crypto_eval.engine2 import run_panel_backtest
|
| 27 |
+
from crypto_eval.grid2 import donchian_panel
|
| 28 |
+
from crypto_eval.cv import make_cpcv
|
| 29 |
+
from crypto_eval.stats import eval_backtest
|
| 30 |
+
|
| 31 |
+
ADV = {"BTC": 20e9, "ETH": 10e9, "LTC": 1e9, "XRP": 1.5e9,
|
| 32 |
+
"ADA": 0.5e9, "DOGE": 1e9, "ETC": 0.3e9, "DASH": 0.1e9}
|
| 33 |
+
|
| 34 |
+
TARGET_HORIZON = 20
|
| 35 |
+
REFIT_EVERY = 60
|
| 36 |
+
MIN_TRAIN = 750
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def build_features(panel: pd.DataFrame) -> pd.DataFrame:
|
| 40 |
+
"""Feature rows indexed by decision date t; all inputs end at t-1."""
|
| 41 |
+
c = panel.shift(1) # data through t-1
|
| 42 |
+
ret = c.pct_change()
|
| 43 |
+
feats = {}
|
| 44 |
+
for lb in (10, 20, 50, 100):
|
| 45 |
+
feats[f"mom_{lb}"] = c / c.shift(lb) - 1
|
| 46 |
+
feats["vol_20"] = ret.rolling(20).std() * np.sqrt(365)
|
| 47 |
+
feats["vol_60"] = ret.rolling(60).std() * np.sqrt(365)
|
| 48 |
+
feats["ma_dist_100"] = c / c.rolling(100).mean() - 1
|
| 49 |
+
feats["donch_rank"] = c / c.rolling(20).max() # near-high vs not
|
| 50 |
+
X = pd.concat(feats, axis=1) # MultiIndex columns: (feature, symbol)
|
| 51 |
+
return X
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def build_target(panel: pd.DataFrame) -> pd.Series:
|
| 55 |
+
"""next-20d return > 0, indexed by decision date t (label window
|
| 56 |
+
[t, t+20]; consumers must not train on rows within 20d of t)."""
|
| 57 |
+
fwd = panel.shift(-TARGET_HORIZON) / panel - 1
|
| 58 |
+
return (fwd["ETH"] > 0).astype(float)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def walk_forward_positions(panel: pd.DataFrame, X: pd.DataFrame,
|
| 62 |
+
y: pd.Series, sym: str, mode: str, depth: int,
|
| 63 |
+
lr: float) -> pd.Series:
|
| 64 |
+
"""Walk-forward predictions -> position series on the asset's index."""
|
| 65 |
+
idx = X.index
|
| 66 |
+
donch = donchian_panel(panel[[sym]], window=20, long_only=True)[sym]
|
| 67 |
+
pos = pd.Series(0.0, index=idx)
|
| 68 |
+
y_arr = y.reindex(idx).to_numpy()
|
| 69 |
+
X_sym = X.xs(sym, axis=1, level=1)
|
| 70 |
+
valid = X_sym.notna().all(axis=1) & ~np.isnan(y_arr)
|
| 71 |
+
|
| 72 |
+
for start in range(MIN_TRAIN, len(idx) - 1, REFIT_EVERY):
|
| 73 |
+
train_end = start - TARGET_HORIZON # purge: labels end before t
|
| 74 |
+
tr = np.where(valid.to_numpy()[:train_end])[0]
|
| 75 |
+
if len(tr) < MIN_TRAIN:
|
| 76 |
+
continue
|
| 77 |
+
model = HistGradientBoostingClassifier(
|
| 78 |
+
max_depth=depth, learning_rate=lr, max_iter=150, random_state=0)
|
| 79 |
+
model.fit(X_sym.to_numpy()[:train_end][tr], y_arr[:train_end][tr])
|
| 80 |
+
# predict one refit window at a time
|
| 81 |
+
end = min(start + REFIT_EVERY, len(idx) - 1)
|
| 82 |
+
p = model.predict_proba(X_sym.to_numpy()[start:end])[:, 1]
|
| 83 |
+
for j, t in enumerate(range(start, end)):
|
| 84 |
+
if not valid.iloc[t]:
|
| 85 |
+
continue
|
| 86 |
+
d = donch.iloc[t]
|
| 87 |
+
if mode == "filter":
|
| 88 |
+
pos.iloc[t] = d if p[j] > 0.5 else 0.0
|
| 89 |
+
else: # scale
|
| 90 |
+
pos.iloc[t] = d * float(np.clip(2.0 * (p[j] - 0.25), 0.0, 1.0))
|
| 91 |
+
# leading rows before first refit: plain donch (documented: warmup)
|
| 92 |
+
pos.iloc[:MIN_TRAIN] = donch.iloc[:MIN_TRAIN]
|
| 93 |
+
return pos
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def main() -> int:
|
| 97 |
+
panel = pd.read_parquet("/tmp/data/panel_daily_close.parquet")
|
| 98 |
+
panel.index = pd.to_datetime(panel.index, utc=True)
|
| 99 |
+
panel = panel.sort_index()["2016-01-01":] # ML needs longer warmup
|
| 100 |
+
eth = panel[["ETH"]]
|
| 101 |
+
print(f"[ml] panel {panel.shape[0]} days from {panel.index[0].date()}",
|
| 102 |
+
flush=True)
|
| 103 |
+
|
| 104 |
+
X = build_features(eth)
|
| 105 |
+
y = build_target(eth)
|
| 106 |
+
|
| 107 |
+
baseline_pos = donchian_panel(eth, window=20, long_only=True)
|
| 108 |
+
results = {}
|
| 109 |
+
|
| 110 |
+
variants = [
|
| 111 |
+
("ml_filter_d2_lr005", "filter", 2, 0.05),
|
| 112 |
+
("ml_filter_d3_lr005", "filter", 3, 0.05),
|
| 113 |
+
("ml_scale_d2_lr005", "scale", 2, 0.05),
|
| 114 |
+
("ml_scale_d3_lr01", "scale", 3, 0.10),
|
| 115 |
+
]
|
| 116 |
+
for name, mode, depth, lr in variants:
|
| 117 |
+
print(f"[ml] {name}: walk-forward refit ...", flush=True)
|
| 118 |
+
pos = walk_forward_positions(eth, X, y, "ETH", mode, depth, lr)
|
| 119 |
+
pos_df = pos.to_frame(name="ETH")
|
| 120 |
+
bt = run_panel_backtest(eth, pos_df, {"ETH": ADV["ETH"]})
|
| 121 |
+
rets = bt["portfolio_return"].to_numpy()
|
| 122 |
+
_, combos, audit = make_cpcv(bt["portfolio_return"].index,
|
| 123 |
+
horizon=1, embargo=5, freq="1D")
|
| 124 |
+
assert audit.ok
|
| 125 |
+
oos = [eval_backtest(rets[t], n_trials=1, trial_sr_variance=0.0,
|
| 126 |
+
periods_per_year=365) for _, t in combos]
|
| 127 |
+
srs = [c["sharpe_annualized"] for c in oos]
|
| 128 |
+
full_sr = float(np.nanmean(rets) / (np.nanstd(rets, ddof=1) + 1e-12)
|
| 129 |
+
* np.sqrt(365))
|
| 130 |
+
results[name] = {
|
| 131 |
+
"full_sample_sr": full_sr,
|
| 132 |
+
"oos_mean_sr": float(np.mean(srs)),
|
| 133 |
+
"oos_combos_positive": int(sum(1 for s in srs if s > 0)),
|
| 134 |
+
"turnover_pct_exposure": float(pos.mean()),
|
| 135 |
+
}
|
| 136 |
+
print(f"[ml] {name}: full {full_sr:.2f} OOS {np.mean(srs):.2f} "
|
| 137 |
+
f"({results[name]['oos_combos_positive']}/15)",
|
| 138 |
+
flush=True)
|
| 139 |
+
|
| 140 |
+
# baseline on the same window for a fair comparison
|
| 141 |
+
bt = run_panel_backtest(eth, baseline_pos, {"ETH": ADV["ETH"]})
|
| 142 |
+
rets = bt["portfolio_return"].to_numpy()
|
| 143 |
+
_, combos, _ = make_cpcv(bt["portfolio_return"].index, horizon=1,
|
| 144 |
+
embargo=5, freq="1D")
|
| 145 |
+
oos = [eval_backtest(rets[t], n_trials=1, trial_sr_variance=0.0,
|
| 146 |
+
periods_per_year=365) for _, t in combos]
|
| 147 |
+
srs = [c["sharpe_annualized"] for c in oos]
|
| 148 |
+
results["baseline_donch20_no_ml"] = {
|
| 149 |
+
"full_sample_sr": float(np.nanmean(rets) / np.nanstd(rets, ddof=1)
|
| 150 |
+
* np.sqrt(365)),
|
| 151 |
+
"oos_mean_sr": float(np.mean(srs)),
|
| 152 |
+
"oos_combos_positive": int(sum(1 for s in srs if s > 0)),
|
| 153 |
+
"turnover_pct_exposure": float(baseline_pos["ETH"].mean()),
|
| 154 |
+
}
|
| 155 |
+
print(f"[ml] baseline: {results['baseline_donch20_no_ml']}", flush=True)
|
| 156 |
+
|
| 157 |
+
Path("/tmp/ml_report.json").write_text(json.dumps(results, indent=2))
|
| 158 |
+
print("[ml] done", flush=True)
|
| 159 |
+
return 0
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
if __name__ == "__main__":
|
| 163 |
+
sys.exit(main())
|