Coverage for evaluation/trade_bootstrap.py: 100%
47 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""Is a sleeve's P&L a repeatable effect or a few lucky fills? (V6.4.0, lead L9.) Pure given closed trades; numpy only.
3`closedTrades` of a Lean run give one P&L per round trip. This module groups them by name, bootstraps the mean P&L per
4trade (resampling trades with replacement), measures how much of the total the best few trades carry, and recomputes the
5total with each name left out in turn.
6"""
8from __future__ import annotations
10from typing import TYPE_CHECKING, Any
12import numpy as np
14if TYPE_CHECKING:
15 from numpy.typing import ArrayLike
18def round_trips_from_closed_trades(run: dict[str, Any], tickers: set[str] | None = None) -> list[dict]:
19 """[{"ticker", "pnl" (net of fees), "notional", "entry"}] for the run's closed trades, restricted to `tickers`
20 (upper-case) when given. Trades with several symbols (option combos) are skipped."""
21 trades = ((run.get("result") or {}).get("totalPerformance") or {}).get("closedTrades") or []
22 out = []
23 for trade in trades:
24 symbols = trade.get("symbols") or []
25 if len(symbols) != 1:
26 continue
27 ticker = str(symbols[0].get("value", "")).upper()
28 if tickers is not None and ticker not in tickers:
29 continue
30 try:
31 pnl = float(trade.get("profitLoss", 0.0)) - float(trade.get("totalFees", 0.0))
32 notional = abs(float(trade.get("entryPrice", 0.0)) * float(trade.get("quantity", 0.0)))
33 except (TypeError, ValueError):
34 continue
35 out.append({"ticker": ticker, "pnl": pnl, "notional": notional, "entry": str(trade.get("entryTime", ""))[:10]})
36 return out
39def bootstrap_mean_pnl(pnls: ArrayLike, n: int = 10000, seed: int = 7, confidence: float = 0.95) -> dict[str, Any]:
40 """Mean P&L per trade with a percentile bootstrap interval; `p_mean_le_0` = the share of resampled means <= 0."""
41 values = np.asarray([float(value) for value in pnls if np.isfinite(value)], dtype=float)
42 if len(values) < 2:
43 return {"n": int(len(values)), "mean": float(values.mean()) if len(values) else None, "ci_low": None, "ci_high": None,
44 "p_mean_le_0": None}
45 rng = np.random.default_rng(seed)
46 means = np.empty(int(n))
47 for index in range(int(n)):
48 means[index] = values[rng.integers(0, len(values), len(values))].mean()
49 tail = (1.0 - confidence) / 2.0
50 return {"n": int(len(values)), "mean": float(values.mean()), "ci_low": float(np.quantile(means, tail)),
51 "ci_high": float(np.quantile(means, 1.0 - tail)), "p_mean_le_0": float((means <= 0.0).mean())}
54def top_k_share(pnls, k: int) -> float | None:
55 """The best `k` trades' P&L as a share of the total (None when the total is not positive or there are no trades)."""
56 values = sorted((float(value) for value in pnls), reverse=True)
57 total = sum(values)
58 if not values or total <= 0.0:
59 return None
60 return float(sum(values[:k]) / total)
63def pnl_by_name(trades: list[dict]) -> dict[str, float]:
64 totals: dict[str, float] = {}
65 for trade in trades:
66 totals[trade["ticker"]] = totals.get(trade["ticker"], 0.0) + trade["pnl"]
67 return totals
70def leave_one_name_out(totals_by_name: dict[str, float]) -> dict[str, float]:
71 """{name: the total P&L without that name}."""
72 total = sum(totals_by_name.values())
73 return {name: total - value for name, value in totals_by_name.items()}
76def repeatable(bootstrap: dict[str, Any], leave_one_out: dict[str, float]) -> bool:
77 """The L9 verdict: the bootstrap interval's lower end is above zero AND every leave-one-name-out total stays positive."""
78 low = bootstrap.get("ci_low")
79 return low is not None and low > 0.0 and bool(leave_one_out) and all(value > 0.0 for value in leave_one_out.values())