prop-mc 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
prop_mc/__init__.py ADDED
@@ -0,0 +1,25 @@
1
+ """Monte Carlo survival, drawdown-ruin, and net-EV simulator for prop-firm accounts."""
2
+
3
+ from prop_mc.rules import DllMode, PropRules, TrailingMode, preset_50k_eod
4
+ from prop_mc.simulate import (
5
+ SimulationResult,
6
+ optimize_scale,
7
+ sample_paths,
8
+ simulate_eval,
9
+ stress_cost_sensitivity,
10
+ )
11
+
12
+ __all__ = [
13
+ "DllMode",
14
+ "PropRules",
15
+ "SimulationResult",
16
+ "TrailingMode",
17
+ "__version__",
18
+ "optimize_scale",
19
+ "preset_50k_eod",
20
+ "sample_paths",
21
+ "simulate_eval",
22
+ "stress_cost_sensitivity",
23
+ ]
24
+
25
+ __version__ = "1.0.0"
prop_mc/cli.py ADDED
@@ -0,0 +1,121 @@
1
+ """Command-line simulator for prop-firm survival and risk-sizing sweeps."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ from collections.abc import Sequence
7
+ from pathlib import Path
8
+
9
+ import polars as pl
10
+
11
+ from prop_mc.rules import PropRules, preset_50k_eod
12
+ from prop_mc.simulate import optimize_scale, simulate_eval
13
+
14
+
15
+ def _load_pnl(path: Path, col: str) -> pl.Series:
16
+ suffix = path.suffix.lower()
17
+ if suffix == ".csv":
18
+ df = pl.read_csv(path)
19
+ elif suffix == ".parquet":
20
+ df = pl.read_parquet(path)
21
+ else:
22
+ raise ValueError(f"unsupported file format {suffix!r}; expected .csv or .parquet")
23
+ if col not in df.columns:
24
+ raise ValueError(f"input file is missing PnL column {col!r}")
25
+ return df[col].cast(pl.Float64)
26
+
27
+
28
+ def _rules_from_args(args: argparse.Namespace) -> PropRules:
29
+ base = preset_50k_eod()
30
+ return PropRules(
31
+ account_size=args.account,
32
+ profit_target=args.target,
33
+ max_drawdown=args.max_dd,
34
+ trailing_mode=args.trailing,
35
+ daily_loss_limit=None if args.dll <= 0 else args.dll,
36
+ dll_mode=args.dll_mode,
37
+ consistency_cap=None if args.consistency <= 0 else args.consistency,
38
+ min_trading_days=base.min_trading_days,
39
+ max_days=args.max_days,
40
+ eval_fee=args.eval_fee,
41
+ activation_fee=args.activation_fee,
42
+ payout_target=args.payout_target,
43
+ payout_split=args.split,
44
+ max_payouts=args.max_payouts,
45
+ )
46
+
47
+
48
+ def _add_rule_flags(p: argparse.ArgumentParser) -> None:
49
+ p.add_argument("path", type=Path, help="Input .csv or .parquet file of daily USD PnL.")
50
+ p.add_argument("--pnl-col", default="pnl", help="Daily USD PnL column (default: pnl).")
51
+ p.add_argument("--trials", type=int, default=5_000, help="Monte Carlo paths (default: 5000).")
52
+ p.add_argument("--block-size", type=int, default=1, help="Bootstrap block length in days.")
53
+ p.add_argument("--seed", type=int, default=7, help="RNG seed.")
54
+ p.add_argument("--account", type=float, default=50_000.0)
55
+ p.add_argument("--target", type=float, default=3_000.0)
56
+ p.add_argument("--max-dd", type=float, default=2_000.0)
57
+ p.add_argument("--trailing", choices=("eod", "static"), default="eod")
58
+ p.add_argument("--dll", type=float, default=1_200.0, help="Daily loss limit (<=0 disables).")
59
+ p.add_argument("--dll-mode", choices=("flatten", "breach"), default="flatten")
60
+ p.add_argument("--consistency", type=float, default=0.50, help="Cap in (0,1] (<=0 disables).")
61
+ p.add_argument("--max-days", type=int, default=252)
62
+ p.add_argument("--eval-fee", type=float, default=150.0)
63
+ p.add_argument("--activation-fee", type=float, default=0.0)
64
+ p.add_argument("--payout-target", type=float, default=3_000.0)
65
+ p.add_argument("--split", type=float, default=0.90)
66
+ p.add_argument("--max-payouts", type=int, default=3)
67
+
68
+
69
+ def main(argv: Sequence[str] | None = None) -> int:
70
+ parser = argparse.ArgumentParser(
71
+ prog="prop-mc",
72
+ description="Monte Carlo survival and net-EV simulator for futures prop-firm accounts.",
73
+ )
74
+ sub = parser.add_subparsers(dest="command", required=True)
75
+
76
+ run_p = sub.add_parser("run", help="Simulate one account configuration.")
77
+ _add_rule_flags(run_p)
78
+ run_p.add_argument("--scale", type=float, default=1.0, help="Position size multiplier.")
79
+ run_p.add_argument("--html", type=Path, default=None, help="Write dark-theme HTML report.")
80
+ run_p.add_argument("--json", type=Path, default=None, help="Write JSON report.")
81
+
82
+ sweep_p = sub.add_parser("sweep", help="Sweep position size multipliers for optimal net EV.")
83
+ _add_rule_flags(sweep_p)
84
+ sweep_p.add_argument(
85
+ "--scales",
86
+ default="0.25,0.5,0.75,1.0,1.25,1.5,2.0",
87
+ help="Comma-separated scale multipliers.",
88
+ )
89
+
90
+ args = parser.parse_args(argv)
91
+ pnl = _load_pnl(args.path, args.pnl_col).to_numpy()
92
+ rules = _rules_from_args(args)
93
+
94
+ if args.command == "run":
95
+ res = simulate_eval(
96
+ pnl,
97
+ rules,
98
+ n_trials=args.trials,
99
+ block_size=args.block_size,
100
+ scale=args.scale,
101
+ seed=args.seed,
102
+ )
103
+ print(res.to_markdown())
104
+ if args.html is not None:
105
+ args.html.write_text(res.to_html(), encoding="utf-8")
106
+ if args.json is not None:
107
+ args.json.write_text(res.to_json(), encoding="utf-8")
108
+ return 0
109
+
110
+ scales = [float(s.strip()) for s in args.scales.split(",") if s.strip()]
111
+ results = optimize_scale(
112
+ pnl, rules, scales=scales, n_trials=args.trials, block_size=args.block_size, seed=args.seed
113
+ )
114
+ print(f"{'scale':>7s} {'pass':>7s} {'ruin':>7s} {'d2p':>6s} {'joint':>7s} {'net_ev':>10s}")
115
+ for r in results:
116
+ d2p = "n/a" if r.median_days_to_pass is None else f"{r.median_days_to_pass:.0f}d"
117
+ print(
118
+ f"{r.scale:6.2f}x {r.pass_rate_horizon:7.1%} {r.ruin_rate:7.1%} "
119
+ f"{d2p:>6s} {r.joint_payout_rate:7.1%} ${r.net_ev_usd:9,.2f}"
120
+ )
121
+ return 0
prop_mc/py.typed ADDED
File without changes
prop_mc/rules.py ADDED
@@ -0,0 +1,122 @@
1
+ """Prop-firm evaluation and funded-payout rule definitions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from dataclasses import dataclass
7
+ from typing import Literal
8
+
9
+ TrailingMode = Literal["eod", "static"]
10
+ DllMode = Literal["flatten", "breach"]
11
+
12
+
13
+ def _pos_finite(value: float, name: str) -> None:
14
+ if not math.isfinite(value) or value <= 0.0:
15
+ raise ValueError(f"{name} must be positive and finite, got {value}")
16
+
17
+
18
+ def _nonneg_finite(value: float, name: str) -> None:
19
+ if not math.isfinite(value) or value < 0.0:
20
+ raise ValueError(f"{name} must be non-negative and finite, got {value}")
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class PropRules:
25
+ """Explicit contract for a two-stage (evaluation + funded) prop account.
26
+
27
+ Parameters
28
+ ----------
29
+ account_size
30
+ Nominal starting balance in USD (e.g. ``50_000.0``).
31
+ profit_target
32
+ Cumulative net profit in USD required to pass the evaluation.
33
+ max_drawdown
34
+ Maximum peak-to-valley drawdown in USD before account termination.
35
+ trailing_mode
36
+ ``"eod"`` raises the drawdown floor with end-of-day peak equity until
37
+ the floor locks at ``account_size``; ``"static"`` keeps the floor fixed
38
+ at ``account_size - max_drawdown``.
39
+ daily_loss_limit
40
+ Optional daily loss cap in USD. ``None`` disables daily limits.
41
+ dll_mode
42
+ ``"flatten"`` caps any losing day at ``-daily_loss_limit`` (simulating
43
+ an intraday auto-liquidation lock); ``"breach"`` terminates the account
44
+ immediately when a day loses at least ``daily_loss_limit``.
45
+ consistency_cap
46
+ Optional fraction in ``(0, 1]`` (e.g. ``0.50``): the largest single
47
+ winning day cannot exceed ``consistency_cap * total_profit`` to pass.
48
+ min_trading_days
49
+ Minimum number of days before an evaluation can pass.
50
+ max_days
51
+ Maximum number of trading days per stage before an unfinished account
52
+ expires without passing.
53
+ eval_fee
54
+ Upfront evaluation fee in USD.
55
+ activation_fee
56
+ Fee in USD paid only upon passing the evaluation.
57
+ payout_target
58
+ Net profit in USD required per funded payout cycle after passing.
59
+ payout_split
60
+ Trader's share of each funded payout in ``(0, 1]``.
61
+ max_payouts
62
+ Number of sequential funded payout cycles simulated (``0`` for eval only).
63
+ """
64
+
65
+ account_size: float = 50_000.0
66
+ profit_target: float = 3_000.0
67
+ max_drawdown: float = 2_000.0
68
+ trailing_mode: TrailingMode = "eod"
69
+ daily_loss_limit: float | None = 1_200.0
70
+ dll_mode: DllMode = "flatten"
71
+ consistency_cap: float | None = 0.50
72
+ min_trading_days: int = 1
73
+ max_days: int = 252
74
+ eval_fee: float = 150.0
75
+ activation_fee: float = 0.0
76
+ payout_target: float = 3_000.0
77
+ payout_split: float = 0.90
78
+ max_payouts: int = 3
79
+
80
+ def __post_init__(self) -> None:
81
+ _pos_finite(self.account_size, "account_size")
82
+ _pos_finite(self.profit_target, "profit_target")
83
+ _pos_finite(self.max_drawdown, "max_drawdown")
84
+ if self.max_drawdown >= self.account_size:
85
+ raise ValueError("max_drawdown must be smaller than account_size")
86
+ if self.trailing_mode not in ("eod", "static"):
87
+ raise ValueError(f"trailing_mode must be 'eod' or 'static', got {self.trailing_mode!r}")
88
+ if self.daily_loss_limit is not None:
89
+ _pos_finite(self.daily_loss_limit, "daily_loss_limit")
90
+ if self.dll_mode not in ("flatten", "breach"):
91
+ raise ValueError(f"dll_mode must be 'flatten' or 'breach', got {self.dll_mode!r}")
92
+ if self.consistency_cap is not None and not (0.0 < self.consistency_cap <= 1.0):
93
+ raise ValueError(f"consistency_cap must lie in (0, 1], got {self.consistency_cap}")
94
+ if self.min_trading_days < 1 or self.max_days < self.min_trading_days:
95
+ raise ValueError("min_trading_days must be >= 1 and <= max_days")
96
+ _nonneg_finite(self.eval_fee, "eval_fee")
97
+ _nonneg_finite(self.activation_fee, "activation_fee")
98
+ _pos_finite(self.payout_target, "payout_target")
99
+ if not (0.0 < self.payout_split <= 1.0):
100
+ raise ValueError(f"payout_split must lie in (0, 1], got {self.payout_split}")
101
+ if self.max_payouts < 0:
102
+ raise ValueError(f"max_payouts must be >= 0, got {self.max_payouts}")
103
+
104
+
105
+ def preset_50k_eod() -> PropRules:
106
+ """Standard $50K EOD-trailing futures prop account with DLL flatten and 50% consistency."""
107
+ return PropRules(
108
+ account_size=50_000.0,
109
+ profit_target=3_000.0,
110
+ max_drawdown=2_000.0,
111
+ trailing_mode="eod",
112
+ daily_loss_limit=1_200.0,
113
+ dll_mode="flatten",
114
+ consistency_cap=0.50,
115
+ min_trading_days=2,
116
+ max_days=252,
117
+ eval_fee=150.0,
118
+ activation_fee=0.0,
119
+ payout_target=3_000.0,
120
+ payout_split=0.90,
121
+ max_payouts=3,
122
+ )
prop_mc/simulate.py ADDED
@@ -0,0 +1,392 @@
1
+ """Vectorized Monte Carlo simulator for prop-firm evaluation and funded survival."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import html
6
+ import json
7
+ from collections.abc import Sequence
8
+ from dataclasses import dataclass
9
+ from typing import Any
10
+
11
+ import numpy as np
12
+ from numpy.typing import ArrayLike, NDArray
13
+
14
+ from prop_mc.rules import PropRules
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class SimulationResult:
19
+ """Summary metrics from a Monte Carlo prop-firm simulation."""
20
+
21
+ n_trials: int
22
+ scale: float
23
+ block_size: int
24
+ pass_rate_30d: float
25
+ pass_rate_60d: float
26
+ pass_rate_horizon: float
27
+ ruin_rate: float
28
+ timeout_rate: float
29
+ dll_hit_rate: float
30
+ consistency_delay_rate: float
31
+ median_days_to_pass: float | None
32
+ funded_payout_rate: float
33
+ joint_payout_rate: float
34
+ expected_payout_usd: float
35
+ net_ev_usd: float
36
+
37
+ def to_dict(self) -> dict[str, Any]:
38
+ return {
39
+ "n_trials": self.n_trials,
40
+ "scale": self.scale,
41
+ "block_size": self.block_size,
42
+ "pass_rate_30d": self.pass_rate_30d,
43
+ "pass_rate_60d": self.pass_rate_60d,
44
+ "pass_rate_horizon": self.pass_rate_horizon,
45
+ "ruin_rate": self.ruin_rate,
46
+ "timeout_rate": self.timeout_rate,
47
+ "dll_hit_rate": self.dll_hit_rate,
48
+ "consistency_delay_rate": self.consistency_delay_rate,
49
+ "median_days_to_pass": self.median_days_to_pass,
50
+ "funded_payout_rate": self.funded_payout_rate,
51
+ "joint_payout_rate": self.joint_payout_rate,
52
+ "expected_payout_usd": self.expected_payout_usd,
53
+ "net_ev_usd": self.net_ev_usd,
54
+ }
55
+
56
+ def to_json(self, *, indent: int = 2) -> str:
57
+ return json.dumps(self.to_dict(), indent=indent)
58
+
59
+ def to_markdown(self) -> str:
60
+ d2p = "n/a" if self.median_days_to_pass is None else f"{self.median_days_to_pass:.0f}d"
61
+ pass_triple = (
62
+ f"{self.pass_rate_30d:.1%} / {self.pass_rate_60d:.1%} / {self.pass_rate_horizon:.1%}"
63
+ )
64
+ lines = [
65
+ (
66
+ f"# prop-mc ({self.n_trials:,} paths, scale={self.scale:.2f}x, "
67
+ f"block={self.block_size}d)"
68
+ ),
69
+ "",
70
+ "| metric | value |",
71
+ "| :--- | ---: |",
72
+ f"| Pass rate (30d / 60d / horizon) | {pass_triple} |",
73
+ f"| Drawdown ruin rate | {self.ruin_rate:.1%} |",
74
+ f"| Timeout rate | {self.timeout_rate:.1%} |",
75
+ f"| DLL hit rate | {self.dll_hit_rate:.1%} |",
76
+ f"| Consistency delay rate | {self.consistency_delay_rate:.1%} |",
77
+ f"| Median days to pass | {d2p} |",
78
+ f"| Funded payout rate (given pass) | {self.funded_payout_rate:.1%} |",
79
+ f"| Joint payout rate | {self.joint_payout_rate:.1%} |",
80
+ f"| Expected gross payout | ${self.expected_payout_usd:,.2f} |",
81
+ f"| Net EV (after fees) | ${self.net_ev_usd:,.2f} |",
82
+ ]
83
+ return "\n".join(lines)
84
+
85
+ def to_html(self, *, title: str = "prop-mc report") -> str:
86
+ d2p = "n/a" if self.median_days_to_pass is None else f"{self.median_days_to_pass:.0f}d"
87
+ ev_color = "#2ec4b6" if self.net_ev_usd > 0.0 else "#e63946"
88
+ pass_triple = (
89
+ f"{self.pass_rate_30d:.1%} / {self.pass_rate_60d:.1%} / {self.pass_rate_horizon:.1%}"
90
+ )
91
+ ev_html = f"<span style='color:{ev_color};font-weight:700'>${self.net_ev_usd:,.2f}</span>"
92
+ rows = [
93
+ ("Pass rate (30d / 60d / horizon)", pass_triple),
94
+ ("Drawdown ruin rate", f"{self.ruin_rate:.1%}"),
95
+ ("Timeout rate", f"{self.timeout_rate:.1%}"),
96
+ ("DLL hit rate", f"{self.dll_hit_rate:.1%}"),
97
+ ("Consistency delay rate", f"{self.consistency_delay_rate:.1%}"),
98
+ ("Median days to pass", d2p),
99
+ ("Funded payout rate (given pass)", f"{self.funded_payout_rate:.1%}"),
100
+ ("Joint payout rate", f"{self.joint_payout_rate:.1%}"),
101
+ ("Expected gross payout", f"${self.expected_payout_usd:,.2f}"),
102
+ ("Net EV (after fees)", ev_html),
103
+ ]
104
+ body = "\n".join(
105
+ f"<tr><td>{html.escape(k)}</td><td style='text-align:right'>{v}</td></tr>"
106
+ for k, v in rows
107
+ )
108
+ t_esc = html.escape(title)
109
+ return (
110
+ "<!doctype html>\n<html lang='en'><head><meta charset='utf-8'>"
111
+ f"<title>{t_esc}</title>"
112
+ "<style>"
113
+ "body{background:#0d0b0c;color:#efe6e4;font-family:ui-sans-serif,system-ui,sans-serif;"
114
+ "margin:0;padding:32px;line-height:1.5}"
115
+ ".wrap{max-width:720px;margin:0 auto}"
116
+ "h1{margin:0 0 6px 0;font-size:24px}"
117
+ ".meta{color:#b8b3b1;margin:0 0 20px 0;font-size:14px}"
118
+ "table{width:100%;border-collapse:collapse;background:#161113;border:1px solid #2a2224}"
119
+ "th,td{padding:10px 12px;border-bottom:1px solid #2a2224;font-size:14px}"
120
+ "th{background:#1a0e10;color:#b8b3b1;text-align:left}"
121
+ "</style></head><body><div class='wrap'>"
122
+ f"<h1>{t_esc}</h1>"
123
+ f"<div class='meta'>{self.n_trials:,} paths · scale {self.scale:.2f}x · "
124
+ f"block {self.block_size}d</div>"
125
+ "<table><thead><tr><th>Metric</th><th style='text-align:right'>Value</th></tr></thead>"
126
+ f"<tbody>{body}</tbody></table></div></body></html>"
127
+ )
128
+
129
+
130
+ def _clean_pnl(daily_pnl: ArrayLike) -> NDArray[np.float64]:
131
+ arr = np.asarray(daily_pnl, dtype=np.float64)
132
+ if arr.ndim != 1 or arr.size < 5:
133
+ raise ValueError(f"daily_pnl must be 1-D with at least 5 observations, got {arr.shape}")
134
+ if not np.all(np.isfinite(arr)):
135
+ raise ValueError("daily_pnl must be finite (no NaN or inf)")
136
+ return arr
137
+
138
+
139
+ def sample_paths(
140
+ daily_pnl: ArrayLike,
141
+ *,
142
+ n_trials: int = 5_000,
143
+ n_days: int = 252,
144
+ block_size: int = 1,
145
+ seed: int = 7,
146
+ ) -> NDArray[np.float64]:
147
+ """Sample ``(n_trials, n_days)`` daily PnL paths via i.i.d. or circular block bootstrap."""
148
+ pnl = _clean_pnl(daily_pnl)
149
+ if n_trials < 1 or n_days < 1:
150
+ raise ValueError("n_trials and n_days must be >= 1")
151
+ if block_size < 1 or block_size > pnl.size:
152
+ raise ValueError(f"block_size must lie in [1, {pnl.size}], got {block_size}")
153
+
154
+ rng = np.random.default_rng(seed)
155
+ n = pnl.size
156
+ if block_size == 1:
157
+ idx = rng.integers(0, n, size=(n_trials, n_days))
158
+ return pnl[idx]
159
+
160
+ n_blocks = (n_days + block_size - 1) // block_size
161
+ starts = rng.integers(0, n, size=(n_trials, n_blocks))
162
+ offsets = np.arange(block_size, dtype=np.int64)
163
+ idx = (starts[:, :, None] + offsets[None, None, :]) % n
164
+ return pnl[idx.reshape(n_trials, n_blocks * block_size)[:, :n_days]]
165
+
166
+
167
+ def _run_stage(
168
+ paths: NDArray[np.float64],
169
+ rules: PropRules,
170
+ *,
171
+ target: float,
172
+ apply_consistency: bool,
173
+ min_days: int,
174
+ ) -> tuple[
175
+ NDArray[np.bool_],
176
+ NDArray[np.bool_],
177
+ NDArray[np.int64],
178
+ NDArray[np.bool_],
179
+ NDArray[np.bool_],
180
+ ]:
181
+ """Run one stage (evaluation or one funded payout cycle) vectorized across trials."""
182
+ n_trials, n_days = paths.shape
183
+ equity = np.full(n_trials, rules.account_size, dtype=np.float64)
184
+ peak = equity.copy()
185
+ floor = np.full(n_trials, rules.account_size - rules.max_drawdown, dtype=np.float64)
186
+ max_day_win = np.zeros(n_trials, dtype=np.float64)
187
+
188
+ active = np.ones(n_trials, dtype=np.bool_)
189
+ passed = np.zeros(n_trials, dtype=np.bool_)
190
+ ruined = np.zeros(n_trials, dtype=np.bool_)
191
+ pass_day = np.zeros(n_trials, dtype=np.int64)
192
+ dll_hit = np.zeros(n_trials, dtype=np.bool_)
193
+ cons_delayed = np.zeros(n_trials, dtype=np.bool_)
194
+
195
+ dll = rules.daily_loss_limit
196
+ cap = rules.consistency_cap if apply_consistency else None
197
+
198
+ for day in range(1, n_days + 1):
199
+ if not np.any(active):
200
+ break
201
+ step = paths[:, day - 1]
202
+ if dll is not None:
203
+ hit_now = active & (step <= -dll)
204
+ dll_hit |= hit_now
205
+ if rules.dll_mode == "breach":
206
+ ruined |= hit_now
207
+ active &= ~hit_now
208
+ step_eff = step
209
+ else:
210
+ step_eff = np.maximum(step, -dll)
211
+ else:
212
+ step_eff = step
213
+
214
+ equity = np.where(active, equity + step_eff, equity)
215
+ breached_dd = active & (equity <= floor)
216
+ ruined |= breached_dd
217
+ active &= ~breached_dd
218
+
219
+ if rules.trailing_mode == "eod":
220
+ peak = np.where(active, np.maximum(peak, equity), peak)
221
+ floor = np.where(
222
+ active,
223
+ np.minimum(rules.account_size, peak - rules.max_drawdown),
224
+ floor,
225
+ )
226
+
227
+ max_day_win = np.where(active, np.maximum(max_day_win, step_eff), max_day_win)
228
+ profit = equity - rules.account_size
229
+ hit_target = active & (profit >= target) & (day >= min_days)
230
+ if cap is not None:
231
+ consistent = max_day_win <= cap * profit + 1e-9
232
+ cons_delayed |= hit_target & ~consistent
233
+ won_now = hit_target & consistent
234
+ else:
235
+ won_now = hit_target
236
+
237
+ passed |= won_now
238
+ pass_day = np.where(won_now, day, pass_day)
239
+ active &= ~won_now
240
+
241
+ return passed, ruined, pass_day, dll_hit, cons_delayed
242
+
243
+
244
+ def simulate_eval(
245
+ daily_pnl: ArrayLike,
246
+ rules: PropRules,
247
+ *,
248
+ n_trials: int = 5_000,
249
+ block_size: int = 1,
250
+ scale: float = 1.0,
251
+ cost_drag: float = 0.0,
252
+ seed: int = 7,
253
+ ) -> SimulationResult:
254
+ """Simulate evaluation and funded payout survival for ``daily_pnl`` under ``rules``.
255
+
256
+ ``scale`` multiplies per-day PnL (e.g. ``0.5`` halves contract size) and
257
+ ``cost_drag`` subtracts a fixed additional per-day USD friction (scaled by
258
+ ``scale``).
259
+ """
260
+ if scale <= 0.0:
261
+ raise ValueError(f"scale must be positive, got {scale}")
262
+ if cost_drag < 0.0:
263
+ raise ValueError(f"cost_drag must be non-negative, got {cost_drag}")
264
+
265
+ pnl = _clean_pnl(daily_pnl) * float(scale) - float(cost_drag) * float(scale)
266
+ eval_paths = sample_paths(
267
+ pnl, n_trials=n_trials, n_days=rules.max_days, block_size=block_size, seed=seed
268
+ )
269
+ passed, ruined, pass_day, dll_hit, cons_delayed = _run_stage(
270
+ eval_paths,
271
+ rules,
272
+ target=rules.profit_target,
273
+ apply_consistency=True,
274
+ min_days=rules.min_trading_days,
275
+ )
276
+
277
+ pass_rate_h = float(np.mean(passed))
278
+ pass_30 = float(np.mean(passed & (pass_day <= 30)))
279
+ pass_60 = float(np.mean(passed & (pass_day <= 60)))
280
+ ruin_rate = float(np.mean(ruined))
281
+ timeout_rate = float(np.mean(~passed & ~ruined))
282
+ dll_rate = float(np.mean(dll_hit))
283
+ cons_rate = float(np.mean(cons_delayed))
284
+ d2p = float(np.median(pass_day[passed])) if np.any(passed) else None
285
+
286
+ # Stage 2: funded payout cycles on independent resampled paths for passers.
287
+ n_passed = int(np.sum(passed))
288
+ payout_counts = np.zeros(n_trials, dtype=np.int64)
289
+ if n_passed > 0 and rules.max_payouts > 0:
290
+ alive = passed.copy()
291
+ for cycle in range(rules.max_payouts):
292
+ if not np.any(alive):
293
+ break
294
+ cycle_paths = sample_paths(
295
+ pnl,
296
+ n_trials=n_trials,
297
+ n_days=rules.max_days,
298
+ block_size=block_size,
299
+ seed=seed + 1_000 + cycle,
300
+ )
301
+ won_c, _ruin_c, _d_c, _dll_c, _cd_c = _run_stage(
302
+ cycle_paths,
303
+ rules,
304
+ target=rules.payout_target,
305
+ apply_consistency=False,
306
+ min_days=1,
307
+ )
308
+ won_alive = alive & won_c
309
+ payout_counts += won_alive.astype(np.int64)
310
+ alive = won_alive
311
+
312
+ got_payout = payout_counts >= 1
313
+ funded_rate = float(np.sum(got_payout)) / n_passed if n_passed > 0 else 0.0
314
+ joint_rate = float(np.mean(got_payout))
315
+ payout_usd = rules.payout_target * rules.payout_split
316
+ expected_payout = float(np.mean(payout_counts)) * payout_usd
317
+ net_ev = expected_payout - rules.eval_fee - pass_rate_h * rules.activation_fee
318
+
319
+ return SimulationResult(
320
+ n_trials=n_trials,
321
+ scale=float(scale),
322
+ block_size=block_size,
323
+ pass_rate_30d=pass_30,
324
+ pass_rate_60d=pass_60,
325
+ pass_rate_horizon=pass_rate_h,
326
+ ruin_rate=ruin_rate,
327
+ timeout_rate=timeout_rate,
328
+ dll_hit_rate=dll_rate,
329
+ consistency_delay_rate=cons_rate,
330
+ median_days_to_pass=d2p,
331
+ funded_payout_rate=funded_rate,
332
+ joint_payout_rate=joint_rate,
333
+ expected_payout_usd=expected_payout,
334
+ net_ev_usd=net_ev,
335
+ )
336
+
337
+
338
+ def optimize_scale(
339
+ daily_pnl: ArrayLike,
340
+ rules: PropRules,
341
+ *,
342
+ scales: Sequence[float] = (0.25, 0.5, 0.75, 1.0, 1.25, 1.5, 2.0),
343
+ n_trials: int = 5_000,
344
+ block_size: int = 1,
345
+ seed: int = 7,
346
+ ) -> list[SimulationResult]:
347
+ """Sweep contract/risk scaling multipliers to map the pass-rate vs. net-EV frontier."""
348
+ if not scales:
349
+ raise ValueError("scales must be a non-empty sequence of positive floats")
350
+ return [
351
+ simulate_eval(
352
+ daily_pnl,
353
+ rules,
354
+ n_trials=n_trials,
355
+ block_size=block_size,
356
+ scale=float(s),
357
+ seed=seed,
358
+ )
359
+ for s in scales
360
+ ]
361
+
362
+
363
+ def stress_cost_sensitivity(
364
+ gross_daily_pnl: ArrayLike,
365
+ daily_costs: ArrayLike,
366
+ rules: PropRules,
367
+ *,
368
+ multipliers: Sequence[float] = (1.0, 1.5, 2.0),
369
+ n_trials: int = 5_000,
370
+ block_size: int = 1,
371
+ seed: int = 7,
372
+ ) -> dict[str, SimulationResult]:
373
+ """Measure how 1x / 1.5x / 2x execution costs erode prop pass rate and net EV."""
374
+ gross = _clean_pnl(gross_daily_pnl)
375
+ costs = np.asarray(daily_costs, dtype=np.float64)
376
+ if costs.ndim != 1 or costs.size != gross.size:
377
+ raise ValueError("gross_daily_pnl and daily_costs must have equal 1-D length")
378
+ if not np.all(np.isfinite(costs)) or np.any(costs < 0.0):
379
+ raise ValueError("daily_costs must be finite and non-negative")
380
+ if not multipliers or any(m < 0.0 for m in multipliers):
381
+ raise ValueError("multipliers must be non-empty and non-negative")
382
+
383
+ return {
384
+ f"{m:.2g}x": simulate_eval(
385
+ gross - float(m) * costs,
386
+ rules,
387
+ n_trials=n_trials,
388
+ block_size=block_size,
389
+ seed=seed,
390
+ )
391
+ for m in multipliers
392
+ }
@@ -0,0 +1,129 @@
1
+ Metadata-Version: 2.5
2
+ Name: prop-mc
3
+ Version: 1.0.0
4
+ Summary: Monte Carlo evaluation survival, trailing-drawdown ruin, and net-EV simulator for futures prop-firm rules.
5
+ Project-URL: Homepage, https://github.com/hontie/prop-mc
6
+ Project-URL: Repository, https://github.com/hontie/prop-mc
7
+ Project-URL: Issues, https://github.com/hontie/prop-mc/issues
8
+ Project-URL: Changelog, https://github.com/hontie/prop-mc/blob/main/CHANGELOG.md
9
+ Author: hontie
10
+ License: MIT
11
+ License-File: LICENSE
12
+ Keywords: drawdown,futures,monte-carlo,polars,prop-trading,quantitative-finance,risk-management
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Financial and Insurance Industry
15
+ Classifier: Intended Audience :: Science/Research
16
+ Classifier: License :: OSI Approved :: MIT License
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Programming Language :: Python :: 3.14
22
+ Classifier: Topic :: Office/Business :: Financial :: Investment
23
+ Classifier: Typing :: Typed
24
+ Requires-Python: >=3.11
25
+ Requires-Dist: numpy>=1.26
26
+ Requires-Dist: polars>=1.0
27
+ Description-Content-Type: text/markdown
28
+
29
+ # prop-mc
30
+
31
+ [![CI](https://github.com/hontie/prop-mc/actions/workflows/ci.yml/badge.svg)](https://github.com/hontie/prop-mc/actions/workflows/ci.yml)
32
+ [![PyPI](https://img.shields.io/pypi/v/prop-mc)](https://pypi.org/project/prop-mc/)
33
+ [![Coverage](https://img.shields.io/badge/coverage-100%25-brightgreen)](https://github.com/hontie/prop-mc/actions/workflows/ci.yml)
34
+ [![Python](https://img.shields.io/badge/python-3.11%2B-blue)](https://pypi.org/project/prop-mc/)
35
+ [![Typing](https://img.shields.io/badge/typing-mypy_strict-blue)](https://github.com/hontie/prop-mc/actions/workflows/ci.yml)
36
+ [![License](https://img.shields.io/badge/license-MIT-green)](LICENSE)
37
+
38
+ A positive-Sharpe trading strategy can still have negative expected value inside a futures prop-firm account. An end-of-day trailing drawdown, a daily loss limit, a 50 percent consistency cap, and reset fees turn position sizing into a boundary-crossing problem rather than a Sharpe maximization problem.
39
+
40
+ `prop-mc` simulates thousands of evaluation and funded-payout paths directly from your daily USD PnL series in vectorized NumPy and Polars. It reports pass rate at 30 days, 60 days, and full horizon, drawdown ruin rate, daily-loss-limit hits, consistency-cap delays, median days to pass, joint funded payout probability, and net expected value after fees.
41
+
42
+ The modeling details and sizing math are in [docs/paper.md](docs/paper.md).
43
+
44
+ ## Why Sharpe does not pick contract size
45
+
46
+ On a seeded positive-expectancy stream (`mean +$65/day`, `std $320/day`, 5,000 paths with 5-day block bootstrap) inside a standard `$50K` EOD-trailing account (`$3K` target, `$2K` trailing DD, `$1.2K` DLL, `50%` consistency cap, `$150` eval fee):
47
+
48
+ | Scale | Pass rate | Ruin rate | Median days | Joint payout | Net EV |
49
+ | ---: | ---: | ---: | ---: | ---: | ---: |
50
+ | `0.25x` | 13.0% | 1.2% | 213d | 1.7% | `-$98.70` |
51
+ | `0.50x` | 60.8% | 21.1% | 141d | 36.4% | `$1,761.06` |
52
+ | `0.75x` | 62.2% | 36.8% | 84d | 38.1% | `$1,898.76` |
53
+ | `1.00x` | 55.8% | 44.1% | 53d | 30.7% | `$1,371.72` |
54
+ | `1.50x` | 48.6% | 51.4% | 26d | 24.4% | `$967.80` |
55
+ | `2.00x` | 46.5% | 53.5% | 16d | 22.2% | `$848.46` |
56
+
57
+ ![Net EV sizing frontier](docs/sizing_frontier.png)
58
+
59
+ Doubling size from `1.0x` to `2.0x` cuts median days to pass from 53 to 16 while cutting net EV by 38 percent. Cutting size too far (`0.25x`) eliminates ruin (`1.2%`) but stalls out below the profit target (`-$98.70` net EV).
60
+
61
+ ![100 simulated prop evaluation paths](docs/equity_fan.png)
62
+
63
+ Both figures are regenerated from the same seed by `uv run python examples/make_figures.py`.
64
+
65
+ ## Install
66
+
67
+ ```bash
68
+ pip install prop-mc
69
+ ```
70
+
71
+ For development:
72
+
73
+ ```bash
74
+ git clone https://github.com/hontie/prop-mc.git
75
+ cd prop-mc
76
+ uv sync --all-extras
77
+ uv run pytest -q --cov=prop_mc
78
+ ```
79
+
80
+ ## Quickstart
81
+
82
+ ```python
83
+ import numpy as np
84
+ from prop_mc import optimize_scale, preset_50k_eod, simulate_eval
85
+
86
+ rng = np.random.default_rng(7)
87
+ daily_pnl = rng.normal(65.0, 320.0, size=500) # daily USD PnL from your backtest
88
+
89
+ rules = preset_50k_eod() # $50K account, $3K target, $2K EOD trailing DD, $1.2K DLL, 50% cap
90
+ res = simulate_eval(daily_pnl, rules, n_trials=5_000, block_size=5, seed=7)
91
+ print(res.to_markdown())
92
+
93
+ # Find the contract-size multiplier that maximizes net EV after reset fees
94
+ frontier = optimize_scale(daily_pnl, rules, scales=(0.5, 0.75, 1.0, 1.5, 2.0), n_trials=5_000)
95
+ ```
96
+
97
+ ## Command line
98
+
99
+ Simulate any daily USD PnL `.csv` or `.parquet` export:
100
+
101
+ ```bash
102
+ prop-mc run daily_pnl.csv --pnl-col pnl --trials 5000 --block-size 5 --html report.html
103
+ ```
104
+
105
+ Sweep risk multipliers to see where oversizing breaks net EV:
106
+
107
+ ```bash
108
+ prop-mc sweep daily_pnl.csv --pnl-col pnl --scales 0.25,0.5,0.75,1.0,1.25,1.5,2.0
109
+ ```
110
+
111
+ All account parameters can be overridden from the command line (`--account`, `--target`, `--max-dd`, `--trailing eod|static`, `--dll`, `--dll-mode flatten|breach`, `--consistency`, `--eval-fee`, `--activation-fee`, `--payout-target`, `--split`, `--max-payouts`).
112
+
113
+ ## What it models
114
+
115
+ - **EOD trailing vs. static drawdown:** in `eod` mode, the floor tracks `min(account_size, peak_equity - max_drawdown)`, locking at starting balance once you clear `max_drawdown` in profit.
116
+ - **Daily loss limits:** `flatten` caps any losing session at `-daily_loss_limit` (matching an intraday auto-liquidation lock); `breach` terminates the account on contact.
117
+ - **Consistency caps:** when `max_single_day_win > consistency_cap * total_profit`, passing is delayed until cumulative profit grows enough to bring the best day inside the cap.
118
+ - **Two-stage survival:** passing an evaluation earns zero dollars by itself. Stage 2 simulates up to `max_payouts` sequential funded payout cycles on independent resampled paths, reporting both conditional funded payout probability and joint `P(pass eval AND collect payout)`.
119
+ - **Block bootstrap:** `block_size > 1` resamples contiguous multi-day blocks so volatility clustering and losing streaks survive into the simulation instead of washing out under i.i.d. draws.
120
+
121
+ ## Related projects
122
+
123
+ - **[clockbars](https://github.com/hontie/clockbars)**: nine activity and flow bar kinds in Polars, verified identical across batch, live, and chunked execution.
124
+ - **[tradesigns](https://github.com/hontie/tradesigns)**: trade classification rules scored against CME aggressor flags on 34.4 million prints.
125
+ - **[auditbacktest](https://github.com/hontie/backtest-audit)**: ten-check leakage, overfitting, decay, and cost-stress auditor for trading backtests.
126
+
127
+ ## License
128
+
129
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,10 @@
1
+ prop_mc/__init__.py,sha256=CMGP5LpCA3jomMEuBTwU97hM6T2KU3LUQM5P4YjQU8g,554
2
+ prop_mc/cli.py,sha256=VdApRHGneIVNZm6vZUjysX_iVDCnvVxf5dOihCRhQJs,5041
3
+ prop_mc/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ prop_mc/rules.py,sha256=4o7aQNncIa_vSf_7fKaeVdmSsoXGCPd-VBW2R8802pY,4910
5
+ prop_mc/simulate.py,sha256=yiwREX1_IorTPgaqw3JPi831sLJ7U_sWaSdfluD29NI,14506
6
+ prop_mc-1.0.0.dist-info/METADATA,sha256=dqnjZXiwjPQF9Prk5YqpUF5XyuoUD6vqRCkfjk92L5g,6748
7
+ prop_mc-1.0.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
8
+ prop_mc-1.0.0.dist-info/entry_points.txt,sha256=jLARggEOb8lAlycMQqk6vcY5EFcz71XSpWfVTSnrJak,45
9
+ prop_mc-1.0.0.dist-info/licenses/LICENSE,sha256=JvW7nF4FYzL2wYCfKcCfXp6XdBsWTxGLeD0FKEwyqS0,1063
10
+ prop_mc-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ prop-mc = prop_mc.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 hontie
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.