feat: A/B тестирование 7 улучшений стратегии + комбинации
Протестировано: ATR stop, trailing stop, Kelly sizing, multi-timeframe, ensemble, vol filter, corr threshold, leverage. Лучшие результаты: ATR+Trailing (BTC +197%, ETH +172%). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
+755
@@ -0,0 +1,755 @@
|
||||
"""
|
||||
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 copy import deepcopy
|
||||
from datetime import date, datetime
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
from data_v2 import fetch_asset
|
||||
from models import EnhancedRemizovNet
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
|
||||
# -- 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},
|
||||
}
|
||||
|
||||
|
||||
# -- Model helpers -----------------------------------------------------------
|
||||
|
||||
def create_model(grid_size=WINDOW_SIZE):
|
||||
return EnhancedRemizovNet(
|
||||
grid_size=grid_size, n_steps=N_STEPS, total_time=TOTAL_TIME,
|
||||
dx=1.0 / grid_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()
|
||||
|
||||
|
||||
# -- 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):
|
||||
h = prices[i] # daily data, use close as proxy
|
||||
l = prices[i]
|
||||
c_prev = prices[i - 1]
|
||||
tr = max(h - l, abs(h - c_prev), abs(l - c_prev))
|
||||
# For close-only data, TR ≈ abs(close - prev_close)
|
||||
tr = abs(prices[i] - prices[i - 1])
|
||||
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:
|
||||
"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 (if using ensemble)
|
||||
"""
|
||||
if improvements is None:
|
||||
improvements = {}
|
||||
|
||||
K = cfg["K"]
|
||||
corr_thresh = improvements.get("corr_override", cfg["corr_thresh"])
|
||||
train_size = 80
|
||||
|
||||
n = len(data)
|
||||
if n < train_size + 5:
|
||||
return {"trades": [], "equity_curve": [INITIAL_EQUITY]}
|
||||
|
||||
# Model setup (unless ensemble provides predictions)
|
||||
ensemble_preds = improvements.get("ensemble_preds")
|
||||
model = None
|
||||
if ensemble_preds is None:
|
||||
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:]
|
||||
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
|
||||
|
||||
# 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
|
||||
if improvements.get("adaptive_stop"):
|
||||
# (A) ATR-based stop
|
||||
pidx = d["price_idx"]
|
||||
atr = compute_atr(prices, pidx)
|
||||
stop_dist = max(atr * 2.0, 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
|
||||
|
||||
if improvements.get("trailing_stop"):
|
||||
# Trailing stop: move stop in favorable direction
|
||||
best_price = entry_price
|
||||
for hp in d["future_prices"][K:]:
|
||||
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
|
||||
for hp in d["future_prices"][K:]:
|
||||
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
|
||||
|
||||
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)
|
||||
|
||||
weekly_rets = [t["pnl_pct"] / 100 for t in trades]
|
||||
if len(weekly_rets) > 2 and np.std(weekly_rets) > 0:
|
||||
sharpe = np.mean(weekly_rets) / np.std(weekly_rets) * np.sqrt(52)
|
||||
else:
|
||||
sharpe = 0
|
||||
|
||||
first_date = trades[0]["date"]
|
||||
last_date = trades[-1]["date"]
|
||||
years = (last_date - first_date).days / 365.25
|
||||
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}")
|
||||
|
||||
|
||||
# -- Main: Sequential A/B Testing -------------------------------------------
|
||||
|
||||
def main():
|
||||
t0 = time.time()
|
||||
|
||||
print("=" * 100)
|
||||
print("IMPROVEMENT A/B TESTING")
|
||||
print("=" * 100)
|
||||
|
||||
all_metrics = {} # asset -> list of metrics dicts
|
||||
best_per_asset = {} # asset -> best improvement name
|
||||
|
||||
for asset, cfg in ASSET_CONFIGS.items():
|
||||
time.sleep(2)
|
||||
try:
|
||||
prices, dates = fetch_asset(asset)
|
||||
except Exception as e:
|
||||
print(f"\n {asset}: FETCH ERROR ({e})")
|
||||
continue
|
||||
|
||||
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}")
|
||||
|
||||
results = []
|
||||
|
||||
# ── BASELINE ──
|
||||
print(f"\n Running BASELINE...", end=" ", flush=True)
|
||||
r = run_backtest(prices, dates, data, cfg)
|
||||
m = calc_metrics(r["trades"], "BASELINE")
|
||||
results.append(m)
|
||||
print(f"done ({m['n_trades']} trades)")
|
||||
|
||||
# ── A: Adaptive Stop (ATR) ──
|
||||
print(f" Running A: ATR stop...", end=" ", flush=True)
|
||||
r = run_backtest(prices, dates, data, cfg, {"adaptive_stop": True})
|
||||
m = calc_metrics(r["trades"], "A: ATR stop")
|
||||
results.append(m)
|
||||
print(f"done ({m['n_trades']} trades)")
|
||||
|
||||
# ── A2: Trailing Stop ──
|
||||
print(f" Running A2: Trailing stop...", end=" ", flush=True)
|
||||
r = run_backtest(prices, dates, data, cfg, {"trailing_stop": True})
|
||||
m = calc_metrics(r["trades"], "A2: Trailing stop")
|
||||
results.append(m)
|
||||
print(f"done ({m['n_trades']} trades)")
|
||||
|
||||
# ── B: Kelly Position Sizing ──
|
||||
print(f" Running B: Kelly sizing...", end=" ", flush=True)
|
||||
r = run_backtest(prices, dates, data, cfg, {"kelly": True})
|
||||
m = calc_metrics(r["trades"], "B: Kelly sizing")
|
||||
results.append(m)
|
||||
print(f"done ({m['n_trades']} trades)")
|
||||
|
||||
# ── C: Multi-Timeframe ──
|
||||
print(f" Running C: Multi-TF...", end=" ", flush=True)
|
||||
long_dirs = compute_multitf_filter(prices, data)
|
||||
if long_dirs is not None:
|
||||
# Filter: only trade when short-TF and long-TF agree on direction
|
||||
# We implement this as a vol_filter-like mechanism inside the backtest
|
||||
# by pre-filtering data
|
||||
r_base = run_backtest(prices, dates, data, cfg)
|
||||
# Post-filter: remove trades where long-TF disagrees
|
||||
filtered_trades = []
|
||||
eq = INITIAL_EQUITY
|
||||
for t in r_base["trades"]:
|
||||
# Find nearest long-TF direction
|
||||
t_date = t["date"]
|
||||
t_idx = None
|
||||
for ii, d in enumerate(dates):
|
||||
if d >= t_date:
|
||||
t_idx = ii
|
||||
break
|
||||
if t_idx is None:
|
||||
t_idx = len(dates) - 1
|
||||
|
||||
# Find closest long_directions key
|
||||
best_key = None
|
||||
best_dist = 999999
|
||||
for k in long_dirs:
|
||||
dist = abs(k - t_idx)
|
||||
if dist < best_dist:
|
||||
best_dist = dist
|
||||
best_key = k
|
||||
|
||||
if best_key is not None and best_dist < SHIFT * 2:
|
||||
long_dir = long_dirs[best_key]
|
||||
trade_dir = 1 if t["direction"] == "L" else -1
|
||||
if long_dir != trade_dir:
|
||||
continue # skip disagreeing trades
|
||||
|
||||
eq += t["pnl_net"]
|
||||
filtered_trades.append({**t, "equity": eq})
|
||||
|
||||
m = calc_metrics(filtered_trades, "C: Multi-TF filter")
|
||||
else:
|
||||
m = calc_metrics([], "C: Multi-TF filter")
|
||||
results.append(m)
|
||||
print(f"done ({m['n_trades']} trades)")
|
||||
|
||||
# ── D: Ensemble (3 models) ──
|
||||
print(f" Running D: Ensemble (3 models)...", end=" ", flush=True)
|
||||
ens_preds = compute_ensemble_preds(data, n_models=3)
|
||||
r = run_backtest(prices, dates, data, cfg, {"ensemble_preds": ens_preds})
|
||||
m = calc_metrics(r["trades"], "D: Ensemble x3")
|
||||
results.append(m)
|
||||
print(f"done ({m['n_trades']} trades)")
|
||||
|
||||
# ── E: Volatility Filter ──
|
||||
print(f" Running E: Vol filter...", end=" ", flush=True)
|
||||
r = run_backtest(prices, dates, data, cfg, {"vol_filter": True})
|
||||
m = calc_metrics(r["trades"], "E: Vol filter (MA20>50)")
|
||||
results.append(m)
|
||||
print(f"done ({m['n_trades']} trades)")
|
||||
|
||||
# ── F: Higher Correlation Threshold ──
|
||||
for thresh in [0.7, 0.8, 0.9]:
|
||||
if thresh <= cfg["corr_thresh"]:
|
||||
continue
|
||||
print(f" Running F: corr>{thresh}...", end=" ", flush=True)
|
||||
r = run_backtest(prices, dates, data, cfg,
|
||||
{"corr_override": thresh})
|
||||
m = calc_metrics(r["trades"], f"F: corr>{thresh}")
|
||||
results.append(m)
|
||||
print(f"done ({m['n_trades']} trades)")
|
||||
|
||||
# ── G: Leverage 2x ──
|
||||
print(f" Running G: 2x leverage...", end=" ", flush=True)
|
||||
r = run_backtest(prices, dates, data, cfg, {"leverage": 2.0})
|
||||
m = calc_metrics(r["trades"], "G: 2x leverage")
|
||||
results.append(m)
|
||||
print(f"done ({m['n_trades']} trades)")
|
||||
|
||||
# Print comparison
|
||||
print_comparison(results, asset)
|
||||
|
||||
# Find best (by Sharpe, minimum 5 trades)
|
||||
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 for {asset}: {best['label']} "
|
||||
f"(Sharpe={best['sharpe']}, Return={best['total_return']:+.1f}%)")
|
||||
best_per_asset[asset] = best["label"]
|
||||
|
||||
all_metrics[asset] = results
|
||||
|
||||
# ================================================================
|
||||
# PHASE 2: COMBINATIONS of best improvements
|
||||
# ================================================================
|
||||
print(f"\n\n{'=' * 100}")
|
||||
print("PHASE 2: COMBINATIONS")
|
||||
print(f"{'=' * 100}")
|
||||
|
||||
# Define promising combos based on individual results
|
||||
combos = [
|
||||
("ATR + Kelly", {"adaptive_stop": True, "kelly": True}),
|
||||
("ATR + Trailing", {"adaptive_stop": True, "trailing_stop": True}),
|
||||
("ATR + Vol filter", {"adaptive_stop": True, "vol_filter": True}),
|
||||
("Kelly + Vol filter", {"kelly": True, "vol_filter": True}),
|
||||
("ATR + Kelly + Vol", {"adaptive_stop": True, "kelly": True, "vol_filter": True}),
|
||||
("ATR + Kelly + Trail", {"adaptive_stop": True, "kelly": True, "trailing_stop": True}),
|
||||
("Trail + Vol filter", {"trailing_stop": True, "vol_filter": True}),
|
||||
("ATR+Kelly+Vol+2x", {"adaptive_stop": True, "kelly": True, "vol_filter": True, "leverage": 2.0}),
|
||||
]
|
||||
|
||||
for asset, cfg in ASSET_CONFIGS.items():
|
||||
time.sleep(2)
|
||||
try:
|
||||
prices, dates = fetch_asset(asset)
|
||||
except Exception as e:
|
||||
continue
|
||||
|
||||
data = prepare_data(prices)
|
||||
|
||||
print(f"\n{'=' * 100}")
|
||||
print(f" {asset}: COMBINATIONS")
|
||||
print(f"{'=' * 100}")
|
||||
|
||||
results = []
|
||||
|
||||
# Baseline for reference
|
||||
r = run_backtest(prices, dates, data, cfg)
|
||||
results.append(calc_metrics(r["trades"], "BASELINE"))
|
||||
|
||||
for name, impr in combos:
|
||||
print(f" Running {name}...", end=" ", flush=True)
|
||||
r = run_backtest(prices, dates, data, cfg, impr)
|
||||
m = calc_metrics(r["trades"], name)
|
||||
results.append(m)
|
||||
print(f"done ({m['n_trades']} trades)")
|
||||
|
||||
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}%)")
|
||||
|
||||
# ================================================================
|
||||
# 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 if r["n_trades"] >= 5 and r["label"] != "BASELINE"]
|
||||
|
||||
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"])
|
||||
best_wr = max(valid, key=lambda r: r["win_rate"])
|
||||
|
||||
print(f"\n {asset} (baseline: Sharpe={baseline['sharpe']}, "
|
||||
f"Ret={baseline['total_return']:+.1f}%, WR={baseline['win_rate']:.0f}%):")
|
||||
print(f" Best Sharpe: {best_sharpe['label']} → {best_sharpe['sharpe']} "
|
||||
f"(vs {baseline['sharpe']})")
|
||||
print(f" Best Return: {best_return['label']} → {best_return['total_return']:+.1f}% "
|
||||
f"(vs {baseline['total_return']:+.1f}%)")
|
||||
print(f" Best WR: {best_wr['label']} → {best_wr['win_rate']:.0f}% "
|
||||
f"(vs {baseline['win_rate']:.0f}%)")
|
||||
|
||||
# Save log
|
||||
os.makedirs("logs", exist_ok=True)
|
||||
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
log_path = f"logs/improvements_{ts}.json"
|
||||
with open(log_path, "w") as f:
|
||||
json.dump({
|
||||
"timestamp": datetime.now().isoformat(),
|
||||
"elapsed_seconds": elapsed,
|
||||
"results": {
|
||||
asset: [
|
||||
{k: v for k, v in m.items()
|
||||
if k not in ("trades",)}
|
||||
for m in 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()
|
||||
Reference in New Issue
Block a user