auditbacktest 1.0.0__tar.gz

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.
Files changed (31) hide show
  1. auditbacktest-1.0.0/.github/workflows/ci.yml +46 -0
  2. auditbacktest-1.0.0/.github/workflows/release.yml +52 -0
  3. auditbacktest-1.0.0/.gitignore +11 -0
  4. auditbacktest-1.0.0/CHANGELOG.md +26 -0
  5. auditbacktest-1.0.0/CITATION.cff +26 -0
  6. auditbacktest-1.0.0/LICENSE +21 -0
  7. auditbacktest-1.0.0/PKG-INFO +201 -0
  8. auditbacktest-1.0.0/README.md +173 -0
  9. auditbacktest-1.0.0/docs/cost_and_decay.png +0 -0
  10. auditbacktest-1.0.0/docs/dsr_haircut.png +0 -0
  11. auditbacktest-1.0.0/docs/gallery.png +0 -0
  12. auditbacktest-1.0.0/docs/paper.md +79 -0
  13. auditbacktest-1.0.0/docs/pbo_logits.png +0 -0
  14. auditbacktest-1.0.0/examples/make_figures.py +408 -0
  15. auditbacktest-1.0.0/examples/quickstart.py +68 -0
  16. auditbacktest-1.0.0/pyproject.toml +79 -0
  17. auditbacktest-1.0.0/src/auditbacktest/__init__.py +43 -0
  18. auditbacktest-1.0.0/src/auditbacktest/cli.py +99 -0
  19. auditbacktest-1.0.0/src/auditbacktest/costs.py +143 -0
  20. auditbacktest-1.0.0/src/auditbacktest/leakage.py +300 -0
  21. auditbacktest-1.0.0/src/auditbacktest/overfitting.py +307 -0
  22. auditbacktest-1.0.0/src/auditbacktest/py.typed +0 -0
  23. auditbacktest-1.0.0/src/auditbacktest/reliability.py +199 -0
  24. auditbacktest-1.0.0/src/auditbacktest/suite.py +119 -0
  25. auditbacktest-1.0.0/src/auditbacktest/types.py +151 -0
  26. auditbacktest-1.0.0/tests/test_costs.py +63 -0
  27. auditbacktest-1.0.0/tests/test_leakage.py +161 -0
  28. auditbacktest-1.0.0/tests/test_overfitting.py +114 -0
  29. auditbacktest-1.0.0/tests/test_reliability.py +69 -0
  30. auditbacktest-1.0.0/tests/test_suite_and_cli.py +134 -0
  31. auditbacktest-1.0.0/uv.lock +1298 -0
