- holidays.py: календарь NYSE holidays 2024–2027 (10 дат/год) - executor: _is_nyse_hours() пропускает праздники - все ORB-бэктесты: исключают holidays из train/test split и run_day() - OOS сравнение: +$18 PnL, +0.8pp WR, Sharpe 0.42→0.47 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
282 lines
11 KiB
Python
282 lines
11 KiB
Python
"""Walk-forward backtest: optimize on in-sample, test on out-of-sample.
|
|
|
|
Adapted from remizov-trader backtest_4h.py approach:
|
|
- Train/test split by date (50/50)
|
|
- Realistic Bybit futures costs (taker 0.055% per side)
|
|
- Dollar-based position sizing and PnL
|
|
- Sharpe ratio, max drawdown %, equity curve
|
|
"""
|
|
|
|
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 holidays import is_nyse_holiday
|
|
from strategy import Params, Trade, run_day
|
|
|
|
NY = ZoneInfo("America/New_York")
|
|
|
|
# ── Config ───────────────────────────────────────────────────────────
|
|
INITIAL_CAPITAL = 1_000.0
|
|
RISK_PCT = 0.05 # 5% risk per trade
|
|
MAKER_FEE = 0.0002 # Bybit maker fee (0.02%) — limit entry
|
|
TAKER_FEE = 0.00055 # Bybit taker fee (0.055%) — SL/TP exit
|
|
LEVERAGE = 10 # max leverage (caps position value)
|
|
TRAIN_RATIO = 0.5 # first 50% days = in-sample
|
|
TIMEFRAME = "5m"
|
|
OR_MINUTES = 15 # opening range duration (3 x 5m candles)
|
|
|
|
GRID = {
|
|
"rr_ratio": [2.0, 2.5, 3.0],
|
|
"max_trades": [99],
|
|
"min_range_pct": [0.0, 0.1, 0.2],
|
|
"min_fvg_pct": [0.0, 0.02, 0.05],
|
|
"first_fvg_only": [False, True],
|
|
"fvg_expiry": [6, 12], # bars (6=30min, 12=1h on 5m TF)
|
|
"stop_multiplier": [1.0, 1.5, 2.0, 2.5, 3.0],
|
|
}
|
|
|
|
|
|
# ── Dollar PnL ───────────────────────────────────────────────────────
|
|
|
|
def trades_to_pnl(trades: list[Trade], capital: float) -> list[dict]:
|
|
"""Convert R-based trades to dollar PnL with commission and leverage cap."""
|
|
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
|
|
|
|
# Leverage cap
|
|
max_pos = equity * LEVERAGE
|
|
if pos_value > max_pos:
|
|
pos_size = max_pos / t.entry
|
|
pos_value = max_pos
|
|
|
|
# Gross PnL
|
|
if t.direction == "long":
|
|
gross = pos_size * (t.exit_price - t.entry)
|
|
else:
|
|
gross = pos_size * (t.entry - t.exit_price)
|
|
|
|
# Commission: maker on entry (limit) + taker on exit (SL/TP)
|
|
commission = pos_value * (MAKER_FEE + TAKER_FEE)
|
|
pnl_net = gross - commission
|
|
|
|
equity += pnl_net
|
|
results.append({
|
|
"pnl_net": pnl_net,
|
|
"pnl_gross": gross,
|
|
"commission": commission,
|
|
"equity_after": equity,
|
|
"entry_time": t.entry_time,
|
|
})
|
|
return results
|
|
|
|
|
|
# ── Metrics (from remizov-trader) ────────────────────────────────────
|
|
|
|
def compute_metrics(dollar_trades: list[dict], initial_capital: float,
|
|
n_days: int) -> dict:
|
|
"""Compute trading metrics: Sharpe, max DD%, PnL, WR."""
|
|
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 & max drawdown
|
|
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())
|
|
|
|
# Sharpe ratio (daily returns, annualized)
|
|
if len(pnls) > 1 and n_days > 1:
|
|
daily_pnl = np.zeros(n_days)
|
|
for t in dollar_trades:
|
|
ts = t["entry_time"]
|
|
if ts is not None:
|
|
day_idx = (ts.astimezone(NY).date() - dollar_trades[0]["entry_time"].astimezone(NY).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(252)) 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,
|
|
}
|
|
|
|
|
|
# ── Grid search on in-sample ─────────────────────────────────────────
|
|
|
|
def _run_on_dates(df: pd.DataFrame, params: Params) -> list[Trade]:
|
|
"""Run strategy on pre-filtered dataframe, return trades."""
|
|
all_trades = []
|
|
for dt, day_df in df.groupby("ny_date"):
|
|
if is_nyse_holiday(dt):
|
|
continue
|
|
all_trades.extend(run_day(day_df.reset_index(drop=True), params, OR_MINUTES))
|
|
return all_trades
|
|
|
|
|
|
def _quick_score(trades: list[Trade]) -> float:
|
|
"""Dollar-based score for grid search (accounts for commissions)."""
|
|
if len(trades) < 3:
|
|
return -999
|
|
dollar = trades_to_pnl(trades, INITIAL_CAPITAL)
|
|
return sum(d["pnl_net"] for d in dollar)
|
|
|
|
|
|
def find_best_params(df_train: pd.DataFrame) -> Params:
|
|
"""Grid search on training data, return best Params."""
|
|
keys = list(GRID.keys())
|
|
combos = list(itertools.product(*GRID.values()))
|
|
best_score = -999
|
|
best_kw = {}
|
|
|
|
for vals in combos:
|
|
kw = dict(zip(keys, vals))
|
|
p = Params(**kw)
|
|
trades = _run_on_dates(df_train, p)
|
|
score = _quick_score(trades)
|
|
if score > best_score:
|
|
best_score = score
|
|
best_kw = kw
|
|
|
|
return Params(**best_kw) if best_kw else Params()
|
|
|
|
|
|
# ── Main walk-forward ─────────────────────────────────────────────────
|
|
|
|
def walk_forward(symbol: str, days: int = 60):
|
|
"""Walk-forward: optimize on first half, test on second half."""
|
|
df = fetch_candles(symbol, days, TIMEFRAME)
|
|
df["ny_date"] = df["timestamp"].dt.tz_convert(NY).dt.date
|
|
|
|
dates = sorted(d for d in df["ny_date"].unique() if not is_nyse_holiday(d))
|
|
split = int(len(dates) * TRAIN_RATIO)
|
|
train_dates = set(dates[:split])
|
|
test_dates = set(dates[split:])
|
|
|
|
df_train = df[df["ny_date"].isin(train_dates)]
|
|
df_test = df[df["ny_date"].isin(test_dates)]
|
|
|
|
print(f"\n{'='*60}")
|
|
print(f" Walk-Forward | {symbol} | {days}d | {TIMEFRAME} | OR={OR_MINUTES}m")
|
|
print(f"{'='*60}")
|
|
print(f" Train: {len(train_dates)} days ({dates[0]} → {dates[split-1]})")
|
|
print(f" Test: {len(test_dates)} days ({dates[split]} → {dates[-1]})")
|
|
print(f" Capital: ${INITIAL_CAPITAL:,.0f} | Risk: {RISK_PCT*100:.0f}% | Leverage: {LEVERAGE}x")
|
|
|
|
# Phase 1: optimize on train
|
|
print(f"\n Phase 1: Grid search ({len(list(itertools.product(*GRID.values())))} combos)...")
|
|
best_params = find_best_params(df_train)
|
|
print(f" Best in-sample params: {best_params}")
|
|
|
|
# In-sample result
|
|
train_trades = _run_on_dates(df_train, best_params)
|
|
train_dollar = trades_to_pnl(train_trades, INITIAL_CAPITAL)
|
|
train_m = compute_metrics(train_dollar, INITIAL_CAPITAL, len(train_dates))
|
|
|
|
# Phase 2: test on out-of-sample
|
|
print(f"\n Phase 2: Out-of-sample test...")
|
|
test_trades = _run_on_dates(df_test, best_params)
|
|
test_dollar = trades_to_pnl(test_trades, INITIAL_CAPITAL)
|
|
test_m = compute_metrics(test_dollar, INITIAL_CAPITAL, len(test_dates))
|
|
|
|
# Print results
|
|
_print_comparison(train_m, test_m, symbol)
|
|
|
|
return {"train": train_m, "test": test_m, "params": best_params}
|
|
|
|
|
|
def _print_comparison(train: dict, test: dict, symbol: str):
|
|
"""Print in-sample vs out-of-sample comparison."""
|
|
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.get('total_comm',0):,.2f}", f"${test.get('total_comm',0):,.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.get('monthly_pnl',0):+,.2f}", f"${test.get('monthly_pnl',0):+,.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:
|
|
degradation = ""
|
|
if train["total_pnl"] > 0 and test["total_pnl"] > 0:
|
|
deg = (1 - test["total_pnl"] / train["total_pnl"]) * 100
|
|
degradation = f" | Degradation: {deg:.0f}%"
|
|
print(f" OOS PnL: ${test['total_pnl']:+,.2f} ({test['total_ret']:+.1f}%){degradation}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
symbols = sys.argv[1:] if len(sys.argv) > 1 else [
|
|
"BTC/USDT:USDT", "ETH/USDT:USDT", "SOL/USDT:USDT"
|
|
]
|
|
days = 365
|
|
all_results = {}
|
|
for sym in symbols:
|
|
all_results[sym] = walk_forward(sym, days)
|
|
|
|
# Summary
|
|
if len(all_results) > 1:
|
|
print(f"\n\n{'='*70}")
|
|
print(f" WALK-FORWARD SUMMARY | ${INITIAL_CAPITAL:,.0f} capital, {RISK_PCT*100:.0f}% risk")
|
|
print(f"{'='*70}")
|
|
print(f" {'Symbol':<16s} {'OOS PnL':>10s} {'OOS Ret':>8s} {'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']:>+7.1f}% "
|
|
f"{t['sharpe']:>8.2f} {t['max_dd']:>6.1f}% {t['trades']:>7d} "
|
|
f"{t['wr']:>5.1f}%")
|