oss-backtest-kit 0.1.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.
- oss_backtest_kit/__init__.py +6 -0
- oss_backtest_kit/data/__init__.py +7 -0
- oss_backtest_kit/data/__main__.py +70 -0
- oss_backtest_kit/data/_http.py +136 -0
- oss_backtest_kit/data/archive.py +289 -0
- oss_backtest_kit/data/check.py +115 -0
- oss_backtest_kit/data/rest_tail.py +150 -0
- oss_backtest_kit/engine.py +405 -0
- oss_backtest_kit/stats.py +246 -0
- oss_backtest_kit-0.1.0.dist-info/METADATA +209 -0
- oss_backtest_kit-0.1.0.dist-info/RECORD +14 -0
- oss_backtest_kit-0.1.0.dist-info/WHEEL +5 -0
- oss_backtest_kit-0.1.0.dist-info/licenses/LICENSE +21 -0
- oss_backtest_kit-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
"""Statistics for judging backtest results.
|
|
2
|
+
|
|
3
|
+
Implements, following Bailey and Lopez de Prado:
|
|
4
|
+
|
|
5
|
+
* Sharpe ratio (per period and annualised)
|
|
6
|
+
* Probabilistic Sharpe Ratio (PSR)
|
|
7
|
+
* Deflated Sharpe Ratio (DSR), which corrects for trying many configurations
|
|
8
|
+
* Probability of Backtest Overfitting via CSCV (PBO)
|
|
9
|
+
* effective number of independent trials
|
|
10
|
+
* circular block bootstrap of a return series
|
|
11
|
+
* Wilson score interval for a proportion
|
|
12
|
+
|
|
13
|
+
All inputs are per-period simple returns (for example daily). Any non-finite
|
|
14
|
+
input raises :class:`StatsError` rather than silently producing a number.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
import itertools
|
|
18
|
+
import math
|
|
19
|
+
|
|
20
|
+
import numpy as np
|
|
21
|
+
from scipy.stats import norm
|
|
22
|
+
|
|
23
|
+
EULER_GAMMA = 0.5772156649015329
|
|
24
|
+
PERIODS_PER_YEAR = 365.25 # calendar days; crypto trades every day
|
|
25
|
+
|
|
26
|
+
__all__ = [
|
|
27
|
+
"StatsError", "sharpe", "sharpe_annualised", "max_drawdown", "psr",
|
|
28
|
+
"expected_max_sharpe", "null_sharpe_variance", "dsr", "n_effective",
|
|
29
|
+
"pbo_cscv", "block_bootstrap", "wilson",
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class StatsError(ValueError):
|
|
34
|
+
"""Raised for empty, non-finite or otherwise unusable input."""
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _finite_array(x, name):
|
|
38
|
+
a = np.asarray(x, dtype=float)
|
|
39
|
+
if a.size == 0 or not np.isfinite(a).all():
|
|
40
|
+
raise StatsError("%s must be non-empty and finite" % name)
|
|
41
|
+
return a
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def sharpe(returns):
|
|
45
|
+
"""Per-period Sharpe ratio (mean / sample std, zero risk-free rate).
|
|
46
|
+
|
|
47
|
+
Returns 0.0 for fewer than two observations or zero variance.
|
|
48
|
+
"""
|
|
49
|
+
r = np.asarray(returns, dtype=float)
|
|
50
|
+
if r.size < 2:
|
|
51
|
+
return 0.0
|
|
52
|
+
sd = r.std(ddof=1)
|
|
53
|
+
return 0.0 if sd == 0 else float(r.mean() / sd)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def sharpe_annualised(returns, periods_per_year=PERIODS_PER_YEAR):
|
|
57
|
+
"""Sharpe ratio scaled by sqrt(periods_per_year)."""
|
|
58
|
+
return sharpe(returns) * math.sqrt(periods_per_year)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def max_drawdown(returns):
|
|
62
|
+
"""Largest peak-to-trough fall of the compounded equity curve, in [0, 1]."""
|
|
63
|
+
r = np.asarray(returns, dtype=float)
|
|
64
|
+
if r.size == 0:
|
|
65
|
+
return 0.0
|
|
66
|
+
eq = np.cumprod(1.0 + r)
|
|
67
|
+
peak = np.maximum.accumulate(np.concatenate([[1.0], eq]))[1:]
|
|
68
|
+
return float((1.0 - eq / peak).max())
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def psr(returns, benchmark_sharpe=0.0):
|
|
72
|
+
"""Probabilistic Sharpe Ratio.
|
|
73
|
+
|
|
74
|
+
Probability that the true per-period Sharpe ratio exceeds
|
|
75
|
+
``benchmark_sharpe``, accounting for sample length, skewness and kurtosis.
|
|
76
|
+
Returns NaN when there are fewer than 3 observations or zero variance.
|
|
77
|
+
"""
|
|
78
|
+
r = np.asarray(returns, dtype=float)
|
|
79
|
+
t = r.size
|
|
80
|
+
if t < 3 or r.std(ddof=0) == 0:
|
|
81
|
+
return float("nan")
|
|
82
|
+
sr = sharpe(r)
|
|
83
|
+
z = (r - r.mean()) / r.std(ddof=0)
|
|
84
|
+
skew = float((z ** 3).mean())
|
|
85
|
+
kurt = float((z ** 4).mean()) # raw (non-excess) kurtosis
|
|
86
|
+
denom = math.sqrt(max(1e-12, 1.0 - skew * sr + (kurt - 1.0) / 4.0 * sr * sr))
|
|
87
|
+
return float(norm.cdf((sr - benchmark_sharpe) * math.sqrt(t - 1) / denom))
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def expected_max_sharpe(n_trials, variance):
|
|
91
|
+
"""Expected maximum Sharpe among ``n_trials`` independent null trials.
|
|
92
|
+
|
|
93
|
+
``variance`` is the cross-trial variance of the Sharpe estimates.
|
|
94
|
+
"""
|
|
95
|
+
if n_trials < 2 or variance <= 0:
|
|
96
|
+
return 0.0
|
|
97
|
+
return math.sqrt(variance) * (
|
|
98
|
+
(1.0 - EULER_GAMMA) * norm.ppf(1.0 - 1.0 / n_trials)
|
|
99
|
+
+ EULER_GAMMA * norm.ppf(1.0 - 1.0 / (n_trials * math.e))
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def null_sharpe_variance(n_obs):
|
|
104
|
+
"""Sampling variance of a per-period Sharpe estimate under a null of zero."""
|
|
105
|
+
return 1.0 / max(1, n_obs - 1)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def dsr(returns, n_trials, trial_sharpes=()):
|
|
109
|
+
"""Deflated Sharpe Ratio.
|
|
110
|
+
|
|
111
|
+
PSR of ``returns`` measured against the expected best Sharpe obtainable by
|
|
112
|
+
luck after ``n_trials`` attempts. The cross-trial variance is taken from
|
|
113
|
+
``trial_sharpes`` (per-period Sharpe of each tried configuration) when at
|
|
114
|
+
least two are given; the larger of that and the null sampling variance is
|
|
115
|
+
used, which is the conservative choice.
|
|
116
|
+
|
|
117
|
+
Returns ``(dsr_value, benchmark_sharpe, variance_used)``.
|
|
118
|
+
"""
|
|
119
|
+
r = _finite_array(returns, "returns")
|
|
120
|
+
ts = np.asarray(trial_sharpes, dtype=float)
|
|
121
|
+
if ts.size and not np.isfinite(ts).all():
|
|
122
|
+
raise StatsError("trial_sharpes must be finite")
|
|
123
|
+
if n_trials < 1:
|
|
124
|
+
raise StatsError("n_trials must be >= 1, got %r" % (n_trials,))
|
|
125
|
+
var = float(np.var(ts, ddof=1)) if ts.size >= 2 else 0.0
|
|
126
|
+
if n_trials >= 2:
|
|
127
|
+
var = max(var, null_sharpe_variance(r.size))
|
|
128
|
+
bench = expected_max_sharpe(n_trials, var)
|
|
129
|
+
return psr(r, bench), bench, var
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def n_effective(matrix):
|
|
133
|
+
"""Effective number of independent trials from a (periods x trials) matrix.
|
|
134
|
+
|
|
135
|
+
Uses the mean pairwise correlation rho: ``N / (1 + (N - 1) * rho)``,
|
|
136
|
+
clipped to ``[1, N]``. Raises :class:`StatsError` for non-finite input,
|
|
137
|
+
fewer than 3 periods, or a trial with zero variance (its correlation is
|
|
138
|
+
undefined; drop or fix such trials explicitly before calling).
|
|
139
|
+
"""
|
|
140
|
+
m = _finite_array(matrix, "matrix")
|
|
141
|
+
if m.ndim != 2:
|
|
142
|
+
raise StatsError("matrix must be 2-D (periods x trials)")
|
|
143
|
+
n = m.shape[1]
|
|
144
|
+
if n < 2:
|
|
145
|
+
return 1.0
|
|
146
|
+
if m.shape[0] < 3:
|
|
147
|
+
raise StatsError("need at least 3 periods, got %d" % m.shape[0])
|
|
148
|
+
flat = np.flatnonzero(np.ptp(m, axis=0) == 0)
|
|
149
|
+
if flat.size:
|
|
150
|
+
raise StatsError("trials with zero variance (columns %s)" % flat.tolist())
|
|
151
|
+
c = np.corrcoef(m.T)
|
|
152
|
+
rho = (c.sum() - n) / (n * (n - 1))
|
|
153
|
+
if not math.isfinite(rho):
|
|
154
|
+
raise StatsError("mean correlation is not finite")
|
|
155
|
+
rho = min(max(rho, 0.0), 1.0)
|
|
156
|
+
return float(min(n, max(1.0, n / (1.0 + (n - 1) * rho))))
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def pbo_cscv(matrix, n_blocks=8):
|
|
160
|
+
"""Probability of Backtest Overfitting by combinatorially symmetric CV.
|
|
161
|
+
|
|
162
|
+
``matrix`` has shape (periods, trials). Rows are cut into ``n_blocks``
|
|
163
|
+
contiguous blocks; for each way of choosing half of them as in-sample, the
|
|
164
|
+
in-sample best trial is located and its out-of-sample relative rank
|
|
165
|
+
omega in (0, 1) is computed (average rank among ties). PBO is the share of
|
|
166
|
+
splits with omega <= 0.5. Pure noise gives roughly 0.5. Returns ``None``
|
|
167
|
+
with fewer than two trials.
|
|
168
|
+
"""
|
|
169
|
+
m = _finite_array(matrix, "matrix")
|
|
170
|
+
if m.ndim != 2:
|
|
171
|
+
raise StatsError("matrix must be 2-D (periods x trials)")
|
|
172
|
+
t, n = m.shape
|
|
173
|
+
if n < 2:
|
|
174
|
+
return None
|
|
175
|
+
if n_blocks % 2 or n_blocks < 4 or t < 2 * n_blocks:
|
|
176
|
+
raise StatsError("need even n_blocks >= 4 and periods >= 2 * n_blocks")
|
|
177
|
+
blocks = np.array_split(np.arange(t), n_blocks)
|
|
178
|
+
low = total = 0
|
|
179
|
+
for chosen in itertools.combinations(range(n_blocks), n_blocks // 2):
|
|
180
|
+
ins = np.concatenate([blocks[i] for i in chosen])
|
|
181
|
+
oos = np.concatenate([blocks[i] for i in range(n_blocks) if i not in chosen])
|
|
182
|
+
sr_in = m[ins].mean(0) / (m[ins].std(0, ddof=1) + 1e-18)
|
|
183
|
+
sr_out = m[oos].mean(0) / (m[oos].std(0, ddof=1) + 1e-18)
|
|
184
|
+
best = int(np.argmax(sr_in))
|
|
185
|
+
less = int((sr_out < sr_out[best]).sum())
|
|
186
|
+
equal = int((sr_out == sr_out[best]).sum()) # includes the winner itself
|
|
187
|
+
omega = (less + (equal + 1) / 2.0) / (n + 1)
|
|
188
|
+
total += 1
|
|
189
|
+
low += omega <= 0.5
|
|
190
|
+
return low / total
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def wilson(successes, n, z=1.959963984540054):
|
|
194
|
+
"""Wilson score interval ``[low, high]`` for a binomial proportion (95% default)."""
|
|
195
|
+
if n <= 0:
|
|
196
|
+
raise StatsError("n must be positive")
|
|
197
|
+
p = successes / n
|
|
198
|
+
den = 1.0 + z * z / n
|
|
199
|
+
centre = (p + z * z / (2.0 * n)) / den
|
|
200
|
+
half = z * math.sqrt(p * (1.0 - p) / n + z * z / (4.0 * n * n)) / den
|
|
201
|
+
return [max(0.0, centre - half), min(1.0, centre + half)]
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def block_bootstrap(returns, n_resamples=2000, block=5, seed=0,
|
|
205
|
+
loss_threshold=None, periods_per_year=PERIODS_PER_YEAR):
|
|
206
|
+
"""Circular block bootstrap of a return series.
|
|
207
|
+
|
|
208
|
+
Resamples blocks of ``block`` consecutive returns (wrapping around the end)
|
|
209
|
+
to rebuild series of the original length, then summarises the drawdown and
|
|
210
|
+
annualised growth distribution. Block resampling keeps short-range
|
|
211
|
+
autocorrelation that plain resampling would destroy.
|
|
212
|
+
|
|
213
|
+
``loss_threshold`` is optional. When given (a positive fraction such as
|
|
214
|
+
0.05), the result also reports the share of resamples containing at least
|
|
215
|
+
one single-period return <= -loss_threshold, with a Wilson interval.
|
|
216
|
+
"""
|
|
217
|
+
r = _finite_array(returns, "returns")
|
|
218
|
+
t = r.size
|
|
219
|
+
if block < 1 or t < 2 * block or n_resamples < 1:
|
|
220
|
+
raise StatsError("series too short: periods=%d block=%d" % (t, block))
|
|
221
|
+
rng = np.random.default_rng(seed)
|
|
222
|
+
n_blocks = math.ceil(t / block)
|
|
223
|
+
offsets = np.arange(block)
|
|
224
|
+
mdd, growth, hits = [], [], 0
|
|
225
|
+
for _ in range(n_resamples):
|
|
226
|
+
starts = rng.integers(0, t, n_blocks)
|
|
227
|
+
idx = ((starts[:, None] + offsets[None, :]) % t).ravel()[:t]
|
|
228
|
+
x = r[idx]
|
|
229
|
+
eq = np.cumprod(1.0 + x)
|
|
230
|
+
peak = np.maximum.accumulate(np.concatenate([[1.0], eq]))[1:]
|
|
231
|
+
mdd.append((1.0 - eq / peak).max())
|
|
232
|
+
growth.append(eq[-1] ** (periods_per_year / t) - 1.0 if eq[-1] > 0 else -1.0)
|
|
233
|
+
if loss_threshold is not None:
|
|
234
|
+
hits += bool((x <= -float(loss_threshold)).any())
|
|
235
|
+
q = lambda a, p: float(np.quantile(a, p))
|
|
236
|
+
out = {
|
|
237
|
+
"n_resamples": n_resamples, "block": block, "seed": seed, "periods": t,
|
|
238
|
+
"mdd_median": q(mdd, 0.5), "mdd_p95": q(mdd, 0.95),
|
|
239
|
+
"growth_p05": q(growth, 0.05), "growth_median": q(growth, 0.5),
|
|
240
|
+
"loss_threshold": loss_threshold,
|
|
241
|
+
"p_loss_exceeded": None, "p_loss_exceeded_wilson95": None,
|
|
242
|
+
}
|
|
243
|
+
if loss_threshold is not None:
|
|
244
|
+
out["p_loss_exceeded"] = hits / n_resamples
|
|
245
|
+
out["p_loss_exceeded_wilson95"] = wilson(hits, n_resamples)
|
|
246
|
+
return out
|
|
@@ -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
|
+
[](https://github.com/ww7411/oss-backtest-kit/actions/workflows/ci.yml)
|
|
43
|
+
[](https://pypi.org/project/oss-backtest-kit/)
|
|
44
|
+
[](https://pypi.org/project/oss-backtest-kit/)
|
|
45
|
+
[](https://github.com/ww7411/oss-backtest-kit/blob/main/LICENSE)
|
|
46
|
+
[](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
|
+

|
|
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,14 @@
|
|
|
1
|
+
oss_backtest_kit/__init__.py,sha256=PMl-vA8CCgxvZaoj41Drwa76TPGRPsXA_qWzU4Gvh0M,134
|
|
2
|
+
oss_backtest_kit/engine.py,sha256=W9biw6aNHQf05JZ8emvPOYSxlFhsIoBqNCf3x8C_pPg,17140
|
|
3
|
+
oss_backtest_kit/stats.py,sha256=t_rB27fjTAB7OY-vHI60BNi405XEmGvZ3ROnFRHQDgU,9608
|
|
4
|
+
oss_backtest_kit/data/__init__.py,sha256=or1NfJ-UP3goxeOPw2ceEiqeCpdCyKvRlExHgjeNT3M,287
|
|
5
|
+
oss_backtest_kit/data/__main__.py,sha256=iqsL11cVC4jJPc03b9Txaf5L9Mu6R6kQzKkqnXe1nw8,2828
|
|
6
|
+
oss_backtest_kit/data/_http.py,sha256=gMwdJAMJoKELu21rN7Pg0GsqkW-jmEIIlnfKFxGtxgY,5067
|
|
7
|
+
oss_backtest_kit/data/archive.py,sha256=uE4n_qVs1D7YO5934XJKaVec-hEl5EjOg2OCHYlj0BA,10973
|
|
8
|
+
oss_backtest_kit/data/check.py,sha256=My9X8souJva0-wRse74p0y779PvG8hu525wogYNmv7M,4094
|
|
9
|
+
oss_backtest_kit/data/rest_tail.py,sha256=D9TmhcIPJGM1vZrPGirnmo-JrK1ZAkyeYxJtBbm6N7o,6057
|
|
10
|
+
oss_backtest_kit-0.1.0.dist-info/licenses/LICENSE,sha256=Jvwg-MdskI18BTkHn6_JmKhl-EB78Bxx6jkBf7o4zqk,1086
|
|
11
|
+
oss_backtest_kit-0.1.0.dist-info/METADATA,sha256=LxKUTdrl4FVkDjQM3HtZd8voYh20Zr0DD48SLvk8stc,12587
|
|
12
|
+
oss_backtest_kit-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
13
|
+
oss_backtest_kit-0.1.0.dist-info/top_level.txt,sha256=JqzPFjNBynBw7mZ3PATFTzjZ5bKDI0r_mqjr06dKz4U,17
|
|
14
|
+
oss_backtest_kit-0.1.0.dist-info/RECORD,,
|
|
@@ -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 @@
|
|
|
1
|
+
oss_backtest_kit
|