@@ -0,0 +1,46 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+ workflow_dispatch:
8
+
9
+ concurrency:
10
+ group: ${{ github.workflow }}-${{ github.ref }}
11
+ cancel-in-progress: true
12
+
13
+ jobs:
14
+ test:
15
+ runs-on: ${{ matrix.os }}
16
+ strategy:
17
+ fail-fast: false
18
+ matrix:
19
+ os: [ubuntu-latest, windows-latest]
20
+ python-version: ["3.11", "3.12", "3.13", "3.14"]
21
+
22
+ steps:
23
+ - uses: actions/checkout@v7
24
+
25
+ - name: Install uv
26
+ uses: astral-sh/setup-uv@v10.4.0
27
+ with:
28
+ enable-cache: true
29
+
30
+ - name: Install Python
31
+ run: uv python install ${{ matrix.python-version }}
32
+
33
+ - name: Sync environment
34
+ run: uv sync --all-extras --python ${{ matrix.python-version }}
35
+
36
+ - name: Lint
37
+ run: uv run ruff check .
38
+
39
+ - name: Type check
40
+ run: uv run mypy src
41
+
42
+ - name: Test
43
+ run: uv run pytest -q --cov=auditbacktest
44
+
45
+ - name: Example
46
+ run: uv run python examples/quickstart.py
@@ -0,0 +1,52 @@
1
+ name: Release
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+
7
+ permissions: {}
8
+
9
+ jobs:
10
+ release:
11
+ runs-on: ubuntu-latest
12
+ permissions:
13
+ id-token: write
14
+
15
+ steps:
16
+ - uses: actions/checkout@v7
17
+
18
+ - name: Install uv
19
+ uses: astral-sh/setup-uv@v10.4.0
20
+ with:
21
+ enable-cache: true
22
+
23
+ - name: Sync environment
24
+ run: uv sync --all-extras
25
+
26
+ - name: Lint
27
+ run: uv run ruff check .
28
+
29
+ - name: Type check
30
+ run: uv run mypy src
31
+
32
+ - name: Test
33
+ run: uv run pytest -q --cov=auditbacktest
34
+
35
+ - name: Build
36
+ run: uv build
37
+
38
+ - name: Check whether the version is already on PyPI
39
+ id: pypi
40
+ run: |
41
+ VERSION="${GITHUB_REF_NAME#v}"
42
+ if curl -fsS "https://pypi.org/pypi/auditbacktest/${VERSION}/json" > /dev/null 2>&1; then
43
+ echo "exists=true" >> "$GITHUB_OUTPUT"
44
+ else
45
+ echo "exists=false" >> "$GITHUB_OUTPUT"
46
+ fi
47
+
48
+ - name: Publish to PyPI
49
+ if: steps.pypi.outputs.exists == 'false'
50
+ uses: pypa/gh-action-pypi-publish@release/v1
51
+ with:
52
+ attestations: true
@@ -0,0 +1,11 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.pyc
4
+ .pytest_cache/
5
+ .ruff_cache/
6
+ .mypy_cache/
7
+ .coverage
8
+ htmlcov/
9
+ dist/
10
+ build/
11
+ *.egg-info/
@@ -0,0 +1,26 @@
1
+ # Changelog
2
+
3
+ All notable changes to auditbacktest are documented here. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versions follow
5
+ [SemVer](https://semver.org/).
6
+
7
+ ## [1.0.0] - 2026-12-03
8
+
9
+ Initial public release.
10
+
11
+ - **Leakage:** `future_mutation_test` (3 future perturbations including sign-flipped
12
+ reversed shock at `atol=1e-12`), `execution_delay_test` (1-bar fill delay),
13
+ and `static_leakage_scan` (AST detection for negative shifts, backward fills,
14
+ centered rolling windows, non-causal `join_asof`, and `.fit_transform()`).
15
+ - **Overfitting:** `probabilistic_sharpe_ratio`, `deflated_sharpe_ratio` with
16
+ Minimum Track Record Length, and `cscv_pbo` (Combinatorially Symmetric
17
+ Cross-Validation).
18
+ - **Reliability:** `cusum_decay_test` (Page CUSUM + anytime-valid e-process),
19
+ `volatility_break_test` (Inclán–Tiao ICSS), and `audit_self_check`
20
+ (seeded-mutant verification).
21
+ - **Costs & parity:** `cost_stress_ladder` (0x to 3x drag + breakeven cost
22
+ multiplier) and `reimplementation_parity`.
23
+ - **Unified suite & CLI:** `run_audit` enforcing Rule 00 (`PASS|WARN|FAIL|SKIP`),
24
+ Markdown/JSON/dark-HTML tearsheets, and `auditbacktest run|scan`.
25
+
26
+ [1.0.0]: https://github.com/hontie/auditbacktest/releases/tag/v1.0.0
@@ -0,0 +1,26 @@
1
+ cff-version: 1.2.0
2
+ message: "If you use auditbacktest in your research, please cite it."
3
+ type: software
4
+ title: auditbacktest
5
+ authors:
6
+ - alias: hontie
7
+ version: 1.0.0
8
+ date-released: "2026-12-03"
9
+ license: MIT
10
+ repository-code: "https://github.com/hontie/auditbacktest"
11
+ abstract: >-
12
+ Ten-check leakage, overfitting, sequential decay, and cost-stress auditor
13
+ for quantitative trading backtests in Polars and NumPy, enforcing Rule 00
14
+ (not checked is not passed) with seeded-mutant self-verification.
15
+ keywords:
16
+ - quantitative-finance
17
+ - backtesting
18
+ - overfitting
19
+ - deflated-sharpe-ratio
20
+ - cscv
21
+ - pbo
22
+ - lookahead-bias
23
+ related-identifiers:
24
+ - type: url
25
+ value: "https://github.com/hontie/auditbacktest/blob/main/docs/paper.md"
26
+ description: Accompanying paper
@@ -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.
@@ -0,0 +1,201 @@
1
+ Metadata-Version: 2.5
2
+ Name: auditbacktest
3
+ Version: 1.0.0
4
+ Summary: Ten-check leakage, overfitting, sequential decay, and cost-stress auditor for trading backtests.
5
+ Project-URL: Homepage, https://github.com/hontie/auditbacktest
6
+ Project-URL: Repository, https://github.com/hontie/auditbacktest
7
+ Project-URL: Issues, https://github.com/hontie/auditbacktest/issues
8
+ Project-URL: Changelog, https://github.com/hontie/auditbacktest/blob/main/CHANGELOG.md
9
+ Author: hontie
10
+ License: MIT
11
+ License-File: LICENSE
12
+ Keywords: backtesting,cscv,deflated-sharpe-ratio,lookahead-bias,overfitting,pbo,polars,quantitative-finance
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
+ # auditbacktest
30
+
31
+ [![CI](https://github.com/hontie/auditbacktest/actions/workflows/ci.yml/badge.svg)](https://github.com/hontie/auditbacktest/actions/workflows/ci.yml)
32
+ [![PyPI](https://img.shields.io/pypi/v/auditbacktest)](https://pypi.org/project/auditbacktest/)
33
+ [![Coverage](https://img.shields.io/badge/coverage-100%25-brightgreen)](https://github.com/hontie/auditbacktest/actions/workflows/ci.yml)
34
+ [![Python](https://img.shields.io/badge/python-3.11%2B-blue)](https://pypi.org/project/auditbacktest/)
35
+ [![Typing](https://img.shields.io/badge/typing-mypy_strict-blue)](https://github.com/hontie/auditbacktest/actions/workflows/ci.yml)
36
+ [![License](https://img.shields.io/badge/license-MIT-green)](LICENSE)
37
+
38
+ A backtest that prints a 2.8 Sharpe ratio and loses money in week two almost always broke in one of four places: future data leaked into a feature or fill, the winning parameter set won a multiple-testing lottery, realistic fills erased the spread, or the live stream decayed without a stopping rule.
39
+
40
+ `auditbacktest` runs ten deterministic checks across those four failure families in Polars and NumPy, completely offline, with no LLM API keys, no `scipy`, and no `pandas`. Every check returns `PASS`, `WARN`, `FAIL`, or `SKIP`. Under strict mode (Rule 00), a skipped check never passes: omitting a test is recorded as a missing gate, not green ink.
41
+
42
+ ```mermaid
43
+ %%{init: {
44
+ "theme": "dark",
45
+ "themeVariables": {
46
+ "background": "#0d0b0c",
47
+ "primaryColor": "#1a0e10",
48
+ "primaryTextColor": "#efe6e4",
49
+ "primaryBorderColor": "#e63946",
50
+ "secondaryColor": "#241418",
51
+ "secondaryTextColor": "#efe6e4",
52
+ "secondaryBorderColor": "#891826",
53
+ "tertiaryColor": "#0d0b0c",
54
+ "tertiaryTextColor": "#b8b3b1",
55
+ "tertiaryBorderColor": "#2a2224",
56
+ "lineColor": "#891826",
57
+ "textColor": "#efe6e4",
58
+ "mainBkg": "#1a0e10",
59
+ "nodeBorder": "#e63946",
60
+ "clusterBkg": "#0d0b0c",
61
+ "titleColor": "#efe6e4",
62
+ "edgeLabelBackground": "#0d0b0c"
63
+ }
64
+ }}%%
65
+ flowchart LR
66
+ I["returns, signals, code, variants"] --> L["Leakage: mutation, delay, AST"]
67
+ I --> O["Overfitting: DSR, MinTRL, CSCV-PBO"]
68
+ I --> R["Reliability: CUSUM, e-process, ICSS, self-check"]
69
+ I --> C["Costs: 0x..3x cliff, breakeven, parity"]
70
+ L --> G["Rule 00 gate: PASS / WARN / FAIL / SKIP"]
71
+ O --> G
72
+ R --> G
73
+ C --> G
74
+ G --> OUT["CLI table, JSON, dark HTML tearsheet"]
75
+
76
+ classDef fam fill:#1a0e10,stroke:#e63946,stroke-width:2px,color:#efe6e4
77
+ classDef gate fill:#241418,stroke:#891826,stroke-width:2px,color:#efe6e4
78
+ classDef io fill:#0d0b0c,stroke:#2a2224,stroke-width:1px,color:#b8b3b1
79
+
80
+ class L,O,R,C fam
81
+ class G gate
82
+ class I,OUT io
83
+ ```
84
+
85
+ The formulas, thresholds, and limitations behind each check are in [docs/paper.md](docs/paper.md).
86
+
87
+ ## Install
88
+
89
+ ```bash
90
+ pip install auditbacktest
91
+ ```
92
+
93
+ For development:
94
+
95
+ ```bash
96
+ git clone https://github.com/hontie/auditbacktest.git
97
+ cd auditbacktest
98
+ uv sync --all-extras
99
+ uv run pytest -q --cov=auditbacktest
100
+ ```
101
+
102
+ ## Ten checks, four families
103
+
104
+ | Family | Check | What it catches |
105
+ | :--- | :--- | :--- |
106
+ | Leakage | `future_mutation` | Any feature or signal whose values at `<= cutoff` change by more than `1e-12` when rows `> cutoff` are perturbed (`+25%`, `-20%`, sign-flipped reversed shock). |
107
+ | Leakage | `execution_delay` | Same-bar close-to-close execution lookahead: compares same-bar fills against `+1` bar delayed positions and fails when edge collapses. |
108
+ | Leakage | `static_leakage_scan` | AST scan for `shift(-k)`, `.bfill()` / `.backward_fill()`, `rolling(center=True)`, `join_asof(strategy="forward"\|"nearest")`, and `.fit_transform()`. |
109
+ | Overfitting | `deflated_sharpe` | Bailey and López de Prado (2014) Deflated Sharpe Ratio and Minimum Track Record Length across skewness, kurtosis, length, and trial count `N`. |
110
+ | Overfitting | `cscv_pbo` | Bailey et al. (2017) Combinatorially Symmetric Cross-Validation Probability of Backtest Overfitting over a `(T, M)` matrix of tested variants. |
111
+ | Reliability | `cusum_decay` | Page's one-sided downward CUSUM (`k=0.5, h=6.0`) paired with an anytime-valid Gaussian e-process (`e_t`) to separate live decay from routine drawdown. |
112
+ | Reliability | `volatility_break` | Inclán and Tiao (1994) centered cumulative sum of squares (`ICSS`) test for structural variance shifts. |
113
+ | Reliability | `audit_self_check` | Injects two known lookahead mutants (1-bar peek and full-sample mean leak) into the wrapper and verifies the detector catches `2/2`. |
114
+ | Costs | `cost_stress_ladder` | Sharpe, Sortino, CAGR, Max Drawdown, Calmar, and Profit Factor across `0x`, `1x`, `1.5x`, `2x`, and `3x` cost drag, plus the exact breakeven cost multiplier. |
115
+ | Costs | `reimplementation_parity` | Max absolute diff and Sharpe gap between a primary return curve and an independent reference implementation (for example, vectorized backtest vs. event-driven fill log). |
116
+
117
+ ## What the checks catch
118
+
119
+ All four figures below are regenerated from seeded streams by `uv run python examples/make_figures.py`.
120
+
121
+ ### Six random-walk strategies, five bugs caught in 0.2 seconds
122
+
123
+ ![Gallery benchmark](docs/gallery.png)
124
+
125
+ On a zero-edge random walk (`T = 600`), same-bar execution lookahead, `shift(-1)`, centered rolling windows, full-history z-scores, and best-of-250 parameter mining all print high backtest Sharpe ratios and fail their corresponding gates, while a causal moving-average baseline clears with zero false alarms.
126
+
127
+ ### The multiple-testing tax (DSR)
128
+
129
+ ![DSR haircut across trial count](docs/dsr_haircut.png)
130
+
131
+ Over a two-year daily record (`T = 504`), an observed `1.50` Sharpe passes at `N = 1` (`DSR = 0.98`) and drops below gate by `N = 10` (`DSR = 0.71`).
132
+
133
+ ### Combinatorially Symmetric Cross-Validation (PBO)
134
+
135
+ ![CSCV rank logit distribution](docs/pbo_logits.png)
136
+
137
+ Across 256 symmetric splits over 24 candidate variants, pure noise-mining yields `PBO = 42.6%` while a genuine persistent variant lands at `PBO = 0.0%`.
138
+
139
+ ### Cost cliff and live sequential decay
140
+
141
+ ![Cost stress cliff and CUSUM decay](docs/cost_and_decay.png)
142
+
143
+ A high-turnover scalper that looks positive at `1x` modelled fees breaks even at `1.39x` and turns negative well before `2x`. On the right, downward Page CUSUM stays quiet during normal fluctuations and crosses `h = 6.0` shortly after a day-140 regime break (`max S_t = 27.6`).
144
+
145
+ ## Quickstart
146
+
147
+ ```python
148
+ import numpy as np
149
+ import polars as pl
150
+ from auditbacktest import run_audit
151
+
152
+ def causal_signal(df: pl.DataFrame) -> pl.Series:
153
+ return (df["close"] - df["close"].rolling_mean(window_size=20)).fill_null(0.0)
154
+
155
+ report = run_audit(
156
+ net_returns,
157
+ title="mnq-breakout-v1",
158
+ n_trials=24,
159
+ signal_fn=causal_signal,
160
+ market_data=bars,
161
+ cutoff=600,
162
+ positions=positions,
163
+ asset_returns=asset_returns,
164
+ source_code="strategies/breakout.py",
165
+ trial_returns=variant_matrix,
166
+ gross_returns=gross_returns,
167
+ trade_costs=trade_costs,
168
+ reference_returns=event_driven_returns,
169
+ )
170
+
171
+ print(report.to_markdown())
172
+ assert report.passed
173
+ ```
174
+
175
+ ## Command line
176
+
177
+ Audit any daily or per-trade `.csv` or `.parquet` export from TradingView, NinjaTrader, Tradovate, or Python:
178
+
179
+ ```bash
180
+ auditbacktest run returns.csv --ret-col net_ret --cost-col cost --n-trials 30 --html tearsheet.html
181
+ ```
182
+
183
+ Scan a strategy script for static lookahead patterns before running a backtest:
184
+
185
+ ```bash
186
+ auditbacktest scan strategies/my_strategy.py
187
+ ```
188
+
189
+ Pass `--strict` in CI to exit nonzero whenever any check fails or is skipped.
190
+
191
+ ## Related work
192
+
193
+ **[backtest-auditor](https://github.com/123Alissaa/backtest-auditor)** is a Streamlit app built around four deterministic checks (delay, hide-the-future, a single 60/40 holdout split, and DSR) plus an LLM explanation and auto-fix loop running inside remote cloud sandboxes. `auditbacktest` targets local research and CI pipelines instead: it ships as a typed PyPI library with zero network or API calls, runs in milliseconds on Polars/NumPy, enforces Rule 00 (`SKIP` never passes under strict mode), and adds six quantitative gates missing from that tool: CSCV/PBO across 256 symmetric splits, Page CUSUM plus anytime-valid e-process decay monitoring, Inclán–Tiao volatility-break detection, `0x..3x` cost-stress and breakeven calculation, independent reimplementation parity, and seeded-mutant self-verification.
194
+
195
+ - **[clockbars](https://github.com/hontie/clockbars)**: nine activity and flow bar kinds in Polars, verified identical across batch, live, and chunked execution.
196
+ - **[tradesigns](https://github.com/hontie/tradesigns)**: trade classification rules scored against CME aggressor flags on 34.4 million prints.
197
+ - **[prop-mc](https://github.com/hontie/prop-mc)**: Monte Carlo survival, drawdown-breach, and net-EV simulator for futures prop-firm rules.
198
+
199
+ ## License
200
+
201
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,173 @@
1
+ # auditbacktest
2
+
3
+ [![CI](https://github.com/hontie/auditbacktest/actions/workflows/ci.yml/badge.svg)](https://github.com/hontie/auditbacktest/actions/workflows/ci.yml)
4
+ [![PyPI](https://img.shields.io/pypi/v/auditbacktest)](https://pypi.org/project/auditbacktest/)
5
+ [![Coverage](https://img.shields.io/badge/coverage-100%25-brightgreen)](https://github.com/hontie/auditbacktest/actions/workflows/ci.yml)
6
+ [![Python](https://img.shields.io/badge/python-3.11%2B-blue)](https://pypi.org/project/auditbacktest/)
7
+ [![Typing](https://img.shields.io/badge/typing-mypy_strict-blue)](https://github.com/hontie/auditbacktest/actions/workflows/ci.yml)
8
+ [![License](https://img.shields.io/badge/license-MIT-green)](LICENSE)
9
+
10
+ A backtest that prints a 2.8 Sharpe ratio and loses money in week two almost always broke in one of four places: future data leaked into a feature or fill, the winning parameter set won a multiple-testing lottery, realistic fills erased the spread, or the live stream decayed without a stopping rule.
11
+
12
+ `auditbacktest` runs ten deterministic checks across those four failure families in Polars and NumPy, completely offline, with no LLM API keys, no `scipy`, and no `pandas`. Every check returns `PASS`, `WARN`, `FAIL`, or `SKIP`. Under strict mode (Rule 00), a skipped check never passes: omitting a test is recorded as a missing gate, not green ink.
13
+
14
+ ```mermaid
15
+ %%{init: {
16
+ "theme": "dark",
17
+ "themeVariables": {
18
+ "background": "#0d0b0c",
19
+ "primaryColor": "#1a0e10",
20
+ "primaryTextColor": "#efe6e4",
21
+ "primaryBorderColor": "#e63946",
22
+ "secondaryColor": "#241418",
23
+ "secondaryTextColor": "#efe6e4",
24
+ "secondaryBorderColor": "#891826",
25
+ "tertiaryColor": "#0d0b0c",
26
+ "tertiaryTextColor": "#b8b3b1",
27
+ "tertiaryBorderColor": "#2a2224",
28
+ "lineColor": "#891826",
29
+ "textColor": "#efe6e4",
30
+ "mainBkg": "#1a0e10",
31
+ "nodeBorder": "#e63946",
32
+ "clusterBkg": "#0d0b0c",
33
+ "titleColor": "#efe6e4",
34
+ "edgeLabelBackground": "#0d0b0c"
35
+ }
36
+ }}%%
37
+ flowchart LR
38
+ I["returns, signals, code, variants"] --> L["Leakage: mutation, delay, AST"]
39
+ I --> O["Overfitting: DSR, MinTRL, CSCV-PBO"]
40
+ I --> R["Reliability: CUSUM, e-process, ICSS, self-check"]
41
+ I --> C["Costs: 0x..3x cliff, breakeven, parity"]
42
+ L --> G["Rule 00 gate: PASS / WARN / FAIL / SKIP"]
43
+ O --> G
44
+ R --> G
45
+ C --> G
46
+ G --> OUT["CLI table, JSON, dark HTML tearsheet"]
47
+
48
+ classDef fam fill:#1a0e10,stroke:#e63946,stroke-width:2px,color:#efe6e4
49
+ classDef gate fill:#241418,stroke:#891826,stroke-width:2px,color:#efe6e4
50
+ classDef io fill:#0d0b0c,stroke:#2a2224,stroke-width:1px,color:#b8b3b1
51
+
52
+ class L,O,R,C fam
53
+ class G gate
54
+ class I,OUT io
55
+ ```
56
+
57
+ The formulas, thresholds, and limitations behind each check are in [docs/paper.md](docs/paper.md).
58
+
59
+ ## Install
60
+
61
+ ```bash
62
+ pip install auditbacktest
63
+ ```
64
+
65
+ For development:
66
+
67
+ ```bash
68
+ git clone https://github.com/hontie/auditbacktest.git
69
+ cd auditbacktest
70
+ uv sync --all-extras
71
+ uv run pytest -q --cov=auditbacktest
72
+ ```
73
+
74
+ ## Ten checks, four families
75
+
76
+ | Family | Check | What it catches |
77
+ | :--- | :--- | :--- |
78
+ | Leakage | `future_mutation` | Any feature or signal whose values at `<= cutoff` change by more than `1e-12` when rows `> cutoff` are perturbed (`+25%`, `-20%`, sign-flipped reversed shock). |
79
+ | Leakage | `execution_delay` | Same-bar close-to-close execution lookahead: compares same-bar fills against `+1` bar delayed positions and fails when edge collapses. |
80
+ | Leakage | `static_leakage_scan` | AST scan for `shift(-k)`, `.bfill()` / `.backward_fill()`, `rolling(center=True)`, `join_asof(strategy="forward"\|"nearest")`, and `.fit_transform()`. |
81
+ | Overfitting | `deflated_sharpe` | Bailey and López de Prado (2014) Deflated Sharpe Ratio and Minimum Track Record Length across skewness, kurtosis, length, and trial count `N`. |
82
+ | Overfitting | `cscv_pbo` | Bailey et al. (2017) Combinatorially Symmetric Cross-Validation Probability of Backtest Overfitting over a `(T, M)` matrix of tested variants. |
83
+ | Reliability | `cusum_decay` | Page's one-sided downward CUSUM (`k=0.5, h=6.0`) paired with an anytime-valid Gaussian e-process (`e_t`) to separate live decay from routine drawdown. |
84
+ | Reliability | `volatility_break` | Inclán and Tiao (1994) centered cumulative sum of squares (`ICSS`) test for structural variance shifts. |
85
+ | Reliability | `audit_self_check` | Injects two known lookahead mutants (1-bar peek and full-sample mean leak) into the wrapper and verifies the detector catches `2/2`. |
86
+ | Costs | `cost_stress_ladder` | Sharpe, Sortino, CAGR, Max Drawdown, Calmar, and Profit Factor across `0x`, `1x`, `1.5x`, `2x`, and `3x` cost drag, plus the exact breakeven cost multiplier. |
87
+ | Costs | `reimplementation_parity` | Max absolute diff and Sharpe gap between a primary return curve and an independent reference implementation (for example, vectorized backtest vs. event-driven fill log). |
88
+
89
+ ## What the checks catch
90
+
91
+ All four figures below are regenerated from seeded streams by `uv run python examples/make_figures.py`.
92
+
93
+ ### Six random-walk strategies, five bugs caught in 0.2 seconds
94
+
95
+ ![Gallery benchmark](docs/gallery.png)
96
+
97
+ On a zero-edge random walk (`T = 600`), same-bar execution lookahead, `shift(-1)`, centered rolling windows, full-history z-scores, and best-of-250 parameter mining all print high backtest Sharpe ratios and fail their corresponding gates, while a causal moving-average baseline clears with zero false alarms.
98
+
99
+ ### The multiple-testing tax (DSR)
100
+
101
+ ![DSR haircut across trial count](docs/dsr_haircut.png)
102
+
103
+ Over a two-year daily record (`T = 504`), an observed `1.50` Sharpe passes at `N = 1` (`DSR = 0.98`) and drops below gate by `N = 10` (`DSR = 0.71`).
104
+
105
+ ### Combinatorially Symmetric Cross-Validation (PBO)
106
+
107
+ ![CSCV rank logit distribution](docs/pbo_logits.png)
108
+
109
+ Across 256 symmetric splits over 24 candidate variants, pure noise-mining yields `PBO = 42.6%` while a genuine persistent variant lands at `PBO = 0.0%`.
110
+
111
+ ### Cost cliff and live sequential decay
112
+
113
+ ![Cost stress cliff and CUSUM decay](docs/cost_and_decay.png)
114
+
115
+ A high-turnover scalper that looks positive at `1x` modelled fees breaks even at `1.39x` and turns negative well before `2x`. On the right, downward Page CUSUM stays quiet during normal fluctuations and crosses `h = 6.0` shortly after a day-140 regime break (`max S_t = 27.6`).
116
+
117
+ ## Quickstart
118
+
119
+ ```python
120
+ import numpy as np
121
+ import polars as pl
122
+ from auditbacktest import run_audit
123
+
124
+ def causal_signal(df: pl.DataFrame) -> pl.Series:
125
+ return (df["close"] - df["close"].rolling_mean(window_size=20)).fill_null(0.0)
126
+
127
+ report = run_audit(
128
+ net_returns,
129
+ title="mnq-breakout-v1",
130
+ n_trials=24,
131
+ signal_fn=causal_signal,
132
+ market_data=bars,
133
+ cutoff=600,
134
+ positions=positions,
135
+ asset_returns=asset_returns,
136
+ source_code="strategies/breakout.py",
137
+ trial_returns=variant_matrix,
138
+ gross_returns=gross_returns,
139
+ trade_costs=trade_costs,
140
+ reference_returns=event_driven_returns,
141
+ )
142
+
143
+ print(report.to_markdown())
144
+ assert report.passed
145
+ ```
146
+
147
+ ## Command line
148
+
149
+ Audit any daily or per-trade `.csv` or `.parquet` export from TradingView, NinjaTrader, Tradovate, or Python:
150
+
151
+ ```bash
152
+ auditbacktest run returns.csv --ret-col net_ret --cost-col cost --n-trials 30 --html tearsheet.html
153
+ ```
154
+
155
+ Scan a strategy script for static lookahead patterns before running a backtest:
156
+
157
+ ```bash
158
+ auditbacktest scan strategies/my_strategy.py
159
+ ```
160
+
161
+ Pass `--strict` in CI to exit nonzero whenever any check fails or is skipped.
162
+
163
+ ## Related work
164
+
165
+ **[backtest-auditor](https://github.com/123Alissaa/backtest-auditor)** is a Streamlit app built around four deterministic checks (delay, hide-the-future, a single 60/40 holdout split, and DSR) plus an LLM explanation and auto-fix loop running inside remote cloud sandboxes. `auditbacktest` targets local research and CI pipelines instead: it ships as a typed PyPI library with zero network or API calls, runs in milliseconds on Polars/NumPy, enforces Rule 00 (`SKIP` never passes under strict mode), and adds six quantitative gates missing from that tool: CSCV/PBO across 256 symmetric splits, Page CUSUM plus anytime-valid e-process decay monitoring, Inclán–Tiao volatility-break detection, `0x..3x` cost-stress and breakeven calculation, independent reimplementation parity, and seeded-mutant self-verification.
166
+
167
+ - **[clockbars](https://github.com/hontie/clockbars)**: nine activity and flow bar kinds in Polars, verified identical across batch, live, and chunked execution.
168
+ - **[tradesigns](https://github.com/hontie/tradesigns)**: trade classification rules scored against CME aggressor flags on 34.4 million prints.
169
+ - **[prop-mc](https://github.com/hontie/prop-mc)**: Monte Carlo survival, drawdown-breach, and net-EV simulator for futures prop-firm rules.
170
+
171
+ ## License
172
+
173
+ MIT. See [LICENSE](LICENSE).
Binary file
Binary file
@@ -0,0 +1,79 @@
1
+ # Four Ways a Backtest Lies
2
+
3
+ **Ten executable checks, Rule 00, and seeded-mutant verification for trading research**
4
+
5
+ hontie, Modeus Lab
6
+ December 2026
7
+
8
+ ---
9
+
10
+ ## Abstract
11
+
12
+ Most retail and institutional backtest failures are not caused by bad luck after launch. They come from four recurring defects: lookahead leakage in features or execution fills, selection bias across repeated parameter sweeps, execution cost fragility, and unmonitored live regime decay. `auditbacktest` packages ten checks across those four families in pure Polars and NumPy, under one rule (Rule 00): a check that did not run cannot pass. Every check returns `PASS`, `WARN`, `FAIL`, or `SKIP`, and the leakage harness verifies itself on every run by injecting two known lookahead mutants and asserting both are caught.
13
+
14
+ ---
15
+
16
+ ## 1. Rule 00: not checked is not passed
17
+
18
+ A common failure in internal research pipelines is silent omission. A team runs a Sharpe check and a cost table, skips future-bar mutation testing because the feature function is awkward to wire up, and calls the strategy audited. Months later, a centered rolling mean or a forward-filled macro column shows up in production.
19
+
20
+ `auditbacktest` makes omission visible. `run_audit()` emits all ten checks in a fixed order. Whenever an input is omitted (for example, no `trial_returns` matrix for CSCV, or no `signal_fn` for future mutation), that check records `SKIP` with the missing input named in its summary. Under `strict=True`, `report.passed` is `False` until every check has run and cleared its gate.
21
+
22
+ ## 2. Family 1: data leakage
23
+
24
+ Three checks target lookahead from different angles.
25
+
26
+ `future_mutation_test(fn, data, cutoff, atol=1e-12)` treats the feature or strategy function as a black box. It evaluates `fn(data)` once, then builds three copies where rows strictly after `cutoff` are modified (`+25%` scale, `-20%` scale, and a sign-flipped reversed shock `-2.5x - 17`). Including a sign-flipping shock catches even binary `+1/-1` lookahead rules that survive positive rescaling. If any numeric output at index `<= cutoff` moves by more than `atol`, the check fails.
27
+
28
+ `execution_delay_test(positions, asset_returns)` compares same-bar returns `positions * asset_returns` against one-bar delayed returns `shift(positions, +1) * asset_returns`. A strategy that silently trades on bar $t$'s close while claiming bar $t$'s return collapses when delayed by one bar.
29
+
30
+ `static_leakage_scan(source)` parses Python syntax trees with `ast` and flags explicit lookahead calls: negative `.shift(-k)`, `.bfill()` or `.backward_fill()`, `fillna(method="bfill")`, `rolling(..., center=True)`, `join_asof(..., strategy="forward"|"nearest")`, and unsplit `.fit_transform()`. It runs in milliseconds and catches common mistakes before a backtest executes.
31
+
32
+ ![Six random-walk strategies audited offline](gallery.png)
33
+
34
+ ## 3. Family 2: selection bias and multiple testing
35
+
36
+ Running 50 parameter variants on a 5-year daily return series and picking the winner inflates the observed Sharpe ratio even when every variant has zero true edge.
37
+
38
+ `deflated_sharpe_ratio` implements Bailey and López de Prado (2014). Given sample length $T$, per-period Sharpe $\widehat{SR}$, skewness $\hat{\gamma}_3$, Pearson kurtosis $\hat{\gamma}_4$, and $N$ independent trials, the expected maximum Sharpe under the null is approximated with the Euler-Mascheroni constant $\gamma \approx 0.5772$:
39
+
40
+ $$SR^* = \sigma_{SR} \left[(1 - \gamma)\Phi^{-1}\!\left(1 - \frac{1}{N}\right) + \gamma\,\Phi^{-1}\!\left(1 - \frac{1}{N e}\right)\right]$$
41
+
42
+ where $\sigma_{SR} = 1/\sqrt{T}$ by default (or the empirical cross-trial standard deviation when supplied). The Deflated Sharpe Ratio evaluates the Probabilistic Sharpe Ratio against $SR^*$:
43
+
44
+ $$\text{DSR} = \Phi\!\left(\frac{(\widehat{SR} - SR^*)\sqrt{T - 1}}{\sqrt{1 - \hat{\gamma}_3 \widehat{SR} + \frac{\hat{\gamma}_4 - 1}{4}\widehat{SR}^2}}\right)$$
45
+
46
+ The function also reports Minimum Track Record Length (MinTRL), the number of observations required for $\widehat{SR}$ to beat $SR^*$ at the requested confidence level.
47
+
48
+ `cscv_pbo` implements Combinatorially Symmetric Cross-Validation (Bailey, Borwein, López de Prado, and Zhu, 2017). A `(T, M)` matrix of tested variants is split into $S$ equal time blocks (default $S=16$). Across symmetric $S/2$ in-sample and $S/2$ out-of-sample partitions, the check selects the in-sample Sharpe winner, measures its out-of-sample relative rank $\omega_c \in (0, 1)$, and computes the logit $\lambda_c = \ln(\omega_c / (1 - \omega_c))$. The Probability of Backtest Overfitting is the share of splits where $\lambda_c \le 0$.
49
+
50
+ ## 4. Family 3: statistical reliability and self-verification
51
+
52
+ Two checks monitor return stability, and one verifies the auditor itself.
53
+
54
+ `cusum_decay_test` tracks Page's one-sided downward cumulative sum $S_t = \max(0, S_{t-1} + (-z_t - k))$ on returns standardized against expected drift $\mu_0$ (with slack $k = 0.50$), paired with a sequential Gaussian e-process $e_t = \exp\left(\sum_{i=1}^t (-\delta z_i - \delta^2/2)\right)$ at $\delta = 0.5$. Because $e_t$ is a nonnegative supermartingale under $H_0: E[z] \ge 0$, Ville's inequality bounds the anytime-valid false-alarm rate by $P(\sup_t e_t \ge 1/\alpha) \le \alpha$ even under continuous live monitoring.
55
+
56
+ `volatility_break_test` implements the Inclán and Tiao (1994) centered cumulative sum of squares statistic $\sqrt{T/2} \max_k |C_k / C_T - k/T|$ on demeaned squared returns against the 5% asymptotic critical value `1.358`.
57
+
58
+ `audit_self_check` addresses a blind spot in testing harnesses: a buggy leakage test can return `PASS` simply because it failed to mutate the columns the model reads. `audit_self_check` wraps `fn` in two deliberate lookahead mutants (a 1-bar future peek at `cutoff + 1` and an additive full-sample mean) and confirms `future_mutation_test` returns `FAIL` on both.
59
+
60
+ ## 5. Family 4: cost stress and reimplementation parity
61
+
62
+ Backtests routinely assume optimistic fills. `cost_stress_ladder` recomputes Sharpe, Sortino, CAGR, Max Drawdown, Calmar, and Profit Factor across `0x`, `1x`, `1.5x`, `2x`, and `3x` per-period cost drag and solves the exact breakeven cost multiplier $m^* = \bar{r}_{\text{gross}} / \bar{c}$. A strategy that dies at `1.3x` modelled costs has no margin for live slippage.
63
+
64
+ `reimplementation_parity` compares two independent return streams (typically a fast vectorized simulator and an event-driven or live fill log) and requires $\max_t |r_t - r'_t| \le \text{atol}$.
65
+
66
+ ## 6. Limitations
67
+
68
+ - `deflated_sharpe_ratio` assumes i.i.d. trials when `trial_sr_std` is omitted; correlated parameter sweeps have a smaller effective trial count $N_{\text{eff}} < N$, which makes passing raw $N$ conservative.
69
+ - `cscv_pbo` requires the full `(T, M)` matrix of variants tried during research. If discarded experiments were not logged, no post-hoc formula can recover them.
70
+ - `static_leakage_scan` inspects AST call shapes, not arbitrary data flow; always pair it with `future_mutation_test`.
71
+
72
+ ## References
73
+
74
+ - Bailey, D. H., and M. López de Prado. 2012. "The Sharpe Ratio Efficient Frontier." *Journal of Risk* 15 (2): 3–44.
75
+ - Bailey, D. H., and M. López de Prado. 2014. "The Deflated Sharpe Ratio: Correcting for Selection Bias, Backtest Overfitting, and Non-Normality." *Journal of Portfolio Management* 40 (5): 94–107.
76
+ - Bailey, D. H., J. M. Borwein, M. López de Prado, and Q. J. Zhu. 2017. "The Probability of Backtest Overfitting." *Journal of Computational Finance* 20 (4): 39–69.
77
+ - Inclán, C., and G. C. Tiao. 1994. "Use of Cumulative Sums of Squares for Retrospective Detection of Changes of Variance." *Journal of the American Statistical Association* 89 (427): 913–923.
78
+ - Page, E. S. 1954. "Continuous Inspection Schemes." *Biometrika* 41 (1–2): 100–115.
79
+ - Ramdas, A., P. Grünwald, V. Vovk, and G. Shafer. 2023. "Game-Theoretic Statistics and Safe Anytime-Valid Inference." *Statistical Science* 38 (4): 576–601.
Binary file