Новые улучшения (поверх ATR+Trailing baseline): 1. Adaptive corr threshold — 3/4 PASS (Sharpe +0.01..+0.06) 2. Partial exit 50% — 0/4 FAIL (ухудшает return) 3. Architecture ensemble (SSM/FNO/SDE) — 1/4 FAIL 4. Regime-adaptive K + stop_mult — 3/4 PASS (Sharpe +0.04..+0.21) 5. Volume filter — 0/4 FAIL Лучшая комбинация: adaptive_corr + regime_adaptive SOL: Sharpe 0.07→0.18, BNB: Sharpe 0.31→0.43 Исправлен баг: K=1 при low vol делал корреляцию невозможной Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
1008 lines
35 KiB
Python
1008 lines
35 KiB
Python
"""
|
|
A/B testing of strategy improvements.
|
|
|
|
Improvements tested:
|
|
A. Adaptive stop-loss (ATR-based)
|
|
B. Dynamic position sizing (Kelly criterion)
|
|
C. Multi-timeframe confirmation (64 + 128 day windows)
|
|
D. Ensemble models (3 models, majority vote)
|
|
E. Volatility filter (MA cross)
|
|
F. SOL higher correlation threshold
|
|
G. Leverage for stable strategies
|
|
|
|
Each tested independently vs baseline, then best combinations.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import time
|
|
import warnings
|
|
from concurrent.futures import ProcessPoolExecutor, as_completed
|
|
from copy import deepcopy
|
|
from datetime import date, datetime
|
|
from multiprocessing import cpu_count
|
|
|
|
import numpy as np
|
|
import torch
|
|
import torch.nn as nn
|
|
|
|
import yfinance as yf
|
|
|
|
from models import EnhancedRemizovNet
|
|
|
|
warnings.filterwarnings("ignore")
|
|
|
|
N_WORKERS = max(1, cpu_count() - 1) # leave 1 core free
|
|
|
|
# -- Base Config (same as final_backtest.py) ---------------------------------
|
|
|
|
WINDOW_SIZE = 64
|
|
N_STEPS = 20
|
|
TOTAL_TIME = 0.5
|
|
EPOCHS = 200
|
|
FINETUNE_EPOCHS = 50
|
|
LR = 3e-3
|
|
SHIFT = 7
|
|
|
|
INITIAL_EQUITY = 10000.0
|
|
RISK_PER_TRADE = 0.02
|
|
COMMISSION = 0.001
|
|
STOP_MULT = 1.5
|
|
|
|
ASSET_CONFIGS = {
|
|
"BTC-USD": {"K": 2, "corr_thresh": 0.7},
|
|
"ETH-USD": {"K": 2, "corr_thresh": 0.5},
|
|
"SOL-USD": {"K": 3, "corr_thresh": 0.5},
|
|
"BNB-USD": {"K": 3, "corr_thresh": 0.5},
|
|
}
|
|
|
|
|
|
# -- Data fetch --------------------------------------------------------------
|
|
|
|
def fetch_asset(ticker, period="max"):
|
|
"""Fetch daily close prices and dates."""
|
|
hist = yf.Ticker(ticker).history(period=period)
|
|
prices = hist["Close"].dropna()
|
|
dates = [d.date() for d in prices.index]
|
|
return prices.values.astype(np.float64), dates
|
|
|
|
|
|
def fetch_asset_with_volume(ticker, period="max"):
|
|
"""Fetch daily close prices, volumes, and dates."""
|
|
hist = yf.Ticker(ticker).history(period=period)
|
|
close = hist["Close"].dropna()
|
|
vol = hist["Volume"].reindex(close.index).fillna(0)
|
|
dates = [d.date() for d in close.index]
|
|
return close.values.astype(np.float64), vol.values.astype(np.float64), dates
|
|
|
|
|
|
# -- Model helpers -----------------------------------------------------------
|
|
|
|
# Architecture configs for ensemble diversity
|
|
ARCH_CONFIGS = [
|
|
{"use_sde": True, "use_ssm": False, "use_fno": False}, # baseline SDE
|
|
{"use_sde": True, "use_ssm": True, "use_fno": False}, # SSM + SDE
|
|
{"use_sde": True, "use_ssm": False, "use_fno": True}, # FNO + SDE
|
|
{"use_sde": True, "use_ssm": True, "use_fno": True}, # all three
|
|
]
|
|
|
|
|
|
def create_model(grid_size=WINDOW_SIZE, arch_idx=None):
|
|
if arch_idx is not None and 0 <= arch_idx < len(ARCH_CONFIGS):
|
|
cfg = ARCH_CONFIGS[arch_idx]
|
|
else:
|
|
cfg = {"use_sde": True, "use_ssm": False, "use_fno": False}
|
|
return EnhancedRemizovNet(
|
|
grid_size=grid_size, n_steps=N_STEPS, total_time=TOTAL_TIME,
|
|
dx=1.0 / grid_size, **cfg,
|
|
)
|
|
|
|
|
|
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()
|
|
|
|
|
|
# -- Data preparation -------------------------------------------------------
|
|
|
|
def prepare_data(prices, window_size=WINDOW_SIZE):
|
|
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({
|
|
"price_at_entry": prices[t - 1],
|
|
"future_prices": future,
|
|
"norm_input": (w - mu) / std,
|
|
"norm_target": (s - mu) / std,
|
|
"mu": mu, "std": std,
|
|
"price_idx": t,
|
|
})
|
|
return data
|
|
|
|
|
|
# -- ATR calculation ---------------------------------------------------------
|
|
|
|
def compute_atr(prices, idx, period=14):
|
|
"""Average True Range ending at prices[idx]."""
|
|
if idx < period + 1:
|
|
return prices[idx] * 0.02 # fallback: 2% of price
|
|
trs = []
|
|
for i in range(idx - period, idx):
|
|
tr = abs(prices[i] - prices[i - 1]) # close-only ATR
|
|
trs.append(tr)
|
|
return np.mean(trs) if trs else prices[idx] * 0.02
|
|
|
|
|
|
# -- Modular Backtest Engine -------------------------------------------------
|
|
|
|
def run_backtest(
|
|
prices: np.ndarray,
|
|
dates: list[date],
|
|
data: list[dict],
|
|
cfg: dict,
|
|
improvements: dict | None = None,
|
|
) -> dict:
|
|
"""Run backtest with configurable improvements.
|
|
|
|
improvements dict keys (original):
|
|
"adaptive_stop": bool — use ATR-based stop instead of pred range
|
|
"kelly": bool — Kelly criterion position sizing
|
|
"trailing_stop": bool — trailing stop-loss
|
|
"vol_filter": bool — skip trades in bearish regime (MA20 < MA50)
|
|
"corr_override": float — override correlation threshold
|
|
"leverage": float — max leverage multiplier (1.0 = no leverage)
|
|
"ensemble_preds": list — pre-computed ensemble predictions
|
|
|
|
New improvement keys (v2):
|
|
"adaptive_corr": bool — dynamic corr threshold based on rolling WR
|
|
"partial_exit": bool — close 50% at 1.5x risk, trail remainder
|
|
"regime_adaptive": bool — adjust K and stop_mult based on ATR/ATR_MA
|
|
"volume_filter": bool — enter only if volume > MA20(volume)
|
|
"volumes": np.ndarray — volume data aligned with prices (for volume_filter)
|
|
"""
|
|
if improvements is None:
|
|
improvements = {}
|
|
|
|
K_base = cfg["K"]
|
|
K = K_base
|
|
corr_thresh_base = improvements.get("corr_override", cfg["corr_thresh"])
|
|
corr_thresh = corr_thresh_base
|
|
train_size = 80
|
|
|
|
n = len(data)
|
|
if n < train_size + 5:
|
|
return {"trades": [], "equity_curve": [INITIAL_EQUITY]}
|
|
|
|
# Model setup (unless ensemble provides predictions or pretrained model given)
|
|
ensemble_preds = improvements.get("ensemble_preds")
|
|
pretrained = improvements.get("pretrained_model")
|
|
model = None
|
|
if ensemble_preds is None:
|
|
if pretrained is not None:
|
|
model = deepcopy(pretrained)
|
|
else:
|
|
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 = []
|
|
equity_curve = [equity]
|
|
retrain_ctr = 0
|
|
consecutive_losses = 0
|
|
leverage_cap = improvements.get("leverage", 1.0)
|
|
|
|
for i in range(train_size, n):
|
|
d = data[i]
|
|
|
|
# Get prediction
|
|
if ensemble_preds is not None:
|
|
pred = ensemble_preds[i]
|
|
else:
|
|
pred = predict(model, d["norm_input"])
|
|
|
|
pred_new = pred[-SHIFT:]
|
|
|
|
# Adaptive correlation threshold (1)
|
|
if improvements.get("adaptive_corr") and len(trades) >= 10:
|
|
recent = trades[-20:]
|
|
rolling_wr = sum(1 for t in recent if t["win"]) / len(recent)
|
|
if rolling_wr > 0.55:
|
|
corr_thresh = max(corr_thresh_base - 0.1, 0.3)
|
|
elif rolling_wr < 0.40:
|
|
corr_thresh = min(corr_thresh_base + 0.1, 0.95)
|
|
else:
|
|
corr_thresh = corr_thresh_base
|
|
|
|
# Regime-adaptive params (4)
|
|
if improvements.get("regime_adaptive"):
|
|
pidx = d["price_idx"]
|
|
atr_now = compute_atr(prices, pidx, period=14)
|
|
atr_ma = compute_atr(prices, pidx, period=50)
|
|
vol_ratio = atr_now / atr_ma if atr_ma > 0 else 1.0
|
|
if vol_ratio > 1.5: # high vol regime
|
|
K = min(K_base + 1, SHIFT - 2)
|
|
elif vol_ratio < 0.7: # low vol regime
|
|
K = max(K_base - 1, 2) # min 2 for correlation
|
|
else:
|
|
K = K_base
|
|
|
|
pred_confirm = pred_new[:K]
|
|
|
|
if len(pred_confirm) < 2:
|
|
equity_curve.append(equity)
|
|
continue
|
|
|
|
# Correlation check
|
|
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:
|
|
equity_curve.append(equity)
|
|
retrain_ctr += 1
|
|
if model and retrain_ctr >= 10:
|
|
ws = np.array([dd["norm_input"] for dd in data[:i + 1]])
|
|
ts = np.array([dd["norm_target"] for dd in data[:i + 1]])
|
|
train_model(model, ws, ts, FINETUNE_EPOCHS)
|
|
retrain_ctr = 0
|
|
continue
|
|
|
|
# Volatility filter (E)
|
|
if improvements.get("vol_filter"):
|
|
pidx = d["price_idx"]
|
|
if pidx >= 50:
|
|
ma20 = prices[pidx - 20:pidx].mean()
|
|
ma50 = prices[pidx - 50:pidx].mean()
|
|
if ma20 < ma50:
|
|
equity_curve.append(equity)
|
|
continue
|
|
|
|
# Volume filter (5)
|
|
volumes = improvements.get("volumes")
|
|
if improvements.get("volume_filter") and volumes is not None:
|
|
pidx = d["price_idx"]
|
|
if pidx >= 20:
|
|
vol_now = volumes[pidx - 1]
|
|
vol_ma20 = volumes[pidx - 20:pidx].mean()
|
|
if vol_now < vol_ma20:
|
|
equity_curve.append(equity)
|
|
continue
|
|
|
|
# Direction
|
|
entry_price = d["future_prices"][K - 1]
|
|
pred_direction = pred_new[-1] - pred_new[K - 1]
|
|
if abs(pred_direction) < 1e-10:
|
|
equity_curve.append(equity)
|
|
continue
|
|
|
|
direction = 1 if pred_direction > 0 else -1
|
|
pred_range = np.max(np.abs(pred_new[K:] - pred_new[K - 1]))
|
|
|
|
# Stop-loss calculation
|
|
stop_mult = STOP_MULT
|
|
if improvements.get("regime_adaptive"):
|
|
pidx = d["price_idx"]
|
|
atr_now = compute_atr(prices, pidx, period=14)
|
|
atr_ma = compute_atr(prices, pidx, period=50)
|
|
vol_ratio = atr_now / atr_ma if atr_ma > 0 else 1.0
|
|
if vol_ratio > 1.5:
|
|
stop_mult = STOP_MULT * 1.5
|
|
elif vol_ratio < 0.7:
|
|
stop_mult = STOP_MULT * 0.8
|
|
|
|
if improvements.get("adaptive_stop"):
|
|
# (A) ATR-based stop
|
|
pidx = d["price_idx"]
|
|
atr = compute_atr(prices, pidx)
|
|
stop_dist = max(atr * 2.0 * (stop_mult / STOP_MULT), entry_price * 0.005)
|
|
else:
|
|
# Baseline: prediction range based
|
|
stop_dist = max(pred_range * d["std"] * stop_mult, entry_price * 0.005)
|
|
|
|
# Position sizing
|
|
if improvements.get("kelly"):
|
|
# (B) Kelly criterion — need running WR and payoff ratio
|
|
if len(trades) >= 10:
|
|
recent = trades[-20:] # last 20 trades
|
|
wins = [t for t in recent if t["win"]]
|
|
losses = [t for t in recent if not t["win"]]
|
|
wr = len(wins) / len(recent)
|
|
avg_w = np.mean([t["pnl_pct"] for t in wins]) if wins else 1
|
|
avg_l = abs(np.mean([t["pnl_pct"] for t in losses])) if losses else 1
|
|
payoff = avg_w / avg_l if avg_l > 0 else 1
|
|
kelly_f = max(0, (wr * payoff - (1 - wr)) / payoff)
|
|
kelly_f = min(kelly_f, 0.25) # cap at 25% (quarter Kelly)
|
|
risk_frac = max(kelly_f, 0.005) # minimum 0.5%
|
|
else:
|
|
risk_frac = RISK_PER_TRADE
|
|
else:
|
|
risk_frac = RISK_PER_TRADE
|
|
|
|
risk_amount = equity * risk_frac
|
|
pos_size = risk_amount / stop_dist
|
|
pos_value = pos_size * entry_price
|
|
|
|
# Leverage cap
|
|
max_pos = equity * leverage_cap
|
|
if pos_value > max_pos:
|
|
pos_size = max_pos / entry_price
|
|
pos_value = max_pos
|
|
|
|
# Simulate trade
|
|
exit_price = d["future_prices"][-1]
|
|
stop_price = entry_price - direction * stop_dist
|
|
stopped = False
|
|
partial_exit_pnl = 0.0 # extra PnL from partial exit
|
|
|
|
use_partial = improvements.get("partial_exit", False)
|
|
partial_done = False
|
|
partial_target = entry_price + direction * stop_dist * 1.5
|
|
|
|
if improvements.get("trailing_stop"):
|
|
# Trailing stop: move stop in favorable direction
|
|
remaining_size = pos_size
|
|
best_price = entry_price
|
|
for hp in d["future_prices"][K:]:
|
|
# Partial exit (2): close 50% at 1.5x risk
|
|
if use_partial and not partial_done:
|
|
if (direction == 1 and hp >= partial_target) or \
|
|
(direction == -1 and hp <= partial_target):
|
|
half = remaining_size * 0.5
|
|
partial_exit_pnl = half * (partial_target - entry_price) * direction
|
|
remaining_size -= half
|
|
partial_done = True
|
|
|
|
if direction == 1:
|
|
best_price = max(best_price, hp)
|
|
trailing_stop = best_price - stop_dist
|
|
if hp <= trailing_stop:
|
|
exit_price = trailing_stop
|
|
stopped = True
|
|
break
|
|
else:
|
|
best_price = min(best_price, hp)
|
|
trailing_stop = best_price + stop_dist
|
|
if hp >= trailing_stop:
|
|
exit_price = trailing_stop
|
|
stopped = True
|
|
break
|
|
else:
|
|
# Fixed stop
|
|
remaining_size = pos_size
|
|
for hp in d["future_prices"][K:]:
|
|
if use_partial and not partial_done:
|
|
if (direction == 1 and hp >= partial_target) or \
|
|
(direction == -1 and hp <= partial_target):
|
|
half = remaining_size * 0.5
|
|
partial_exit_pnl = half * (partial_target - entry_price) * direction
|
|
remaining_size -= half
|
|
partial_done = True
|
|
|
|
if direction == 1 and hp <= stop_price:
|
|
exit_price = stop_price
|
|
stopped = True
|
|
break
|
|
elif direction == -1 and hp >= stop_price:
|
|
exit_price = stop_price
|
|
stopped = True
|
|
break
|
|
|
|
if use_partial and partial_done:
|
|
remaining_size = pos_size * 0.5
|
|
pnl_gross = partial_exit_pnl + remaining_size * (exit_price - entry_price) * direction
|
|
else:
|
|
pnl_gross = pos_size * (exit_price - entry_price) * direction
|
|
commission_cost = pos_value * COMMISSION * 2
|
|
pnl_net = pnl_gross - commission_cost
|
|
equity += pnl_net
|
|
|
|
win = pnl_net > 0
|
|
if win:
|
|
consecutive_losses = 0
|
|
else:
|
|
consecutive_losses += 1
|
|
|
|
pidx = d["price_idx"]
|
|
trade_date = dates[min(pidx, len(dates) - 1)]
|
|
|
|
trades.append({
|
|
"date": trade_date,
|
|
"direction": "L" if direction == 1 else "S",
|
|
"entry": entry_price,
|
|
"exit": exit_price,
|
|
"pnl_pct": pnl_net / pos_value * 100 if pos_value > 0 else 0,
|
|
"pnl_net": pnl_net,
|
|
"win": win,
|
|
"stopped": stopped,
|
|
"equity": equity,
|
|
"correlation": corr,
|
|
})
|
|
equity_curve.append(equity)
|
|
|
|
retrain_ctr += 1
|
|
if model and retrain_ctr >= 10:
|
|
ws = np.array([dd["norm_input"] for dd in data[:i + 1]])
|
|
ts = np.array([dd["norm_target"] for dd in data[:i + 1]])
|
|
train_model(model, ws, ts, FINETUNE_EPOCHS)
|
|
retrain_ctr = 0
|
|
|
|
return {"trades": trades, "equity_curve": equity_curve}
|
|
|
|
|
|
# -- Ensemble predictions ---------------------------------------------------
|
|
|
|
def compute_ensemble_preds(data, n_models=3, train_size=80):
|
|
"""Train N models with different seeds, average predictions."""
|
|
n = len(data)
|
|
# Initialize ensemble predictions as None
|
|
preds = {i: [] for i in range(n)}
|
|
|
|
for seed in range(n_models):
|
|
torch.manual_seed(seed * 42)
|
|
np.random.seed(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)
|
|
|
|
retrain_ctr = 0
|
|
for i in range(train_size, n):
|
|
pred = predict(model, data[i]["norm_input"])
|
|
preds[i].append(pred)
|
|
|
|
retrain_ctr += 1
|
|
if retrain_ctr >= 10:
|
|
ws = np.array([dd["norm_input"] for dd in data[:i + 1]])
|
|
ts = np.array([dd["norm_target"] for dd in data[:i + 1]])
|
|
train_model(model, ws, ts, FINETUNE_EPOCHS)
|
|
retrain_ctr = 0
|
|
|
|
# Average predictions
|
|
ensemble = {}
|
|
for i in range(n):
|
|
if preds[i]:
|
|
ensemble[i] = np.mean(preds[i], axis=0)
|
|
else:
|
|
ensemble[i] = None
|
|
|
|
return ensemble
|
|
|
|
|
|
# -- Multi-timeframe predictions --------------------------------------------
|
|
|
|
def compute_multitf_filter(prices, data, train_size=80, long_window=128):
|
|
"""Train a second model on longer window, return direction agreement mask."""
|
|
data_long = prepare_data(prices, window_size=long_window)
|
|
if len(data_long) < train_size + 5:
|
|
return None # not enough data
|
|
|
|
model_long = create_model(grid_size=long_window)
|
|
windows = np.array([d["norm_input"] for d in data_long[:train_size]])
|
|
targets = np.array([d["norm_target"] for d in data_long[:train_size]])
|
|
train_model(model_long, windows, targets, EPOCHS)
|
|
|
|
# Build date -> long-tf direction map
|
|
long_directions = {}
|
|
retrain_ctr = 0
|
|
for i in range(train_size, len(data_long)):
|
|
d = data_long[i]
|
|
pred = predict(model_long, d["norm_input"])
|
|
pred_new = pred[-SHIFT:]
|
|
direction = 1 if pred_new[-1] > pred_new[0] else -1
|
|
pidx = d["price_idx"]
|
|
long_directions[pidx] = direction
|
|
|
|
retrain_ctr += 1
|
|
if retrain_ctr >= 10:
|
|
ws = np.array([dd["norm_input"] for dd in data_long[:i + 1]])
|
|
ts = np.array([dd["norm_target"] for dd in data_long[:i + 1]])
|
|
train_model(model_long, ws, ts, FINETUNE_EPOCHS)
|
|
retrain_ctr = 0
|
|
|
|
return long_directions
|
|
|
|
|
|
# -- Metrics -----------------------------------------------------------------
|
|
|
|
def calc_metrics(trades, label=""):
|
|
"""Calculate key metrics from trades list."""
|
|
if not trades:
|
|
return {
|
|
"label": label, "n_trades": 0, "final_equity": INITIAL_EQUITY,
|
|
"total_return": 0, "win_rate": 0, "avg_win": 0, "avg_loss": 0,
|
|
"max_loss": 0, "profit_factor": 0, "sharpe": 0, "max_dd": 0,
|
|
"stopped": 0, "annual_ret": 0,
|
|
}
|
|
|
|
wins = [t for t in trades if t["win"]]
|
|
losses = [t for t in trades if not t["win"]]
|
|
final_eq = trades[-1]["equity"]
|
|
total_ret = (final_eq / INITIAL_EQUITY - 1) * 100
|
|
|
|
wr = len(wins) / len(trades)
|
|
avg_win = np.mean([t["pnl_pct"] for t in wins]) if wins else 0
|
|
avg_loss = np.mean([t["pnl_pct"] for t in losses]) if losses else 0
|
|
max_loss = min((t["pnl_pct"] for t in losses), default=0)
|
|
pf = abs(sum(t["pnl_pct"] for t in wins) / sum(t["pnl_pct"] for t in losses)) \
|
|
if losses and sum(t["pnl_pct"] for t in losses) != 0 else float("inf")
|
|
|
|
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)
|
|
|
|
first_date = trades[0]["date"]
|
|
last_date = trades[-1]["date"]
|
|
years = (last_date - first_date).days / 365.25
|
|
|
|
# Sharpe: annualize based on actual trading frequency
|
|
trade_rets = [t["pnl_pct"] / 100 for t in trades]
|
|
if len(trade_rets) > 2 and np.std(trade_rets) > 0:
|
|
trades_per_year = len(trade_rets) / years if years > 0 else 52
|
|
sharpe = np.mean(trade_rets) / np.std(trade_rets) * np.sqrt(trades_per_year)
|
|
else:
|
|
sharpe = 0
|
|
annual_ret = ((final_eq / INITIAL_EQUITY) ** (1 / years) - 1) * 100 if years > 0 else 0
|
|
|
|
return {
|
|
"label": label,
|
|
"n_trades": len(trades),
|
|
"wins": len(wins),
|
|
"losses": len(losses),
|
|
"final_equity": round(final_eq, 2),
|
|
"total_return": round(total_ret, 1),
|
|
"annual_ret": round(annual_ret, 1),
|
|
"win_rate": round(wr * 100, 1),
|
|
"avg_win": round(avg_win, 2),
|
|
"avg_loss": round(avg_loss, 2),
|
|
"max_loss": round(max_loss, 2),
|
|
"profit_factor": round(pf, 2),
|
|
"sharpe": round(sharpe, 2),
|
|
"max_dd": round(max_dd * 100, 1),
|
|
"stopped": sum(1 for t in trades if t["stopped"]),
|
|
}
|
|
|
|
|
|
def print_comparison(results: list[dict], asset: str):
|
|
"""Print comparison table of multiple strategy results."""
|
|
print(f"\n {'Label':<25s} {'N':>4s} {'W/L':>7s} {'WR%':>5s} "
|
|
f"{'Ret%':>7s} {'$/yr':>6s} {'Sharpe':>6s} {'DD%':>6s} "
|
|
f"{'PF':>5s} {'Stops':>5s} {'Equity':>10s}")
|
|
print(f" {'─' * 95}")
|
|
|
|
for r in results:
|
|
if r["n_trades"] == 0:
|
|
print(f" {r['label']:<25s} NO TRADES")
|
|
continue
|
|
print(f" {r['label']:<25s} {r['n_trades']:>4d} "
|
|
f"{r['wins']:>3d}/{r['losses']:<3d} {r['win_rate']:>4.0f}% "
|
|
f"{r['total_return']:>+6.1f}% {r['annual_ret']:>+5.1f}% "
|
|
f"{r['sharpe']:>5.2f} {r['max_dd']:>+5.1f}% "
|
|
f"{r['profit_factor']:>5.2f} {r['stopped']:>5d} "
|
|
f"${r['final_equity']:>9,.0f}")
|
|
|
|
|
|
# -- Parallel worker ---------------------------------------------------------
|
|
|
|
def _worker_backtest(args):
|
|
"""Worker for ProcessPoolExecutor. Recreates model from state_dict."""
|
|
label, prices, dates, data, cfg, impr, state_dict, grid_size = args
|
|
|
|
torch.set_num_threads(1) # avoid thread contention in workers
|
|
|
|
if state_dict is not None:
|
|
model = create_model(grid_size=grid_size)
|
|
model.load_state_dict(state_dict)
|
|
impr = {**impr, "pretrained_model": model}
|
|
|
|
r = run_backtest(prices, dates, data, cfg, impr)
|
|
return calc_metrics(r["trades"], label)
|
|
|
|
|
|
def _worker_ensemble_single(args):
|
|
"""Train one ensemble member and return predictions."""
|
|
seed, data, grid_size, train_size = args
|
|
|
|
torch.set_num_threads(1)
|
|
torch.manual_seed(seed * 42)
|
|
np.random.seed(seed * 42)
|
|
|
|
model = create_model(grid_size=grid_size)
|
|
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)
|
|
|
|
n = len(data)
|
|
preds = {}
|
|
retrain_ctr = 0
|
|
for i in range(train_size, n):
|
|
preds[i] = predict(model, data[i]["norm_input"])
|
|
retrain_ctr += 1
|
|
if retrain_ctr >= 10:
|
|
ws = np.array([dd["norm_input"] for dd in data[:i + 1]])
|
|
ts = np.array([dd["norm_target"] for dd in data[:i + 1]])
|
|
train_model(model, ws, ts, FINETUNE_EPOCHS)
|
|
retrain_ctr = 0
|
|
|
|
return preds
|
|
|
|
|
|
def compute_ensemble_parallel(data, n_models=3, train_size=80):
|
|
"""Train N models in parallel, average predictions."""
|
|
args = [(seed, data, WINDOW_SIZE, train_size) for seed in range(n_models)]
|
|
|
|
with ProcessPoolExecutor(max_workers=min(n_models, N_WORKERS)) as pool:
|
|
all_preds = list(pool.map(_worker_ensemble_single, args))
|
|
|
|
# Average
|
|
n = len(data)
|
|
ensemble = {}
|
|
for i in range(n):
|
|
member_preds = [p[i] for p in all_preds if i in p]
|
|
if member_preds:
|
|
ensemble[i] = np.mean(member_preds, axis=0)
|
|
else:
|
|
ensemble[i] = None
|
|
return ensemble
|
|
|
|
|
|
# -- Architecture ensemble --------------------------------------------------
|
|
|
|
def _worker_arch_ensemble_single(args):
|
|
"""Train one architecture variant and return predictions."""
|
|
arch_idx, data, grid_size, train_size = args
|
|
|
|
torch.set_num_threads(1)
|
|
torch.manual_seed(42)
|
|
np.random.seed(42)
|
|
|
|
model = create_model(grid_size=grid_size, arch_idx=arch_idx)
|
|
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)
|
|
|
|
n = len(data)
|
|
preds = {}
|
|
retrain_ctr = 0
|
|
for i in range(train_size, n):
|
|
preds[i] = predict(model, data[i]["norm_input"])
|
|
retrain_ctr += 1
|
|
if retrain_ctr >= 10:
|
|
ws = np.array([dd["norm_input"] for dd in data[:i + 1]])
|
|
ts = np.array([dd["norm_target"] for dd in data[:i + 1]])
|
|
train_model(model, ws, ts, FINETUNE_EPOCHS)
|
|
retrain_ctr = 0
|
|
|
|
return preds
|
|
|
|
|
|
def compute_arch_ensemble_parallel(data, train_size=80):
|
|
"""Train 4 architecturally diverse models in parallel, average predictions."""
|
|
n_archs = len(ARCH_CONFIGS)
|
|
args = [(idx, data, WINDOW_SIZE, train_size) for idx in range(n_archs)]
|
|
|
|
with ProcessPoolExecutor(max_workers=min(n_archs, N_WORKERS)) as pool:
|
|
all_preds = list(pool.map(_worker_arch_ensemble_single, args))
|
|
|
|
n = len(data)
|
|
ensemble = {}
|
|
for i in range(n):
|
|
member_preds = [p[i] for p in all_preds if i in p]
|
|
if member_preds:
|
|
ensemble[i] = np.mean(member_preds, axis=0)
|
|
else:
|
|
ensemble[i] = None
|
|
return ensemble
|
|
|
|
|
|
# -- Main: Parallel A/B Testing ---------------------------------------------
|
|
|
|
def run_asset_tests(asset, cfg, prices, dates, volumes=None):
|
|
"""Run all tests for one asset. Returns list of metrics."""
|
|
data = prepare_data(prices)
|
|
n = len(data)
|
|
|
|
print(f"\n{'=' * 100}")
|
|
print(f" {asset}: {n} windows, K={cfg['K']}, corr>{cfg['corr_thresh']}")
|
|
print(f"{'=' * 100}")
|
|
|
|
# Train base model (sequential — must happen first)
|
|
print(f"\n Training base model (seed=42)...", end=" ", flush=True)
|
|
torch.manual_seed(42)
|
|
np.random.seed(42)
|
|
base_model = create_model()
|
|
train_size = 80
|
|
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(base_model, windows, targets, EPOCHS)
|
|
sd = base_model.state_dict()
|
|
print("done")
|
|
|
|
# Baseline = ATR + Trailing (proven best from previous A/B)
|
|
baseline_impr = {"adaptive_stop": True, "trailing_stop": True}
|
|
|
|
# Define all tests — each new improvement ON TOP of baseline
|
|
tests = [
|
|
("BASELINE (ATR+Trail)", baseline_impr),
|
|
("1: Adaptive corr", {**baseline_impr, "adaptive_corr": True}),
|
|
("2: Partial exit", {**baseline_impr, "partial_exit": True}),
|
|
("4: Regime adaptive", {**baseline_impr, "regime_adaptive": True}),
|
|
("5: Volume filter", {**baseline_impr, "volume_filter": True,
|
|
"volumes": volumes}),
|
|
]
|
|
|
|
# Run parallel tests
|
|
print(f" Running {len(tests)} tests in parallel ({N_WORKERS} workers)...",
|
|
end=" ", flush=True)
|
|
|
|
worker_args = [
|
|
(label, prices, dates, data, cfg, impr, sd, WINDOW_SIZE)
|
|
for label, impr in tests
|
|
]
|
|
|
|
with ProcessPoolExecutor(max_workers=N_WORKERS) as pool:
|
|
results = list(pool.map(_worker_backtest, worker_args))
|
|
|
|
print("done")
|
|
|
|
# Architecture ensemble (3: parallel model training)
|
|
print(f" Running 3: Arch ensemble (4 archs, parallel)...", end=" ", flush=True)
|
|
arch_preds = compute_arch_ensemble_parallel(data)
|
|
r = run_backtest(prices, dates, data, cfg,
|
|
{**baseline_impr, "ensemble_preds": arch_preds})
|
|
m = calc_metrics(r["trades"], "3: Arch ensemble x4")
|
|
results.append(m)
|
|
print(f"done ({m['n_trades']} trades)")
|
|
|
|
# Print
|
|
print_comparison(results, asset)
|
|
|
|
baseline = results[0]
|
|
valid = [r for r in results[1:] if r["n_trades"] >= 5]
|
|
if valid:
|
|
# Show improvements vs baseline
|
|
print(f"\n vs BASELINE (Sharpe={baseline['sharpe']}, "
|
|
f"Ret={baseline['total_return']:+.1f}%):")
|
|
for r in valid:
|
|
s_diff = r["sharpe"] - baseline["sharpe"]
|
|
r_diff = r["total_return"] - baseline["total_return"]
|
|
verdict = "BETTER" if r["sharpe"] > baseline["sharpe"] else "WORSE"
|
|
print(f" {r['label']:<25s} Sharpe {s_diff:+.2f}, "
|
|
f"Ret {r_diff:+.1f}% [{verdict}]")
|
|
|
|
return results
|
|
|
|
|
|
def run_asset_combos(asset, cfg, prices, dates, volumes=None, passed_keys=None):
|
|
"""Run combination tests for one asset. Only combines improvements that passed."""
|
|
data = prepare_data(prices)
|
|
|
|
print(f"\n{'=' * 100}")
|
|
print(f" {asset}: COMBINATIONS (v2)")
|
|
print(f"{'=' * 100}")
|
|
|
|
if not passed_keys:
|
|
print(" No improvements passed — skipping combos")
|
|
return []
|
|
|
|
torch.manual_seed(42)
|
|
np.random.seed(42)
|
|
base_model = create_model()
|
|
train_size = 80
|
|
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(base_model, windows, targets, EPOCHS)
|
|
sd = base_model.state_dict()
|
|
|
|
# Baseline = ATR + Trailing
|
|
base = {"adaptive_stop": True, "trailing_stop": True}
|
|
|
|
# Map improvement names to dict keys
|
|
key_map = {
|
|
"adaptive_corr": {"adaptive_corr": True},
|
|
"partial_exit": {"partial_exit": True},
|
|
"regime_adaptive": {"regime_adaptive": True},
|
|
"volume_filter": {"volume_filter": True, "volumes": volumes},
|
|
}
|
|
|
|
# Generate all pairs from passed keys
|
|
combos = [("BASELINE (ATR+Trail)", base)]
|
|
passed_list = [k for k in passed_keys if k in key_map] # exclude arch_ensemble
|
|
|
|
from itertools import combinations as iter_combos
|
|
# Pairs
|
|
for a, b in iter_combos(passed_list, 2):
|
|
label = f"{a} + {b}"
|
|
impr = {**base, **key_map[a], **key_map[b]}
|
|
combos.append((label, impr))
|
|
|
|
# Triples (if 3+ passed)
|
|
if len(passed_list) >= 3:
|
|
for combo in iter_combos(passed_list, 3):
|
|
label = " + ".join(combo)
|
|
impr = dict(base)
|
|
for k in combo:
|
|
impr.update(key_map[k])
|
|
combos.append((label, impr))
|
|
|
|
print(f" Running {len(combos)} combos in parallel...", end=" ", flush=True)
|
|
worker_args = [
|
|
(label, prices, dates, data, cfg, impr, sd, WINDOW_SIZE)
|
|
for label, impr in combos
|
|
]
|
|
with ProcessPoolExecutor(max_workers=N_WORKERS) as pool:
|
|
results = list(pool.map(_worker_backtest, worker_args))
|
|
print("done")
|
|
|
|
print_comparison(results, asset)
|
|
|
|
valid = [r for r in results if r["n_trades"] >= 5]
|
|
if valid:
|
|
best = max(valid, key=lambda r: r["sharpe"])
|
|
print(f"\n BEST COMBO for {asset}: {best['label']} "
|
|
f"(Sharpe={best['sharpe']}, Return={best['total_return']:+.1f}%)")
|
|
|
|
return results
|
|
|
|
|
|
def main():
|
|
t0 = time.time()
|
|
|
|
print("=" * 100)
|
|
print(f"IMPROVEMENT A/B TESTING v2 (parallel, {N_WORKERS} workers)")
|
|
print("=" * 100)
|
|
print(" Baseline: ATR + Trailing stop")
|
|
print(" New improvements: adaptive_corr, partial_exit, arch_ensemble,")
|
|
print(" regime_adaptive, volume_filter")
|
|
print()
|
|
|
|
all_metrics = {}
|
|
all_data = {} # cache prices/volumes/dates per asset
|
|
|
|
# Phase 1: Individual improvements
|
|
for asset, cfg in ASSET_CONFIGS.items():
|
|
time.sleep(2)
|
|
try:
|
|
prices, volumes, dates = fetch_asset_with_volume(asset)
|
|
except Exception as e:
|
|
print(f"\n {asset}: FETCH ERROR ({e})")
|
|
continue
|
|
all_data[asset] = (prices, volumes, dates)
|
|
all_metrics[asset] = run_asset_tests(asset, cfg, prices, dates, volumes)
|
|
|
|
# Phase 2: Determine which improvements passed (Sharpe > baseline on >=2 assets)
|
|
improvement_labels = {
|
|
"1: Adaptive corr": "adaptive_corr",
|
|
"2: Partial exit": "partial_exit",
|
|
"3: Arch ensemble x4": "arch_ensemble",
|
|
"4: Regime adaptive": "regime_adaptive",
|
|
"5: Volume filter": "volume_filter",
|
|
}
|
|
|
|
pass_counts = {key: 0 for key in improvement_labels.values()}
|
|
for asset, results in all_metrics.items():
|
|
if not results:
|
|
continue
|
|
baseline_sharpe = results[0]["sharpe"]
|
|
for r in results[1:]:
|
|
for label, key in improvement_labels.items():
|
|
if r["label"] == label and r["sharpe"] > baseline_sharpe:
|
|
pass_counts[key] += 1
|
|
|
|
print(f"\n\n{'=' * 100}")
|
|
print("PHASE 2: FILTERING — which improvements passed (>= 2 assets)?")
|
|
print(f"{'=' * 100}")
|
|
|
|
passed_keys = []
|
|
for key, count in pass_counts.items():
|
|
verdict = "PASS" if count >= 2 else "FAIL"
|
|
print(f" {key:<20s}: {count}/4 assets [{verdict}]")
|
|
if count >= 2:
|
|
passed_keys.append(key)
|
|
|
|
# Phase 3: Combinations (only passed improvements, excluding arch_ensemble)
|
|
combo_keys = [k for k in passed_keys if k != "arch_ensemble"]
|
|
|
|
if combo_keys:
|
|
print(f"\n\n{'=' * 100}")
|
|
print(f"PHASE 3: COMBINATIONS ({len(combo_keys)} passed improvements)")
|
|
print(f"{'=' * 100}")
|
|
|
|
for asset, cfg in ASSET_CONFIGS.items():
|
|
if asset not in all_data:
|
|
continue
|
|
prices, volumes, dates = all_data[asset]
|
|
run_asset_combos(asset, cfg, prices, dates, volumes, combo_keys)
|
|
else:
|
|
print("\n No improvements passed — skipping combinations")
|
|
|
|
# Final summary
|
|
elapsed = time.time() - t0
|
|
print(f"\n\n{'=' * 100}")
|
|
print(f"FINAL SUMMARY ({elapsed:.0f}s)")
|
|
print(f"{'=' * 100}")
|
|
|
|
for asset in ASSET_CONFIGS:
|
|
if asset not in all_metrics:
|
|
continue
|
|
results = all_metrics[asset]
|
|
baseline = results[0]
|
|
valid = [r for r in results[1:] if r["n_trades"] >= 5]
|
|
|
|
if not valid:
|
|
print(f"\n {asset}: no valid improvements")
|
|
continue
|
|
|
|
best_sharpe = max(valid, key=lambda r: r["sharpe"])
|
|
best_return = max(valid, key=lambda r: r["total_return"])
|
|
|
|
print(f"\n {asset} (baseline: Sharpe={baseline['sharpe']}, "
|
|
f"Ret={baseline['total_return']:+.1f}%):")
|
|
print(f" Best Sharpe: {best_sharpe['label']} → {best_sharpe['sharpe']} "
|
|
f"(vs {baseline['sharpe']})")
|
|
print(f" Best Return: {best_return['label']} → "
|
|
f"{best_return['total_return']:+.1f}% "
|
|
f"(vs {baseline['total_return']:+.1f}%)")
|
|
|
|
print(f"\n Passed improvements: {passed_keys if passed_keys else 'none'}")
|
|
|
|
# Save log
|
|
os.makedirs("logs", exist_ok=True)
|
|
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
|
log_path = f"logs/improvements_v2_{ts}.json"
|
|
with open(log_path, "w") as f:
|
|
json.dump({
|
|
"timestamp": datetime.now().isoformat(),
|
|
"elapsed_seconds": elapsed,
|
|
"passed_improvements": passed_keys,
|
|
"pass_counts": pass_counts,
|
|
"results": {
|
|
asset: metrics
|
|
for asset, metrics in all_metrics.items()
|
|
},
|
|
}, f, indent=2, default=str)
|
|
|
|
print(f"\n Log saved: {log_path}")
|
|
print(f"{'=' * 100}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|