oss-backtest-kit 0.1.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 (30) hide show
  1. oss_backtest_kit-0.1.0/CHANGELOG.md +12 -0
  2. oss_backtest_kit-0.1.0/LICENSE +21 -0
  3. oss_backtest_kit-0.1.0/MANIFEST.in +4 -0
  4. oss_backtest_kit-0.1.0/PKG-INFO +209 -0
  5. oss_backtest_kit-0.1.0/README.md +170 -0
  6. oss_backtest_kit-0.1.0/docs/social_preview.png +0 -0
  7. oss_backtest_kit-0.1.0/examples/equity_psr_dsr.png +0 -0
  8. oss_backtest_kit-0.1.0/examples/equity_psr_dsr.py +130 -0
  9. oss_backtest_kit-0.1.0/examples/ma_crossover.py +63 -0
  10. oss_backtest_kit-0.1.0/examples/quickstart.ipynb +167 -0
  11. oss_backtest_kit-0.1.0/pyproject.toml +49 -0
  12. oss_backtest_kit-0.1.0/setup.cfg +4 -0
  13. oss_backtest_kit-0.1.0/src/oss_backtest_kit/__init__.py +6 -0
  14. oss_backtest_kit-0.1.0/src/oss_backtest_kit/data/__init__.py +7 -0
  15. oss_backtest_kit-0.1.0/src/oss_backtest_kit/data/__main__.py +70 -0
  16. oss_backtest_kit-0.1.0/src/oss_backtest_kit/data/_http.py +136 -0
  17. oss_backtest_kit-0.1.0/src/oss_backtest_kit/data/archive.py +289 -0
  18. oss_backtest_kit-0.1.0/src/oss_backtest_kit/data/check.py +115 -0
  19. oss_backtest_kit-0.1.0/src/oss_backtest_kit/data/rest_tail.py +150 -0
  20. oss_backtest_kit-0.1.0/src/oss_backtest_kit/engine.py +405 -0
  21. oss_backtest_kit-0.1.0/src/oss_backtest_kit/stats.py +246 -0
  22. oss_backtest_kit-0.1.0/src/oss_backtest_kit.egg-info/PKG-INFO +209 -0
  23. oss_backtest_kit-0.1.0/src/oss_backtest_kit.egg-info/SOURCES.txt +28 -0
  24. oss_backtest_kit-0.1.0/src/oss_backtest_kit.egg-info/dependency_links.txt +1 -0
  25. oss_backtest_kit-0.1.0/src/oss_backtest_kit.egg-info/requires.txt +15 -0
  26. oss_backtest_kit-0.1.0/src/oss_backtest_kit.egg-info/top_level.txt +1 -0
  27. oss_backtest_kit-0.1.0/tests/test_data.py +422 -0
  28. oss_backtest_kit-0.1.0/tests/test_engine.py +370 -0
  29. oss_backtest_kit-0.1.0/tests/test_examples.py +95 -0
  30. oss_backtest_kit-0.1.0/tests/test_stats.py +193 -0
