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/types.py ADDED
@@ -0,0 +1,151 @@
1
+ """Core audit result types and report renderers.
2
+
3
+ Rule 00: not checked is not passed. Every check returns a typed CheckResult
4
+ carrying an explicit PASS, WARN, FAIL, or SKIP status.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import html
10
+ import json
11
+ from dataclasses import dataclass, field
12
+ from typing import Any, Literal
13
+
14
+ Status = Literal["PASS", "WARN", "FAIL", "SKIP"]
15
+
16
+ _STATUS_COLOR: dict[Status, str] = {
17
+ "PASS": "#2ec4b6",
18
+ "WARN": "#f4a261",
19
+ "FAIL": "#e63946",
20
+ "SKIP": "#8d99ae",
21
+ }
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class CheckResult:
26
+ """Outcome of a single audit check."""
27
+
28
+ name: str
29
+ family: str
30
+ status: Status
31
+ summary: str
32
+ metric: float | None = None
33
+ threshold: float | None = None
34
+ details: dict[str, Any] = field(default_factory=dict)
35
+
36
+ def to_dict(self) -> dict[str, Any]:
37
+ return {
38
+ "name": self.name,
39
+ "family": self.family,
40
+ "status": self.status,
41
+ "metric": self.metric,
42
+ "threshold": self.threshold,
43
+ "summary": self.summary,
44
+ "details": self.details,
45
+ }
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class AuditReport:
50
+ """Collection of CheckResults with Rule 00 pass/fail aggregation."""
51
+
52
+ results: tuple[CheckResult, ...]
53
+ title: str = "auditbacktest"
54
+ strict: bool = True
55
+
56
+ @property
57
+ def passed(self) -> bool:
58
+ """True only when zero checks failed, and zero skipped under strict mode."""
59
+ if not self.results:
60
+ return False
61
+ for item in self.results:
62
+ if item.status == "FAIL":
63
+ return False
64
+ if self.strict and item.status == "SKIP":
65
+ return False
66
+ return True
67
+
68
+ def counts(self) -> dict[Status, int]:
69
+ out: dict[Status, int] = {"PASS": 0, "WARN": 0, "FAIL": 0, "SKIP": 0}
70
+ for item in self.results:
71
+ out[item.status] += 1
72
+ return out
73
+
74
+ def to_dict(self) -> dict[str, Any]:
75
+ return {
76
+ "title": self.title,
77
+ "strict": self.strict,
78
+ "passed": self.passed,
79
+ "counts": self.counts(),
80
+ "checks": [item.to_dict() for item in self.results],
81
+ }
82
+
83
+ def to_json(self, *, indent: int = 2) -> str:
84
+ return json.dumps(self.to_dict(), indent=indent)
85
+
86
+ def to_markdown(self) -> str:
87
+ verdict = "PASS" if self.passed else "FAIL"
88
+ counts = self.counts()
89
+ lines = [
90
+ f"# {self.title} — {verdict}",
91
+ "",
92
+ (
93
+ f"PASS: {counts['PASS']} | WARN: {counts['WARN']} | "
94
+ f"FAIL: {counts['FAIL']} | SKIP: {counts['SKIP']}"
95
+ ),
96
+ "",
97
+ "| family | check | status | metric | summary |",
98
+ "| :--- | :--- | :--- | ---: | :--- |",
99
+ ]
100
+ for item in self.results:
101
+ m = "n/a" if item.metric is None else f"{item.metric:.4g}"
102
+ lines.append(
103
+ f"| {item.family} | {item.name} | **{item.status}** | {m} | {item.summary} |"
104
+ )
105
+ return "\n".join(lines)
106
+
107
+ def to_html(self) -> str:
108
+ verdict = "PASS" if self.passed else "FAIL"
109
+ v_color = _STATUS_COLOR["PASS"] if self.passed else _STATUS_COLOR["FAIL"]
110
+ counts = self.counts()
111
+ rows: list[str] = []
112
+ for item in self.results:
113
+ color = _STATUS_COLOR[item.status]
114
+ m = "n/a" if item.metric is None else f"{item.metric:.4g}"
115
+ rows.append(
116
+ "<tr>"
117
+ f"<td>{html.escape(item.family)}</td>"
118
+ f"<td><code>{html.escape(item.name)}</code></td>"
119
+ f"<td style='color:{color};font-weight:700'>{item.status}</td>"
120
+ f"<td style='text-align:right;font-variant-numeric:tabular-nums'>{m}</td>"
121
+ f"<td>{html.escape(item.summary)}</td>"
122
+ "</tr>"
123
+ )
124
+ body_rows = "\n".join(rows)
125
+ title_esc = html.escape(self.title)
126
+ return (
127
+ "<!doctype html>\n<html lang='en'><head><meta charset='utf-8'>"
128
+ f"<title>{title_esc}</title>"
129
+ "<style>"
130
+ "body{background:#0d0b0c;color:#efe6e4;font-family:ui-sans-serif,system-ui,sans-serif;"
131
+ "margin:0;padding:32px;line-height:1.5}"
132
+ ".wrap{max-width:980px;margin:0 auto}"
133
+ "h1{margin:0 0 8px 0;font-size:24px}"
134
+ ".badge{display:inline-block;padding:3px 10px;border-radius:4px;"
135
+ f"background:{v_color};color:#0d0b0c;font-weight:700;font-size:13px}}"
136
+ ".meta{color:#b8b3b1;margin:8px 0 24px 0;font-size:14px}"
137
+ "table{width:100%;border-collapse:collapse;background:#161113;"
138
+ "border:1px solid #2a2224}"
139
+ "th,td{padding:10px 12px;border-bottom:1px solid #2a2224;text-align:left;"
140
+ "font-size:14px}"
141
+ "th{color:#b8b3b1;font-weight:600;background:#1a0e10}"
142
+ "code{font-family:ui-monospace,Consolas,monospace;font-size:13px}"
143
+ "</style></head><body><div class='wrap'>"
144
+ f"<h1>{title_esc} <span class='badge'>{verdict}</span></h1>"
145
+ f"<div class='meta'>PASS {counts['PASS']} · WARN {counts['WARN']} · "
146
+ f"FAIL {counts['FAIL']} · SKIP {counts['SKIP']} · "
147
+ f"Rule 00 strict={'on' if self.strict else 'off'}</div>"
148
+ "<table><thead><tr><th>Family</th><th>Check</th><th>Status</th>"
149
+ "<th style='text-align:right'>Metric</th><th>Summary</th></tr></thead>"
150
+ f"<tbody>{body_rows}</tbody></table></div></body></html>"
151
+ )
@@ -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,14 @@
1
+ auditbacktest/__init__.py,sha256=pcNbp6LXDPzgnk9HgCvuq3zy1TxeoxeARgm8SjVHMQU,1080
2
+ auditbacktest/cli.py,sha256=5RUCmIyoyd2ASzWKZ-MxD74JjC1aXXtafbOl_ayxkfc,4287
3
+ auditbacktest/costs.py,sha256=y6Z4daP-eebf6ZMDQCfYWfDrRcE0FNTJooWIatpkxlo,5119
4
+ auditbacktest/leakage.py,sha256=uyjkGmZ6to4InIBVjaoz3LFU0AUy2jOth6Py4YsbohI,11208
5
+ auditbacktest/overfitting.py,sha256=gS79ijjZiTZuzzGkVdCEepDgD2BliTHurV_w81MKtJE,10088
6
+ auditbacktest/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ auditbacktest/reliability.py,sha256=PMDo424UPAYpTB7LxBqJa7_cREJJDEt0v2yR41aKD9I,6748
8
+ auditbacktest/suite.py,sha256=LMbFRBPBQhAYJHW57IlR_AwGrSAO6yBapgzWAxuOfkU,4242
9
+ auditbacktest/types.py,sha256=cwxJEfV_ybiDIuh4x8eGB_gB4PofoIrcM7gGauikErs,5566
10
+ auditbacktest-1.0.0.dist-info/METADATA,sha256=o5cOX4XhUethfhTE3DA-TA3Ps6WjSJ4R15aWFkFwMBU,10075
11
+ auditbacktest-1.0.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
12
+ auditbacktest-1.0.0.dist-info/entry_points.txt,sha256=jAdVVry3KS7o-xgkEy9kQyJ2QLMYirj0mfQmUmtkvq4,57
13
+ auditbacktest-1.0.0.dist-info/licenses/LICENSE,sha256=JvW7nF4FYzL2wYCfKcCfXp6XdBsWTxGLeD0FKEwyqS0,1063
14
+ auditbacktest-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
+ auditbacktest = auditbacktest.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.