Files
remizov-trader/backtest_futures.py
anorandClaude Opus 4.6 f6e5d9c115 feat: exp31 — миграция 1h→4h, OHLCV bar-by-bar stops, 18-coin scan
- fix: optimize-windows использует OHLCV high/low для стопов (не close)
- fix: проверка стопа adverse price ПЕРЕД trailing update (conservative)
- feat: exp31_4h_migration — полный набор экспериментов:
  - 18 монет, walk-forward 30/70, delayed entry, leverage
  - Все 18 прибыльны на 4h shift=14 SM=4
  - Top-8: DOGE/APT/FIL/LINK/ETH/INJ/AVAX/WIF
  - Portfolio 1x: $23.5/mo, 75% profitable months
- add: backtest_futures.py, backtest_futures_80.py, backtest_frozen.py

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-16 13:20:50 +10:00

368 lines
14 KiB
Python

"""Walk-forward backtest: futures long+short 1x 1h.
Tests UNI, ATOM, SUI with per-asset params from new config.yaml.
Matches production logic: time_exit in bars, futures commission 0.055%.
"""
import sys
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
RISK_CFG = RiskConfig(
per_trade=0.05, max_position_pct=0.40,
max_open_positions=3, leverage=1,
)
INITIAL_CAPITAL = 177.0
TRAILING_STOP = True
TRAIN_RATIO = 0.3
LONG_ONLY = False # futures: long + short
COMMISSION = 0.00055 # futures taker fee
TIME_EXIT = True # critical: backtest uses time exit
TIMEFRAME = "1h"
# Per-asset configs from new production config.yaml
# NOTE: use spot symbols for OHLCV fetch (same prices, no linear market needed)
ASSETS = [
{
"symbol": "UNI/USDT:USDT", "ticker": "UNI-USD",
"window_size": 64, "K": 2, "shift": 14,
"epochs": 300, "lr": 0.005,
"stop_mult": 1.25, "stop_scale": 0.75,
"cooldown_bars": 3, "shape_confirm": False,
"corr_thresh": 0.5, "weight": 0.34,
},
{
"symbol": "ATOM/USDT:USDT", "ticker": "ATOM-USD",
"window_size": 64, "K": 3, "shift": 10,
"epochs": 300, "lr": 0.005,
"stop_mult": 0.75, "stop_scale": 1.0,
"cooldown_bars": 3, "shape_confirm": False,
"corr_thresh": 0.5, "weight": 0.33,
},
{
"symbol": "SUI/USDT:USDT", "ticker": "SUI-USD",
"window_size": 64, "K": 2, "shift": 10,
"epochs": 300, "lr": 0.005,
"stop_mult": 1.0, "stop_scale": 1.0,
"cooldown_bars": 3, "shape_confirm": False,
"corr_thresh": 0.5, "weight": 0.33,
},
]
def run_backtest(asset: dict, prices: np.ndarray, highs: np.ndarray = None,
lows: np.ndarray = None):
"""Walk-forward backtest with exact prod params.
If highs/lows provided, uses them for bar-by-bar stop checks.
"""
if highs is None:
highs = prices
if lows is None:
lows = prices
ws = asset["window_size"]
shift = asset["shift"]
K = asset["K"]
corr_thresh = asset["corr_thresh"]
shape_confirm = asset["shape_confirm"]
stop_mult_base = asset["stop_mult"]
stop_scale = asset["stop_scale"]
cooldown_bars = asset["cooldown_bars"]
if cooldown_bars == -1:
cooldown_bars = shift
model_cfg = ModelConfig(
window_size=ws, n_steps=20, total_time=0.5,
shift=shift, epochs=asset["epochs"],
finetune_epochs=50, lr=asset["lr"],
)
data = signals.prepare_windows(prices, ws, shift)
if len(data) < 30:
print(f" Not enough windows: {len(data)}")
return None
n_train = max(int(len(data) * TRAIN_RATIO), 20)
train_data = data[:n_train]
test_data = data[n_train:]
print(f" Windows: {len(data)} total, {n_train} train, {len(test_data)} test")
# Train
torch.manual_seed(42)
np.random.seed(42)
mdl = 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(mdl, windows, targets, model_cfg.epochs, model_cfg.lr)
print(f" Train loss: {loss:.6f}")
# Simulate (per-bar stop checking — matches lab methodology)
capital = INITIAL_CAPITAL * asset["weight"]
equity = capital
trades = []
position = None
equity_curve = [equity]
cooldown_until = 0
prev_price_idx = test_data[0]["price_idx"] if test_data else 0
for i, d in enumerate(test_data):
price_idx = d["price_idx"]
# Per-bar stop check: walk every bar between prev and current window
if position is not None and price_idx > prev_price_idx:
p = position
for bar in range(prev_price_idx + 1, price_idx + 1):
h, l = float(highs[bar]), float(lows[bar])
bar_close = float(prices[bar])
# Check stop FIRST with adverse price (conservative)
adv = l if p["direction"] == 1 else h
stopped = risk.is_stopped(adv, p["stop_price"], p["direction"])
bars_held = bar - p["entry_bar"]
time_exit = TIME_EXIT and bars_held >= (shift - p["k_used"])
if stopped or time_exit:
# Stop: exit at stop_price (triggers intra-bar near stop level)
# Time: exit at market (bar close)
exit_price = p["stop_price"] if stopped else bar_close
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"],
commission=COMMISSION,
)
equity += pnl_net
trades.append({
"direction": p["direction"],
"entry_price": p["entry_price"],
"exit_price": exit_price,
"pnl_net": pnl_net,
"pnl_pct": pnl_pct,
"reason": reason,
"equity_at_entry": p["equity_at_entry"],
"entry_idx": p["entry_bar"],
})
position = None
if stopped:
cooldown_until = bar + cooldown_bars
break
# Update trailing AFTER stop check (conservative)
fav = h if p["direction"] == 1 else l
if TRAILING_STOP:
p["best_price"], p["stop_price"] = risk.update_trailing_stop(
fav, p["best_price"], p["stop_price"],
p["stop_dist"], p["direction"],
)
prev_price_idx = price_idx
current_price = float(prices[price_idx])
# New signal
if position is None and price_idx >= ws + K and price_idx >= cooldown_until:
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:]
if shape_confirm:
corr, confirmed = signals.check_shape_confirmation(
pred_new, confirm, mu, std, K, corr_thresh,
)
else:
confirmed = True
if confirmed:
direction = signals.get_direction(pred_new, K)
if direction is not None and not (LONG_ONLY and direction == -1):
entry_price = current_price
atr = risk.compute_atr(prices, price_idx)
stop_dist = max(atr * stop_mult_base * stop_scale,
entry_price * 0.005)
stop_price = entry_price - direction * stop_dist
pos_size, pos_value = risk.calculate_position(
equity, entry_price, stop_dist, RISK_CFG,
)
position = {
"direction": direction,
"entry_price": entry_price,
"stop_price": stop_price,
"stop_dist": stop_dist,
"best_price": entry_price,
"pos_size": pos_size,
"pos_value": pos_value,
"entry_bar": price_idx,
"k_used": K,
"equity_at_entry": equity,
}
equity_curve.append(equity)
# Close remaining
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"],
commission=COMMISSION,
)
equity += pnl_net
trades.append({
"direction": position["direction"],
"entry_price": position["entry_price"],
"exit_price": last_price,
"pnl_net": pnl_net,
"pnl_pct": pnl_pct,
"reason": "end",
"equity_at_entry": position["equity_at_entry"],
"entry_idx": position["entry_bar"],
})
equity_curve.append(equity)
if not trades:
print(" No trades!")
return None
# Metrics
pnls = [t["pnl_net"] for t in trades]
wins = [t for t in trades if t["pnl_net"] > 0]
losses = [t for t in trades if t["pnl_net"] <= 0]
longs = [t for t in trades if t["direction"] == 1]
shorts = [t for t in trades if t["direction"] == -1]
total_pnl = equity - capital
total_ret = total_pnl / capital * 100
first_bar = test_data[0]["price_idx"]
last_bar = test_data[-1]["price_idx"]
n_bars = last_bar - first_bar
# 1h bars: 24 bars/day, 365.25 days/year
bars_per_day = 24
years = n_bars / (365.25 * bars_per_day)
# Sharpe (annualized from daily returns)
if len(pnls) > 1 and years > 0:
n_days = max(n_bars // bars_per_day, 1)
daily_pnl = np.zeros(n_days)
for t in trades:
day = min((t.get("entry_idx", first_bar) - first_bar) // bars_per_day,
n_days - 1)
daily_pnl[day] += t["pnl_net"]
daily_ret = daily_pnl / 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
# Max DD
eq = np.array(equity_curve)
peak = np.maximum.accumulate(eq)
dd = (peak - eq) / peak
max_dd = dd.max() * 100
months = years * 12
# Time exit stats
time_exits = [t for t in trades if t["reason"] == "time"]
stop_exits = [t for t in trades if t["reason"] == "stop"]
return {
"ticker": asset["ticker"],
"trades": len(trades), "wins": len(wins), "losses": len(losses),
"wr": len(wins) / len(trades) * 100,
"longs": len(longs), "shorts": len(shorts),
"long_wr": len([t for t in longs if t["pnl_net"] > 0]) / len(longs) * 100 if longs else 0,
"short_wr": len([t for t in shorts if t["pnl_net"] > 0]) / len(shorts) * 100 if shorts else 0,
"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,
"avg_pnl": np.mean(pnls),
"avg_win": np.mean([t["pnl_net"] for t in wins]) if wins else 0,
"avg_loss": np.mean([t["pnl_net"] for t in losses]) if losses else 0,
"time_exits": len(time_exits), "stop_exits": len(stop_exits),
"capital": capital,
}
def main():
results = []
for asset in ASSETS:
print(f"\n--- {asset['symbol']} ({asset['ticker']}) ---")
print(f" Params: K={asset['K']} shift={asset['shift']} "
f"stop_mult={asset['stop_mult']} stop_scale={asset['stop_scale']} "
f"cooldown={asset['cooldown_bars']} lr={asset['lr']}")
print(f" Fetching {TIMEFRAME} OHLCV data...")
ohlcv, dates = signals.fetch_ohlcv_ccxt(asset["symbol"], TIMEFRAME, "max")
if ohlcv is None:
print(f" No data")
continue
prices = ohlcv[:, 3] # close
highs = ohlcv[:, 1]
lows = ohlcv[:, 2]
print(f" Got {len(prices)} bars ({len(prices)/24:.0f} days)")
r = run_backtest(asset, prices, highs, lows)
if r:
results.append(r)
print(f"\n{'='*65}")
print(f" {r['ticker']} — FUTURES 1H LONG+SHORT BACKTEST")
print(f"{'='*65}")
print(f" Period: ~{r['months']:.1f} months | Capital: ${r['capital']:.0f}")
print(f" Trades: {r['trades']} (W:{r['wins']} L:{r['losses']} WR:{r['wr']:.1f}%)")
print(f" Longs: {r['longs']} (WR:{r['long_wr']:.1f}%) | "
f"Shorts: {r['shorts']} (WR:{r['short_wr']:.1f}%)")
print(f" Exits: {r['time_exits']} time | {r['stop_exits']} stop")
print(f" Total PnL: ${r['total_pnl']:+,.2f} ({r['total_ret']:+.1f}%)")
print(f" Sharpe: {r['sharpe']:.2f}")
print(f" Max DD: {r['max_dd']:.1f}%")
print(f" Monthly: ${r['monthly_pnl']:+,.2f}/mo")
print(f" Avg win: ${r['avg_win']:+,.2f} | Avg loss: ${r['avg_loss']:+,.2f}")
print(f"{'='*65}")
if results:
total_pnl = sum(r["total_pnl"] for r in results)
total_cap = sum(r["capital"] for r in results)
total_trades = sum(r["trades"] for r in results)
total_longs = sum(r["longs"] for r in results)
total_shorts = sum(r["shorts"] for r in results)
print(f"\n\n{'='*65}")
print(f" PORTFOLIO — FUTURES 1H LONG+SHORT 1x | ${INITIAL_CAPITAL:.0f} capital")
print(f" Commission: {COMMISSION*100:.3f}% | Time exit: {TIME_EXIT}")
print(f"{'='*65}")
print(f" {'Asset':<12s} {'Sharpe':>8s} {'Return':>10s} {'PnL':>10s} "
f"{'Trades':>7s} {'L/S':>6s} {'WR':>6s} {'MaxDD':>7s}")
print(f" {'-'*65}")
for r in sorted(results, key=lambda x: x["sharpe"], reverse=True):
print(f" {r['ticker']:<12s} {r['sharpe']:>8.2f} {r['total_ret']:>+9.1f}% "
f"${r['total_pnl']:>+9.2f} {r['trades']:>7d} "
f"{r['longs']:>2d}/{r['shorts']:<2d} {r['wr']:>5.1f}% "
f"{r['max_dd']:>6.1f}%")
print(f" {'-'*65}")
print(f" {'TOTAL':<12s} {'':>8s} {total_pnl/total_cap*100:>+9.1f}% "
f"${total_pnl:>+9.2f} {total_trades:>7d} "
f"{total_longs:>2d}/{total_shorts:<2d}")
print(f"{'='*65}")
# Caveat
print(f"\n ⚠ CAVEAT: backtest overestimates ~2-3x (slippage=0, corr=0)")
print(f" Expected real monthly: ${sum(r['monthly_pnl'] for r in results) * 0.4:+,.1f}/mo")
if __name__ == "__main__":
main()