Files
scalp-bot/backtest_experiments.py
T

237 lines
8.8 KiB
Python

"""Walk-forward tests for multi-session and volume-spike strategies."""
from __future__ import annotations
import itertools
import sys
from zoneinfo import ZoneInfo
import numpy as np
import pandas as pd
from data import fetch_candles
from strategy import Trade
from strategy_multi import MultiParams, run_multi
from strategy_volume import VolumeParams, run_volume
NY = ZoneInfo("America/New_York")
INITIAL_CAPITAL = 1_000.0
RISK_PCT = 0.02
MAKER_FEE = 0.0002
TAKER_FEE = 0.00055
LEVERAGE = 10
TRAIN_RATIO = 0.5
TIMEFRAME = "5m"
# ── Grids ────────────────────────────────────────────────────────────
GRID_MULTI = {
"rr_ratio": [2.0, 2.5, 3.0],
"max_trades": [1, 2],
"fvg_expiry": [6, 12],
"min_range_pct": [0.0, 0.1, 0.2],
"min_fvg_pct": [0.0, 0.02],
"first_fvg_only": [False, True],
} # 3*2*2*3*2*2 = 144
GRID_VOLUME = {
"vol_lookback": [12, 24],
"vol_mult": [1.5, 2.0, 3.0],
"spike_bars": [2, 3],
"rr_ratio": [2.0, 2.5, 3.0],
"fvg_expiry": [6, 12],
"cooldown": [6, 12],
"min_fvg_pct": [0.0, 0.02],
"first_fvg_only": [False, True],
} # 2*3*2*3*2*2*2*2 = 576
# ── Shared infra ─────────────────────────────────────────────────────
def trades_to_pnl(trades: list[Trade], capital: float) -> list[dict]:
results = []
equity = capital
for t in trades:
risk_dollar = equity * RISK_PCT
risk_dist = abs(t.entry - t.stop)
if risk_dist <= 0 or equity <= 0:
continue
pos_size = risk_dollar / risk_dist
pos_value = pos_size * t.entry
max_pos = equity * LEVERAGE
if pos_value > max_pos:
pos_size = max_pos / t.entry
pos_value = max_pos
if t.direction == "long":
gross = pos_size * (t.exit_price - t.entry)
else:
gross = pos_size * (t.entry - t.exit_price)
commission = pos_value * (MAKER_FEE + TAKER_FEE)
pnl_net = gross - commission
equity += pnl_net
results.append({
"pnl_net": pnl_net, "commission": commission,
"equity_after": equity, "entry_time": t.entry_time,
})
return results
def compute_metrics(dollar_trades: list[dict], initial_capital: float,
n_days: int) -> dict:
empty = {"trades": 0, "wr": 0, "total_pnl": 0, "total_comm": 0,
"total_ret": 0, "sharpe": 0, "max_dd": 0, "monthly_pnl": 0,
"avg_win": 0, "avg_loss": 0}
if not dollar_trades:
return empty
pnls = [t["pnl_net"] for t in dollar_trades]
wins = [p for p in pnls if p > 0]
losses = [p for p in pnls if p <= 0]
total_pnl = sum(pnls)
total_comm = sum(t["commission"] for t in dollar_trades)
wr = len(wins) / len(pnls) * 100
equity_curve = [initial_capital]
for t in dollar_trades:
equity_curve.append(t["equity_after"])
eq = np.array(equity_curve)
peak = np.maximum.accumulate(eq)
dd_pct = (peak - eq) / peak * 100
max_dd = float(dd_pct.max())
if len(pnls) > 1 and n_days > 1:
daily_pnl = np.zeros(n_days)
t0 = pd.Timestamp(dollar_trades[0]["entry_time"])
if t0.tzinfo is None:
t0 = t0.tz_localize("UTC")
t0_date = t0.date()
for t in dollar_trades:
tsi = pd.Timestamp(t["entry_time"])
if tsi.tzinfo is None:
tsi = tsi.tz_localize("UTC")
day_idx = (tsi.date() - t0_date).days
day_idx = max(0, min(day_idx, n_days - 1))
daily_pnl[day_idx] += t["pnl_net"]
daily_ret = daily_pnl / initial_capital
std = np.std(daily_ret)
sharpe = float(np.mean(daily_ret) / std * np.sqrt(365)) if std > 0 else 0.0
else:
sharpe = 0.0
months = n_days / 30.44
return {
"trades": len(pnls), "wr": round(wr, 1),
"total_pnl": round(total_pnl, 2), "total_comm": round(total_comm, 2),
"total_ret": round(total_pnl / initial_capital * 100, 1),
"sharpe": round(sharpe, 2), "max_dd": round(max_dd, 1),
"monthly_pnl": round(total_pnl / months, 2) if months > 0 else 0,
"avg_win": round(np.mean(wins), 2) if wins else 0,
"avg_loss": round(np.mean(losses), 2) if losses else 0,
}
def _split(df):
df["_date"] = df["timestamp"].dt.date
dates = sorted(df["_date"].unique())
split = int(len(dates) * TRAIN_RATIO)
train_dates = set(dates[:split])
test_dates = set(dates[split:])
df_train = df[df["_date"].isin(train_dates)].copy().drop(columns=["_date"])
df_test = df[df["_date"].isin(test_dates)].copy().drop(columns=["_date"])
df.drop(columns=["_date"], inplace=True)
return df_train, df_test, dates, split
def _print_result(name: str, train: dict, test: dict, params):
print(f"\n {'Metric':<14s} {'In-Sample':>12s} {'Out-of-Sample':>14s}")
print(f" {'-'*42}")
for label, k in [("Trades","trades"),("WR%","wr"),("PnL","total_pnl"),
("Return%","total_ret"),("Comm","total_comm"),
("Sharpe","sharpe"),("MaxDD","max_dd"),("$/mo","monthly_pnl")]:
tv, ev = train[k], test[k]
if k in ("total_pnl","total_comm","monthly_pnl","avg_win","avg_loss"):
print(f" {label:<14s} ${tv:>+11,.2f} ${ev:>+13,.2f}")
elif k in ("wr","total_ret","max_dd"):
print(f" {label:<14s} {tv:>11.1f}% {ev:>13.1f}%")
elif k == "sharpe":
print(f" {label:<14s} {tv:>12.2f} {ev:>14.2f}")
else:
print(f" {label:<14s} {tv:>12} {ev:>14}")
verdict = "PASS" if test.get("total_pnl", 0) > 0 else "FAIL"
print(f"\n OOS: {verdict} | ${test['total_pnl']:+,.2f} ({test['total_ret']:+.1f}%)")
# ── Multi-session experiment ─────────────────────────────────────────
def test_multi(symbol: str, df: pd.DataFrame):
df_train, df_test, dates, split = _split(df.copy())
n_train, n_test = split, len(dates) - split
print(f"\n{'='*65}")
print(f" MULTI-SESSION | {symbol} | Asia+London+NYSE")
print(f"{'='*65}")
keys = list(GRID_MULTI.keys())
combos = list(itertools.product(*GRID_MULTI.values()))
best_score, best_kw = -999.0, {}
for vals in combos:
kw = dict(zip(keys, vals))
trades = run_multi(df_train.copy(), MultiParams(**kw))
score = sum(t.pnl_r for t in trades) if len(trades) >= 3 else -999
if score > best_score:
best_score, best_kw = score, kw
best = MultiParams(**best_kw) if best_kw else MultiParams()
print(f" Best: {best}")
train_trades = run_multi(df_train.copy(), best)
test_trades = run_multi(df_test.copy(), best)
train_m = compute_metrics(trades_to_pnl(train_trades, INITIAL_CAPITAL), INITIAL_CAPITAL, n_train)
test_m = compute_metrics(trades_to_pnl(test_trades, INITIAL_CAPITAL), INITIAL_CAPITAL, n_test)
_print_result("Multi", train_m, test_m, best)
return test_m
# ── Volume-spike experiment ──────────────────────────────────────────
def test_volume(symbol: str, df: pd.DataFrame):
df_train, df_test, dates, split = _split(df.copy())
n_train, n_test = split, len(dates) - split
print(f"\n{'='*65}")
print(f" VOLUME-SPIKE | {symbol} | 24/7")
print(f"{'='*65}")
keys = list(GRID_VOLUME.keys())
combos = list(itertools.product(*GRID_VOLUME.values()))
best_score, best_kw = -999.0, {}
for idx, vals in enumerate(combos):
kw = dict(zip(keys, vals))
trades = run_volume(df_train.copy(), VolumeParams(**kw))
score = sum(t.pnl_r for t in trades) if len(trades) >= 3 else -999
if score > best_score:
best_score, best_kw = score, kw
if (idx + 1) % 100 == 0:
print(f"\r {idx+1}/{len(combos)}...", end="", flush=True)
print(f"\r {len(combos)}/{len(combos)} done. ")
best = VolumeParams(**best_kw) if best_kw else VolumeParams()
print(f" Best: {best}")
train_trades = run_volume(df_train.copy(), best)
test_trades = run_volume(df_test.copy(), best)
train_m = compute_metrics(trades_to_pnl(train_trades, INITIAL_CAPITAL), INITIAL_CAPITAL, n_train)
test_m = compute_metrics(trades_to_pnl(test_trades, INITIAL_CAPITAL), INITIAL_CAPITAL, n_test)
_print_result("Volume", train_m, test_m, best)
return test_m
if __name__ == "__main__":
symbols = sys.argv[1:] if len(sys.argv) > 1 else [
"ETH/USDT:USDT", "SOL/USDT:USDT", "BTC/USDT:USDT"
]
for sym in symbols:
df = fetch_candles(sym, 60, TIMEFRAME)
test_multi(sym, df)
test_volume(sym, df)