batter 0.4.2__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.
Files changed (45) hide show
  1. batter-0.4.2.dist-info/METADATA +73 -0
  2. batter-0.4.2.dist-info/RECORD +45 -0
  3. batter-0.4.2.dist-info/WHEEL +4 -0
  4. batter-0.4.2.dist-info/entry_points.txt +2 -0
  5. batter-0.4.2.dist-info/licenses/LICENSE +190 -0
  6. pancake_engine/__init__.py +71 -0
  7. pancake_engine/__version__.py +28 -0
  8. pancake_engine/canonical.py +213 -0
  9. pancake_engine/cli.py +203 -0
  10. pancake_engine/compile/__init__.py +6 -0
  11. pancake_engine/compile/condition.py +122 -0
  12. pancake_engine/compile/spec.py +84 -0
  13. pancake_engine/config.py +105 -0
  14. pancake_engine/hash.py +19 -0
  15. pancake_engine/io/__init__.py +5 -0
  16. pancake_engine/io/dump.py +39 -0
  17. pancake_engine/io/load.py +60 -0
  18. pancake_engine/metrics/__init__.py +24 -0
  19. pancake_engine/metrics/bootstrap.py +198 -0
  20. pancake_engine/metrics/credibility.py +168 -0
  21. pancake_engine/metrics/permutation.py +151 -0
  22. pancake_engine/metrics/pm.py +135 -0
  23. pancake_engine/metrics/series.py +129 -0
  24. pancake_engine/metrics/standard.py +267 -0
  25. pancake_engine/result.py +188 -0
  26. pancake_engine/runner/__init__.py +5 -0
  27. pancake_engine/runner/engine.py +512 -0
  28. pancake_engine/runner/events.py +32 -0
  29. pancake_engine/runner/ledger.py +83 -0
  30. pancake_engine/runner/observation.py +63 -0
  31. pancake_engine/runner/position.py +37 -0
  32. pancake_engine/runner/sizing.py +46 -0
  33. pancake_engine/runner/trade.py +33 -0
  34. pancake_engine/types.py +167 -0
  35. pancake_engine/validate/__init__.py +17 -0
  36. pancake_engine/validate/dataset.py +197 -0
  37. pancake_engine/validate/spec.py +48 -0
  38. pancake_engine/validate/verdict.py +63 -0
  39. pancake_engine/walkforward/__init__.py +32 -0
  40. pancake_engine/walkforward/aggregate.py +186 -0
  41. pancake_engine/walkforward/result.py +208 -0
  42. pancake_engine/walkforward/runner.py +385 -0
  43. pancake_engine/walkforward/schedule.py +119 -0
  44. pancake_engine/walkforward/window.py +113 -0
  45. pancake_engine/warnings.py +105 -0
