From 3dda7b433c73a3d6b45c2289c4daba537b4a8a36 Mon Sep 17 00:00:00 2001 From: anor Date: Fri, 13 Mar 2026 03:40:52 +1000 Subject: [PATCH] =?UTF-8?q?fix:=20=D0=B4=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D1=82=D1=8C=20leverage=20cap=20=D0=B2=20backtest=5Fwf=20(?= =?UTF-8?q?=D0=B1=D1=8B=D0=BB=D0=BE=20=D0=B1=D0=B5=D1=81=D0=BA=D0=BE=D0=BD?= =?UTF-8?q?=D0=B5=D1=87=D0=BD=D0=BE=D0=B5=20=D0=BF=D0=BB=D0=B5=D1=87=D0=BE?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - trades_to_pnl: ограничение позиции по leverage (дефолт 10x) - compute_metrics: полный dict при 0 трейдах (был KeyError) - ETH OOS: +$87.50 (+8.8%) при 10x вместо +$105 при ∞x Co-Authored-By: Claude Opus 4.6 --- backtest_wf.py | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/backtest_wf.py b/backtest_wf.py index d06a8aa..bf8fc60 100644 --- a/backtest_wf.py +++ b/backtest_wf.py @@ -25,6 +25,7 @@ NY = ZoneInfo("America/New_York") INITIAL_CAPITAL = 1_000.0 RISK_PCT = 0.02 # 2% risk per trade TAKER_FEE = 0.00055 # Bybit linear futures taker fee (0.055%) +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) @@ -42,17 +43,23 @@ GRID = { # ── Dollar PnL ─────────────────────────────────────────────────────── def trades_to_pnl(trades: list[Trade], capital: float) -> list[dict]: - """Convert R-based trades to dollar PnL with commission.""" + """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: + 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) @@ -80,7 +87,9 @@ 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} + 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] @@ -186,7 +195,7 @@ def walk_forward(symbol: str, days: int = 60): 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}%") + 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)...")