@@ -0,0 +1,12 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0
4
+
5
+ First packaged release.
6
+
7
+ - Multiple-testing statistics: Sharpe, PSR, DSR, PBO (CSCV), effective number of trials, circular block bootstrap, Wilson interval.
8
+ - Binance public archive download with SHA-256 verification, manifest, and gap / duplicate checks; REST helper that exports recent bars to separate CSV files.
9
+ - Config-driven perpetual-futures backtest engine: next-open fills, funding, `base` and `stressed` cost levels.
10
+ - Packaging metadata, README quick start, MIT licence.
11
+ - Examples: effect chart script with PSR / DSR computed by the library (`examples/equity_psr_dsr.py`, matplotlib via the optional `examples` extra), a Colab quick start notebook (`examples/quickstart.ipynb`), and a 1280x640 social preview card; smoke tests for the examples. Release workflow runs the offline tests first and requires the tag to equal `v` plus the pyproject version; CI runs on pushes to `main` and on pull requests. The test jobs install matplotlib and nbformat (in the `test` extra) so the example tests run instead of being skipped; the release workflow also refuses a tag whose commit is not on `main`. The full-dependency test jobs also fail if any test is skipped.
12
+ - Dependency floors (numpy 1.21.6, scipy 1.7.3), CI workflow for Python 3.9 to 3.13, tag-triggered release workflow (PyPI Trusted Publishing), sdist includes this changelog.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 oss-backtest-kit contributors
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,4 @@
1
+ include CHANGELOG.md
2
+ include LICENSE
3
+ recursive-include examples *.py *.png *.ipynb
4
+ include docs/social_preview.png
@@ -0,0 +1,209 @@
1
+ Metadata-Version: 2.4
2
+ Name: oss-backtest-kit
3
+ Version: 0.1.0
4
+ Summary: A small, generic toolkit for crypto strategy research and backtest statistics.
5
+ License-Expression: MIT
6
+ Project-URL: Homepage, https://github.com/ww7411/oss-backtest-kit
7
+ Project-URL: Source, https://github.com/ww7411/oss-backtest-kit
8
+ Project-URL: Issues, https://github.com/ww7411/oss-backtest-kit/issues
9
+ Project-URL: Changelog, https://github.com/ww7411/oss-backtest-kit/blob/main/CHANGELOG.md
10
+ Keywords: backtest,crypto,deflated-sharpe-ratio,overfitting,quant,binance
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Intended Audience :: Financial and Insurance Industry
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Scientific/Engineering
22
+ Classifier: Topic :: Office/Business :: Financial :: Investment
23
+ Requires-Python: >=3.9
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Requires-Dist: numpy>=1.21.6
27
+ Requires-Dist: scipy>=1.7.3
28
+ Provides-Extra: test
29
+ Requires-Dist: pytest; extra == "test"
30
+ Requires-Dist: matplotlib; extra == "test"
31
+ Requires-Dist: nbformat; extra == "test"
32
+ Provides-Extra: examples
33
+ Requires-Dist: matplotlib; extra == "examples"
34
+ Provides-Extra: dev
35
+ Requires-Dist: pytest; extra == "dev"
36
+ Requires-Dist: matplotlib; extra == "dev"
37
+ Requires-Dist: nbformat; extra == "dev"
38
+ Dynamic: license-file
39
+
40
+ # oss-backtest-kit
41
+
42
+ [![CI](https://github.com/ww7411/oss-backtest-kit/actions/workflows/ci.yml/badge.svg)](https://github.com/ww7411/oss-backtest-kit/actions/workflows/ci.yml)
43
+ [![PyPI](https://img.shields.io/pypi/v/oss-backtest-kit.svg)](https://pypi.org/project/oss-backtest-kit/)
44
+ [![Python versions](https://img.shields.io/pypi/pyversions/oss-backtest-kit.svg)](https://pypi.org/project/oss-backtest-kit/)
45
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/ww7411/oss-backtest-kit/blob/main/LICENSE)
46
+ [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/ww7411/oss-backtest-kit/blob/main/examples/quickstart.ipynb)
47
+
48
+ **Is your backtest real, or did you just try enough ideas until one looked good?** A small, honest toolkit for crypto futures research: verified public data, a no-look-ahead backtest engine, and the statistics that tell you how much of your Sharpe ratio is luck.
49
+
50
+ ![Equity curve of the best of 9 variants with PSR and DSR computed by the library; synthetic data, not a trading result](https://raw.githubusercontent.com/ww7411/oss-backtest-kit/main/examples/equity_psr_dsr.png)
51
+
52
+ *Synthetic data, not a trading result. The best of 9 moving-average variants has an average return just above zero (Sharpe ratio slightly positive, PSR 0.53), but the equity curve still ends a little below its start (0.97), because volatility drags down compounded growth; after charging for the 9 tries the DSR is 0.07, so there is no evidence of skill. Reproduce it with `examples/equity_psr_dsr.py`.*
53
+
54
+ ## Highlights
55
+
56
+ - **Overfitting checks built in.** Deflated Sharpe Ratio, Probabilistic Sharpe Ratio and Probability of Backtest Overfitting (CSCV) adjust your result for how many variants you tried, so a lucky curve is easier to spot before it costs money.
57
+ - **Data you can trust.** Every Binance public archive file is checked against its published SHA-256 before it is saved; a manifest records what you have; gaps and duplicate bars are reported, not silently filled.
58
+ - **No look-ahead by design.** Your strategy is called at a bar's close and sees only bars up to that point; orders fill at the next bar's open with slippage and fees.
59
+ - **Costs that bite.** Perpetual-futures funding is included, and a `stressed` cost level lets you check whether an edge survives worse fills.
60
+ - **Small and readable.** Pure Python with only numpy and scipy; 62 offline tests; no account, API key or paid data needed.
61
+ - **MIT licensed** code (the market data has its own terms; see below).
62
+
63
+ ## Who it is for
64
+
65
+ Individual researchers and students who write their own strategies in Python and want a quick, sober second opinion on a backtest. It is not a trading bot, does not place orders and does not connect to any exchange account.
66
+
67
+ ## What is inside
68
+
69
+ A small research toolkit for crypto strategies, in three parts:
70
+
71
+ 1. **Multiple-testing statistics** (`oss_backtest_kit.stats`): Sharpe, Probabilistic Sharpe Ratio (PSR), Deflated Sharpe Ratio (DSR), Probability of Backtest Overfitting (CSCV), effective number of trials, circular block bootstrap, Wilson intervals.
72
+ 2. **Public data download and verification** (`oss_backtest_kit.data`): fetches Binance public archive files, verifies each against its published SHA-256 checksum, records a manifest, and checks bar continuity. A REST helper exports the most recent days as separate CSV files (not loaded by the engine).
73
+ 3. **A simple, config-driven backtest engine** (`oss_backtest_kit.engine`) for a portfolio of perpetual futures, with funding and a two-level cost model.
74
+
75
+ ## DISCLAIMER
76
+
77
+ This project is for **research and education only**. It is **not investment advice**. It comes with **no warranty** of any kind; you use it **at your own risk**. **Backtest results are not live results**: past or simulated performance says little about future outcomes, and you can lose money trading.
78
+
79
+ ## Status
80
+
81
+ Early release (version 0.1.0). The project is maintained: bug reports and pull requests are welcome. The API may still change before 1.0; see [CHANGELOG.md](https://github.com/ww7411/oss-backtest-kit/blob/main/CHANGELOG.md).
82
+
83
+ ## Try it in 30 seconds
84
+
85
+ No data download and no account needed:
86
+
87
+ ```
88
+ pip install oss-backtest-kit
89
+ python -c "import numpy as np; from oss_backtest_kit import stats; r = np.random.default_rng(0).normal(0.0005, 0.01, 500); print('PSR', stats.psr(r)); print('DSR', stats.dsr(r, n_trials=20, trial_sharpes=[0.01, 0.03, 0.02])[0])"
90
+ ```
91
+
92
+ The second number is lower than the first: the Deflated Sharpe Ratio charges you for the 20 variants you tried.
93
+
94
+ ## Requirements and install
95
+
96
+ - Python 3.9 or newer, with numpy and scipy (installed automatically below).
97
+ - Internet access only if you download data; everything else, tests included, runs offline.
98
+ - Some Python knowledge: you write your strategy as a small Python function.
99
+
100
+ ```
101
+ git clone https://github.com/ww7411/oss-backtest-kit.git
102
+ cd oss-backtest-kit
103
+ pip install -e .
104
+ ```
105
+
106
+ Tests use pytest (install the test extra first: `pip install -e ".[test]"`). The stats, engine and data test files can also be run directly with `python3`.
107
+
108
+ ## Quick start
109
+
110
+ Download public data (nothing is downloaded unless you run this; the output folder is yours to choose):
111
+
112
+ ```
113
+ python -m oss_backtest_kit.data archive --kinds klines,fundingRate --symbols BTCUSDT \
114
+ --interval 1d --from 2024-01 --to 2024-06 --out ./market_data
115
+ python -m oss_backtest_kit.data check --out ./market_data \
116
+ --kind klines --symbol BTCUSDT --interval 1d
117
+ ```
118
+
119
+ Kinds: `klines` (needs `--interval`), `markPriceKlines`, `indexPriceKlines`, `premiumIndexKlines`, `fundingRate`, `metrics`. Files that fail the checksum are neither saved nor recorded; existing files are never overwritten. Recent bars not yet in the archive can be exported with the `rest` subcommand; it writes standalone CSV files under `<out>/rest/` for inspection or your own merging. They are not added to the manifest and `load_market_data` does not read them, so a backtest ends at the last archive file.
120
+
121
+ Run the moving-average crossover example (synthetic data, nothing downloaded):
122
+
123
+ ```
124
+ python3 examples/ma_crossover.py
125
+ ```
126
+
127
+ Draw the effect chart above (needs matplotlib, an optional extra that is not a runtime dependency):
128
+
129
+ ```
130
+ pip install -e ".[examples]"
131
+ python3 examples/equity_psr_dsr.py
132
+ ```
133
+
134
+ Or open the [quick start notebook in Colab](https://colab.research.google.com/github/ww7411/oss-backtest-kit/blob/main/examples/quickstart.ipynb) (synthetic data, no download).
135
+
136
+ Use the statistics:
137
+
138
+ ```python
139
+ import numpy as np
140
+ from oss_backtest_kit import stats
141
+
142
+ returns = np.random.default_rng(0).normal(0.0005, 0.01, 500)
143
+ print(stats.psr(returns)) # P(true Sharpe > 0)
144
+ value, benchmark, var = stats.dsr(returns, n_trials=20, # penalise 20 tries
145
+ trial_sharpes=[0.01, 0.03, 0.02])
146
+ print(stats.wilson(7, 50)) # 95% interval for 7/50
147
+ ```
148
+
149
+ Run a backtest on your own downloaded data:
150
+
151
+ ```python
152
+ from oss_backtest_kit.engine import EngineConfig, load_market_data, run_backtest
153
+
154
+ data = load_market_data("./market_data", ["BTCUSDT"], interval="1d")
155
+ cfg = EngineConfig(symbols=["BTCUSDT"], max_leverage=1.0, rebalance_threshold=0.02)
156
+
157
+ def strategy(t, history): # called at the close of bar t, sees bars 0..t only
158
+ return {"BTCUSDT": 1.0} # sum(|weights|) must not exceed max_leverage
159
+
160
+ result = run_backtest(data, strategy, cfg, cost_level="stressed")
161
+ print(result.summary()) # result.returns feeds stats.psr / stats.dsr
162
+ ```
163
+
164
+ ## Modules
165
+
166
+ | Module | Purpose |
167
+ | --- | --- |
168
+ | `stats` | PSR, DSR, PBO (CSCV), effective trials, block bootstrap, Wilson interval |
169
+ | `data.archive` | Archive download with checksum verification, manifest, exclusive-create writes |
170
+ | `data.rest_tail` | Recent closed bars and funding from public REST endpoints |
171
+ | `data.check` | Manifest SHA check, gap and duplicate detection |
172
+ | `engine` | Config, market data loader, backtest loop, result summary |
173
+
174
+ The data client allows a single host per task, uses https only, ignores environment proxy settings, refuses redirects, bounds response size and time, and stops when free disk space is low.
175
+
176
+ ## Tests
177
+
178
+ ```
179
+ pip install -e ".[test]"
180
+ python3 -m pytest
181
+ ```
182
+
183
+ All tests run offline with synthetic data and fake network responses.
184
+
185
+ ## Known limitations
186
+
187
+ - Fills are modelled from OHLC bars (decision at a bar close, fill at the next open with slippage and a proportional fee). Real fills depend on order books, latency and size.
188
+ - Funding is modelled as position x price x rate at each funding time, using the open price of the bar that contains the event; margin, liquidation and exchange rules are not modelled beyond stopping at zero equity (limited liability: positions are closed at that bar's close and any loss beyond zero is reported as `ruin_shortfall`, so `sum(pnl_by_symbol) + ruin_shortfall` equals the change in equity).
189
+ - Survivorship bias: the symbols you choose are the ones that exist today; delisted symbols are not included unless you add them.
190
+ - Cost defaults (`base` and `stressed`) are placeholders, not estimates for any venue. Set your own numbers.
191
+ - Statistics assume the return series is a fair sample; PSR/DSR/PBO reduce, but do not remove, the risk of overfitting.
192
+
193
+ ## Data terms
194
+
195
+ This kit ships **code only and never any data**. It downloads from two different sources, which have **different terms**. Nothing here is legal advice; read the current terms yourself before downloading, using or sharing any data.
196
+
197
+ **1. Archive files from `data.binance.vision`** (`archive` subcommand). These are described in the `binance/binance-public-data` repository (https://github.com/binance/binance-public-data), whose `TERMS_AND_CONDITIONS.md` states a CC BY-NC-SA 4.0 licence (https://creativecommons.org/licenses/by-nc-sa/4.0/). As we read that licence, it means:
198
+
199
+ - **Attribution**: if you share the data or anything derived from it (cleaned files, aggregated tables, published charts of the data), credit the source, link the licence, and say whether you changed it.
200
+ - **NonCommercial**: no commercial use of the data.
201
+ - **ShareAlike**: data you derive from it and share must be shared under the same licence.
202
+
203
+ **2. Recent data from the REST API at `fapi.binance.com`** (`rest` subcommand). This is **not** covered by the archive licence above. It falls under the exchange's own API and website terms of use, which this project has **not** reviewed; we make no statement about what they allow. Check them before using or sharing REST data.
204
+
205
+ You alone are responsible for complying with the terms of each source and with the exchange's rules.
206
+
207
+ ## License
208
+
209
+ MIT; see [LICENSE](https://github.com/ww7411/oss-backtest-kit/blob/main/LICENSE). The licence covers this code only, not any market data you download with it (see the data terms above).
@@ -0,0 +1,170 @@
1
+ # oss-backtest-kit
2
+
3
+ [![CI](https://github.com/ww7411/oss-backtest-kit/actions/workflows/ci.yml/badge.svg)](https://github.com/ww7411/oss-backtest-kit/actions/workflows/ci.yml)
4
+ [![PyPI](https://img.shields.io/pypi/v/oss-backtest-kit.svg)](https://pypi.org/project/oss-backtest-kit/)
5
+ [![Python versions](https://img.shields.io/pypi/pyversions/oss-backtest-kit.svg)](https://pypi.org/project/oss-backtest-kit/)
6
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/ww7411/oss-backtest-kit/blob/main/LICENSE)
7
+ [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/ww7411/oss-backtest-kit/blob/main/examples/quickstart.ipynb)
8
+
9
+ **Is your backtest real, or did you just try enough ideas until one looked good?** A small, honest toolkit for crypto futures research: verified public data, a no-look-ahead backtest engine, and the statistics that tell you how much of your Sharpe ratio is luck.
10
+
11
+ ![Equity curve of the best of 9 variants with PSR and DSR computed by the library; synthetic data, not a trading result](https://raw.githubusercontent.com/ww7411/oss-backtest-kit/main/examples/equity_psr_dsr.png)
12
+
13
+ *Synthetic data, not a trading result. The best of 9 moving-average variants has an average return just above zero (Sharpe ratio slightly positive, PSR 0.53), but the equity curve still ends a little below its start (0.97), because volatility drags down compounded growth; after charging for the 9 tries the DSR is 0.07, so there is no evidence of skill. Reproduce it with `examples/equity_psr_dsr.py`.*
14
+
15
+ ## Highlights
16
+
17
+ - **Overfitting checks built in.** Deflated Sharpe Ratio, Probabilistic Sharpe Ratio and Probability of Backtest Overfitting (CSCV) adjust your result for how many variants you tried, so a lucky curve is easier to spot before it costs money.
18
+ - **Data you can trust.** Every Binance public archive file is checked against its published SHA-256 before it is saved; a manifest records what you have; gaps and duplicate bars are reported, not silently filled.
19
+ - **No look-ahead by design.** Your strategy is called at a bar's close and sees only bars up to that point; orders fill at the next bar's open with slippage and fees.
20
+ - **Costs that bite.** Perpetual-futures funding is included, and a `stressed` cost level lets you check whether an edge survives worse fills.
21
+ - **Small and readable.** Pure Python with only numpy and scipy; 62 offline tests; no account, API key or paid data needed.
22
+ - **MIT licensed** code (the market data has its own terms; see below).
23
+
24
+ ## Who it is for
25
+
26
+ Individual researchers and students who write their own strategies in Python and want a quick, sober second opinion on a backtest. It is not a trading bot, does not place orders and does not connect to any exchange account.
27
+
28
+ ## What is inside
29
+
30
+ A small research toolkit for crypto strategies, in three parts:
31
+
32
+ 1. **Multiple-testing statistics** (`oss_backtest_kit.stats`): Sharpe, Probabilistic Sharpe Ratio (PSR), Deflated Sharpe Ratio (DSR), Probability of Backtest Overfitting (CSCV), effective number of trials, circular block bootstrap, Wilson intervals.
33
+ 2. **Public data download and verification** (`oss_backtest_kit.data`): fetches Binance public archive files, verifies each against its published SHA-256 checksum, records a manifest, and checks bar continuity. A REST helper exports the most recent days as separate CSV files (not loaded by the engine).
34
+ 3. **A simple, config-driven backtest engine** (`oss_backtest_kit.engine`) for a portfolio of perpetual futures, with funding and a two-level cost model.
35
+
36
+ ## DISCLAIMER
37
+
38
+ This project is for **research and education only**. It is **not investment advice**. It comes with **no warranty** of any kind; you use it **at your own risk**. **Backtest results are not live results**: past or simulated performance says little about future outcomes, and you can lose money trading.
39
+
40
+ ## Status
41
+
42
+ Early release (version 0.1.0). The project is maintained: bug reports and pull requests are welcome. The API may still change before 1.0; see [CHANGELOG.md](https://github.com/ww7411/oss-backtest-kit/blob/main/CHANGELOG.md).
43
+
44
+ ## Try it in 30 seconds
45
+
46
+ No data download and no account needed:
47
+
48
+ ```
49
+ pip install oss-backtest-kit
50
+ python -c "import numpy as np; from oss_backtest_kit import stats; r = np.random.default_rng(0).normal(0.0005, 0.01, 500); print('PSR', stats.psr(r)); print('DSR', stats.dsr(r, n_trials=20, trial_sharpes=[0.01, 0.03, 0.02])[0])"
51
+ ```
52
+
53
+ The second number is lower than the first: the Deflated Sharpe Ratio charges you for the 20 variants you tried.
54
+
55
+ ## Requirements and install
56
+
57
+ - Python 3.9 or newer, with numpy and scipy (installed automatically below).
58
+ - Internet access only if you download data; everything else, tests included, runs offline.
59
+ - Some Python knowledge: you write your strategy as a small Python function.
60
+
61
+ ```
62
+ git clone https://github.com/ww7411/oss-backtest-kit.git
63
+ cd oss-backtest-kit
64
+ pip install -e .
65
+ ```
66
+
67
+ Tests use pytest (install the test extra first: `pip install -e ".[test]"`). The stats, engine and data test files can also be run directly with `python3`.
68
+
69
+ ## Quick start
70
+
71
+ Download public data (nothing is downloaded unless you run this; the output folder is yours to choose):
72
+
73
+ ```
74
+ python -m oss_backtest_kit.data archive --kinds klines,fundingRate --symbols BTCUSDT \
75
+ --interval 1d --from 2024-01 --to 2024-06 --out ./market_data
76
+ python -m oss_backtest_kit.data check --out ./market_data \
77
+ --kind klines --symbol BTCUSDT --interval 1d
78
+ ```
79
+
80
+ Kinds: `klines` (needs `--interval`), `markPriceKlines`, `indexPriceKlines`, `premiumIndexKlines`, `fundingRate`, `metrics`. Files that fail the checksum are neither saved nor recorded; existing files are never overwritten. Recent bars not yet in the archive can be exported with the `rest` subcommand; it writes standalone CSV files under `<out>/rest/` for inspection or your own merging. They are not added to the manifest and `load_market_data` does not read them, so a backtest ends at the last archive file.
81
+
82
+ Run the moving-average crossover example (synthetic data, nothing downloaded):
83
+
84
+ ```
85
+ python3 examples/ma_crossover.py
86
+ ```
87
+
88
+ Draw the effect chart above (needs matplotlib, an optional extra that is not a runtime dependency):
89
+
90
+ ```
91
+ pip install -e ".[examples]"
92
+ python3 examples/equity_psr_dsr.py
93
+ ```
94
+
95
+ Or open the [quick start notebook in Colab](https://colab.research.google.com/github/ww7411/oss-backtest-kit/blob/main/examples/quickstart.ipynb) (synthetic data, no download).
96
+
97
+ Use the statistics:
98
+
99
+ ```python
100
+ import numpy as np
101
+ from oss_backtest_kit import stats
102
+
103
+ returns = np.random.default_rng(0).normal(0.0005, 0.01, 500)
104
+ print(stats.psr(returns)) # P(true Sharpe > 0)
105
+ value, benchmark, var = stats.dsr(returns, n_trials=20, # penalise 20 tries
106
+ trial_sharpes=[0.01, 0.03, 0.02])
107
+ print(stats.wilson(7, 50)) # 95% interval for 7/50
108
+ ```
109
+
110
+ Run a backtest on your own downloaded data:
111
+
112
+ ```python
113
+ from oss_backtest_kit.engine import EngineConfig, load_market_data, run_backtest
114
+
115
+ data = load_market_data("./market_data", ["BTCUSDT"], interval="1d")
116
+ cfg = EngineConfig(symbols=["BTCUSDT"], max_leverage=1.0, rebalance_threshold=0.02)
117
+
118
+ def strategy(t, history): # called at the close of bar t, sees bars 0..t only
119
+ return {"BTCUSDT": 1.0} # sum(|weights|) must not exceed max_leverage
120
+
121
+ result = run_backtest(data, strategy, cfg, cost_level="stressed")
122
+ print(result.summary()) # result.returns feeds stats.psr / stats.dsr
123
+ ```
124
+
125
+ ## Modules
126
+
127
+ | Module | Purpose |
128
+ | --- | --- |
129
+ | `stats` | PSR, DSR, PBO (CSCV), effective trials, block bootstrap, Wilson interval |
130
+ | `data.archive` | Archive download with checksum verification, manifest, exclusive-create writes |
131
+ | `data.rest_tail` | Recent closed bars and funding from public REST endpoints |
132
+ | `data.check` | Manifest SHA check, gap and duplicate detection |
133
+ | `engine` | Config, market data loader, backtest loop, result summary |
134
+
135
+ The data client allows a single host per task, uses https only, ignores environment proxy settings, refuses redirects, bounds response size and time, and stops when free disk space is low.
136
+
137
+ ## Tests
138
+
139
+ ```
140
+ pip install -e ".[test]"
141
+ python3 -m pytest
142
+ ```
143
+
144
+ All tests run offline with synthetic data and fake network responses.
145
+
146
+ ## Known limitations
147
+
148
+ - Fills are modelled from OHLC bars (decision at a bar close, fill at the next open with slippage and a proportional fee). Real fills depend on order books, latency and size.
149
+ - Funding is modelled as position x price x rate at each funding time, using the open price of the bar that contains the event; margin, liquidation and exchange rules are not modelled beyond stopping at zero equity (limited liability: positions are closed at that bar's close and any loss beyond zero is reported as `ruin_shortfall`, so `sum(pnl_by_symbol) + ruin_shortfall` equals the change in equity).
150
+ - Survivorship bias: the symbols you choose are the ones that exist today; delisted symbols are not included unless you add them.
151
+ - Cost defaults (`base` and `stressed`) are placeholders, not estimates for any venue. Set your own numbers.
152
+ - Statistics assume the return series is a fair sample; PSR/DSR/PBO reduce, but do not remove, the risk of overfitting.
153
+
154
+ ## Data terms
155
+
156
+ This kit ships **code only and never any data**. It downloads from two different sources, which have **different terms**. Nothing here is legal advice; read the current terms yourself before downloading, using or sharing any data.
157
+
158
+ **1. Archive files from `data.binance.vision`** (`archive` subcommand). These are described in the `binance/binance-public-data` repository (https://github.com/binance/binance-public-data), whose `TERMS_AND_CONDITIONS.md` states a CC BY-NC-SA 4.0 licence (https://creativecommons.org/licenses/by-nc-sa/4.0/). As we read that licence, it means:
159
+
160
+ - **Attribution**: if you share the data or anything derived from it (cleaned files, aggregated tables, published charts of the data), credit the source, link the licence, and say whether you changed it.
161
+ - **NonCommercial**: no commercial use of the data.
162
+ - **ShareAlike**: data you derive from it and share must be shared under the same licence.
163
+
164
+ **2. Recent data from the REST API at `fapi.binance.com`** (`rest` subcommand). This is **not** covered by the archive licence above. It falls under the exchange's own API and website terms of use, which this project has **not** reviewed; we make no statement about what they allow. Check them before using or sharing REST data.
165
+
166
+ You alone are responsible for complying with the terms of each source and with the exchange's rules.
167
+
168
+ ## License
169
+
170
+ MIT; see [LICENSE](https://github.com/ww7411/oss-backtest-kit/blob/main/LICENSE). The licence covers this code only, not any market data you download with it (see the data terms above).
@@ -0,0 +1,130 @@
1
+ """Effect chart: equity curve plus PSR / DSR, all computed by the library on synthetic data.
2
+
3
+ SYNTHETIC DATA, NOT A TRADING RESULT. The prices are a seeded random walk; the chart only
4
+ shows how the statistics adjust a "best of N variants" backtest for the number of tries.
5
+
6
+ Install (matplotlib is an optional extra, only needed to draw the picture):
7
+
8
+ pip install "oss-backtest-kit[examples]" # from PyPI, after release
9
+ # or, from a clone of the repository:
10
+ pip install -e ".[examples]"
11
+
12
+ Run from the project root (writes examples/equity_psr_dsr.png):
13
+
14
+ python3 examples/equity_psr_dsr.py
15
+ python3 examples/equity_psr_dsr.py --social docs/social_preview.png # also the 1280x640 card
16
+
17
+ The numbers come from `compute()`, which needs no matplotlib and is covered by the tests.
18
+ """
19
+
20
+ import argparse
21
+ import os
22
+ import sys
23
+
24
+ import numpy as np
25
+
26
+ HERE = os.path.dirname(os.path.abspath(__file__))
27
+ sys.path.insert(0, os.path.join(HERE, "..", "src"))
28
+ sys.path.insert(0, HERE)
29
+
30
+ from ma_crossover import ma_crossover, synthetic_market # noqa: E402
31
+ from oss_backtest_kit import stats # noqa: E402
32
+ from oss_backtest_kit.engine import EngineConfig, run_backtest # noqa: E402
33
+
34
+ GRID = [(f, s) for f in (5, 10, 20) for s in (30, 40, 60)]
35
+ LABEL = "synthetic data, not a trading result"
36
+ BLUE, GREY, RED = "#2a6fb0", "#666666", "#b03a2e"
37
+
38
+
39
+ def compute(seed=0):
40
+ """Run the 9-variant grid, pick the best by Sharpe, and return its statistics."""
41
+ data = synthetic_market(seed=seed)
42
+ cfg = EngineConfig(symbols=data.symbols, max_leverage=1.0, rebalance_threshold=0.02)
43
+ results = [run_backtest(data, ma_crossover(f, s), cfg) for f, s in GRID]
44
+ srs = [stats.sharpe(r.returns) for r in results]
45
+ best = int(np.argmax(srs))
46
+ returns = results[best].returns
47
+ dsr_value, bench, _ = stats.dsr(returns, len(GRID), srs)
48
+ return {
49
+ "variant": GRID[best],
50
+ "n_trials": len(GRID),
51
+ "equity": results[best].equity,
52
+ "sharpe_annualised": stats.sharpe_annualised(returns, results[best].periods_per_year),
53
+ "psr": stats.psr(returns),
54
+ "dsr": dsr_value,
55
+ "benchmark_sharpe_per_bar": bench,
56
+ }
57
+
58
+
59
+ def _pyplot():
60
+ try:
61
+ import matplotlib
62
+ matplotlib.use("Agg")
63
+ import matplotlib.pyplot as plt
64
+ except ImportError:
65
+ sys.exit('matplotlib is missing. Install the extra: pip install -e ".[examples]"')
66
+ return plt
67
+
68
+
69
+ def _save(fig, path):
70
+ # Software=None keeps the PNG free of version / path style text chunks.
71
+ fig.savefig(path, dpi=100, metadata={"Software": None})
72
+
73
+
74
+ def plot_chart(res, path):
75
+ plt = _pyplot()
76
+ fig, ax = plt.subplots(figsize=(9, 5), dpi=100)
77
+ ax.plot(res["equity"] / res["equity"][0], color=BLUE, lw=1.6)
78
+ ax.axhline(1.0, color=GREY, lw=0.8, ls="--")
79
+ ax.set_xlabel("bar (daily, synthetic)")
80
+ ax.set_ylabel("equity (start = 1.0)")
81
+ ax.set_title("Best of %d moving-average variants: equity curve and overfitting statistics"
82
+ % res["n_trials"], fontsize=11)
83
+ text = ("variant (fast, slow) = %s\nannualised Sharpe = %.2f\nPSR (vs 0) = %.3f\n"
84
+ "DSR (%d trials) = %.3f" % (res["variant"], res["sharpe_annualised"], res["psr"],
85
+ res["n_trials"], res["dsr"]))
86
+ ax.text(0.02, 0.04, text, transform=ax.transAxes, va="bottom", fontsize=10, family="monospace",
87
+ bbox={"boxstyle": "round", "facecolor": "white", "edgecolor": GREY})
88
+ fig.text(0.5, 0.01, LABEL, ha="center", color=RED, fontsize=9)
89
+ fig.tight_layout(rect=(0, 0.04, 1, 1))
90
+ _save(fig, path)
91
+ plt.close(fig)
92
+
93
+
94
+ def plot_social(res, path):
95
+ """1280x640 card for the repository social preview (upload is done by hand)."""
96
+ plt = _pyplot()
97
+ fig = plt.figure(figsize=(12.8, 6.4), dpi=100)
98
+ fig.text(0.06, 0.80, "oss-backtest-kit", fontsize=44, weight="bold")
99
+ fig.text(0.06, 0.66, "Is your backtest real, or just the best of many tries?", fontsize=20)
100
+ fig.text(0.06, 0.52, "PSR | DSR | PBO | checked data | no look-ahead engine",
101
+ fontsize=16, color=GREY)
102
+ fig.text(0.06, 0.40, "PSR %.2f -> DSR %.2f after %d trials" % (res["psr"], res["dsr"],
103
+ res["n_trials"]),
104
+ fontsize=16, family="monospace", color=BLUE)
105
+ fig.text(0.06, 0.08, LABEL + ". Research only, not investment advice.", fontsize=13, color=RED)
106
+ ax = fig.add_axes([0.58, 0.14, 0.36, 0.30])
107
+ ax.plot(res["equity"] / res["equity"][0], color=BLUE, lw=1.4)
108
+ ax.set_xticks([])
109
+ ax.set_yticks([])
110
+ for side in ("top", "right"):
111
+ ax.spines[side].set_visible(False)
112
+ _save(fig, path)
113
+ plt.close(fig)
114
+
115
+
116
+ def main(argv=None):
117
+ ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
118
+ ap.add_argument("--out", default=os.path.join(HERE, "equity_psr_dsr.png"))
119
+ ap.add_argument("--social", help="also write the 1280x640 social preview card here")
120
+ args = ap.parse_args(argv)
121
+ res = compute()
122
+ print("best variant %s Sharpe=%.2f PSR=%.3f DSR=%.3f (%d trials)" % (
123
+ res["variant"], res["sharpe_annualised"], res["psr"], res["dsr"], res["n_trials"]))
124
+ plot_chart(res, args.out)
125
+ if args.social:
126
+ plot_social(res, args.social)
127
+
128
+
129
+ if __name__ == "__main__":
130
+ main()
@@ -0,0 +1,63 @@
1
+ """Moving-average crossover on synthetic data: a textbook example, not a trading recommendation.
2
+
3
+ Run from the project root: python3 examples/ma_crossover.py
4
+ """
5
+
6
+ import os
7
+ import sys
8
+
9
+ import numpy as np
10
+
11
+ sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "src"))
12
+
13
+ from oss_backtest_kit import stats # noqa: E402
14
+ from oss_backtest_kit.engine import EngineConfig, MarketData, run_backtest # noqa: E402
15
+
16
+ DAY = 86400000
17
+
18
+
19
+ def synthetic_market(n_bars=1000, symbols=("AAA", "BBB"), seed=0):
20
+ """Geometric random walks with a little drift, plus a funding rate every bar."""
21
+ rng = np.random.default_rng(seed)
22
+ m = len(symbols)
23
+ rets = rng.normal(0.0003, 0.02, (n_bars, m))
24
+ close = 100.0 * np.cumprod(1.0 + rets, axis=0)
25
+ open_ = np.vstack([np.full((1, m), 100.0), close[:-1]])
26
+ high, low = np.maximum(open_, close) * 1.005, np.minimum(open_, close) * 0.995
27
+ times = 1_600_000_000_000 - (1_600_000_000_000 % DAY) + DAY * np.arange(n_bars)
28
+ fund_px = 0.0001 * open_ # constant small positive funding rate
29
+ return MarketData(list(symbols), times, open_, high, low, close, fund_px)
30
+
31
+
32
+ def ma_crossover(fast=10, slow=40):
33
+ """Long when the fast average is above the slow one, otherwise flat; equal split."""
34
+ def weights(t, hist):
35
+ if t + 1 < slow:
36
+ return {}
37
+ long_syms = [s for i, s in enumerate(hist.symbols)
38
+ if hist.close[t - fast + 1:t + 1, i].mean() > hist.close[t - slow + 1:t + 1, i].mean()]
39
+ return {s: 1.0 / len(hist.symbols) for s in long_syms}
40
+ return weights
41
+
42
+
43
+ def main():
44
+ data = synthetic_market()
45
+ cfg = EngineConfig(symbols=data.symbols, max_leverage=1.0, rebalance_threshold=0.02)
46
+ for level in ("base", "stressed"):
47
+ res = run_backtest(data, ma_crossover(), cfg, cost_level=level)
48
+ s = res.summary()
49
+ print("%-9s return=%+.3f sharpe=%.2f maxdd=%.3f psr=%.3f fees=%.4f funding=%+.4f"
50
+ % (level, s["total_return"], s["sharpe_annualised"], s["max_drawdown"],
51
+ s["psr_vs_zero"], s["fees"], s["funding_net"]))
52
+ # Deflate against the number of variants tried (here: a small grid of windows).
53
+ grid = [(f, sl) for f in (5, 10, 20) for sl in (30, 40, 60)]
54
+ runs = [run_backtest(data, ma_crossover(f, sl), cfg).returns for f, sl in grid]
55
+ srs = [stats.sharpe(r) for r in runs]
56
+ best = int(np.argmax(srs))
57
+ value, bench, _ = stats.dsr(runs[best], len(grid), srs)
58
+ print("best of %d variants %s: PSR=%.3f DSR=%.3f (benchmark SR/bar %.4f)"
59
+ % (len(grid), grid[best], stats.psr(runs[best]), value, bench))
60
+
61
+
62
+ if __name__ == "__main__":
63
+ main()