Sharpe считался через sqrt(trades_per_year), что завышало метрику в ~2x. Исправлено на daily returns + sqrt(252) во всех бэктест скриптах. Утечка памяти: добавлен del tensors в model.train() и evaluate.py. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
468 lines
16 KiB
Python
468 lines
16 KiB
Python
"""Backtest: compare retrain strategies for RemizovNet.
|
|
|
|
Strategies:
|
|
A) baseline — retrain every 10 signals (current production)
|
|
B) no_retrain — never retrain (control group)
|
|
C) event — retrain after 3 consecutive losses OR ATR regime change
|
|
D) scheduled — retrain every 42 bars (~7 days) with champion-challenger
|
|
E) combined — scheduled + champion-challenger + emergency (3 losses)
|
|
"""
|
|
import copy
|
|
import json
|
|
import sys
|
|
from datetime import datetime
|
|
from pathlib import Path
|
|
|
|
sys.path.insert(0, "src")
|
|
|
|
import numpy as np
|
|
import torch
|
|
|
|
from remizov_trader.core import model as model_mod, signals, risk
|
|
from remizov_trader.config import ModelConfig, RiskConfig
|
|
|
|
# Config
|
|
MODEL_CFG = ModelConfig(
|
|
window_size=64, n_steps=20, total_time=0.5,
|
|
shift=7, epochs=200, finetune_epochs=50, lr=0.003,
|
|
)
|
|
RISK_CFG = RiskConfig(
|
|
per_trade=0.05, max_position_pct=0.25,
|
|
max_open_positions=1, leverage=1,
|
|
)
|
|
|
|
K = 2
|
|
CORR_THRESH = 0.5
|
|
INITIAL_CAPITAL = 10_000.0
|
|
TRAILING_STOP = True
|
|
TRAIN_RATIO = 0.3
|
|
|
|
|
|
# ── Retrain strategies ──────────────────────────────────────
|
|
|
|
class RetrainStrategy:
|
|
"""Base: never retrain."""
|
|
name = "no_retrain"
|
|
|
|
def __init__(self):
|
|
self.retrain_count = 0
|
|
|
|
def should_retrain(self, state: dict) -> bool:
|
|
return False
|
|
|
|
def accept_new_model(self, old_model, new_model, prices, price_idx, data) -> bool:
|
|
"""Always accept (no champion-challenger)."""
|
|
return True
|
|
|
|
|
|
class BaselineRetrain(RetrainStrategy):
|
|
"""Current production: retrain every 10 signals."""
|
|
name = "baseline"
|
|
|
|
def should_retrain(self, state: dict) -> bool:
|
|
return state["signals_since_retrain"] >= 10
|
|
|
|
|
|
class EventRetrain(RetrainStrategy):
|
|
"""Retrain after 3 consecutive losses OR ATR regime change."""
|
|
name = "event"
|
|
|
|
def __init__(self):
|
|
super().__init__()
|
|
self._prev_regime = None # "low", "normal", "high"
|
|
|
|
def should_retrain(self, state: dict) -> bool:
|
|
# 3 consecutive losses
|
|
if state["consecutive_losses"] >= 3:
|
|
return True
|
|
# ATR regime change
|
|
regime = state.get("atr_regime")
|
|
if self._prev_regime is not None and regime != self._prev_regime:
|
|
self._prev_regime = regime
|
|
return True
|
|
self._prev_regime = regime
|
|
return False
|
|
|
|
|
|
class ScheduledRetrain(RetrainStrategy):
|
|
"""Retrain every 42 bars (~7 days on 4h) with champion-challenger."""
|
|
name = "scheduled"
|
|
|
|
def should_retrain(self, state: dict) -> bool:
|
|
return state["bars_since_retrain"] >= 42
|
|
|
|
def accept_new_model(self, old_model, new_model, prices, price_idx, data) -> bool:
|
|
"""Champion-challenger: accept only if new model has lower MSE on recent data."""
|
|
# Validation: last 20% of available windows before current point
|
|
val_data = [d for d in data if d["price_idx"] < price_idx]
|
|
if len(val_data) < 10:
|
|
return True # not enough data to validate
|
|
n_val = max(int(len(val_data) * 0.2), 5)
|
|
val_set = val_data[-n_val:]
|
|
|
|
windows = np.array([d["norm_input"] for d in val_set])
|
|
targets = np.array([d["norm_target"] for d in val_set])
|
|
|
|
old_mse = _compute_mse(old_model, windows, targets)
|
|
new_mse = _compute_mse(new_model, windows, targets)
|
|
|
|
return new_mse < old_mse
|
|
|
|
|
|
class CombinedRetrain(ScheduledRetrain):
|
|
"""Scheduled + champion-challenger + emergency retrain after 3 losses."""
|
|
name = "combined"
|
|
|
|
def should_retrain(self, state: dict) -> bool:
|
|
# Emergency: 3 consecutive losses
|
|
if state["consecutive_losses"] >= 3:
|
|
return True
|
|
# Scheduled: every 42 bars
|
|
return state["bars_since_retrain"] >= 42
|
|
|
|
|
|
def _compute_mse(model, windows, targets):
|
|
"""Compute MSE of model on given data."""
|
|
model.eval()
|
|
with torch.no_grad():
|
|
inp = torch.tensor(windows, dtype=torch.float32)
|
|
tgt = torch.tensor(targets, dtype=torch.float32)
|
|
pred = model(inp, stochastic=False)
|
|
return float(torch.nn.functional.mse_loss(pred, tgt))
|
|
|
|
|
|
# ── Core backtest engine ────────────────────────────────────
|
|
|
|
def _get_atr_regime(prices, idx):
|
|
"""Classify ATR regime: low/normal/high."""
|
|
atr14 = risk.compute_atr(prices, idx, period=14)
|
|
atr50 = risk.compute_atr(prices, idx, period=50)
|
|
ratio = atr14 / atr50 if atr50 > 0 else 1.0
|
|
if ratio < 0.7:
|
|
return "low"
|
|
if ratio > 1.5:
|
|
return "high"
|
|
return "normal"
|
|
|
|
|
|
def _do_retrain(model, prices, price_idx, all_data, strategy, cfg):
|
|
"""Finetune model on recent data. Returns (model, accepted)."""
|
|
# Use last 200 windows (not all history — O(1) instead of O(n))
|
|
train_windows = [d for d in all_data if d["price_idx"] <= price_idx]
|
|
if len(train_windows) < 20:
|
|
return model, False
|
|
train_windows = train_windows[-200:] # cap to recent data
|
|
|
|
windows = np.array([d["norm_input"] for d in train_windows])
|
|
targets = np.array([d["norm_target"] for d in train_windows])
|
|
|
|
# Finetune copy of existing model (not from scratch)
|
|
new_model = copy.deepcopy(model)
|
|
model_mod.train(new_model, windows, targets, 20, cfg.lr * 0.3) # fewer epochs, lower lr
|
|
|
|
# Champion-challenger check
|
|
if strategy.accept_new_model(model, new_model, prices, price_idx, all_data):
|
|
strategy.retrain_count += 1
|
|
return new_model, True
|
|
return model, False
|
|
|
|
|
|
def run_backtest_with_retrain(ticker, prices, dates, all_data, train_data,
|
|
test_data, initial_model, strategy):
|
|
"""Run backtest with given retrain strategy."""
|
|
ws = MODEL_CFG.window_size
|
|
shift = MODEL_CFG.shift
|
|
|
|
# Deep copy model so strategies don't interfere
|
|
mdl = copy.deepcopy(initial_model)
|
|
|
|
equity = INITIAL_CAPITAL
|
|
peak_equity = equity
|
|
trades = []
|
|
position = None
|
|
equity_curve = [equity]
|
|
|
|
# State tracking
|
|
signals_since_retrain = 0
|
|
bars_since_retrain = 0
|
|
consecutive_losses = 0
|
|
last_retrain_bar = test_data[0]["price_idx"] if test_data else 0
|
|
retrain_log = []
|
|
|
|
for i, d in enumerate(test_data):
|
|
price_idx = d["price_idx"]
|
|
current_price = float(prices[price_idx])
|
|
bars_since_retrain = price_idx - last_retrain_bar
|
|
|
|
# Check open position
|
|
if position is not None:
|
|
p = position
|
|
|
|
if TRAILING_STOP:
|
|
p["best_price"], p["stop_price"] = risk.update_trailing_stop(
|
|
current_price, p["best_price"], p["stop_price"],
|
|
p["stop_dist"], p["direction"],
|
|
)
|
|
|
|
stopped = risk.is_stopped(current_price, p["stop_price"], p["direction"])
|
|
bars_held = price_idx - p["entry_bar"]
|
|
max_hold = shift - p["k_used"]
|
|
time_exit = bars_held >= max_hold
|
|
|
|
if stopped or time_exit:
|
|
exit_price = p["stop_price"] if stopped else current_price
|
|
reason = "stop" if stopped else "time"
|
|
pnl_net, pnl_pct = risk.calculate_pnl(
|
|
p["entry_price"], exit_price, p["direction"],
|
|
p["pos_size"], p["pos_value"],
|
|
)
|
|
equity += pnl_net
|
|
peak_equity = max(peak_equity, equity)
|
|
|
|
if pnl_net > 0:
|
|
consecutive_losses = 0
|
|
else:
|
|
consecutive_losses += 1
|
|
|
|
trades.append({
|
|
"pnl_net": pnl_net,
|
|
"pnl_pct": pnl_pct,
|
|
"equity_at_entry": p["equity_at_entry"],
|
|
"reason": reason,
|
|
})
|
|
position = None
|
|
|
|
# Check retrain (only when no position)
|
|
if position is None:
|
|
state = {
|
|
"signals_since_retrain": signals_since_retrain,
|
|
"bars_since_retrain": bars_since_retrain,
|
|
"consecutive_losses": consecutive_losses,
|
|
"atr_regime": _get_atr_regime(prices, price_idx),
|
|
}
|
|
if strategy.should_retrain(state):
|
|
mdl, accepted = _do_retrain(
|
|
mdl, prices, price_idx, all_data, strategy, MODEL_CFG,
|
|
)
|
|
retrain_log.append({
|
|
"bar": price_idx,
|
|
"accepted": accepted,
|
|
"reason": "scheduled" if bars_since_retrain >= 42
|
|
else "event",
|
|
"consecutive_losses": consecutive_losses,
|
|
})
|
|
if accepted:
|
|
signals_since_retrain = 0
|
|
last_retrain_bar = price_idx
|
|
consecutive_losses = 0
|
|
|
|
# New signal
|
|
if position is None and price_idx >= ws + K:
|
|
w = prices[price_idx - ws - K:price_idx - K].copy()
|
|
confirm = prices[price_idx - K:price_idx].copy()
|
|
mu, std = w.mean(), w.std()
|
|
if std < 1e-10:
|
|
equity_curve.append(equity)
|
|
continue
|
|
norm_input = (w - mu) / std
|
|
|
|
pred = model_mod.predict(mdl, norm_input)
|
|
pred_new = pred[-shift:]
|
|
corr, confirmed = signals.check_shape_confirmation(
|
|
pred_new, confirm, mu, std, K, CORR_THRESH,
|
|
)
|
|
|
|
signals_since_retrain += 1
|
|
|
|
if confirmed:
|
|
direction = signals.get_direction(pred_new, K)
|
|
if direction is not None:
|
|
k_adj, stop_mult = risk.regime_adaptive_params(
|
|
prices, price_idx, K,
|
|
)
|
|
atr = risk.compute_atr(prices, price_idx)
|
|
stop_dist = max(atr * stop_mult, current_price * 0.005)
|
|
stop_price = current_price - direction * stop_dist
|
|
pos_size, pos_value = risk.calculate_position(
|
|
equity, current_price, stop_dist, RISK_CFG,
|
|
)
|
|
position = {
|
|
"direction": direction,
|
|
"entry_price": current_price,
|
|
"stop_price": stop_price,
|
|
"stop_dist": stop_dist,
|
|
"best_price": current_price,
|
|
"pos_size": pos_size,
|
|
"pos_value": pos_value,
|
|
"entry_bar": price_idx,
|
|
"k_used": k_adj,
|
|
"equity_at_entry": equity,
|
|
}
|
|
|
|
equity_curve.append(equity)
|
|
|
|
# Close remaining position
|
|
if position is not None:
|
|
last_price = float(prices[-1])
|
|
pnl_net, pnl_pct = risk.calculate_pnl(
|
|
position["entry_price"], last_price, position["direction"],
|
|
position["pos_size"], position["pos_value"],
|
|
)
|
|
equity += pnl_net
|
|
trades.append({
|
|
"pnl_net": pnl_net,
|
|
"pnl_pct": pnl_pct,
|
|
"equity_at_entry": position["equity_at_entry"],
|
|
"reason": "end",
|
|
})
|
|
equity_curve.append(equity)
|
|
|
|
# Metrics
|
|
if not trades:
|
|
return None
|
|
|
|
pnls = [t["pnl_net"] for t in trades]
|
|
wins = [t for t in trades if t["pnl_net"] > 0]
|
|
losses_list = [t for t in trades if t["pnl_net"] <= 0]
|
|
|
|
total_pnl = equity - INITIAL_CAPITAL
|
|
total_ret = total_pnl / INITIAL_CAPITAL * 100
|
|
|
|
first_bar = test_data[0]["price_idx"]
|
|
last_bar = test_data[-1]["price_idx"]
|
|
bars_per_year = 365.25 * 6
|
|
years = (last_bar - first_bar) / bars_per_year
|
|
|
|
if len(pnls) > 1 and years > 0:
|
|
# Daily returns Sharpe (proper annualization)
|
|
n_days = max((last_bar - first_bar) // 6, 1)
|
|
daily_pnl = np.zeros(n_days)
|
|
for t in trades:
|
|
day = min((t.get("bar", t.get("entry_idx", first_bar)) - first_bar) // 6, n_days - 1)
|
|
daily_pnl[day] += t["pnl_net"]
|
|
daily_ret = daily_pnl / INITIAL_CAPITAL
|
|
sharpe = float(np.mean(daily_ret) / np.std(daily_ret) * np.sqrt(252)) if np.std(daily_ret) > 0 else 0
|
|
else:
|
|
sharpe = 0
|
|
|
|
eq = np.array(equity_curve)
|
|
peak = np.maximum.accumulate(eq)
|
|
dd = (peak - eq) / peak
|
|
max_dd = dd.max() * 100
|
|
months = years * 12
|
|
|
|
return {
|
|
"strategy": strategy.name,
|
|
"ticker": ticker,
|
|
"trades": len(trades),
|
|
"wins": len(wins),
|
|
"losses": len(losses_list),
|
|
"wr": len(wins) / len(trades) * 100,
|
|
"total_pnl": total_pnl,
|
|
"total_ret": total_ret,
|
|
"sharpe": sharpe,
|
|
"max_dd": max_dd,
|
|
"monthly_pnl": total_pnl / months if months > 0 else 0,
|
|
"months": months,
|
|
"retrains": strategy.retrain_count,
|
|
"retrain_log": retrain_log,
|
|
}
|
|
|
|
|
|
# ── Main ────────────────────────────────────────────────────
|
|
|
|
def main():
|
|
symbol = "ETH/USDC"
|
|
ticker = "ETH-USD"
|
|
|
|
print(f"Fetching {symbol} 4H data from Bybit...")
|
|
prices, dates = signals.fetch_prices_ccxt(symbol, "4h", "max")
|
|
if prices is None:
|
|
print("No data!")
|
|
return
|
|
print(f"Got {len(prices)} bars, range: ${prices.min():.2f} - ${prices.max():.2f}")
|
|
|
|
# Prepare windows
|
|
ws = MODEL_CFG.window_size
|
|
shift = MODEL_CFG.shift
|
|
all_data = signals.prepare_windows(prices, ws, shift)
|
|
n_train = max(int(len(all_data) * TRAIN_RATIO), 20)
|
|
train_data = all_data[:n_train]
|
|
test_data = all_data[n_train:]
|
|
|
|
print(f"Windows: {len(all_data)} total, {n_train} train, {len(test_data)} test")
|
|
|
|
# Train initial model (same for all strategies)
|
|
torch.manual_seed(42)
|
|
np.random.seed(42)
|
|
initial_model = model_mod.create_model(MODEL_CFG)
|
|
windows = np.array([d["norm_input"] for d in train_data])
|
|
targets = np.array([d["norm_target"] for d in train_data])
|
|
loss = model_mod.train(initial_model, windows, targets, MODEL_CFG.epochs, MODEL_CFG.lr)
|
|
print(f"Initial model trained, loss={loss:.6f}")
|
|
|
|
# Run all strategies
|
|
strategies = [
|
|
RetrainStrategy(), # A: no_retrain (control)
|
|
BaselineRetrain(), # B: baseline (current production)
|
|
EventRetrain(), # C: event-driven
|
|
ScheduledRetrain(), # D: scheduled + champion-challenger
|
|
CombinedRetrain(), # E: combined
|
|
]
|
|
|
|
results = []
|
|
for strat in strategies:
|
|
print(f"\n Running: {strat.name}...", end="", flush=True)
|
|
r = run_backtest_with_retrain(
|
|
ticker, prices, dates, all_data, train_data,
|
|
test_data, initial_model, strat,
|
|
)
|
|
if r:
|
|
results.append(r)
|
|
print(f" done ({r['trades']} trades, {r['retrains']} retrains)")
|
|
else:
|
|
print(" no trades")
|
|
|
|
# Print results
|
|
print(f"\n\n{'='*80}")
|
|
print(f" RETRAIN STRATEGY COMPARISON — {symbol} 4H")
|
|
print(f"{'='*80}")
|
|
print(f" {'Strategy':<16s} {'Sharpe':>8s} {'Return':>10s} {'Trades':>7s} "
|
|
f"{'WR':>6s} {'MaxDD':>7s} {'Retrains':>9s} {'$/mo':>10s}")
|
|
print(f" {'-'*73}")
|
|
|
|
for r in sorted(results, key=lambda x: x["sharpe"], reverse=True):
|
|
print(f" {r['strategy']:<16s} {r['sharpe']:>8.2f} {r['total_ret']:>+9.1f}% "
|
|
f"{r['trades']:>7d} {r['wr']:>5.1f}% {r['max_dd']:>6.1f}% "
|
|
f"{r['retrains']:>9d} ${r['monthly_pnl']:>+8,.0f}")
|
|
|
|
print(f"{'='*80}")
|
|
|
|
# Save results to JSON
|
|
log_dir = Path("data/backtest_logs")
|
|
log_dir.mkdir(parents=True, exist_ok=True)
|
|
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
|
log_path = log_dir / f"retrain_comparison_{ts}.json"
|
|
|
|
log_data = {
|
|
"timestamp": ts,
|
|
"symbol": symbol,
|
|
"config": {
|
|
"window_size": ws, "shift": shift, "K": K,
|
|
"corr_thresh": CORR_THRESH, "epochs": MODEL_CFG.epochs,
|
|
"finetune_epochs": MODEL_CFG.finetune_epochs,
|
|
"initial_capital": INITIAL_CAPITAL,
|
|
"train_ratio": TRAIN_RATIO,
|
|
"n_bars": len(prices),
|
|
},
|
|
"results": [{k: v for k, v in r.items() if k != "retrain_log"}
|
|
for r in results],
|
|
"retrain_logs": {r["strategy"]: r["retrain_log"] for r in results},
|
|
}
|
|
log_path.write_text(json.dumps(log_data, indent=2, default=str))
|
|
print(f"\nResults saved: {log_path}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|