235 lines
8.6 KiB
Python
235 lines
8.6 KiB
Python
"""Walk-forward backtest for rolling range strategy (24/7)."""
|
|
|
|
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_rolling import RollingParams, run_continuous
|
|
|
|
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"
|
|
|
|
GRID = {
|
|
"range_period": [6, 12, 24], # 30min, 1h, 2h on 5m
|
|
"rr_ratio": [2.0, 2.5, 3.0],
|
|
"fvg_expiry": [6, 12],
|
|
"cooldown": [3, 6, 12],
|
|
"min_range_pct": [0.0, 0.1, 0.2],
|
|
"min_fvg_pct": [0.0, 0.02],
|
|
"first_fvg_only": [False, True],
|
|
}
|
|
# 3*3*2*3*3*2*2 = 648 combos
|
|
|
|
|
|
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:
|
|
if not dollar_trades:
|
|
return {"trades": 0, "wins": 0, "losses": 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}
|
|
|
|
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)
|
|
ts0 = pd.Timestamp(dollar_trades[0]["entry_time"])
|
|
t0 = (ts0.tz_convert(NY) if ts0.tzinfo else ts0.tz_localize("UTC").tz_convert(NY)).date()
|
|
for t in dollar_trades:
|
|
ts = t["entry_time"]
|
|
if ts is not None:
|
|
tsi = pd.Timestamp(ts)
|
|
d = (tsi.tz_convert(NY) if tsi.tzinfo else tsi.tz_localize("UTC").tz_convert(NY)).date()
|
|
day_idx = (d - t0).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), "wins": len(wins), "losses": len(losses),
|
|
"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_by_date(df: pd.DataFrame):
|
|
"""Split dataframe into train/test by calendar date."""
|
|
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()
|
|
df_test = df[df["_date"].isin(test_dates)].copy()
|
|
df.drop(columns=["_date"], inplace=True)
|
|
df_train.drop(columns=["_date"], inplace=True)
|
|
df_test.drop(columns=["_date"], inplace=True)
|
|
return df_train, df_test, dates, split
|
|
|
|
|
|
def find_best_params(df_train: pd.DataFrame) -> RollingParams:
|
|
keys = list(GRID.keys())
|
|
combos = list(itertools.product(*GRID.values()))
|
|
best_score = -999.0
|
|
best_kw = {}
|
|
|
|
for idx, vals in enumerate(combos):
|
|
kw = dict(zip(keys, vals))
|
|
p = RollingParams(**kw)
|
|
trades = run_continuous(df_train, p)
|
|
score = sum(t.pnl_r for t in trades) if len(trades) >= 3 else -999
|
|
if score > best_score:
|
|
best_score = score
|
|
best_kw = kw
|
|
if (idx + 1) % 100 == 0:
|
|
print(f"\r {idx+1}/{len(combos)}...", end="", flush=True)
|
|
|
|
print(f"\r {len(combos)}/{len(combos)} done. ")
|
|
return RollingParams(**best_kw) if best_kw else RollingParams()
|
|
|
|
|
|
def walk_forward(symbol: str, days: int = 60):
|
|
df = fetch_candles(symbol, days, TIMEFRAME)
|
|
df_train, df_test, dates, split = _split_by_date(df)
|
|
n_train = split
|
|
n_test = len(dates) - split
|
|
|
|
print(f"\n{'='*65}")
|
|
print(f" Rolling WF | {symbol} | {days}d | {TIMEFRAME} | 24/7")
|
|
print(f"{'='*65}")
|
|
print(f" Train: {n_train} days ({dates[0]} → {dates[split-1]})")
|
|
print(f" Test: {n_test} days ({dates[split]} → {dates[-1]})")
|
|
print(f" Capital: ${INITIAL_CAPITAL:,.0f} | Risk: {RISK_PCT*100:.0f}% | Lev: {LEVERAGE}x")
|
|
|
|
n_combos = len(list(itertools.product(*GRID.values())))
|
|
print(f"\n Phase 1: Grid search ({n_combos} combos)...")
|
|
best = find_best_params(df_train)
|
|
print(f" Best params: {best}")
|
|
|
|
# In-sample
|
|
train_trades = run_continuous(df_train, best)
|
|
train_dollar = trades_to_pnl(train_trades, INITIAL_CAPITAL)
|
|
train_m = compute_metrics(train_dollar, INITIAL_CAPITAL, n_train)
|
|
|
|
# Out-of-sample
|
|
print(f"\n Phase 2: Out-of-sample test...")
|
|
test_trades = run_continuous(df_test, best)
|
|
test_dollar = trades_to_pnl(test_trades, INITIAL_CAPITAL)
|
|
test_m = compute_metrics(test_dollar, INITIAL_CAPITAL, n_test)
|
|
|
|
_print_comparison(train_m, test_m)
|
|
return {"train": train_m, "test": test_m, "params": best}
|
|
|
|
|
|
def _print_comparison(train: dict, test: dict):
|
|
print(f"\n {'Metric':<14s} {'In-Sample':>12s} {'Out-of-Sample':>14s}")
|
|
print(f" {'-'*42}")
|
|
rows = [
|
|
("Trades", f"{train['trades']}", f"{test['trades']}"),
|
|
("Win Rate", f"{train['wr']}%", f"{test['wr']}%"),
|
|
("Total PnL", f"${train['total_pnl']:+,.2f}", f"${test['total_pnl']:+,.2f}"),
|
|
("Return", f"{train['total_ret']:+.1f}%", f"{test['total_ret']:+.1f}%"),
|
|
("Commission", f"${train['total_comm']:,.2f}", f"${test['total_comm']:,.2f}"),
|
|
("Sharpe", f"{train['sharpe']:.2f}", f"{test['sharpe']:.2f}"),
|
|
("Max DD", f"{train['max_dd']:.1f}%", f"{test['max_dd']:.1f}%"),
|
|
("Monthly PnL", f"${train['monthly_pnl']:+,.2f}", f"${test['monthly_pnl']:+,.2f}"),
|
|
("Avg Win", f"${train['avg_win']:+,.2f}", f"${test['avg_win']:+,.2f}"),
|
|
("Avg Loss", f"${train['avg_loss']:+,.2f}", f"${test['avg_loss']:+,.2f}"),
|
|
]
|
|
for label, tv, ev in rows:
|
|
print(f" {label:<14s} {tv:>12s} {ev:>14s}")
|
|
|
|
print(f"\n {'='*42}")
|
|
verdict = "PASS" if test.get("total_pnl", 0) > 0 else "FAIL"
|
|
print(f" OOS Verdict: {verdict}")
|
|
if test["trades"] > 0:
|
|
print(f" OOS PnL: ${test['total_pnl']:+,.2f} ({test['total_ret']:+.1f}%)")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
symbols = sys.argv[1:] if len(sys.argv) > 1 else [
|
|
"BTC/USDT:USDT", "ETH/USDT:USDT", "SOL/USDT:USDT"
|
|
]
|
|
all_results = {}
|
|
for sym in symbols:
|
|
all_results[sym] = walk_forward(sym, 60)
|
|
|
|
if len(all_results) > 1:
|
|
print(f"\n\n{'='*70}")
|
|
print(f" ROLLING WF SUMMARY | ${INITIAL_CAPITAL:,.0f} | {RISK_PCT*100:.0f}% risk | {LEVERAGE}x | 24/7")
|
|
print(f"{'='*70}")
|
|
print(f" {'Symbol':<16s} {'OOS PnL':>10s} {'Ret%':>7s} {'Sharpe':>8s} "
|
|
f"{'MaxDD':>7s} {'Trades':>7s} {'WR':>6s}")
|
|
print(f" {'-'*62}")
|
|
for sym, r in all_results.items():
|
|
t = r["test"]
|
|
tag = sym.split("/")[0]
|
|
print(f" {tag:<16s} ${t['total_pnl']:>+9,.2f} {t['total_ret']:>+6.1f}% "
|
|
f"{t['sharpe']:>8.2f} {t['max_dd']:>6.1f}% {t['trades']:>7d} "
|
|
f"{t['wr']:>5.1f}%")
|