"""Exp26: Ablation study — isolated factor contributions on single asset. ADA-USD only. Baseline = naked Remizov formula (predict → direction → enter). Part 1: ON/OFF toggles (each factor individually on top of baseline) Part 2: Parameter sweeps (one param varied at a time) """ import copy import sys from pathlib import Path from dataclasses import dataclass sys.path.insert(0, str(Path(__file__).parent.parent.parent / "src")) sys.path.insert(0, str(Path(__file__).parent.parent)) import numpy as np import pandas as pd import torch import backtrader as bt from remizov_trader.core import model as model_mod, signals, risk from remizov_trader.core.net import EnhancedRemizovNet from remizov_trader.config import ModelConfig from common.metrics import save_results from common.dataset import load_or_fetch # --- Single asset: ADA-USD --- TICKER = "ADA-USD" TF = "4h" TF_HOURS = 4 TOTAL_CAPITAL = 254.0 TRAIN_RATIO = 0.3 # Bybit margin constants CVR = 0.90 SPOT_IM_PCT = 0.05 INTEREST_RATE_DAILY = 0.0002 COMMISSION_PCT = 0.001 MARKET_ORDER_BUFFER = 0.02 # ADA defaults DEF_WS, DEF_K, DEF_SHIFT = 64, 3, 7 DEF_LEV, DEF_EPOCHS = 2, 200 DEF_STOP_MULT, DEF_CORR_THRESH = 2.0, 0.5 @dataclass class Cfg: """All toggles and params for a single run.""" label: str # ON/OFF toggles (baseline = all off) shape_confirm: bool = False min_confidence: float = 0.0 retrain_mode: str = "off" regime_adaptive: bool = False cooldown_bars: int = 0 adaptive_corr: bool = False trailing_stop: bool = False stop_scale: float = 1.0 # Model / data params ws: int = DEF_WS K: int = DEF_K shift: int = DEF_SHIFT leverage: int = DEF_LEV epochs: int = DEF_EPOCHS stop_mult: float = DEF_STOP_MULT corr_thresh: float = DEF_CORR_THRESH # ══════════════════════════════════════════════ # Part 1: ON/OFF (trailing_stop is CORE, always on in baseline) # ══════════════════════════════════════════════ ONOFF = [ Cfg("baseline", trailing_stop=True), Cfg("+shape_confirm", trailing_stop=True, shape_confirm=True), Cfg("+confidence>=1.5", trailing_stop=True, min_confidence=1.5), Cfg("+retrain_losses", trailing_stop=True, retrain_mode="losses_only"), Cfg("+regime_adaptive", trailing_stop=True, regime_adaptive=True), Cfg("+cooldown=7", trailing_stop=True, cooldown_bars=7), Cfg("+adaptive_corr", trailing_stop=True, adaptive_corr=True, shape_confirm=True), Cfg("+stop_scale=0.5", trailing_stop=True, stop_scale=0.5), Cfg("-trailing_stop", trailing_stop=False), # ablation: what if we REMOVE it ] # ══════════════════════════════════════════════ # Part 2: Parameter sweeps (all with trailing_stop=True) # ══════════════════════════════════════════════ SWEEPS = [] for v in [32, 48, 96, 128]: SWEEPS.append(Cfg(f"ws={v}", trailing_stop=True, ws=v)) for v in [2, 4, 5]: SWEEPS.append(Cfg(f"K={v}", trailing_stop=True, K=v)) for v in [3, 5, 10, 14]: # shift=3 + K=3 → 0 trades (direction always None) SWEEPS.append(Cfg(f"shift={v}", trailing_stop=True, shift=v)) for v in [50, 100, 300, 500]: SWEEPS.append(Cfg(f"epochs={v}", trailing_stop=True, epochs=v)) for v in [1, 3]: SWEEPS.append(Cfg(f"leverage={v}", trailing_stop=True, leverage=v)) for v in [1.0, 1.5, 2.5, 3.0]: SWEEPS.append(Cfg(f"stop_mult={v}", trailing_stop=True, stop_mult=v)) for v in [0.2, 0.3, 0.4, 0.6, 0.7]: SWEEPS.append(Cfg(f"corr>={v}", trailing_stop=True, shape_confirm=True, corr_thresh=v)) for v in [0.5, 1.0, 2.0, 2.5, 3.0]: SWEEPS.append(Cfg(f"conf>={v}", trailing_stop=True, min_confidence=v)) # ══════════════════════════════════════════════ # Part 3: Key combinations (progressive build-up) # ══════════════════════════════════════════════ COMBOS = [ Cfg("trail+cool", trailing_stop=True, cooldown_bars=7), Cfg("trail+cool+shape", trailing_stop=True, cooldown_bars=7, shape_confirm=True), Cfg("trail+cool+conf1.5", trailing_stop=True, cooldown_bars=7, min_confidence=1.5), Cfg("trail+cool+conf+shape", trailing_stop=True, cooldown_bars=7, min_confidence=1.5, shape_confirm=True), Cfg("trail+cool+conf+sh+reg", trailing_stop=True, cooldown_bars=7, min_confidence=1.5, shape_confirm=True, regime_adaptive=True), Cfg("trail+cool+conf+sh+re+rt", trailing_stop=True, cooldown_bars=7, min_confidence=1.5, shape_confirm=True, regime_adaptive=True, retrain_mode="losses_only"), Cfg("PROD_LIKE", trailing_stop=True, cooldown_bars=7, min_confidence=1.5, shape_confirm=True, regime_adaptive=True, retrain_mode="losses_only", adaptive_corr=True, stop_scale=0.5), ] ALL = ONOFF + SWEEPS + COMBOS # ══════════════════════════════════════════════ # Strategy # ══════════════════════════════════════════════ @dataclass class Pos: direction: int; entry_price: float; entry_bar: int stop_price: float; stop_dist: float; best_price: float pos_size: float; pos_value: float margin_locked: float; borrowed: float class AblationStrategy(bt.Strategy): params = (('cfg', None), ('meta', None)) def __init__(self): self.free_usdc = TOTAL_CAPITAL self.pos = None self.last_stop_bar = -999 self.wins = 0 self.trades_count = 0 self.consec_losses = 0 self.last_regime = "normal" self.trades_list = [] self.skip = {"cooldown": 0, "corr": 0, "short": 0, "low_conf": 0, "margin": 0, "retrain": 0} self.peak_eq = TOTAL_CAPITAL self.max_dd = 0.0 self._prev_len = 0 def prenext(self): self.next() def next(self): cur_len = len(self.data) if cur_len == self._prev_len: return self._prev_len = cur_len bar = cur_len - 1 meta = self.p.meta if bar < meta["test_start"]: return price = float(self.data.close[0]) if self.pos is not None: self._check_stop(bar, price) if bar in meta["signal_bars"]: self._maybe_retrain(bar) if self.pos is None: self._check_signal(bar, price) def _check_stop(self, bar, price): cfg, pos = self.p.cfg, self.pos if cfg.trailing_stop: pos.best_price, pos.stop_price = risk.update_trailing_stop( price, pos.best_price, pos.stop_price, pos.stop_dist, pos.direction) if not risk.is_stopped(price, pos.stop_price, pos.direction): return bars_held = bar - pos.entry_bar pnl_gross = pos.pos_size * (price - pos.entry_price) * pos.direction commission = pos.pos_value * COMMISSION_PCT * 2 interest = pos.borrowed * INTEREST_RATE_DAILY * bars_held * TF_HOURS / 24 pnl = pnl_gross - commission - interest self.free_usdc += pos.margin_locked + pnl self.pos = None self.last_stop_bar = bar self.trades_list.append({"pnl_net": pnl, "bars_held": bars_held, "equity_at_entry": pos.margin_locked}) self.trades_count += 1 if pnl > 0: self.wins += 1; self.consec_losses = 0 else: self.consec_losses += 1 eq = self.free_usdc self.peak_eq = max(self.peak_eq, eq) dd = (self.peak_eq - eq) / self.peak_eq if self.peak_eq > 0 else 0 self.max_dd = max(self.max_dd, dd) def _maybe_retrain(self, bar): cfg = self.p.cfg if cfg.retrain_mode == "off": return if self.consec_losses < 3: return meta = self.p.meta data = signals.prepare_windows(meta["prices"][:bar + 1], cfg.ws, cfg.shift) if len(data) >= 20: recent = data[-200:] w = np.array([d["norm_input"] for d in recent]) t = np.array([d["norm_target"] for d in recent]) model_mod.train(meta["model"], w, t, epochs=20, lr=0.003 * 0.3) self.consec_losses = 0 self.skip["retrain"] += 1 def _check_signal(self, bar, price): cfg = self.p.cfg meta = self.p.meta prices = meta["prices"] ws, K, shift = cfg.ws, cfg.K, cfg.shift if bar < ws + K: return # Cooldown if cfg.cooldown_bars > 0 and bar - self.last_stop_bar < cfg.cooldown_bars: self.skip["cooldown"] += 1 return # Predict w = prices[bar - ws - K: bar - K].copy() confirm = prices[bar - K: bar].copy() mu, std = w.mean(), w.std() if std < 1e-10: return pred = model_mod.predict(meta["model"], (w - mu) / std) pred_new = pred[-shift:] # Stop mult (regime adaptive or fixed) if cfg.regime_adaptive: _, stop_m = risk.regime_adaptive_params(prices, bar, K) else: stop_m = cfg.stop_mult # Shape confirmation (always compute corr for confidence) ct = cfg.corr_thresh if cfg.adaptive_corr: ct = risk.adaptive_corr_threshold(ct, self.wins, self.trades_count) corr, confirmed = signals.check_shape_confirmation( pred_new, confirm, mu, std, K, ct) if cfg.shape_confirm and not confirmed: self.skip["corr"] += 1 return # Confidence filter atr = risk.compute_atr(prices, bar) if cfg.min_confidence > 0 and atr > 0: pred_denorm = pred_new * std + mu amp = float(np.max(pred_denorm) - np.min(pred_denorm)) conf = abs(corr) * (amp / atr) if conf < cfg.min_confidence: self.skip["low_conf"] += 1 return # Direction (long only) direction = signals.get_direction(pred_new, K) if direction is None: return if direction == -1: self.skip["short"] += 1 return # Position sizing eq = self.free_usdc if eq <= 5: return lev = cfg.leverage freeze_rate = 1 / lev + (1 - CVR) + (1 - 1 / lev) * SPOT_IM_PCT + MARKET_ORDER_BUFFER pos_value = min(eq * lev, eq / freeze_rate) if pos_value < 5: self.skip["margin"] += 1 return margin = pos_value / lev borrowed = pos_value - margin stop_dist = max(atr * stop_m * cfg.stop_scale, price * 0.005) self.free_usdc -= margin self.pos = Pos( direction=direction, entry_price=price, entry_bar=bar, stop_price=price - direction * stop_dist, stop_dist=stop_dist, best_price=price, pos_size=pos_value / price, pos_value=pos_value, margin_locked=margin, borrowed=borrowed, ) def stop(self): if self.pos is None: return meta = self.p.meta last_bar = meta["last_test_bar"] last_price = float(meta["prices"][last_bar]) pos = self.pos bars_held = last_bar - pos.entry_bar pnl = (pos.pos_size * (last_price - pos.entry_price) * pos.direction - pos.pos_value * COMMISSION_PCT * 2 - pos.borrowed * INTEREST_RATE_DAILY * bars_held * TF_HOURS / 24) self.free_usdc += pos.margin_locked + pnl self.trades_list.append({"pnl_net": pnl, "bars_held": bars_held, "equity_at_entry": pos.margin_locked}) # ══════════════════════════════════════════════ # Runner # ══════════════════════════════════════════════ _model_cache = {} # (ws, shift, epochs) → (model, data, n_train) def _get_or_train(prices, ws, shift, epochs): key = (ws, shift, epochs) if key not in _model_cache: data = signals.prepare_windows(prices, ws, shift) n_train = max(int(len(data) * TRAIN_RATIO), 20) torch.manual_seed(42); np.random.seed(42) mdl = EnhancedRemizovNet(grid_size=ws, n_steps=20, total_time=0.5, dx=1.0 / ws, use_sde=True) model_mod.train(mdl, np.array([d["norm_input"] for d in data[:n_train]]), np.array([d["norm_target"] for d in data[:n_train]]), epochs, 0.003) _model_cache[key] = (mdl, data, n_train) return _model_cache[key] def _run(cfg: Cfg, prices, df): mdl_orig, data, n_train = _get_or_train(prices, cfg.ws, cfg.shift, cfg.epochs) test_data = data[n_train:] if not test_data: return {"label": cfg.label, "total_pnl": 0, "sharpe": 0, "max_dd": 0, "trades": 0, "wr": 0, "retrains": 0, "skipped": {}} meta = { "model": copy.deepcopy(mdl_orig), "prices": prices, "test_start": test_data[0]["price_idx"], "last_test_bar": test_data[-1]["price_idx"], "signal_bars": {d["price_idx"] for d in test_data}, } cerebro = bt.Cerebro() cerebro.broker.setcash(1_000_000) cerebro.broker.setcommission(commission=0) cerebro.adddata(bt.feeds.PandasData(dataname=df), name=TICKER) cerebro.addstrategy(AblationStrategy, cfg=cfg, meta=meta) strat = cerebro.run()[0] trades = strat.trades_list n = len(trades) total_pnl = strat.free_usdc - TOTAL_CAPITAL wins = sum(1 for t in trades if t["pnl_net"] > 0) sharpe = 0.0 if n >= 2: rets = np.array([t["pnl_net"] / t["equity_at_entry"] for t in trades if t["equity_at_entry"] > 0]) if len(rets) >= 2 and np.std(rets) > 0: test_bars = meta["last_test_bar"] - meta["test_start"] test_years = max(test_bars * TF_HOURS / 8766, 0.1) sharpe = float(np.mean(rets) / np.std(rets) * np.sqrt(n / test_years)) return { "label": cfg.label, "total_pnl": round(total_pnl, 2), "sharpe": round(sharpe, 2), "max_dd": round(strat.max_dd * 100, 1), "trades": n, "wins": wins, "wr": round(wins / n * 100, 1) if n else 0, "retrains": strat.skip.get("retrain", 0), "skipped": dict(strat.skip), } def main(): results_dir = Path(__file__).parent / "results" print("=" * 75) print("EXP26: ABLATION STUDY — ADA-USD (single asset)") print("=" * 75) print(f"Capital=${TOTAL_CAPITAL} | Baseline: Remizov + trailing stop (core mechanics)") print(f"Defaults: ws={DEF_WS} K={DEF_K} shift={DEF_SHIFT} lev={DEF_LEV} " f"ep={DEF_EPOCHS} stop={DEF_STOP_MULT}") print(f"Configs: {len(ONOFF)} ON/OFF + {len(SWEEPS)} sweeps + {len(COMBOS)} combos " f"= {len(ALL)} total\n") dataset = load_or_fetch("default") if TICKER not in dataset: print(f"ERROR: {TICKER} not in dataset"); return d = dataset[TICKER] prices, dates, ohlcv = d["prices"], d["dates"], d.get("ohlcv") if ohlcv is not None and len(ohlcv) == len(prices): df = pd.DataFrame({'open': ohlcv[:, 0], 'high': ohlcv[:, 1], 'low': ohlcv[:, 2], 'close': ohlcv[:, 3], 'volume': 0.0, 'openinterest': 0.0}, index=pd.to_datetime(dates)) else: df = pd.DataFrame({'open': prices, 'high': prices, 'low': prices, 'close': prices, 'volume': 0.0, 'openinterest': 0.0}, index=pd.to_datetime(dates)) print(f"ADA-USD: {len(prices)} bars\n") all_results = [] for i, cfg in enumerate(ALL): print(f" [{i + 1:2d}/{len(ALL)}] {cfg.label:<22s}", end=" ", flush=True) r = _run(cfg, prices, df) all_results.append(r) if r["trades"]: print(f"PnL=${r['total_pnl']:+.0f} Sharpe={r['sharpe']:.2f} " f"DD={r['max_dd']:.1f}% Trades={r['trades']} WR={r['wr']:.1f}%") else: print("NO TRADES") # ── Summary ── bp = all_results[0]["total_pnl"] bs = all_results[0]["sharpe"] print(f"\n{'=' * 75}") print("PART 1: ON/OFF FACTORS") print(f"{'=' * 75}") hdr = f" {'Config':<22s} {'PnL':>7s} {'d PnL':>7s} {'Shrp':>5s} {'dS':>5s} {'DD%':>5s} {'Trds':>5s} {'WR%':>5s}" print(hdr); print(f" {'-' * 70}") for r in all_results[:len(ONOFF)]: dp = r["total_pnl"] - bp ds = r["sharpe"] - bs dps = f"{'':>7s}" if r["label"] == "baseline" else f"${dp:>+6.0f}" dss = f"{'':>5s}" if r["label"] == "baseline" else f"{ds:>+5.2f}" print(f" {r['label']:<22s} ${r['total_pnl']:>+6.0f} {dps} {r['sharpe']:>5.2f} " f"{dss} {r['max_dd']:>4.1f}% {r['trades']:>5d} {r['wr']:>4.1f}%") print(f"\n{'=' * 75}") print("PART 2: PARAMETER SWEEPS") print(f"{'=' * 75}") sweep_end = len(ONOFF) + len(SWEEPS) cur_p = "" for r in all_results[len(ONOFF):sweep_end]: p = r["label"].split("=")[0].rstrip(">") if "=" in r["label"] else r["label"] if p != cur_p: cur_p = p print(f"\n --- {p} ---") print(f" {'Value':<22s} {'PnL':>7s} {'d PnL':>7s} {'Shrp':>5s} {'DD%':>5s} {'Trds':>5s} {'WR%':>5s}") print(f" {'-' * 60}") dp = r["total_pnl"] - bp print(f" {r['label']:<22s} ${r['total_pnl']:>+6.0f} ${dp:>+6.0f} {r['sharpe']:>5.2f} " f"{r['max_dd']:>4.1f}% {r['trades']:>5d} {r['wr']:>4.1f}%") # Part 3: Combinations if len(all_results) > sweep_end: print(f"\n{'=' * 75}") print("PART 3: COMBINATIONS (progressive build-up)") print(f"{'=' * 75}") print(f" {'Config':<26s} {'PnL':>7s} {'Shrp':>5s} {'DD%':>5s} {'Trds':>5s} {'WR%':>5s}") print(f" {'-' * 58}") for r in all_results[sweep_end:]: print(f" {r['label']:<26s} ${r['total_pnl']:>+6.0f} {r['sharpe']:>5.2f} " f"{r['max_dd']:>4.1f}% {r['trades']:>5d} {r['wr']:>4.1f}%") # Top/bottom by Sharpe print(f"\n{'=' * 75}") print("RANKING BY SHARPE") print(f"{'=' * 75}") ranked = sorted(all_results, key=lambda r: r["sharpe"], reverse=True) print(f" {'#':>3s} {'Config':<22s} {'Shrp':>5s} {'PnL':>7s} {'DD%':>5s} {'Trds':>5s} {'WR%':>5s}") print(f" {'-' * 55}") for i, r in enumerate(ranked[:10]): print(f" {i + 1:3d} {r['label']:<22s} {r['sharpe']:>5.2f} ${r['total_pnl']:>+6.0f} " f"{r['max_dd']:>4.1f}% {r['trades']:>5d} {r['wr']:>4.1f}%") print(f" {'...':>3s}") for i, r in enumerate(ranked[-5:], len(ranked) - 4): print(f" {i:3d} {r['label']:<22s} {r['sharpe']:>5.2f} ${r['total_pnl']:>+6.0f} " f"{r['max_dd']:>4.1f}% {r['trades']:>5d} {r['wr']:>4.1f}%") path = save_results({"results": all_results, "baseline": all_results[0]}, results_dir, "exp26_ablation") print(f"\nSaved: {path}") if __name__ == "__main__": main()