auditbacktest 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.
- auditbacktest/__init__.py +43 -0
- auditbacktest/cli.py +99 -0
- auditbacktest/costs.py +143 -0
- auditbacktest/leakage.py +300 -0
- auditbacktest/overfitting.py +307 -0
- auditbacktest/py.typed +0 -0
- auditbacktest/reliability.py +199 -0
- auditbacktest/suite.py +119 -0
- auditbacktest/types.py +151 -0
- auditbacktest-1.0.0.dist-info/METADATA +201 -0
- auditbacktest-1.0.0.dist-info/RECORD +14 -0
- auditbacktest-1.0.0.dist-info/WHEEL +4 -0
- auditbacktest-1.0.0.dist-info/entry_points.txt +2 -0
- auditbacktest-1.0.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
"""Family 2 — Overfitting & multiple-testing audits (PSR, DSR, MinTRL, CSCV/PBO)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
from itertools import combinations
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
from numpy.typing import ArrayLike, NDArray
|
|
10
|
+
|
|
11
|
+
from auditbacktest.types import CheckResult, Status
|
|
12
|
+
|
|
13
|
+
_EULER_GAMMA = 0.5772156649015329
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def norm_cdf(x: float) -> float:
|
|
17
|
+
"""Standard normal CDF via ``math.erf``."""
|
|
18
|
+
return 0.5 * (1.0 + math.erf(x / math.sqrt(2.0)))
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def norm_ppf(p: float) -> float:
|
|
22
|
+
"""Inverse standard normal CDF (Acklam's rational approximation, err < 1.15e-9)."""
|
|
23
|
+
if not (0.0 < p < 1.0):
|
|
24
|
+
raise ValueError(f"p must lie strictly inside (0, 1), got {p}")
|
|
25
|
+
a = (
|
|
26
|
+
-3.969683028665376e01,
|
|
27
|
+
2.209460984245205e02,
|
|
28
|
+
-2.759285104469687e02,
|
|
29
|
+
1.383577518672690e02,
|
|
30
|
+
-3.066479806614716e01,
|
|
31
|
+
2.506628277459239e00,
|
|
32
|
+
)
|
|
33
|
+
b = (
|
|
34
|
+
-5.447609879822406e01,
|
|
35
|
+
1.615858368580409e02,
|
|
36
|
+
-1.556989798598866e02,
|
|
37
|
+
6.680131188771972e01,
|
|
38
|
+
-1.328068155288572e01,
|
|
39
|
+
)
|
|
40
|
+
c = (
|
|
41
|
+
-7.784894002430293e-03,
|
|
42
|
+
-3.223964580411365e-01,
|
|
43
|
+
-2.400758277161838e00,
|
|
44
|
+
-2.549732539343734e00,
|
|
45
|
+
4.374664141464968e00,
|
|
46
|
+
2.938163982698783e00,
|
|
47
|
+
)
|
|
48
|
+
d = (
|
|
49
|
+
7.784695709041462e-03,
|
|
50
|
+
3.224671290700398e-01,
|
|
51
|
+
2.445134137142996e00,
|
|
52
|
+
3.754408661907416e00,
|
|
53
|
+
)
|
|
54
|
+
p_low = 0.02425
|
|
55
|
+
p_high = 1.0 - p_low
|
|
56
|
+
|
|
57
|
+
if p < p_low:
|
|
58
|
+
q = math.sqrt(-2.0 * math.log(p))
|
|
59
|
+
return (((((c[0] * q + c[1]) * q + c[2]) * q + c[3]) * q + c[4]) * q + c[5]) / (
|
|
60
|
+
(((d[0] * q + d[1]) * q + d[2]) * q + d[3]) * q + 1.0
|
|
61
|
+
)
|
|
62
|
+
if p <= p_high:
|
|
63
|
+
q = p - 0.5
|
|
64
|
+
r = q * q
|
|
65
|
+
return (
|
|
66
|
+
(((((a[0] * r + a[1]) * r + a[2]) * r + a[3]) * r + a[4]) * r + a[5])
|
|
67
|
+
* q
|
|
68
|
+
/ (((((b[0] * r + b[1]) * r + b[2]) * r + b[3]) * r + b[4]) * r + 1.0)
|
|
69
|
+
)
|
|
70
|
+
q = math.sqrt(-2.0 * math.log(1.0 - p))
|
|
71
|
+
return -(((((c[0] * q + c[1]) * q + c[2]) * q + c[3]) * q + c[4]) * q + c[5]) / (
|
|
72
|
+
(((d[0] * q + d[1]) * q + d[2]) * q + d[3]) * q + 1.0
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _clean_returns(returns: ArrayLike) -> NDArray[np.float64]:
|
|
77
|
+
arr = np.asarray(returns, dtype=np.float64)
|
|
78
|
+
if arr.ndim != 1:
|
|
79
|
+
raise ValueError(f"returns must be 1-D, got shape {arr.shape}")
|
|
80
|
+
if arr.size < 4:
|
|
81
|
+
raise ValueError(f"returns needs at least 4 observations, got {arr.size}")
|
|
82
|
+
if not np.all(np.isfinite(arr)):
|
|
83
|
+
raise ValueError("returns must be finite (no NaN or inf)")
|
|
84
|
+
return arr
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def sharpe_stats(returns: ArrayLike, *, periods_per_year: int = 252) -> dict[str, float]:
|
|
88
|
+
"""Compute per-period Sharpe, annualized Sharpe, skewness, and kurtosis (Pearson)."""
|
|
89
|
+
if periods_per_year < 1:
|
|
90
|
+
raise ValueError(f"periods_per_year must be >= 1, got {periods_per_year}")
|
|
91
|
+
r = _clean_returns(returns)
|
|
92
|
+
mean = float(np.mean(r))
|
|
93
|
+
std = float(np.std(r, ddof=1))
|
|
94
|
+
if std == 0.0:
|
|
95
|
+
return {
|
|
96
|
+
"n": float(r.size),
|
|
97
|
+
"sr": 0.0,
|
|
98
|
+
"ann_sr": 0.0,
|
|
99
|
+
"skew": 0.0,
|
|
100
|
+
"kurtosis": 3.0,
|
|
101
|
+
}
|
|
102
|
+
z = (r - mean) / std
|
|
103
|
+
skew = float(np.mean(z**3))
|
|
104
|
+
kurt = float(np.mean(z**4))
|
|
105
|
+
sr = mean / std
|
|
106
|
+
return {
|
|
107
|
+
"n": float(r.size),
|
|
108
|
+
"sr": sr,
|
|
109
|
+
"ann_sr": sr * math.sqrt(periods_per_year),
|
|
110
|
+
"skew": skew,
|
|
111
|
+
"kurtosis": kurt,
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _psr_from_moments(sr: float, sr0: float, n: float, skew: float, kurt: float) -> float:
|
|
116
|
+
denom_sq = 1.0 - skew * sr + ((kurt - 1.0) / 4.0) * (sr * sr)
|
|
117
|
+
denom = math.sqrt(max(denom_sq, 1e-12))
|
|
118
|
+
z = (sr - sr0) * math.sqrt(n - 1.0) / denom
|
|
119
|
+
return norm_cdf(z)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def probabilistic_sharpe_ratio(
|
|
123
|
+
returns: ArrayLike,
|
|
124
|
+
*,
|
|
125
|
+
benchmark_sr: float = 0.0,
|
|
126
|
+
periods_per_year: int = 252,
|
|
127
|
+
) -> float:
|
|
128
|
+
"""Bailey & López de Prado (2012) Probabilistic Sharpe Ratio against ``benchmark_sr``."""
|
|
129
|
+
stats = sharpe_stats(returns, periods_per_year=periods_per_year)
|
|
130
|
+
sr0 = benchmark_sr / math.sqrt(periods_per_year)
|
|
131
|
+
return _psr_from_moments(stats["sr"], sr0, stats["n"], stats["skew"], stats["kurtosis"])
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def deflated_sharpe_ratio(
|
|
135
|
+
returns: ArrayLike,
|
|
136
|
+
*,
|
|
137
|
+
n_trials: int = 1,
|
|
138
|
+
periods_per_year: int = 252,
|
|
139
|
+
trial_sr_std: float | None = None,
|
|
140
|
+
min_dsr: float = 0.95,
|
|
141
|
+
) -> CheckResult:
|
|
142
|
+
"""Bailey & López de Prado (2014) Deflated Sharpe Ratio and Minimum Track Record Length.
|
|
143
|
+
|
|
144
|
+
Adjusts observed Sharpe for non-normality (skewness and kurtosis), sample
|
|
145
|
+
length, and multiple testing across ``n_trials`` independent variants.
|
|
146
|
+
When ``trial_sr_std`` is omitted, uses the standard theoretical variance
|
|
147
|
+
``1 / T`` under the null of zero-skill trials.
|
|
148
|
+
"""
|
|
149
|
+
if n_trials < 1:
|
|
150
|
+
raise ValueError(f"n_trials must be >= 1, got {n_trials}")
|
|
151
|
+
if not (0.0 < min_dsr < 1.0):
|
|
152
|
+
raise ValueError(f"min_dsr must lie in (0, 1), got {min_dsr}")
|
|
153
|
+
|
|
154
|
+
stats = sharpe_stats(returns, periods_per_year=periods_per_year)
|
|
155
|
+
n = stats["n"]
|
|
156
|
+
sr = stats["sr"]
|
|
157
|
+
skew = stats["skew"]
|
|
158
|
+
kurt = stats["kurtosis"]
|
|
159
|
+
|
|
160
|
+
if n_trials == 1:
|
|
161
|
+
sr_star = 0.0
|
|
162
|
+
else:
|
|
163
|
+
sr_scale = math.sqrt(1.0 / n) if trial_sr_std is None else float(trial_sr_std)
|
|
164
|
+
if sr_scale <= 0.0:
|
|
165
|
+
raise ValueError(f"trial_sr_std must be positive, got {sr_scale}")
|
|
166
|
+
z1 = norm_ppf(1.0 - 1.0 / n_trials)
|
|
167
|
+
z2 = norm_ppf(1.0 - 1.0 / (n_trials * math.e))
|
|
168
|
+
sr_star = sr_scale * ((1.0 - _EULER_GAMMA) * z1 + _EULER_GAMMA * z2)
|
|
169
|
+
|
|
170
|
+
dsr = _psr_from_moments(sr, sr_star, n, skew, kurt)
|
|
171
|
+
z_alpha = norm_ppf(min_dsr)
|
|
172
|
+
if sr > sr_star:
|
|
173
|
+
var_factor = max(1.0 - skew * sr + ((kurt - 1.0) / 4.0) * (sr * sr), 1e-12)
|
|
174
|
+
min_trl = 1.0 + var_factor * (z_alpha / (sr - sr_star)) ** 2
|
|
175
|
+
else:
|
|
176
|
+
min_trl = float("inf")
|
|
177
|
+
|
|
178
|
+
status: Status
|
|
179
|
+
if dsr >= min_dsr:
|
|
180
|
+
status = "PASS"
|
|
181
|
+
elif dsr >= 0.80:
|
|
182
|
+
status = "WARN"
|
|
183
|
+
else:
|
|
184
|
+
status = "FAIL"
|
|
185
|
+
|
|
186
|
+
ann_star = sr_star * math.sqrt(periods_per_year)
|
|
187
|
+
return CheckResult(
|
|
188
|
+
name="deflated_sharpe",
|
|
189
|
+
family="overfitting",
|
|
190
|
+
status=status,
|
|
191
|
+
metric=dsr,
|
|
192
|
+
threshold=min_dsr,
|
|
193
|
+
summary=(
|
|
194
|
+
f"DSR={dsr:.4f} (ann SR={stats['ann_sr']:.2f} vs haircut {ann_star:.2f}, "
|
|
195
|
+
f"N={n_trials})"
|
|
196
|
+
),
|
|
197
|
+
details={
|
|
198
|
+
"dsr": dsr,
|
|
199
|
+
"ann_sr": stats["ann_sr"],
|
|
200
|
+
"ann_haircut_sr": ann_star,
|
|
201
|
+
"n_trials": n_trials,
|
|
202
|
+
"n_obs": int(n),
|
|
203
|
+
"skew": skew,
|
|
204
|
+
"kurtosis": kurt,
|
|
205
|
+
"min_trl_obs": min_trl,
|
|
206
|
+
},
|
|
207
|
+
)
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _col_sharpe(mat: NDArray[np.float64]) -> NDArray[np.float64]:
|
|
211
|
+
mean = np.mean(mat, axis=0)
|
|
212
|
+
std = np.std(mat, axis=0, ddof=1)
|
|
213
|
+
return np.where(std > 0.0, mean / std, 0.0)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def cscv_pbo(
|
|
217
|
+
trial_returns: ArrayLike,
|
|
218
|
+
*,
|
|
219
|
+
n_slices: int = 16,
|
|
220
|
+
max_combos: int = 256,
|
|
221
|
+
max_pbo: float = 0.20,
|
|
222
|
+
seed: int = 7,
|
|
223
|
+
) -> CheckResult:
|
|
224
|
+
"""Bailey et al. (2017) Combinatorially Symmetric Cross-Validation PBO.
|
|
225
|
+
|
|
226
|
+
Partitions ``(T, M)`` trial returns into ``n_slices`` equal blocks (even),
|
|
227
|
+
evaluates symmetric IS/OOS splits, and measures how often the IS-optimal
|
|
228
|
+
variant lands below the OOS median (``lambda < 0``).
|
|
229
|
+
"""
|
|
230
|
+
mat = np.asarray(trial_returns, dtype=np.float64)
|
|
231
|
+
if mat.ndim != 2 or mat.shape[1] < 2:
|
|
232
|
+
raise ValueError(f"trial_returns must be 2-D with >= 2 trials, got shape {mat.shape}")
|
|
233
|
+
if not np.all(np.isfinite(mat)):
|
|
234
|
+
raise ValueError("trial_returns must be finite (no NaN or inf)")
|
|
235
|
+
if n_slices < 4 or n_slices % 2 != 0:
|
|
236
|
+
raise ValueError(f"n_slices must be an even integer >= 4, got {n_slices}")
|
|
237
|
+
if mat.shape[0] < n_slices * 2:
|
|
238
|
+
raise ValueError(
|
|
239
|
+
f"trial_returns needs at least {n_slices * 2} rows for {n_slices} slices, "
|
|
240
|
+
f"got {mat.shape[0]}"
|
|
241
|
+
)
|
|
242
|
+
|
|
243
|
+
usable = (mat.shape[0] // n_slices) * n_slices
|
|
244
|
+
trimmed = mat[:usable]
|
|
245
|
+
blocks = np.array_split(trimmed, n_slices, axis=0)
|
|
246
|
+
half = n_slices // 2
|
|
247
|
+
total_combos = math.comb(n_slices, half)
|
|
248
|
+
|
|
249
|
+
if total_combos <= max_combos:
|
|
250
|
+
splits = list(combinations(range(n_slices), half))
|
|
251
|
+
else:
|
|
252
|
+
rng = np.random.default_rng(seed)
|
|
253
|
+
seen: set[tuple[int, ...]] = set()
|
|
254
|
+
splits = []
|
|
255
|
+
while len(splits) < max_combos:
|
|
256
|
+
pick = tuple(sorted(int(x) for x in rng.choice(n_slices, size=half, replace=False)))
|
|
257
|
+
if pick not in seen:
|
|
258
|
+
seen.add(pick)
|
|
259
|
+
splits.append(pick)
|
|
260
|
+
|
|
261
|
+
m = mat.shape[1]
|
|
262
|
+
logits: list[float] = []
|
|
263
|
+
oos_neg = 0
|
|
264
|
+
all_idx = set(range(n_slices))
|
|
265
|
+
for is_idx in splits:
|
|
266
|
+
oos_idx = sorted(all_idx - set(is_idx))
|
|
267
|
+
is_mat = np.vstack([blocks[i] for i in is_idx])
|
|
268
|
+
oos_mat = np.vstack([blocks[i] for i in oos_idx])
|
|
269
|
+
is_sr = _col_sharpe(is_mat)
|
|
270
|
+
oos_sr = _col_sharpe(oos_mat)
|
|
271
|
+
best = int(np.argmax(is_sr))
|
|
272
|
+
# Relative OOS rank in (0, 1), bounded away from 0 and 1 for finite logits.
|
|
273
|
+
rank = (float(np.sum(oos_sr <= oos_sr[best]))) / (m + 1.0)
|
|
274
|
+
omega = min(max(rank, 1.0 / (m + 1.0)), m / (m + 1.0))
|
|
275
|
+
logits.append(math.log(omega / (1.0 - omega)))
|
|
276
|
+
if oos_sr[best] <= 0.0:
|
|
277
|
+
oos_neg += 1
|
|
278
|
+
|
|
279
|
+
logit_arr = np.asarray(logits, dtype=np.float64)
|
|
280
|
+
pbo = float(np.mean(logit_arr <= 0.0))
|
|
281
|
+
neg_rate = oos_neg / len(splits)
|
|
282
|
+
status: Status
|
|
283
|
+
if pbo <= max_pbo:
|
|
284
|
+
status = "PASS"
|
|
285
|
+
elif pbo <= max_pbo + 0.15:
|
|
286
|
+
status = "WARN"
|
|
287
|
+
else:
|
|
288
|
+
status = "FAIL"
|
|
289
|
+
|
|
290
|
+
return CheckResult(
|
|
291
|
+
name="cscv_pbo",
|
|
292
|
+
family="overfitting",
|
|
293
|
+
status=status,
|
|
294
|
+
metric=pbo,
|
|
295
|
+
threshold=max_pbo,
|
|
296
|
+
summary=(
|
|
297
|
+
f"PBO={pbo:.3f} across {len(splits)} splits "
|
|
298
|
+
f"(median logit={float(np.median(logit_arr)):+.2f}, OOS<=0 rate={neg_rate:.1%})"
|
|
299
|
+
),
|
|
300
|
+
details={
|
|
301
|
+
"pbo": pbo,
|
|
302
|
+
"n_splits": len(splits),
|
|
303
|
+
"n_trials": m,
|
|
304
|
+
"median_logit": float(np.median(logit_arr)),
|
|
305
|
+
"oos_nonpositive_rate": neg_rate,
|
|
306
|
+
},
|
|
307
|
+
)
|
auditbacktest/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
"""Family 3 — Statistical reliability: CUSUM decay, volatility breaks, and self-check."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
from collections.abc import Callable
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
import polars as pl
|
|
11
|
+
from numpy.typing import ArrayLike, NDArray
|
|
12
|
+
|
|
13
|
+
from auditbacktest.leakage import future_mutation_test
|
|
14
|
+
from auditbacktest.types import CheckResult
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _validate_series(returns: ArrayLike, min_len: int = 10) -> NDArray[np.float64]:
|
|
18
|
+
arr = np.asarray(returns, dtype=np.float64)
|
|
19
|
+
if arr.ndim != 1 or arr.size < min_len:
|
|
20
|
+
raise ValueError(f"returns must be 1-D with at least {min_len} rows, got {arr.shape}")
|
|
21
|
+
if not np.all(np.isfinite(arr)):
|
|
22
|
+
raise ValueError("returns must be finite (no NaN or inf)")
|
|
23
|
+
return arr
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def cusum_decay_test(
|
|
27
|
+
returns: ArrayLike,
|
|
28
|
+
*,
|
|
29
|
+
expected_sr: float = 0.0,
|
|
30
|
+
periods_per_year: int = 252,
|
|
31
|
+
threshold: float = 6.0,
|
|
32
|
+
e_threshold: float = 20.0,
|
|
33
|
+
) -> CheckResult:
|
|
34
|
+
"""Monitor for downward performance decay using Page's CUSUM and an e-process.
|
|
35
|
+
|
|
36
|
+
Standardizes returns against the expected per-period drift
|
|
37
|
+
``mu0 = (expected_sr / sqrt(periods_per_year)) * sigma`` and tracks the
|
|
38
|
+
downward CUSUM ``S_t = max(0, S_{t-1} + (-z_t - k))`` with reference slack
|
|
39
|
+
``k = 0.5`` alongside an anytime-valid Gaussian e-process testing
|
|
40
|
+
``H0: mu >= mu0`` against downward shift ``delta = 0.5`` standard deviations.
|
|
41
|
+
"""
|
|
42
|
+
r = _validate_series(returns, min_len=10)
|
|
43
|
+
if threshold <= 0.0 or e_threshold <= 1.0:
|
|
44
|
+
raise ValueError("threshold must be > 0 and e_threshold must be > 1")
|
|
45
|
+
|
|
46
|
+
std = float(np.std(r, ddof=1))
|
|
47
|
+
if std == 0.0:
|
|
48
|
+
return CheckResult(
|
|
49
|
+
name="cusum_decay",
|
|
50
|
+
family="reliability",
|
|
51
|
+
status="PASS" if float(np.mean(r)) >= 0.0 else "FAIL",
|
|
52
|
+
metric=0.0,
|
|
53
|
+
threshold=threshold,
|
|
54
|
+
summary="zero-variance return stream",
|
|
55
|
+
details={"max_cusum": 0.0, "max_e_value": 1.0},
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
mu0 = (expected_sr / math.sqrt(periods_per_year)) * std
|
|
59
|
+
z = (r - mu0) / std
|
|
60
|
+
|
|
61
|
+
# Downward one-sided Page CUSUM (k=0.5 calibrated for a 1-sigma shift)
|
|
62
|
+
s = 0.0
|
|
63
|
+
max_s = 0.0
|
|
64
|
+
peak_idx = 0
|
|
65
|
+
k_slack = 0.5
|
|
66
|
+
for idx, zi in enumerate(z.tolist()):
|
|
67
|
+
s = max(0.0, s + (-zi - k_slack))
|
|
68
|
+
if s > max_s:
|
|
69
|
+
max_s = s
|
|
70
|
+
peak_idx = idx
|
|
71
|
+
|
|
72
|
+
# Anytime-valid e-process for H0: E[z] >= 0 vs H1: E[z] = -delta
|
|
73
|
+
delta = 0.5
|
|
74
|
+
log_e = np.cumsum(-delta * z - 0.5 * delta * delta)
|
|
75
|
+
max_log_e = float(np.max(log_e))
|
|
76
|
+
max_e = math.exp(min(max_log_e, 700.0))
|
|
77
|
+
|
|
78
|
+
breached = max_s >= threshold or max_e >= e_threshold
|
|
79
|
+
return CheckResult(
|
|
80
|
+
name="cusum_decay",
|
|
81
|
+
family="reliability",
|
|
82
|
+
status="FAIL" if breached else "PASS",
|
|
83
|
+
metric=max_s,
|
|
84
|
+
threshold=threshold,
|
|
85
|
+
summary=(
|
|
86
|
+
f"no decay break (max CUSUM={max_s:.2f} < {threshold:.2f}, max e={max_e:.2f})"
|
|
87
|
+
if not breached
|
|
88
|
+
else f"DECAY DETECTED at obs {peak_idx} (max CUSUM={max_s:.2f}, max e={max_e:.2f})"
|
|
89
|
+
),
|
|
90
|
+
details={
|
|
91
|
+
"max_cusum": max_s,
|
|
92
|
+
"peak_index": peak_idx,
|
|
93
|
+
"max_e_value": max_e,
|
|
94
|
+
"e_threshold": e_threshold,
|
|
95
|
+
},
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def volatility_break_test(
|
|
100
|
+
returns: ArrayLike,
|
|
101
|
+
*,
|
|
102
|
+
critical: float = 1.358,
|
|
103
|
+
) -> CheckResult:
|
|
104
|
+
"""Inclán-Tiao (1994) centered cumulative sum of squares (ICSS) stability test.
|
|
105
|
+
|
|
106
|
+
Computes ``stat = sqrt(T / 2) * max_k |C_k / C_T - k / T|`` on demeaned
|
|
107
|
+
squared returns; ``critical = 1.358`` corresponds to the 5% asymptotic level.
|
|
108
|
+
"""
|
|
109
|
+
r = _validate_series(returns, min_len=10)
|
|
110
|
+
if critical <= 0.0:
|
|
111
|
+
raise ValueError(f"critical must be positive, got {critical}")
|
|
112
|
+
|
|
113
|
+
centered = r - float(np.mean(r))
|
|
114
|
+
sq = centered * centered
|
|
115
|
+
total = float(np.sum(sq))
|
|
116
|
+
if total == 0.0:
|
|
117
|
+
return CheckResult(
|
|
118
|
+
name="volatility_break",
|
|
119
|
+
family="reliability",
|
|
120
|
+
status="PASS",
|
|
121
|
+
metric=0.0,
|
|
122
|
+
threshold=critical,
|
|
123
|
+
summary="constant returns (zero variance)",
|
|
124
|
+
details={"stat": 0.0, "break_index": 0},
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
t = r.size
|
|
128
|
+
cum_sq = np.cumsum(sq)
|
|
129
|
+
frac = np.arange(1, t + 1, dtype=np.float64) / float(t)
|
|
130
|
+
dk = np.abs(cum_sq / total - frac)
|
|
131
|
+
break_idx = int(np.argmax(dk))
|
|
132
|
+
stat = math.sqrt(t / 2.0) * float(dk[break_idx])
|
|
133
|
+
passed = stat < critical
|
|
134
|
+
|
|
135
|
+
return CheckResult(
|
|
136
|
+
name="volatility_break",
|
|
137
|
+
family="reliability",
|
|
138
|
+
status="PASS" if passed else "WARN",
|
|
139
|
+
metric=stat,
|
|
140
|
+
threshold=critical,
|
|
141
|
+
summary=(
|
|
142
|
+
f"stable volatility (ICSS={stat:.3f} < {critical:.3f})"
|
|
143
|
+
if passed
|
|
144
|
+
else f"volatility shift near obs {break_idx} (ICSS={stat:.3f} >= {critical:.3f})"
|
|
145
|
+
),
|
|
146
|
+
details={"stat": stat, "break_index": break_idx, "n_obs": t},
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def audit_self_check(
|
|
151
|
+
fn: Callable[[Any], Any],
|
|
152
|
+
data: pl.DataFrame | NDArray[np.float64],
|
|
153
|
+
cutoff: int,
|
|
154
|
+
*,
|
|
155
|
+
atol: float = 1e-12,
|
|
156
|
+
) -> CheckResult:
|
|
157
|
+
"""Seeded-fault mutation check proving the leakage detector catches real bugs.
|
|
158
|
+
|
|
159
|
+
Wraps ``fn`` with two deliberate lookahead faults (a 1-bar future peek at
|
|
160
|
+
``cutoff + 1`` and a full-sample mean leak) and verifies
|
|
161
|
+
:func:`future_mutation_test` rejects both.
|
|
162
|
+
"""
|
|
163
|
+
|
|
164
|
+
def _as_arr(out: Any) -> NDArray[np.float64]:
|
|
165
|
+
if isinstance(out, pl.DataFrame):
|
|
166
|
+
num_cols = [c for c, dt in out.schema.items() if dt.is_numeric()]
|
|
167
|
+
return out.select(num_cols).to_numpy().astype(np.float64, copy=True)
|
|
168
|
+
if isinstance(out, pl.Series):
|
|
169
|
+
return out.cast(pl.Float64).to_numpy().astype(np.float64, copy=True)
|
|
170
|
+
return np.asarray(out, dtype=np.float64).copy()
|
|
171
|
+
|
|
172
|
+
def _peek_mutant(d: Any) -> NDArray[np.float64]:
|
|
173
|
+
arr = _as_arr(fn(d))
|
|
174
|
+
if arr.shape[0] > cutoff + 1:
|
|
175
|
+
arr[cutoff] = arr[cutoff + 1]
|
|
176
|
+
return arr
|
|
177
|
+
|
|
178
|
+
def _full_mean_mutant(d: Any) -> NDArray[np.float64]:
|
|
179
|
+
arr = _as_arr(fn(d))
|
|
180
|
+
return arr + float(np.nanmean(arr))
|
|
181
|
+
|
|
182
|
+
caught = 0
|
|
183
|
+
details: dict[str, str] = {}
|
|
184
|
+
for label, mutant in (("peek_next_bar", _peek_mutant), ("full_sample_mean", _full_mean_mutant)):
|
|
185
|
+
res = future_mutation_test(mutant, data, cutoff, atol=atol)
|
|
186
|
+
details[label] = res.status
|
|
187
|
+
if res.status == "FAIL":
|
|
188
|
+
caught += 1
|
|
189
|
+
|
|
190
|
+
ok = caught == 2
|
|
191
|
+
return CheckResult(
|
|
192
|
+
name="audit_self_check",
|
|
193
|
+
family="reliability",
|
|
194
|
+
status="PASS" if ok else "FAIL",
|
|
195
|
+
metric=float(caught),
|
|
196
|
+
threshold=2.0,
|
|
197
|
+
summary=f"caught {caught}/2 seeded lookahead mutants",
|
|
198
|
+
details={"caught": caught, "total": 2, "mutants": details},
|
|
199
|
+
)
|
auditbacktest/suite.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""Unified 9-check audit runner enforcing Rule 00 (not checked is not passed)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
import polars as pl
|
|
11
|
+
from numpy.typing import ArrayLike, NDArray
|
|
12
|
+
|
|
13
|
+
from auditbacktest.costs import cost_stress_ladder, reimplementation_parity
|
|
14
|
+
from auditbacktest.leakage import (
|
|
15
|
+
execution_delay_test,
|
|
16
|
+
future_mutation_test,
|
|
17
|
+
static_leakage_scan,
|
|
18
|
+
)
|
|
19
|
+
from auditbacktest.overfitting import cscv_pbo, deflated_sharpe_ratio
|
|
20
|
+
from auditbacktest.reliability import (
|
|
21
|
+
audit_self_check,
|
|
22
|
+
cusum_decay_test,
|
|
23
|
+
volatility_break_test,
|
|
24
|
+
)
|
|
25
|
+
from auditbacktest.types import AuditReport, CheckResult
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _skip(name: str, family: str, reason: str) -> CheckResult:
|
|
29
|
+
return CheckResult(name=name, family=family, status="SKIP", summary=reason)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def run_audit(
|
|
33
|
+
returns: ArrayLike,
|
|
34
|
+
*,
|
|
35
|
+
title: str = "auditbacktest",
|
|
36
|
+
n_trials: int = 1,
|
|
37
|
+
periods_per_year: int = 252,
|
|
38
|
+
expected_sr: float = 0.0,
|
|
39
|
+
strict: bool = True,
|
|
40
|
+
signal_fn: Callable[[Any], Any] | None = None,
|
|
41
|
+
market_data: pl.DataFrame | NDArray[np.float64] | None = None,
|
|
42
|
+
cutoff: int | None = None,
|
|
43
|
+
positions: ArrayLike | None = None,
|
|
44
|
+
asset_returns: ArrayLike | None = None,
|
|
45
|
+
source_code: str | Path | None = None,
|
|
46
|
+
trial_returns: ArrayLike | None = None,
|
|
47
|
+
gross_returns: ArrayLike | None = None,
|
|
48
|
+
trade_costs: ArrayLike | None = None,
|
|
49
|
+
reference_returns: ArrayLike | None = None,
|
|
50
|
+
) -> AuditReport:
|
|
51
|
+
"""Run all four audit families and return an :class:`AuditReport`.
|
|
52
|
+
|
|
53
|
+
Any check whose required inputs are omitted is explicitly recorded as
|
|
54
|
+
``SKIP`` rather than silently omitted or marked green. Under ``strict=True``
|
|
55
|
+
(Rule 00), any ``SKIP`` causes ``report.passed`` to be ``False``.
|
|
56
|
+
"""
|
|
57
|
+
checks: list[CheckResult] = []
|
|
58
|
+
|
|
59
|
+
# Family 1: Leakage
|
|
60
|
+
if signal_fn is not None and market_data is not None and cutoff is not None:
|
|
61
|
+
checks.append(future_mutation_test(signal_fn, market_data, cutoff))
|
|
62
|
+
else:
|
|
63
|
+
checks.append(
|
|
64
|
+
_skip("future_mutation", "leakage", "requires signal_fn, market_data, and cutoff")
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
if positions is not None and asset_returns is not None:
|
|
68
|
+
checks.append(
|
|
69
|
+
execution_delay_test(positions, asset_returns, periods_per_year=periods_per_year)
|
|
70
|
+
)
|
|
71
|
+
else:
|
|
72
|
+
checks.append(
|
|
73
|
+
_skip("execution_delay", "leakage", "requires positions and asset_returns")
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
if source_code is not None:
|
|
77
|
+
checks.append(static_leakage_scan(source_code))
|
|
78
|
+
else:
|
|
79
|
+
checks.append(_skip("static_leakage_scan", "leakage", "requires source_code path or text"))
|
|
80
|
+
|
|
81
|
+
# Family 2: Overfitting
|
|
82
|
+
checks.append(
|
|
83
|
+
deflated_sharpe_ratio(returns, n_trials=n_trials, periods_per_year=periods_per_year)
|
|
84
|
+
)
|
|
85
|
+
if trial_returns is not None:
|
|
86
|
+
checks.append(cscv_pbo(trial_returns))
|
|
87
|
+
else:
|
|
88
|
+
checks.append(_skip("cscv_pbo", "overfitting", "requires (T, M) trial_returns matrix"))
|
|
89
|
+
|
|
90
|
+
# Family 3: Reliability
|
|
91
|
+
checks.append(
|
|
92
|
+
cusum_decay_test(returns, expected_sr=expected_sr, periods_per_year=periods_per_year)
|
|
93
|
+
)
|
|
94
|
+
checks.append(volatility_break_test(returns))
|
|
95
|
+
if signal_fn is not None and market_data is not None and cutoff is not None:
|
|
96
|
+
checks.append(audit_self_check(signal_fn, market_data, cutoff))
|
|
97
|
+
else:
|
|
98
|
+
checks.append(
|
|
99
|
+
_skip("audit_self_check", "reliability", "requires signal_fn, market_data, and cutoff")
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
# Family 4: Costs & Parity
|
|
103
|
+
if gross_returns is not None and trade_costs is not None:
|
|
104
|
+
checks.append(
|
|
105
|
+
cost_stress_ladder(gross_returns, trade_costs, periods_per_year=periods_per_year)
|
|
106
|
+
)
|
|
107
|
+
else:
|
|
108
|
+
checks.append(
|
|
109
|
+
_skip("cost_stress_ladder", "costs", "requires gross_returns and trade_costs")
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
if reference_returns is not None:
|
|
113
|
+
checks.append(
|
|
114
|
+
reimplementation_parity(returns, reference_returns, periods_per_year=periods_per_year)
|
|
115
|
+
)
|
|
116
|
+
else:
|
|
117
|
+
checks.append(_skip("reimplementation_parity", "costs", "requires reference_returns"))
|
|
118
|
+
|
|
119
|
+
return AuditReport(results=tuple(checks), title=title, strict=strict)
|