fix: добавить leverage cap в backtest_wf (было бесконечное плечо)
- 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 <noreply@anthropic.com>
This commit is contained in:
+13
-4
@@ -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)...")
|
||||
|
||||
Reference in New Issue
Block a user