@@ -0,0 +1,73 @@
1
+ Metadata-Version: 2.4
2
+ Name: batter
3
+ Version: 0.4.2
4
+ Summary: Deterministic Python research engine for prediction-market evidence-backed backtests
5
+ Project-URL: Repository, https://github.com/usepancake/batter
6
+ Project-URL: Homepage, https://usepancake.com
7
+ Author-email: Michael Mustopo <michael.mustopo@gmail.com>
8
+ License: Apache-2.0
9
+ License-File: LICENSE
10
+ Keywords: backtest,batter,deterministic,evidence,pancake,prediction-market
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Topic :: Office/Business :: Financial :: Investment
17
+ Requires-Python: >=3.12
18
+ Requires-Dist: numpy>=1.26
19
+ Requires-Dist: pydantic<3,>=2.5
20
+ Requires-Dist: scipy>=1.17.1
21
+ Provides-Extra: dev
22
+ Requires-Dist: ipykernel>=6.29; extra == 'dev'
23
+ Requires-Dist: mypy; extra == 'dev'
24
+ Requires-Dist: nbclient>=0.10; extra == 'dev'
25
+ Requires-Dist: nbformat>=5.10; extra == 'dev'
26
+ Requires-Dist: pytest-cov; extra == 'dev'
27
+ Requires-Dist: pytest>=8; extra == 'dev'
28
+ Requires-Dist: ruff; extra == 'dev'
29
+ Description-Content-Type: text/markdown
30
+
31
+ # batter
32
+
33
+ [![Test](https://github.com/usepancake/batter/actions/workflows/test.yml/badge.svg)](https://github.com/usepancake/batter/actions/workflows/test.yml)
34
+
35
+ `batter` is a deterministic Python research engine for prediction-market evidence-backed backtests. Given a backtest spec and an `EvidenceDataset`, it produces a canonical `result_hash` — identical bytes across ubuntu / macos / windows on Python 3.12+ — enabling reproducible research and auditability of strategy claims. Engine 0.4 adds Monte Carlo bootstrap confidence intervals and a sign-permutation Sharpe test so credibility signals travel with every result.
36
+
37
+ The PyPI package is `batter`; the Python module is `pancake_engine` (sklearn-style rename: `pip install batter` then `import pancake_engine`).
38
+
39
+ ## Install
40
+
41
+ ```bash
42
+ pip install batter
43
+ ```
44
+
45
+ ## Quickstart
46
+
47
+ ```python
48
+ import json
49
+ from pancake_engine import run_backtest, BacktestSpec, EvidenceDataset, BacktestConfig
50
+
51
+ spec = BacktestSpec(**json.load(open("spec.json")))
52
+ dataset = EvidenceDataset(**json.load(open("dataset.json")))
53
+ config = BacktestConfig()
54
+
55
+ result = run_backtest(spec, dataset, config)
56
+ print(result.result_hash) # deterministic SHA-256 over canonical JSON
57
+ print(result.metrics.sharpe)
58
+ print(result.bootstrap_ci) # 95% CI on cagr / sharpe / sortino (0.4+)
59
+ ```
60
+
61
+ ## Determinism
62
+
63
+ The same `(spec, dataset, config)` produces the same `result_hash` across ubuntu / macos / windows on Python 3.12+. Verification method, fixture set, and numeric bounds are documented in [docs/math-audit-0.4.md §"Verification verdict"](docs/math-audit-0.4.md#verification-verdict).
64
+
65
+ **Supported Python versions: 3.12 and 3.13.** Python 3.11 is permanently out of scope — `sum()` semantics changed in 3.12 (compensated float accumulation), causing the bootstrap CI values to differ by 1 ULP and producing a different `result_hash`. No code change can reconcile this without reverse-engineering 3.12's exact internal accumulation path. See [docs/py311-investigation-2026-05-27.md](docs/py311-investigation-2026-05-27.md) for the full root-cause analysis and [docs/math-audit-0.4.md §"Known scope qualifier — Python 3.11"](docs/math-audit-0.4.md#known-scope-qualifier--python-311) for the audit entry.
66
+
67
+ ## Cross-platform
68
+
69
+ CI enforces a 6-cell matrix (ubuntu-latest + macos-latest + windows-latest) × (Python 3.12 + 3.13). See the badge above.
70
+
71
+ ## License
72
+
73
+ Apache-2.0 — Copyright 2026 Michael Mustopo
@@ -0,0 +1,45 @@
1
+ pancake_engine/__init__.py,sha256=8wJ5fL3TQOG5obTmi11wPlnzG9TzXPdPwqcyJkGN29c,1847
2
+ pancake_engine/__version__.py,sha256=UBWgFRDOBY_ms-ZKfvLQEQqoYYWc-hZccvbLQj-Xb_A,1166
3
+ pancake_engine/canonical.py,sha256=P1cp36YiffDqxkv05mWhXUIzbAyb50zlBMdHRHJlKqg,7655
4
+ pancake_engine/cli.py,sha256=K1xs5LXxf3PIDOGFqG_arttWcP2WHz0PlnPzDchfQFE,8439
5
+ pancake_engine/config.py,sha256=9sZYrhFZZslLeJ8Od3VvgNtNz1vfuxMP4zD_2B1nP4g,4103
6
+ pancake_engine/hash.py,sha256=YbPxfmb2nx9SlVDiQ1JiiZg1UBthP8u94Z9M25m6dpo,547
7
+ pancake_engine/result.py,sha256=sWOjXBloEavSFVBXidPyhGQv9zQ3Kja8oJzOXpdT0dI,5791
8
+ pancake_engine/types.py,sha256=iFQYfPB7Q5y9gXqy1bmLU0x7-TDnFIFp2EaS12MZSnA,4756
9
+ pancake_engine/warnings.py,sha256=OEVxdjMg5Wehhj9jxqBdX6U3qz7zDYkBO-2ecbS7Kdc,4229
10
+ pancake_engine/compile/__init__.py,sha256=6NPTRt1STfcddVsR54oHjVSdMW0JMcxRYCXbt4ebcTU,226
11
+ pancake_engine/compile/condition.py,sha256=yWt8-IKbUfTj0u5kFht9rg2WWF4PW8smf53rXCVZraE,4293
12
+ pancake_engine/compile/spec.py,sha256=F59ZVjGwxJUSg3h_fJvWb6R4SGGwryuX73T5E4aXcuY,2701
13
+ pancake_engine/io/__init__.py,sha256=4WuKeA7zTNuDCdmfNMpQkLfKf2iEEAw01DXzGyOyKms,151
14
+ pancake_engine/io/dump.py,sha256=6VoqARlLM8bxb129G2pJm3UnZHj-dyEkp6Euww4wEQU,1249
15
+ pancake_engine/io/load.py,sha256=0zK-ytn2QKehjMK_2fL9hSa8LCG_wy39mdDU7k9fgIU,1999
16
+ pancake_engine/metrics/__init__.py,sha256=6Hd7zlbNlUzkOvXhuCfkDOoxOn4jV3ZvCqjSPR6LPZU,833
17
+ pancake_engine/metrics/bootstrap.py,sha256=axsyFjsRIgDSCKx-_WhmL_NoxYmtXZNkjAB9b_qoGqo,8161
18
+ pancake_engine/metrics/credibility.py,sha256=uh_qn9RMk6E2_KQsYON3i7sXPt_YVhLe9oXbMTwh0Uc,6796
19
+ pancake_engine/metrics/permutation.py,sha256=DLYTRfkNcPT9-sPbi17zHr3FH6R8sAtUXsdfjdp3O6I,5946
20
+ pancake_engine/metrics/pm.py,sha256=aNxpSB2qILBZtMvpJzId-p0_zJcgKmIQHXxIz9VwR-4,4215
21
+ pancake_engine/metrics/series.py,sha256=yqijeY4qWqcICtuy6EsTHmgY2gxZaMcbRF8Uw8ytl84,4909
22
+ pancake_engine/metrics/standard.py,sha256=S8WNqZhY18CAUA4lHFdWnmDsj6wpq_IlQQk3PudTaLQ,9402
23
+ pancake_engine/runner/__init__.py,sha256=o5aKIOfVz26a7_lI0x_LPhZifXUw5do4j1IoQT21iW0,117
24
+ pancake_engine/runner/engine.py,sha256=5NnumlzBC62QR277D8slA0s88tnFI0f1sFJdx0UI7_A,19002
25
+ pancake_engine/runner/events.py,sha256=yiD3b5InUBuC4tcd9ZwQrk4GP_6i5Dvm5rWvssouaOE,837
26
+ pancake_engine/runner/ledger.py,sha256=gWFwcUZU_PzML9dfcdkwY3pMI8WFNGNrDBIy0alfHEo,2807
27
+ pancake_engine/runner/observation.py,sha256=KgJNaHPO95Wn7faKE8A3-nbyHLPpGR055RtcwvD7to8,2006
28
+ pancake_engine/runner/position.py,sha256=mG2NqwWIiI19v4nHwT0R9j5eZs-tsqJ1Mmhi7LlFEcs,857
29
+ pancake_engine/runner/sizing.py,sha256=g80ifGsJlgjGEmkrq5m8z2cFmKburEuLpRHmNEtfYLY,1310
30
+ pancake_engine/runner/trade.py,sha256=3yBx-Z44J02Wjkcr62NfYSuSQo3GpaQC6VTgbB08de8,955
31
+ pancake_engine/validate/__init__.py,sha256=DLNmCrdEoNgTkRhWJErTiQsXYdQRxzmwq2BkcOm3btk,447
32
+ pancake_engine/validate/dataset.py,sha256=UepaudnpAPfsQqaVuHLsnICkCyR91gByrlhkAp-W64M,7581
33
+ pancake_engine/validate/spec.py,sha256=1vAjaXwAcRRp5jT99BiOMld5oGKCgg7Prr7uwCVsPdI,1656
34
+ pancake_engine/validate/verdict.py,sha256=ZgetjXnqJ2l1cD8V9Z_NczPg2EP2vaDWxBFLdyURw-Q,1954
35
+ pancake_engine/walkforward/__init__.py,sha256=o1IaCmrxlK3W30yBYwGMZx3Am030RD9CsAyPrzHcqOU,782
36
+ pancake_engine/walkforward/aggregate.py,sha256=l8ufOaGM12HQ6b8yGmaeraCMNo5wCvHS_HAHgs7gvFA,7428
37
+ pancake_engine/walkforward/result.py,sha256=u1D8tiLtYts4SHGKCdQ8nteyBTBhySv_Cg4x_Fddhxc,6521
38
+ pancake_engine/walkforward/runner.py,sha256=UId2p8e01p5jyRcBEUBeEmUAuQ9PhpMAgcpOO-JWF7w,15334
39
+ pancake_engine/walkforward/schedule.py,sha256=MCrDwvAEfss6-xayobY1Fecj7_dVjAVBlYSfLMPTo2c,4382
40
+ pancake_engine/walkforward/window.py,sha256=65ZOwqXtPCL85AJT_Efn0yGCafWXNEXg2ArC8SRcYdQ,3723
41
+ batter-0.4.2.dist-info/METADATA,sha256=fYRHE7MpLLj1xWgNkhFcp8e9UM537y5XAFeNXAnklp8,3647
42
+ batter-0.4.2.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
43
+ batter-0.4.2.dist-info/entry_points.txt,sha256=D3N8rYaXvyRFbN4vwoUiAy_hZzezxljV9qjhrAeKg8g,51
44
+ batter-0.4.2.dist-info/licenses/LICENSE,sha256=_WuiGaixQIvKktGbcW1N-VmdDJyL3_fB9CevQ29AjY4,10702
45
+ batter-0.4.2.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ batter = pancake_engine.cli:main
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Support. While redistributing the Work or
166
+ Derivative Works thereof, You may choose to offer, and charge a
167
+ fee for, acceptance of support, warranty, indemnity, or other
168
+ liability obligations and/or rights consistent with this License.
169
+ However, in accepting such obligations, You may act only on Your
170
+ own behalf and on Your sole responsibility, not on behalf of any
171
+ other Contributor, and only if You agree to indemnify, defend, and
172
+ hold each Contributor harmless for any liability incurred by, or
173
+ claims asserted against, such Contributor by reason of your accepting
174
+ any such warranty or support.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2026 Michael Mustopo
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
@@ -0,0 +1,71 @@
1
+ """Pancake Engine 0.3 — deterministic Python research engine over EvidenceDataset.
2
+
3
+ Engine 0.3 is correctness-first, not TS parity. Known TS divergences are documented
4
+ in pancake-production/docs/research/pancake-engine-0.3-ts-divergences.md.
5
+
6
+ PR-0 shipped the canonicalization substrate.
7
+ PR-1 ships the event-time ledger runner, validation, metrics, warnings, and CLI.
8
+ """
9
+
10
+ from .__version__ import ENGINE, ENGINE_MODE, ENGINE_VERSION, __version__
11
+ from .canonical import canonical_string, canonicalize
12
+ from .config import BacktestConfig, WalkforwardConfig
13
+ from .hash import sha256_canonical
14
+ from .io.dump import dump_result, result_to_canonical_json
15
+ from .io.load import load_dataset, load_json, load_spec
16
+ from .result import (
17
+ BacktestResult,
18
+ DrawdownPoint,
19
+ EquityPoint,
20
+ Metrics,
21
+ MetricsPM,
22
+ MetricsStandard,
23
+ MonthlyReturn,
24
+ )
25
+ from .runner import run_backtest
26
+ from .walkforward import (
27
+ AggregateMetrics,
28
+ Fold,
29
+ FoldDefinition,
30
+ WalkforwardResult,
31
+ run_walkforward,
32
+ )
33
+ from .types import EvidenceDataset, EvidenceSpec
34
+ from .validate import ValidationVerdict
35
+ from .warnings import Severity, Warning, WarningCode
36
+
37
+ __all__ = [
38
+ "ENGINE",
39
+ "ENGINE_MODE",
40
+ "ENGINE_VERSION",
41
+ "__version__",
42
+ "canonical_string",
43
+ "canonicalize",
44
+ "sha256_canonical",
45
+ "load_dataset",
46
+ "load_json",
47
+ "load_spec",
48
+ "dump_result",
49
+ "result_to_canonical_json",
50
+ "EvidenceDataset",
51
+ "EvidenceSpec",
52
+ "BacktestConfig",
53
+ "BacktestResult",
54
+ "Metrics",
55
+ "MetricsStandard",
56
+ "MetricsPM",
57
+ "EquityPoint",
58
+ "DrawdownPoint",
59
+ "MonthlyReturn",
60
+ "Severity",
61
+ "Warning",
62
+ "WarningCode",
63
+ "ValidationVerdict",
64
+ "run_backtest",
65
+ "WalkforwardConfig",
66
+ "WalkforwardResult",
67
+ "Fold",
68
+ "FoldDefinition",
69
+ "AggregateMetrics",
70
+ "run_walkforward",
71
+ ]
@@ -0,0 +1,28 @@
1
+ """Version + engine identity constants for Pancake Engine 0.4.
2
+
3
+ These constants are written into every result emitted by the runner (PR-1+).
4
+ They are also part of `result_hash` — bumping any of them is a deliberate
5
+ breaking change to the receipt contract.
6
+
7
+ 0.4.0 adds:
8
+ - MC bootstrap CI for cagr / sharpe / sortino (percentile method, PCG64 RNG)
9
+ - Sign-permutation test for Sharpe null (Good 2005)
10
+ - numpy>=1.26 as hard dependency
11
+ - New warning codes: BOOTSTRAP_INSUFFICIENT, CI_TOO_WIDE, PERMUTATION_P_HIGH
12
+
13
+ 0.4.1 (docs+config patch):
14
+ - Permanently scope-qualifies Python 3.11 after root-cause investigation
15
+ (sum() float accumulation changed in 3.12; 1-ULP CI drift; unfixable).
16
+ - See docs/py311-investigation-2026-05-27.md for full analysis.
17
+ - No math changes; result_hash unchanged for Python 3.12+ users.
18
+
19
+ 0.4.2 (first PyPI release):
20
+ - First release published to PyPI via Trusted Publishing (OIDC).
21
+ - Engine code byte-identical to 0.4.1; result_hash unchanged.
22
+ - Install: `pip install batter` (previously git-only via release tarball).
23
+ """
24
+
25
+ __version__ = "0.4.2"
26
+ ENGINE = "batter"
27
+ ENGINE_VERSION = "0.4.0"
28
+ ENGINE_MODE = "event_time_v1"
@@ -0,0 +1,213 @@
1
+ """Canonical serialization for Pancake Engine 0.3.
2
+
3
+ Engine 0.3 is correctness-first, not TS parity. Known TS divergences are
4
+ documented in pancake-production/docs/research/pancake-engine-0.3-ts-divergences.md.
5
+
6
+ This module implements byte-identical canonical serialization compatible with
7
+ ECMA-262 §6.1.6.1.13 NumberToString and V8's ``JSON.stringify`` number output.
8
+
9
+ The canonical bytes are the substrate for every hash in Engine 0.3:
10
+ ``schema_sha256``, ``rows_sha256``, ``compiled_spec_hash``, ``config_hash``,
11
+ ``result_hash``. Cross-runtime byte-equality is the determinism gate.
12
+
13
+ Rules:
14
+
15
+ - ``null``, ``true``, ``false`` — literal.
16
+ - ``int`` — decimal repr; reject ``|x| > 2**53`` (silent precision loss on JS round-trip).
17
+ - ``float`` — ECMA-262 NumberToString. Reject NaN, +Inf, -Inf. Normalize -0 to 0.
18
+ - ``str`` — NFC-normalize then JSON-escape per RFC 8259. Reject lone surrogates.
19
+ - ``list`` / ``tuple`` — order preserved; never sorted.
20
+ - ``dict`` — keys sorted by Unicode codepoint, recursively. Duplicate-key
21
+ rejection happens **at JSON parse time** in :mod:`pancake_engine.io.load`,
22
+ not here — raw Python dicts cannot detect duplicates after parse.
23
+ - ``datetime`` and other types — rejected. Callers serialize times to unix-int seconds first.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import math
29
+ import unicodedata
30
+ from typing import Any
31
+
32
+ __all__ = ["canonicalize", "canonical_string", "MAX_SAFE_INTEGER"]
33
+
34
+ # JavaScript Number.MAX_SAFE_INTEGER = 2**53 - 1; we allow up to 2**53 inclusive
35
+ # because 2**53 is exactly representable as a float. Anything strictly larger
36
+ # loses precision on the V8 side.
37
+ MAX_SAFE_INTEGER = 2**53
38
+
39
+
40
+ def canonicalize(obj: Any) -> bytes:
41
+ """Return the canonical UTF-8 byte representation of ``obj``."""
42
+ return canonical_string(obj).encode("utf-8")
43
+
44
+
45
+ def canonical_string(obj: Any) -> str:
46
+ """Return the canonical string representation (UTF-8 encoding deferred to caller)."""
47
+ return _canon(obj)
48
+
49
+
50
+ def _canon(obj: Any) -> str:
51
+ # bool is a subclass of int in Python; match it before int.
52
+ if obj is None:
53
+ return "null"
54
+ if obj is True:
55
+ return "true"
56
+ if obj is False:
57
+ return "false"
58
+ if isinstance(obj, bool):
59
+ # Defensive — `obj is True/False` above already covers all bool instances,
60
+ # but a custom subclass of bool would slip through without this branch.
61
+ return "true" if obj else "false"
62
+ if isinstance(obj, int):
63
+ if abs(obj) > MAX_SAFE_INTEGER:
64
+ raise ValueError(
65
+ f"E_INTEGER_TOO_LARGE: {obj} exceeds 2**53; "
66
+ "use a string for large integers to avoid silent precision loss on JS round-trip"
67
+ )
68
+ return str(obj)
69
+ if isinstance(obj, float):
70
+ return _number_to_string(obj)
71
+ if isinstance(obj, str):
72
+ return _escape_string(obj)
73
+ if isinstance(obj, (list, tuple)):
74
+ return "[" + ",".join(_canon(x) for x in obj) + "]"
75
+ if isinstance(obj, dict):
76
+ # Sort keys by Unicode codepoint order. Python's default `<` on str
77
+ # is codepoint-ordered.
78
+ keys = sorted(obj.keys())
79
+ parts = []
80
+ for k in keys:
81
+ if not isinstance(k, str):
82
+ raise ValueError(f"E_NON_STRING_KEY: {k!r}")
83
+ parts.append(_escape_string(k) + ":" + _canon(obj[k]))
84
+ return "{" + ",".join(parts) + "}"
85
+ raise ValueError(f"E_UNSUPPORTED_TYPE: {type(obj).__name__}")
86
+
87
+
88
+ def _number_to_string(x: float) -> str:
89
+ """ECMA-262 §6.1.6.1.13 NumberToString for finite floats.
90
+
91
+ Matches V8 ``JSON.stringify(<number>)`` byte-for-byte on finite values.
92
+ Rejects NaN and ±Infinity. Normalizes -0 to 0.
93
+
94
+ The shortest round-trip digit sequence is sourced from CPython's
95
+ ``repr(float)``, which uses Grisu/Ryu — same algorithm V8 uses. CPython
96
+ and V8 differ only in exponential-notation thresholds; this function
97
+ re-applies the ECMA thresholds.
98
+ """
99
+ if math.isnan(x):
100
+ raise ValueError("E_NONFINITE: NaN is not representable in canonical form")
101
+ if math.isinf(x):
102
+ raise ValueError("E_NONFINITE: Infinity is not representable in canonical form")
103
+ if x == 0:
104
+ # -0.0 == 0.0 in Python; both normalize to "0", matching V8.
105
+ return "0"
106
+
107
+ negative = x < 0
108
+ if negative:
109
+ x = -x
110
+
111
+ r = repr(x)
112
+
113
+ # Split into mantissa and explicit exponent
114
+ if "e" in r:
115
+ mantissa_str, exp_str = r.split("e")
116
+ exp = int(exp_str)
117
+ else:
118
+ mantissa_str = r
119
+ exp = 0
120
+
121
+ # Split mantissa into integer and fractional parts
122
+ if "." in mantissa_str:
123
+ int_part, frac_part = mantissa_str.split(".")
124
+ if frac_part == "0":
125
+ frac_part = ""
126
+ else:
127
+ int_part = mantissa_str
128
+ frac_part = ""
129
+
130
+ # Combine digits; adjust exp for the decimal point position
131
+ all_digits = int_part + frac_part
132
+ exp -= len(frac_part)
133
+
134
+ # Strip leading zeros (e.g., 0.001 → int_part="0", frac="001", all="0001")
135
+ stripped = all_digits.lstrip("0")
136
+ if stripped == "":
137
+ # Unreachable under x != 0; defensive.
138
+ return "0"
139
+ all_digits = stripped
140
+
141
+ # Strip trailing zeros, rolling them into the exponent
142
+ rstripped = all_digits.rstrip("0")
143
+ if rstripped == "":
144
+ rstripped = "0"
145
+ exp += len(all_digits) - len(rstripped)
146
+ all_digits = rstripped
147
+
148
+ # The canonical digit string has no leading/trailing zeros (except "0" itself).
149
+ # Numeric value = int(all_digits) × 10**exp.
150
+ # k = number of significant digits
151
+ # n = decimal point position from the left, where n == k means integer ending,
152
+ # n > k means trailing zeros, n < k means digits after decimal point.
153
+ k = len(all_digits)
154
+ n = k + exp
155
+
156
+ if k <= n <= 21:
157
+ # Integer in regular notation: digits then trailing zeros
158
+ result = all_digits + "0" * (n - k)
159
+ elif 0 < n <= 21:
160
+ # Fractional in regular notation: split digits at position n
161
+ result = all_digits[:n] + "." + all_digits[n:]
162
+ elif -6 < n <= 0:
163
+ # Small number: 0. then leading zeros then digits
164
+ result = "0." + "0" * (-n) + all_digits
165
+ elif k == 1:
166
+ # Single-digit scientific
167
+ e = n - 1
168
+ sign = "+" if e >= 0 else "-"
169
+ result = all_digits + "e" + sign + str(abs(e))
170
+ else:
171
+ # Multi-digit scientific
172
+ e = n - 1
173
+ sign = "+" if e >= 0 else "-"
174
+ result = all_digits[0] + "." + all_digits[1:] + "e" + sign + str(abs(e))
175
+
176
+ return ("-" if negative else "") + result
177
+
178
+
179
+ def _escape_string(s: str) -> str:
180
+ """JSON-escape a string with NFC normalization and lone-surrogate rejection."""
181
+ s = unicodedata.normalize("NFC", s)
182
+
183
+ # Reject lone surrogates by attempting UTF-8 encode. Python strings can
184
+ # contain unpaired surrogates if produced from certain decode operations;
185
+ # we refuse to canonicalize them rather than emit garbled UTF-8.
186
+ try:
187
+ s.encode("utf-8")
188
+ except UnicodeEncodeError as e:
189
+ raise ValueError(f"E_LONE_SURROGATE: {e}") from e
190
+
191
+ out: list[str] = ['"']
192
+ for ch in s:
193
+ code = ord(ch)
194
+ if ch == '"':
195
+ out.append('\\"')
196
+ elif ch == "\\":
197
+ out.append("\\\\")
198
+ elif ch == "\b":
199
+ out.append("\\b")
200
+ elif ch == "\f":
201
+ out.append("\\f")
202
+ elif ch == "\n":
203
+ out.append("\\n")
204
+ elif ch == "\r":
205
+ out.append("\\r")
206
+ elif ch == "\t":
207
+ out.append("\\t")
208
+ elif code < 0x20:
209
+ out.append(f"\\u{code:04x}")
210
+ else:
211
+ out.append(ch)
212
+ out.append('"')
213
+ return "".join(out)