Perps-Terminal / backend /scripts /run_backtest.py
Naufal Arhab
chore: full codebase audit fixes, L2/whale/calibration upgrades, and rebuild frontend dist
48f60d7
Raw History Blame Contribute Delete
25.2 kB
"""
Causal Historical Replay Backtester CLI
======================================
Usage:
python backend/scripts/run_backtest.py --fixture path/to/history.json
python backend/scripts/run_backtest.py --symbol BTCUSDT --days 14 --json
python backend/scripts/run_backtest.py --symbols BTCUSDT,ETHUSDT,SOLUSDT --days 14 --walk-forward --json
"""
from __future__ import annotations
import argparse
import asyncio
import json
import os
import sys
import time
from typing import Any
import httpx
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
from config import BINANCE_FUTURES_BASE_URL, PROXY_URL
from engine.backtester import CausalBacktester
from engine.symbol_resolver import get_symbol_variations
from database.db import db_get_microstructure_tape
from engine.factor_calibrator import calibrate_whale_thresholds, compute_factor_calibration_report
async def fetch_historical_dataset(symbol: str, days: int) -> tuple[list[dict], list[dict], list[dict], list[dict]]:
"""Fetch historical 1H + paginated 15m OHLCV, 8H funding rate, and 15m OI series from Binance Futures public endpoints."""
bars_needed = max(48, min(1000, days * 24))
start_ms = int((time.time() - days * 86400) * 1000)
client_kwargs: dict[str, Any] = {
"base_url": BINANCE_FUTURES_BASE_URL,
"timeout": httpx.Timeout(connect=5.0, read=15.0, write=5.0, pool=10.0),
"verify": True,
}
if PROXY_URL:
client_kwargs["proxy"] = PROXY_URL
async with httpx.AsyncClient(**client_kwargs) as client:
resolved_sym = symbol.upper().strip()
klines_raw: list = []
for candidate in get_symbol_variations(resolved_sym):
resp = await client.get(
"/fapi/v1/klines",
params={"symbol": candidate, "interval": "1h", "limit": bars_needed},
)
if resp.status_code == 200 and isinstance(resp.json(), list) and resp.json():
resolved_sym = candidate
klines_raw = resp.json()
break
if not klines_raw:
raise RuntimeError(f"Tidak dapat mengambil historical 1H klines untuk {symbol}.")
candles = [
{
"timestamp": int(row[0]),
"open": float(row[1]),
"high": float(row[2]),
"low": float(row[3]),
"close": float(row[4]),
"volume": float(row[5]),
"taker_buy_volume": float(row[9]) if len(row) > 9 else None,
}
for row in klines_raw
]
# Paginated 15m klines (up to 4 pages of 1500 bars for up to 60 days)
klines_15m: list[dict] = []
cursor_ms = int(candles[0]["timestamp"]) if candles else start_ms
bars_15m_target = max(192, min(6000, days * 96))
for _ in range(4):
if len(klines_15m) >= bars_15m_target:
break
page_limit = min(1500, bars_15m_target - len(klines_15m))
r15 = await client.get(
"/fapi/v1/klines",
params={"symbol": resolved_sym, "interval": "15m", "startTime": cursor_ms, "limit": page_limit},
)
if r15.status_code != 200 or not isinstance(r15.json(), list) or not r15.json():
break
batch = r15.json()
for row in batch:
klines_15m.append({
"timestamp": int(row[0]),
"open": float(row[1]),
"high": float(row[2]),
"low": float(row[3]),
"close": float(row[4]),
"volume": float(row[5]),
"taker_buy_volume": float(row[9]) if len(row) > 9 else None,
})
next_cursor = int(batch[-1][0]) + 900_000
if next_cursor <= cursor_ms or len(batch) < page_limit:
break
cursor_ms = next_cursor
funding_history: list[dict] = []
fr_resp = await client.get(
"/fapi/v1/fundingRate",
params={"symbol": resolved_sym, "startTime": start_ms, "limit": 1000},
)
if fr_resp.status_code == 200 and isinstance(fr_resp.json(), list):
for item in fr_resp.json():
funding_history.append({
"timestamp": int(item["fundingTime"]),
"funding_rate": float(item["fundingRate"]),
})
# Paginated 15m Open Interest History (Binance limit: days <= 30)
oi_history: list[dict] = []
if days <= 30:
cursor_oi_ms = int(candles[0]["timestamp"]) if candles else start_ms
bars_oi_target = max(96, min(3000, days * 96))
try:
for _ in range(8):
if len(oi_history) >= bars_oi_target:
break
page_limit = min(500, bars_oi_target - len(oi_history))
r_oi = await client.get(
"/futures/data/openInterestHist",
params={
"symbol": resolved_sym,
"period": "15m",
"startTime": cursor_oi_ms,
"limit": page_limit,
},
)
if r_oi.status_code != 200 or not isinstance(r_oi.json(), list) or not r_oi.json():
break
batch = r_oi.json()
for item in batch:
oi_history.append({
"timestamp": int(item.get("timestamp") or item.get("time") or 0),
"open_interest": float(item.get("sumOpenInterest") or item.get("open_interest") or 0.0),
"sumOpenInterest": float(item.get("sumOpenInterest") or item.get("open_interest") or 0.0),
"open_interest_value": float(item.get("sumOpenInterestValue") or item.get("open_interest_value") or 0.0) if (item.get("sumOpenInterestValue") is not None or item.get("open_interest_value") is not None) else None,
"sumOpenInterestValue": float(item.get("sumOpenInterestValue") or item.get("open_interest_value") or 0.0) if (item.get("sumOpenInterestValue") is not None or item.get("open_interest_value") is not None) else None,
})
next_cursor = int(batch[-1].get("timestamp") or batch[-1].get("time") or 0) + 900_000
if next_cursor <= cursor_oi_ms or len(batch) < page_limit:
break
cursor_oi_ms = next_cursor
except Exception:
oi_history = []
return candles, funding_history, klines_15m, oi_history
def _run_walk_forward(
bt: CausalBacktester,
symbol: str,
candles: list[dict],
funding: list[dict],
candles_by_tf: dict[str, list[dict]] | None,
klines_15m: list[dict] | None,
oi_history: list[dict] | None,
horizon: str,
sniper_only: bool,
breakeven_after_tp1: bool,
threshold: int | None,
verbose: bool = False,
tape_history: list[dict] | None = None,
) -> dict[str, Any]:
candles = sorted(candles, key=lambda c: int(c["timestamp"]))
mid = len(candles) // 2
warmup = bt.warmup_bars
if mid <= warmup + 1 or len(candles) - mid <= 1:
raise ValueError(
f"Minimal {2 * (warmup + 2)} candle 1H dibutuhkan untuk walk-forward split (diterima {len(candles)})."
)
# In-Sample: [0 : mid]
is_candles = candles[:mid]
t_is_end = int(candles[mid - 1]["timestamp"])
is_funding = [f for f in funding if int(f["timestamp"]) <= t_is_end] if funding else None
is_15m = [k for k in klines_15m if int(k["timestamp"]) <= t_is_end] if klines_15m else None
is_oi = [o for o in oi_history if int(o.get("timestamp") or o.get("time") or 0) <= t_is_end] if oi_history else None
is_tape = [t for t in tape_history if int(t.get("timestamp_ms") or 0) <= t_is_end] if tape_history else None
is_c_tf = {
tf: [b for b in b_list if int(b["timestamp"]) <= t_is_end]
for tf, b_list in candles_by_tf.items()
} if candles_by_tf else None
is_rep = bt.run(
symbol=symbol,
candles_1h=is_candles,
funding_history=is_funding,
candles_by_tf=is_c_tf,
klines_15m=is_15m,
oi_history=is_oi,
tape_history=is_tape,
horizon=horizon,
sniper_only=sniper_only,
breakeven_after_tp1=breakeven_after_tp1,
signal_threshold=threshold,
)
# Out-of-Sample: [mid - warmup :] preserving warmup bars and historical carry-forward context
# (CausalBacktester slices funding, HTF bars, 15m, and OI strictly <= t_now per bar).
oos_candles = candles[mid - warmup:]
t_oos_start = int(oos_candles[0]["timestamp"])
if funding:
sorted_funding = sorted(funding, key=lambda f: int(f["timestamp"]))
prior_funding = [f for f in sorted_funding if int(f["timestamp"]) <= t_oos_start]
after_funding = [f for f in sorted_funding if int(f["timestamp"]) > t_oos_start]
oos_funding = ([prior_funding[-1]] + after_funding) if prior_funding else after_funding
else:
oos_funding = None
oos_15m = klines_15m
oos_oi = oi_history
oos_c_tf = candles_by_tf
oos_rep = bt.run(
symbol=symbol,
candles_1h=oos_candles,
funding_history=oos_funding,
candles_by_tf=oos_c_tf,
klines_15m=oos_15m,
oi_history=oos_oi,
tape_history=tape_history,
horizon=horizon,
sniper_only=sniper_only,
breakeven_after_tp1=breakeven_after_tp1,
signal_threshold=threshold,
)
is_exp = float(is_rep.get("expectancy_r", 0.0) or 0.0)
oos_exp = float(oos_rep.get("expectancy_r", 0.0) or 0.0)
oos_retention_ratio = round(oos_exp / is_exp, 4) if is_exp > 0 else 0.0
if not verbose:
is_rep.pop("equity_curve", None)
is_rep.pop("trades", None)
oos_rep.pop("equity_curve", None)
oos_rep.pop("trades", None)
return {
"symbol": symbol.upper(),
"telemetry_fidelity": "FULL_TELEMETRY_REPLAY" if tape_history else "OHLCV_FUNDING_ONLY",
"walk_forward": True,
"split_ratio": "50/50",
"in_sample": is_rep,
"out_of_sample": oos_rep,
"oos_retention_ratio": oos_retention_ratio,
}
def _run_for_dataset(
bt: CausalBacktester,
symbol: str,
candles: list[dict],
funding: list[dict],
candles_by_tf: dict[str, list[dict]] | None,
klines_15m: list[dict] | None,
oi_history: list[dict] | None,
args: argparse.Namespace,
) -> dict[str, Any]:
tape_history = None
if getattr(args, "use_db_tape", False) or getattr(args, "calibrate", False):
try:
tape_history = db_get_microstructure_tape(symbol=symbol, days=args.days)
except Exception as exc:
print(f"[Warning] Failed to fetch db tape: {exc}", file=sys.stderr)
if getattr(args, "calibrate", False):
calib_report = compute_factor_calibration_report(tape_history or [], symbol=symbol)
thresh_opt = calibrate_whale_thresholds(tape_history or [])
return {
"symbol": symbol,
"calibration_report": calib_report,
"threshold_optimization": thresh_opt,
}
if args.walk_forward and args.compare_ab:
base_wf = _run_walk_forward(
bt=bt,
symbol=symbol,
candles=candles,
funding=funding,
candles_by_tf=candles_by_tf,
klines_15m=klines_15m,
oi_history=oi_history,
horizon=args.horizon,
sniper_only=False,
breakeven_after_tp1=False,
threshold=args.threshold,
verbose=args.verbose,
tape_history=tape_history,
)
sniper_wf = _run_walk_forward(
bt=bt,
symbol=symbol,
candles=candles,
funding=funding,
candles_by_tf=candles_by_tf,
klines_15m=klines_15m,
oi_history=oi_history,
horizon=args.horizon,
sniper_only=True,
breakeven_after_tp1=True,
threshold=args.threshold,
verbose=args.verbose,
tape_history=tape_history,
)
base_oos = base_wf["out_of_sample"]
sniper_oos = sniper_wf["out_of_sample"]
return {
"symbol": symbol,
"telemetry_fidelity": "FULL_TELEMETRY_REPLAY" if tape_history else "OHLCV_FUNDING_ONLY",
"walk_forward": True,
"in_sample": sniper_wf["in_sample"],
"out_of_sample": sniper_wf["out_of_sample"],
"oos_retention_ratio": sniper_wf["oos_retention_ratio"],
"baseline": base_wf,
"sniper_dual_horizon": sniper_wf,
"delta": {
"total_trades_diff": sniper_oos["total_trades"] - base_oos["total_trades"],
"win_rate_pct_diff": round(sniper_oos["win_rate_pct"] - base_oos["win_rate_pct"], 2),
"profit_factor_diff": round(sniper_oos["profit_factor"] - base_oos["profit_factor"], 4),
"expectancy_r_diff": round(sniper_oos["expectancy_r"] - base_oos["expectancy_r"], 4),
"max_drawdown_pct_diff": round(sniper_oos["max_drawdown_pct"] - base_oos["max_drawdown_pct"], 2),
"net_return_pct_diff": round(sniper_oos["net_return_pct"] - base_oos["net_return_pct"], 2),
"oos_retention_ratio_diff": round(sniper_wf["oos_retention_ratio"] - base_wf["oos_retention_ratio"], 4),
},
}
if args.walk_forward:
return _run_walk_forward(
bt=bt,
symbol=symbol,
candles=candles,
funding=funding,
candles_by_tf=candles_by_tf,
klines_15m=klines_15m,
oi_history=oi_history,
horizon=args.horizon,
sniper_only=args.sniper_only,
breakeven_after_tp1=args.breakeven_after_tp1,
threshold=args.threshold,
verbose=args.verbose,
tape_history=tape_history,
)
if args.compare_ab:
base_rep = bt.run(
symbol=symbol,
candles_1h=candles,
funding_history=funding,
candles_by_tf=candles_by_tf,
klines_15m=klines_15m,
oi_history=oi_history,
tape_history=tape_history,
horizon=args.horizon,
sniper_only=False,
breakeven_after_tp1=False,
signal_threshold=args.threshold,
)
sniper_rep = bt.run(
symbol=symbol,
candles_1h=candles,
funding_history=funding,
candles_by_tf=candles_by_tf,
klines_15m=klines_15m,
oi_history=oi_history,
tape_history=tape_history,
horizon=args.horizon,
sniper_only=True,
breakeven_after_tp1=True,
signal_threshold=args.threshold,
)
if not args.verbose:
base_rep.pop("equity_curve", None)
base_rep.pop("trades", None)
sniper_rep.pop("equity_curve", None)
sniper_rep.pop("trades", None)
return {
"symbol": symbol,
"telemetry_fidelity": "FULL_TELEMETRY_REPLAY" if tape_history else "OHLCV_FUNDING_ONLY",
"baseline": base_rep,
"sniper_dual_horizon": sniper_rep,
"delta": {
"total_trades_diff": sniper_rep["total_trades"] - base_rep["total_trades"],
"win_rate_pct_diff": round(sniper_rep["win_rate_pct"] - base_rep["win_rate_pct"], 2),
"profit_factor_diff": round(sniper_rep["profit_factor"] - base_rep["profit_factor"], 4),
"expectancy_r_diff": round(sniper_rep["expectancy_r"] - base_rep["expectancy_r"], 4),
"max_drawdown_pct_diff": round(sniper_rep["max_drawdown_pct"] - base_rep["max_drawdown_pct"], 2),
"net_return_pct_diff": round(sniper_rep["net_return_pct"] - base_rep["net_return_pct"], 2),
},
}
rep = bt.run(
symbol=symbol,
candles_1h=candles,
funding_history=funding,
candles_by_tf=candles_by_tf,
klines_15m=klines_15m,
oi_history=oi_history,
tape_history=tape_history,
horizon=args.horizon,
sniper_only=args.sniper_only,
breakeven_after_tp1=args.breakeven_after_tp1,
signal_threshold=args.threshold,
)
if not args.verbose:
rep.pop("equity_curve", None)
rep.pop("trades", None)
return rep
def _print_summary(report: dict[str, Any]) -> None:
if "calibration_report" in report and "threshold_optimization" in report:
cal = report["calibration_report"]
opt = report["threshold_optimization"]
print(f"=== Factor Calibration Report: {report.get('symbol', 'ALL')} ===")
print(f"Status : {cal.get('status')} (evaluated={cal.get('total_evaluated_samples', 0)})")
print(f"Opt Thresholds : {opt.get('status')} -> {opt.get('optimal_thresholds')}")
if opt.get("performance"):
print(f"Opt Performance : {opt['performance']}")
return
if report.get("walk_forward") and "in_sample" in report and "out_of_sample" in report:
print(f"=== Walk-Forward Report (50% IS / 50% OOS): {report['symbol']} ===")
print(f"OOS Retention Ratio : {report.get('oos_retention_ratio', 0.0):.4f}")
print("\n--- In-Sample ---")
_print_summary(report["in_sample"])
print("\n--- Out-of-Sample ---")
_print_summary(report["out_of_sample"])
if "delta" in report and isinstance(report["delta"], dict):
d = report["delta"]
print(
f"\nDelta Win Rate: {d.get('win_rate_pct_diff', 0.0):+.2f}% | "
f"Delta Expectancy R: {d.get('expectancy_r_diff', 0.0):+.4f} | "
f"Delta OOS Retention: {d.get('oos_retention_ratio_diff', 0.0):+.4f}"
)
return
if "baseline" in report and "sniper_dual_horizon" in report:
print("=== BASELINE ===")
_print_summary(report["baseline"])
print("\n=== SNIPER DUAL-HORIZON + BREAKEVEN ===")
_print_summary(report["sniper_dual_horizon"])
d = report.get("delta", {})
print(f"\nDelta Win Rate: {d.get('win_rate_pct_diff', 0.0):+.2f}% | Delta Expectancy R: {d.get('expectancy_r_diff', 0.0):+.4f}")
return
print(f"=== Causal Backtest Report: {report['symbol']} ===")
print(f"Bars Evaluated : {report['bars_evaluated']} (warmup {report['warmup_bars']})")
print(f"Total Trades : {report['total_trades']} (Win {report['winning_trades']} / Loss {report['losing_trades']})")
print(f"Win Rate : {report['win_rate_pct']:.2f}%")
print(f"Profit Factor : {report['profit_factor']:.4f}")
print(f"Expectancy : ${report['expectancy_usd']:.2f} ({report['expectancy_r']:+.3f} R)")
print(f"Sharpe / Sort. : {report['sharpe_ratio']:.3f} / {report['sortino_ratio']:.3f}")
print(f"Max Drawdown : {report['max_drawdown_pct']:.2f}%")
print(f"Fees / Funding : ${report['total_fees_usd']:.2f} / ${report['total_funding_usd']:+.2f}")
print(f"Net Return : {report['net_return_pct']:+.2f}% (${report['initial_capital_usd']:.2f} -> ${report['final_equity_usd']:.2f})")
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description="Causal Historical Replay Backtester")
parser.add_argument("--symbol", default="BTCUSDT", help="Perpetual symbol (default: BTCUSDT)")
parser.add_argument("--symbols", default=None, help="Comma-separated perpetual symbols (e.g. BTCUSDT,ETHUSDT,SOLUSDT)")
parser.add_argument("--days", type=int, default=14, help="Lookback days for live fetch (default: 14)")
parser.add_argument("--fixture", default=None, help="Optional path to offline JSON {symbol, candles_1h, funding_history}")
parser.add_argument("--capital", type=float, default=10_000.0, help="Initial capital USD")
parser.add_argument("--size-pct", type=float, default=0.25, help="Fraction of equity per trade")
parser.add_argument("--leverage", type=float, default=1.0, help="Position leverage")
parser.add_argument("--fee-bps", type=float, default=5.5, help="Taker fee bps per leg")
parser.add_argument("--slippage-bps", type=float, default=3.0, help="Slippage bps per leg")
parser.add_argument("--warmup", type=int, default=30, help="Warmup 1h bars before evaluating signals")
parser.add_argument("--horizon", choices=["primary", "intraday", "swing"], default="primary", help="Target horizon (default: primary)")
parser.add_argument("--sniper-only", action="store_true", help="Filter entries strictly to SNIPER_A_PLUS setups")
parser.add_argument("--breakeven-after-tp1", action="store_true", help="Move runner SL to entry + 6 bps after TP1 fills")
parser.add_argument("--threshold", type=int, default=None, help="Override confluence score threshold for OHLCV replay")
parser.add_argument("--compare-ab", action="store_true", help="Compare baseline vs Sniper Dual-Horizon + Auto-Breakeven")
parser.add_argument("--walk-forward", action="store_true", help="Evaluate 50%/50% In-Sample vs Out-of-Sample walk-forward split")
parser.add_argument("--use-db-tape", action="store_true", help="Replay recorded microstructure_tape telemetry from DB")
parser.add_argument("--calibrate", action="store_true", help="Run empirical factor and threshold calibration on DB tape")
parser.add_argument("--json", action="store_true", help="Print compact JSON report (excludes full curve/trades unless --verbose)")
parser.add_argument("--verbose", action="store_true", help="Include full trades and equity_curve in JSON output")
args = parser.parse_args(argv)
if args.symbols:
symbols = [s.strip().upper() for s in args.symbols.split(",") if s.strip()]
else:
symbols = [args.symbol.strip().upper()]
bt = CausalBacktester(
initial_capital_usd=args.capital,
position_size_pct=args.size_pct,
leverage=args.leverage,
taker_fee_bps=args.fee_bps,
slippage_bps=args.slippage_bps,
warmup_bars=args.warmup,
)
if args.fixture:
with open(args.fixture, "r", encoding="utf-8") as fh:
data = json.load(fh)
if "candles_1h" in data:
symbol = data.get("symbol", symbols[0])
candles = data["candles_1h"]
funding = data.get("funding_history", [])
candles_by_tf = data.get("candles_by_tf")
klines_15m = data.get("klines_15m")
oi_history = data.get("oi_history") or data.get("open_interest_history")
rep = _run_for_dataset(bt, symbol, candles, funding, candles_by_tf, klines_15m, oi_history, args)
if len(symbols) > 1:
final_out = {"symbols": {symbol: rep}}
else:
final_out = rep
else:
sym_reports = {}
for sym, sdata in data.items():
if isinstance(sdata, dict) and "candles_1h" in sdata:
c = sdata["candles_1h"]
f = sdata.get("funding_history", [])
c_tf = sdata.get("candles_by_tf")
k15 = sdata.get("klines_15m")
oi = sdata.get("oi_history") or sdata.get("open_interest_history")
sym_reports[sym] = _run_for_dataset(bt, sym, c, f, c_tf, k15, oi, args)
final_out = {"symbols": sym_reports}
else:
if getattr(args, "calibrate", False):
if len(symbols) == 1:
final_out = _run_for_dataset(bt, symbols[0], [], [], None, None, None, args)
else:
final_out = {
"symbols": {
sym: _run_for_dataset(bt, sym, [], [], None, None, None, args)
for sym in symbols
}
}
elif len(symbols) == 1:
sym = symbols[0]
candles, funding, klines_15m, oi_history = asyncio.run(fetch_historical_dataset(sym, args.days))
final_out = _run_for_dataset(bt, sym, candles, funding, None, klines_15m, oi_history, args)
else:
sym_reports = {}
for sym in symbols:
c, f, k15, oi = asyncio.run(fetch_historical_dataset(sym, args.days))
sym_reports[sym] = _run_for_dataset(bt, sym, c, f, None, k15, oi, args)
final_out = {"symbols": sym_reports}
if args.json:
print(json.dumps(final_out, indent=2))
else:
if "symbols" in final_out and isinstance(final_out["symbols"], dict):
for sym, srep in final_out["symbols"].items():
_print_summary(srep)
else:
_print_summary(final_out)
return 0
if __name__ == "__main__":
raise SystemExit(main())