diff --git a/cb_backtest.py b/cb_backtest.py new file mode 100644 index 0000000..70abfd9 --- /dev/null +++ b/cb_backtest.py @@ -0,0 +1,380 @@ +""" +Backtest circuit breaker on historical data. + +Compare: + A) Baseline: ATR + Trailing stop (no circuit breaker) + B) CB: same + circuit breaker (ATR spike + DD protection + position cap) + +Tests on all 4 assets with daily data. +""" + +from __future__ import annotations + +import time +import warnings + +import numpy as np +import torch +import torch.nn as nn +import yfinance as yf + +from models import EnhancedRemizovNet + +warnings.filterwarnings("ignore") + +WINDOW_SIZE = 64 +N_STEPS = 20 +TOTAL_TIME = 0.5 +EPOCHS = 200 +FINETUNE_EPOCHS = 50 +LR = 3e-3 +SHIFT = 7 +K = 2 +CORR_THRESH = 0.5 + +INITIAL_EQUITY = 10000.0 +RISK_PER_TRADE = 0.02 +COMMISSION = 0.001 + +# Circuit breaker params +CB_ATR_RATIO = 3.0 +CB_ATR_RESET = 2.0 +CB_MAX_DD = 0.20 +CB_DD_RESET = 0.10 +CB_MAX_POS_PCT = 0.30 + + +def create_model(): + return EnhancedRemizovNet( + grid_size=WINDOW_SIZE, n_steps=N_STEPS, total_time=TOTAL_TIME, + dx=1.0 / WINDOW_SIZE, use_sde=True, + ) + + +def train_model(model, windows, targets, epochs): + g = torch.tensor(windows, dtype=torch.float32) + y = torch.tensor(targets, dtype=torch.float32) + opt = torch.optim.Adam(model.parameters(), lr=LR, weight_decay=1e-4) + crit = nn.MSELoss() + bs = min(64, len(windows)) + for _ in range(epochs): + model.train() + perm = torch.randperm(len(g)) + for i in range(0, len(g), bs): + idx = perm[i:i + bs] + opt.zero_grad() + loss = crit(model(g[idx], stochastic=True), y[idx]) + loss.backward() + torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) + opt.step() + + +def predict(model, norm_input): + model.eval() + with torch.no_grad(): + inp = torch.tensor(norm_input, dtype=torch.float32).unsqueeze(0) + return model(inp, stochastic=False).squeeze(0).numpy() + + +def fetch_data(ticker): + hist = yf.Ticker(ticker).history(period="max", interval="1d") + if hist.empty: + return None, None + close = hist["Close"].dropna().values.astype(np.float64) + dates = [d.date() if hasattr(d, 'date') else d for d in hist["Close"].dropna().index] + return close, dates + + +def prepare_data(prices): + data = [] + n = len(prices) + for t in range(WINDOW_SIZE, n - SHIFT, SHIFT): + w = prices[t - WINDOW_SIZE:t].copy() + future = prices[t:t + SHIFT].copy() + if len(future) < SHIFT: + continue + mu, std = w.mean(), w.std() + if std < 1e-10: + continue + s = prices[t - WINDOW_SIZE + SHIFT:t + SHIFT].copy() + data.append({ + "future_prices": future, + "norm_input": (w - mu) / std, + "norm_target": (s - mu) / std, + "mu": mu, "std": std, + "price_idx": t, + }) + return data + + +def compute_atr(prices, idx, period=14): + if idx < period + 1: + return prices[idx] * 0.02 + trs = [abs(prices[i] - prices[i - 1]) for i in range(idx - period, idx)] + return np.mean(trs) if trs else prices[idx] * 0.02 + + +def run_backtest(prices, dates, data, use_cb=False): + """Run backtest with optional circuit breaker.""" + train_size = min(80, len(data) - 10) + if train_size < 20: + return {"trades": [], "n_windows": len(data), "cb_events": []} + + torch.manual_seed(42) + np.random.seed(42) + model = create_model() + windows = np.array([d["norm_input"] for d in data[:train_size]]) + targets = np.array([d["norm_target"] for d in data[:train_size]]) + train_model(model, windows, targets, EPOCHS) + + equity = INITIAL_EQUITY + peak_equity = INITIAL_EQUITY + trades = [] + retrain_ctr = 0 + cb_active = False + cb_events = [] + cb_skipped = 0 + + for i in range(train_size, len(data)): + d = data[i] + pidx = d["price_idx"] + + # Circuit breaker check + if use_cb: + atr14 = compute_atr(prices, pidx, period=14) + atr50 = compute_atr(prices, pidx, period=50) + atr_ratio = atr14 / atr50 if atr50 > 0 else 1.0 + + dd = 1.0 - equity / peak_equity if peak_equity > 0 else 0.0 + + was_active = cb_active + + if not cb_active: + if atr_ratio > CB_ATR_RATIO: + cb_active = True + cb_events.append({ + "idx": i, "date": dates[min(pidx, len(dates) - 1)], + "action": "ON", "reason": "atr_spike", + "ratio": round(atr_ratio, 2), + }) + elif dd > CB_MAX_DD: + cb_active = True + cb_events.append({ + "idx": i, "date": dates[min(pidx, len(dates) - 1)], + "action": "ON", "reason": "drawdown", + "dd_pct": round(dd * 100, 1), + }) + else: + # Check if we can deactivate + if atr_ratio < CB_ATR_RESET and dd < CB_DD_RESET: + cb_active = False + cb_events.append({ + "idx": i, "date": dates[min(pidx, len(dates) - 1)], + "action": "OFF", + }) + + if cb_active: + cb_skipped += 1 + retrain_ctr += 1 + if retrain_ctr >= 10: + ws = np.array([dd2["norm_input"] for dd2 in data[:i + 1]]) + ts = np.array([dd2["norm_target"] for dd2 in data[:i + 1]]) + train_model(model, ws, ts, FINETUNE_EPOCHS) + retrain_ctr = 0 + continue + + pred = predict(model, d["norm_input"]) + pred_new = pred[-SHIFT:] + pred_confirm = pred_new[:K] + + if len(pred_confirm) < 2: + continue + + actual_norm = (d["future_prices"][:K] - d["mu"]) / d["std"] + corr = np.corrcoef(pred_confirm, actual_norm)[0, 1] + + if np.isnan(corr) or corr < CORR_THRESH: + retrain_ctr += 1 + if retrain_ctr >= 10: + ws = np.array([dd2["norm_input"] for dd2 in data[:i + 1]]) + ts = np.array([dd2["norm_target"] for dd2 in data[:i + 1]]) + train_model(model, ws, ts, FINETUNE_EPOCHS) + retrain_ctr = 0 + continue + + entry_price = d["future_prices"][K - 1] + pred_direction = pred_new[-1] - pred_new[K - 1] + if abs(pred_direction) < 1e-10: + continue + direction = 1 if pred_direction > 0 else -1 + + # ATR stop + atr = compute_atr(prices, pidx) + stop_dist = max(atr * 2.0, entry_price * 0.005) + + risk_amount = equity * RISK_PER_TRADE + pos_size = risk_amount / stop_dist + pos_value = pos_size * entry_price + + # Position cap + if use_cb: + max_pos = equity * CB_MAX_POS_PCT + if pos_value > max_pos: + pos_size = max_pos / entry_price + pos_value = max_pos + else: + if pos_value > equity: + pos_size = equity / entry_price + pos_value = equity + + # Trailing stop simulation + exit_price = d["future_prices"][-1] + stopped = False + best_price = entry_price + for hp in d["future_prices"][K:]: + if direction == 1: + best_price = max(best_price, hp) + if hp <= best_price - stop_dist: + exit_price = best_price - stop_dist + stopped = True + break + else: + best_price = min(best_price, hp) + if hp >= best_price + stop_dist: + exit_price = best_price + stop_dist + stopped = True + break + + pnl_gross = pos_size * (exit_price - entry_price) * direction + commission_cost = pos_value * COMMISSION * 2 + pnl_net = pnl_gross - commission_cost + equity += pnl_net + peak_equity = max(peak_equity, equity) + + trade_date = dates[min(pidx, len(dates) - 1)] + trades.append({ + "date": trade_date, + "pnl_pct": pnl_net / pos_value * 100 if pos_value > 0 else 0, + "pnl_net": pnl_net, + "win": pnl_net > 0, + "stopped": stopped, + "equity": equity, + }) + + retrain_ctr += 1 + if retrain_ctr >= 10: + ws = np.array([dd2["norm_input"] for dd2 in data[:i + 1]]) + ts = np.array([dd2["norm_target"] for dd2 in data[:i + 1]]) + train_model(model, ws, ts, FINETUNE_EPOCHS) + retrain_ctr = 0 + + return { + "trades": trades, "n_windows": len(data), + "cb_events": cb_events, "cb_skipped": cb_skipped, + } + + +def print_result(trades, label, n_windows, cb_skipped=0): + if not trades: + print(f" {label:<35s} win={n_windows:>5d} skip={cb_skipped:>3d} NO TRADES") + return + + n = len(trades) + wins = sum(1 for t in trades if t["win"]) + final_eq = trades[-1]["equity"] + total_ret = (final_eq / INITIAL_EQUITY - 1) * 100 + wr = wins / n * 100 + + peak = INITIAL_EQUITY + max_dd = 0 + for t in trades: + peak = max(peak, t["equity"]) + dd = (t["equity"] - peak) / peak + max_dd = min(max_dd, dd) + + trade_rets = [t["pnl_pct"] / 100 for t in trades] + first = trades[0]["date"] + last = trades[-1]["date"] + if hasattr(first, 'date'): + first = first.date() + if hasattr(last, 'date'): + last = last.date() + days = (last - first).days + years = days / 365.25 if days > 0 else 1 + tpy = n / years + + if len(trade_rets) > 2 and np.std(trade_rets) > 0: + sharpe = np.mean(trade_rets) / np.std(trade_rets) * np.sqrt(tpy) + else: + sharpe = 0 + + stopped = sum(1 for t in trades if t["stopped"]) + monthly_pnl = sum(t["pnl_net"] for t in trades) / max(years * 12, 1) + + print(f" {label:<35s} win={n_windows:>5d} N={n:>4d} WR={wr:>4.0f}% " + f"Ret={total_ret:>+7.1f}% Sharpe={sharpe:>+5.2f} DD={max_dd*100:>+5.1f}% " + f"skip={cb_skipped:>3d} $/mo={monthly_pnl:>+7.0f} Eq=${final_eq:>9,.0f}") + + +def main(): + t0 = time.time() + + print("=" * 120) + print("CIRCUIT BREAKER BACKTEST") + print("=" * 120) + print(f" CB params: ATR spike > {CB_ATR_RATIO}x (reset < {CB_ATR_RESET}x), " + f"DD > {CB_MAX_DD*100:.0f}% (reset < {CB_DD_RESET*100:.0f}%), " + f"max pos {CB_MAX_POS_PCT*100:.0f}%") + print() + + assets = ["BTC-USD", "ETH-USD", "SOL-USD", "BNB-USD"] + + for asset in assets: + print(f"\n{'=' * 120}") + print(f" {asset}") + print(f"{'=' * 120}") + + print(" Fetching data...", end=" ", flush=True) + prices, dates = fetch_data(asset) + if prices is None: + print("ERROR") + continue + print(f"{len(prices)} bars") + + data = prepare_data(prices) + + # A) Baseline + print(" A) Baseline...", end=" ", flush=True) + r_base = run_backtest(prices, dates, data, use_cb=False) + print("done") + print_result(r_base["trades"], "A) Baseline", r_base["n_windows"]) + + # B) With circuit breaker + print(" B) Circuit breaker...", end=" ", flush=True) + r_cb = run_backtest(prices, dates, data, use_cb=True) + print("done") + print_result(r_cb["trades"], "B) + Circuit breaker", + r_cb["n_windows"], r_cb.get("cb_skipped", 0)) + + # Show CB events + if r_cb["cb_events"]: + print(f"\n Circuit breaker events ({len(r_cb['cb_events'])}):") + for ev in r_cb["cb_events"]: + if ev["action"] == "ON": + reason = ev.get("reason", "?") + detail = "" + if "ratio" in ev: + detail = f" (ATR ratio={ev['ratio']})" + elif "dd_pct" in ev: + detail = f" (DD={ev['dd_pct']}%)" + print(f" {ev['date']} CB ON — {reason}{detail}") + else: + print(f" {ev['date']} CB OFF") + + elapsed = time.time() - t0 + print(f"\n\nCompleted in {elapsed:.0f}s") + print("=" * 120) + + +if __name__ == "__main__": + main()