Coverage for evaluation/monte_carlo.py: 100%

63 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""V5.3.8 - Monte Carlo simulation testing layer (pure core). 

2 

3Resamples the offline rank book's daily NET return series into N 

4alternative equity histories so risk can be stated as a DISTRIBUTION 

5instead of a single path: percentile bands for total return / Sharpe / 

6max drawdown, probability of loss, and the average compounded curve that 

7the README visual draws as its red center line. 

8 

9Two resampling methods: 

10- "block" (default): stationary block bootstrap - contiguous chunks of 

11 `block_size` days are resampled with replacement, preserving the 

12 short-horizon autocorrelation/volatility clustering a naive i.i.d. 

13 shuffle would erase. 

14- "iid": element-wise resampling - the classical Monte Carlo baseline. 

15 

16Pure: numpy only, no I/O, no torch, deterministic given (`seed`, inputs). 

17The heavy per-run curve matrix is returned DOWNSAMPLED (`n_plot_points`) 

18so callers can persist it without multi-megabyte payloads. 

19""" 

20 

21from __future__ import annotations 

22 

23from typing import TYPE_CHECKING, Any 

24 

25import numpy as np 

26 

27if TYPE_CHECKING: 

28 from numpy.typing import ArrayLike 

29 

30TRADING_DAYS_PER_YEAR = 252 

31 

32 

33def _max_drawdown(equity: np.ndarray) -> float: 

34 peak = np.maximum.accumulate(equity) 

35 drawdown = 1.0 - equity / peak 

36 return float(drawdown.max()) if drawdown.size else 0.0 

37 

38 

39def _annualized_sharpe(sampled_returns: np.ndarray, periods_per_year: float = TRADING_DAYS_PER_YEAR) -> float: 

40 if sampled_returns.size < 2: 

41 return 0.0 

42 std = sampled_returns.std(ddof=1) 

43 if std == 0: 

44 return 0.0 

45 return float(sampled_returns.mean() / std * np.sqrt(periods_per_year)) 

46 

47 

48def _resample_indices(n: int, block_size: int, method: str, rng: np.random.Generator) -> np.ndarray: 

49 if method == "iid": 

50 return rng.integers(0, n, n) 

51 n_blocks = int(np.ceil(n / block_size)) 

52 starts = rng.integers(0, n, size=n_blocks) 

53 idx = (starts[:, None] + np.arange(block_size)[None, :]).ravel() 

54 return idx[:n] % n 

55 

56 

57def _percentiles(values: np.ndarray) -> dict[str, float]: 

58 pct = np.percentile(values, [5, 25, 50, 75, 95]) 

59 keys = ["p5", "p25", "p50", "p75", "p95"] 

60 return {k: round(float(v), 6) for k, v in zip(keys, pct, strict=False)} 

61 

62 

63def run_monte_carlo( 

64 per_date_net_returns: ArrayLike, 

65 *, 

66 n_runs: int = 1000, 

67 block_size: int = 20, 

68 seed: int = 42, 

69 method: str = "block", 

70 n_plot_points: int = 500, 

71 periods_per_year: float = TRADING_DAYS_PER_YEAR, 

72) -> dict[str, Any]: 

73 """Runs the bootstrap and returns a self-describing result dict: 

74 

75 {"config": {...}, 

76 "status": "OK" | "SKIPPED: <reason>", 

77 "avg_curve": [...], # downsampled, red line 

78 "pct_band": {"p5": [...], "p25": [...], "p75": [...], "p95": [...]}, 

79 "runs_curves": np.ndarray (n_runs x points), # downsampled, for PNG 

80 "final_return_pct": {...percentiles}, "sharpe": {...}, "max_drawdown": {...}, 

81 "prob_negative_return": float, "best_run_total_return": ..., "worst_run_total_return": ...} 

82 

83 Equity curves are compounded from resampled daily returns and start at 

84 1.0. The average curve is the element-wise MEAN over all runs (the red 

85 line), NOT the mean of final values. 

86 """ 

87 config = { 

88 "n_runs": int(n_runs), 

89 "block_size": int(block_size), 

90 "seed": int(seed), 

91 "method": str(method), 

92 "trading_days_per_year": periods_per_year, 

93 } 

94 empty = { 

95 "config": config, 

96 "status": "", 

97 "avg_curve": [], 

98 "pct_band": {}, 

99 "final_return_pct": {}, 

100 "sharpe": {}, 

101 "max_drawdown": {}, 

102 "prob_negative_return": None, 

103 "best_run_total_return": None, 

104 "worst_run_total_return": None, 

105 } 

106 returns = np.asarray(list(per_date_net_returns), dtype=float) 

107 returns = returns[~np.isnan(returns)] 

108 if returns.size < 30: 

109 empty["status"] = f"SKIPPED: need >= 30 daily returns, got {returns.size}" 

110 return empty 

111 if n_runs < 1: 

112 empty["status"] = "SKIPPED: n_runs < 1" 

113 return empty 

114 if method not in ("block", "iid"): 

115 empty["status"] = f"SKIPPED: unknown method {method}" 

116 return empty 

117 

118 n = returns.size 

119 rng = np.random.default_rng(seed) 

120 

121 plot_points = min(n, max(int(n_plot_points), 2)) 

122 plot_idx = np.linspace(0, n - 1, plot_points).astype(int) 

123 

124 curves = np.empty((int(n_runs), plot_points), dtype=float) 

125 final_returns = np.empty(int(n_runs)) 

126 sharpes = np.empty(int(n_runs)) 

127 drawdowns = np.empty(int(n_runs)) 

128 

129 for run in range(int(n_runs)): 

130 sampled = returns[_resample_indices(n, block_size, method, rng)] 

131 equity = np.cumprod(1.0 + sampled) 

132 sharpes[run] = _annualized_sharpe(sampled, periods_per_year) 

133 drawdowns[run] = _max_drawdown(equity) 

134 final_returns[run] = equity[-1] - 1.0 

135 curves[run] = equity[plot_idx] 

136 

137 # Normalize every plotted curve to start exactly at 1.0 for readability. 

138 starts = curves[:, [0]] 

139 starts[starts == 0] = 1.0 

140 curves = curves / starts 

141 

142 avg_curve = curves.mean(axis=0) 

143 pct_band = { 

144 "p5": np.percentile(curves, 5, axis=0), 

145 "p25": np.percentile(curves, 25, axis=0), 

146 "p75": np.percentile(curves, 75, axis=0), 

147 "p95": np.percentile(curves, 95, axis=0), 

148 } 

149 

150 def _round_list(arr: np.ndarray, digits: int = 6) -> list[float]: 

151 return [round(float(v), digits) for v in arr] 

152 

153 return { 

154 "config": config, 

155 "status": "OK", 

156 "avg_curve": _round_list(avg_curve), 

157 "pct_band": {k: _round_list(v) for k, v in pct_band.items()}, 

158 "runs_curves": curves, 

159 "final_return_pct": _percentiles(final_returns * 100.0), 

160 "sharpe": _percentiles(sharpes), 

161 "max_drawdown": _percentiles(drawdowns * 100.0), 

162 "prob_negative_return": round(float((final_returns < 0).mean()), 4), 

163 "best_run_total_return": round(float(final_returns.max()) * 100.0, 4), 

164 "worst_run_total_return": round(float(final_returns.min()) * 100.0, 4), 

165 }