algobacktesting 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.
- algobacktesting/__init__.py +51 -0
- algobacktesting/cv.py +251 -0
- algobacktesting/pbo.py +252 -0
- algobacktesting/py.typed +0 -0
- algobacktesting/sharpe.py +337 -0
- algobacktesting-0.1.0.dist-info/METADATA +204 -0
- algobacktesting-0.1.0.dist-info/RECORD +9 -0
- algobacktesting-0.1.0.dist-info/WHEEL +4 -0
- algobacktesting-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""algobacktesting: tools for telling real trading edges from backtest overfitting.
|
|
2
|
+
|
|
3
|
+
Published by The Market Maker Holdings & Co. Not investment advice.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from algobacktesting.cv import (
|
|
7
|
+
CPCVResult,
|
|
8
|
+
Split,
|
|
9
|
+
combinatorial_purged_cv,
|
|
10
|
+
purged_kfold,
|
|
11
|
+
)
|
|
12
|
+
from algobacktesting.pbo import (
|
|
13
|
+
PBOResult,
|
|
14
|
+
column_sharpe_ratios,
|
|
15
|
+
probability_of_backtest_overfitting,
|
|
16
|
+
)
|
|
17
|
+
from algobacktesting.sharpe import (
|
|
18
|
+
EULER_GAMMA,
|
|
19
|
+
ReturnStats,
|
|
20
|
+
annualize_sharpe,
|
|
21
|
+
deannualize_sharpe,
|
|
22
|
+
deflated_sharpe_ratio,
|
|
23
|
+
expected_max_sharpe,
|
|
24
|
+
min_track_record_length,
|
|
25
|
+
probabilistic_sharpe_ratio,
|
|
26
|
+
return_stats,
|
|
27
|
+
sharpe_ratio,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
__version__ = "0.1.0"
|
|
31
|
+
|
|
32
|
+
__all__ = [
|
|
33
|
+
"EULER_GAMMA",
|
|
34
|
+
"CPCVResult",
|
|
35
|
+
"PBOResult",
|
|
36
|
+
"ReturnStats",
|
|
37
|
+
"Split",
|
|
38
|
+
"__version__",
|
|
39
|
+
"annualize_sharpe",
|
|
40
|
+
"column_sharpe_ratios",
|
|
41
|
+
"combinatorial_purged_cv",
|
|
42
|
+
"deannualize_sharpe",
|
|
43
|
+
"deflated_sharpe_ratio",
|
|
44
|
+
"expected_max_sharpe",
|
|
45
|
+
"min_track_record_length",
|
|
46
|
+
"probabilistic_sharpe_ratio",
|
|
47
|
+
"probability_of_backtest_overfitting",
|
|
48
|
+
"purged_kfold",
|
|
49
|
+
"return_stats",
|
|
50
|
+
"sharpe_ratio",
|
|
51
|
+
]
|
algobacktesting/cv.py
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
"""Leak-free cross-validation for financial labels: purged k-fold and CPCV.
|
|
2
|
+
|
|
3
|
+
In finance a label usually spans time. A trade opened on Monday may be labelled by what
|
|
4
|
+
happens up to Friday. If a training observation's label overlaps the test period, the
|
|
5
|
+
model has seen test-period information, and the cross-validated score is too good. Two
|
|
6
|
+
fixes:
|
|
7
|
+
|
|
8
|
+
* **Purging:** drop every training observation whose label interval overlaps a test
|
|
9
|
+
block. Labels are compared by their *start and end* times, not just their start.
|
|
10
|
+
* **Embargo:** after each test block, also drop a few training observations that come
|
|
11
|
+
right after it. Serially correlated features can still carry test-period information
|
|
12
|
+
forward. The embargo applies only *after* a test block, never before.
|
|
13
|
+
|
|
14
|
+
**Combinatorial purged cross-validation (CPCV)** splits the data into N groups and uses
|
|
15
|
+
every choice of k groups as the test set. The test groups' out-of-sample predictions can
|
|
16
|
+
then be stitched into C(N-1, k-1) complete backtest paths instead of one.
|
|
17
|
+
|
|
18
|
+
.. warning::
|
|
19
|
+
**Not verified against a primary source.** These follow the standard definitions in
|
|
20
|
+
López de Prado (2018), *Advances in Financial Machine Learning*, Chapters 7 (purged
|
|
21
|
+
k-fold, embargo) and 12 (CPCV). The book was not available when this was written, so
|
|
22
|
+
the implementation is built from those definitions and checked against a brute-force
|
|
23
|
+
reference, not against the book's code. It needs review against AFML before being
|
|
24
|
+
relied on.
|
|
25
|
+
|
|
26
|
+
Partial check (2026-11): a secondary reproduction of AFML Snippet 7.3 (``PurgedKFold``)
|
|
27
|
+
was compared rule by rule and in a 200-case randomized test. On tie-free timestamps the
|
|
28
|
+
training sets are identical. The only difference is at exactly touching labels, which
|
|
29
|
+
the snippet keeps and this module purges. With zero-length labels the snippet's rules
|
|
30
|
+
can place test rows in the training set; closed intervals prevent that.
|
|
31
|
+
|
|
32
|
+
Conventions (deliberate, documented):
|
|
33
|
+
|
|
34
|
+
* Label intervals are **closed**: [start, end]. Two labels overlap if they share any
|
|
35
|
+
instant, including an end that equals another's start. This is the conservative
|
|
36
|
+
choice: it purges slightly more.
|
|
37
|
+
* Purging around one contiguous test block uses that block's **span**: from the first
|
|
38
|
+
test label's start to the latest test label's end. Separate (non-adjacent) test blocks
|
|
39
|
+
in CPCV are purged and embargoed **separately**, never as one span from the first block
|
|
40
|
+
to the last.
|
|
41
|
+
* The embargo is a number of observations: ``floor(embargo * n_observations)``. It is
|
|
42
|
+
counted from the first observation after the test block that survives purging.
|
|
43
|
+
* Groups and folds are contiguous runs of observations, sized with ``numpy.array_split``
|
|
44
|
+
(sizes differ by at most one).
|
|
45
|
+
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
from __future__ import annotations
|
|
49
|
+
|
|
50
|
+
import itertools
|
|
51
|
+
import math
|
|
52
|
+
from collections.abc import Sequence
|
|
53
|
+
from dataclasses import dataclass
|
|
54
|
+
from typing import Any, NamedTuple
|
|
55
|
+
|
|
56
|
+
import numpy as np
|
|
57
|
+
from numpy.typing import ArrayLike, NDArray
|
|
58
|
+
|
|
59
|
+
__all__ = [
|
|
60
|
+
"CPCVResult",
|
|
61
|
+
"Split",
|
|
62
|
+
"combinatorial_purged_cv",
|
|
63
|
+
"purged_kfold",
|
|
64
|
+
]
|
|
65
|
+
|
|
66
|
+
IntArray = NDArray[np.int64]
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class Split(NamedTuple):
|
|
70
|
+
"""Row indices for one train/test split (both sorted ascending)."""
|
|
71
|
+
|
|
72
|
+
train: IntArray
|
|
73
|
+
test: IntArray
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@dataclass(frozen=True)
|
|
77
|
+
class CPCVResult:
|
|
78
|
+
"""Output of :func:`combinatorial_purged_cv`.
|
|
79
|
+
|
|
80
|
+
Attributes:
|
|
81
|
+
splits: One :class:`Split` per combination of test groups, in the order of
|
|
82
|
+
``test_groups``.
|
|
83
|
+
test_groups: The k group numbers used as the test set in each split.
|
|
84
|
+
groups: Row indices belonging to each of the N groups.
|
|
85
|
+
paths: Array of shape (n_paths, N). ``paths[p, g]`` is the index (into ``splits``)
|
|
86
|
+
of the split whose out-of-sample predictions fill group ``g`` in backtest
|
|
87
|
+
path ``p``. Every group appears exactly once per path, and every
|
|
88
|
+
(split, test group) pair is used by exactly one path.
|
|
89
|
+
|
|
90
|
+
"""
|
|
91
|
+
|
|
92
|
+
splits: list[Split]
|
|
93
|
+
test_groups: list[tuple[int, ...]]
|
|
94
|
+
groups: list[IntArray]
|
|
95
|
+
paths: IntArray
|
|
96
|
+
|
|
97
|
+
@property
|
|
98
|
+
def n_paths(self) -> int:
|
|
99
|
+
"""Number of complete backtest paths, C(N - 1, k - 1)."""
|
|
100
|
+
return int(self.paths.shape[0])
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _intervals(label_starts: ArrayLike, label_ends: ArrayLike) -> tuple[NDArray[Any], NDArray[Any]]:
|
|
104
|
+
starts = np.asarray(label_starts)
|
|
105
|
+
ends = np.asarray(label_ends)
|
|
106
|
+
if starts.ndim != 1 or ends.ndim != 1:
|
|
107
|
+
raise ValueError("label_starts and label_ends must be 1-D")
|
|
108
|
+
if starts.shape != ends.shape:
|
|
109
|
+
raise ValueError(
|
|
110
|
+
f"label_starts and label_ends differ in length: {starts.size} vs {ends.size}"
|
|
111
|
+
)
|
|
112
|
+
if starts.size < 2:
|
|
113
|
+
raise ValueError("need at least 2 observations")
|
|
114
|
+
if starts.dtype.kind in "fc" and not (
|
|
115
|
+
np.all(np.isfinite(starts)) and np.all(np.isfinite(ends))
|
|
116
|
+
):
|
|
117
|
+
raise ValueError("label times contain NaN or infinite values")
|
|
118
|
+
if starts.dtype.kind == "M" and (np.any(np.isnat(starts)) or np.any(np.isnat(ends))):
|
|
119
|
+
raise ValueError("label times contain NaT")
|
|
120
|
+
if np.any(starts[1:] < starts[:-1]):
|
|
121
|
+
raise ValueError("observations must be sorted by label start time")
|
|
122
|
+
if np.any(ends < starts):
|
|
123
|
+
raise ValueError("every label must end at or after it starts")
|
|
124
|
+
return starts, ends
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _embargo_size(embargo: float, n: int) -> int:
|
|
128
|
+
if not (math.isfinite(embargo) and 0.0 <= embargo < 1.0):
|
|
129
|
+
raise ValueError("embargo must be a fraction in [0, 1)")
|
|
130
|
+
return int(embargo * n)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _train_mask(
|
|
134
|
+
starts: NDArray[Any],
|
|
135
|
+
ends: NDArray[Any],
|
|
136
|
+
test_blocks: Sequence[IntArray],
|
|
137
|
+
embargo_obs: int,
|
|
138
|
+
) -> NDArray[np.bool_]:
|
|
139
|
+
"""Rows usable for training, given contiguous test blocks (each purged separately)."""
|
|
140
|
+
n = starts.size
|
|
141
|
+
keep = np.ones(n, dtype=bool)
|
|
142
|
+
for block in test_blocks:
|
|
143
|
+
keep[block] = False
|
|
144
|
+
block_start = starts[block[0]]
|
|
145
|
+
block_end = np.max(ends[block])
|
|
146
|
+
# Purge: closed-interval overlap with [block_start, block_end].
|
|
147
|
+
keep &= ~((starts <= block_end) & (ends >= block_start))
|
|
148
|
+
# Embargo: the next `embargo_obs` rows after the block that survived purging.
|
|
149
|
+
after = np.flatnonzero((np.arange(n) > block[-1]) & (starts > block_end))
|
|
150
|
+
keep[after[:embargo_obs]] = False
|
|
151
|
+
return keep
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _contiguous_blocks(indices: IntArray) -> list[IntArray]:
|
|
155
|
+
"""Split sorted row indices into runs of consecutive integers."""
|
|
156
|
+
breaks = np.flatnonzero(np.diff(indices) != 1) + 1
|
|
157
|
+
return [b for b in np.split(indices, breaks) if b.size]
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def purged_kfold(
|
|
161
|
+
label_starts: ArrayLike,
|
|
162
|
+
label_ends: ArrayLike,
|
|
163
|
+
n_splits: int = 5,
|
|
164
|
+
*,
|
|
165
|
+
embargo: float = 0.0,
|
|
166
|
+
) -> list[Split]:
|
|
167
|
+
"""Return k-fold splits with purging and embargo (AFML Ch. 7, from the definitions).
|
|
168
|
+
|
|
169
|
+
Folds are contiguous and are not shuffled. For each fold used as the test set, the
|
|
170
|
+
training set is every other observation, minus those whose label overlaps the test
|
|
171
|
+
fold (purging), minus the ``embargo`` share of observations right after it.
|
|
172
|
+
|
|
173
|
+
Args:
|
|
174
|
+
label_starts: Start time of each observation's label (e.g. the event time), sorted
|
|
175
|
+
ascending. Numbers or ``numpy.datetime64``.
|
|
176
|
+
label_ends: End time of each label (e.g. when a barrier was touched). Same type.
|
|
177
|
+
n_splits: Number of folds k (at least 2).
|
|
178
|
+
embargo: Share of all observations to drop after each test fold, in [0, 1).
|
|
179
|
+
AFML suggests about 0.01.
|
|
180
|
+
|
|
181
|
+
Returns:
|
|
182
|
+
A list of :class:`Split` (train and test row indices), one per fold, in time order.
|
|
183
|
+
|
|
184
|
+
>>> s = purged_kfold([0, 1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 6], n_splits=3)
|
|
185
|
+
>>> s[1].test.tolist(), s[1].train.tolist() # test rows 2-3; rows 1 and 4 overlap
|
|
186
|
+
([2, 3], [0, 5])
|
|
187
|
+
|
|
188
|
+
"""
|
|
189
|
+
starts, ends = _intervals(label_starts, label_ends)
|
|
190
|
+
n = starts.size
|
|
191
|
+
if not 2 <= n_splits <= n:
|
|
192
|
+
raise ValueError(f"n_splits must be between 2 and the number of observations ({n})")
|
|
193
|
+
h = _embargo_size(embargo, n)
|
|
194
|
+
folds = np.array_split(np.arange(n, dtype=np.int64), n_splits)
|
|
195
|
+
splits = []
|
|
196
|
+
for fold in folds:
|
|
197
|
+
keep = _train_mask(starts, ends, [fold], h)
|
|
198
|
+
splits.append(Split(train=np.flatnonzero(keep).astype(np.int64), test=fold))
|
|
199
|
+
return splits
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def combinatorial_purged_cv(
|
|
203
|
+
label_starts: ArrayLike,
|
|
204
|
+
label_ends: ArrayLike,
|
|
205
|
+
n_groups: int = 6,
|
|
206
|
+
n_test_groups: int = 2,
|
|
207
|
+
*,
|
|
208
|
+
embargo: float = 0.0,
|
|
209
|
+
) -> CPCVResult:
|
|
210
|
+
"""Return combinatorial purged CV splits and backtest paths (AFML Ch. 12, from definitions).
|
|
211
|
+
|
|
212
|
+
The observations are cut into ``n_groups`` (N) contiguous groups. Every choice of
|
|
213
|
+
``n_test_groups`` (k) groups is a test set, giving C(N, k) splits. Adjacent test
|
|
214
|
+
groups merge into one block; each separate test block is purged and embargoed on its
|
|
215
|
+
own. The splits' test predictions combine into C(N - 1, k - 1) backtest paths.
|
|
216
|
+
|
|
217
|
+
Args:
|
|
218
|
+
label_starts: Start time of each label, sorted ascending.
|
|
219
|
+
label_ends: End time of each label.
|
|
220
|
+
n_groups: N, the number of groups (at least 2).
|
|
221
|
+
n_test_groups: k, groups per test set (1 <= k < N).
|
|
222
|
+
embargo: Share of all observations to drop after each test block, in [0, 1).
|
|
223
|
+
|
|
224
|
+
>>> r = combinatorial_purged_cv(list(range(12)), list(range(12)), n_groups=6, n_test_groups=2)
|
|
225
|
+
>>> len(r.splits), r.n_paths # C(6, 2) = 15 splits, C(5, 1) = 5 paths
|
|
226
|
+
(15, 5)
|
|
227
|
+
|
|
228
|
+
"""
|
|
229
|
+
starts, ends = _intervals(label_starts, label_ends)
|
|
230
|
+
n = starts.size
|
|
231
|
+
if not 2 <= n_groups <= n:
|
|
232
|
+
raise ValueError(f"n_groups must be between 2 and the number of observations ({n})")
|
|
233
|
+
if not 1 <= n_test_groups < n_groups:
|
|
234
|
+
raise ValueError("n_test_groups must be at least 1 and less than n_groups")
|
|
235
|
+
h = _embargo_size(embargo, n)
|
|
236
|
+
groups = [g.astype(np.int64) for g in np.array_split(np.arange(n), n_groups)]
|
|
237
|
+
|
|
238
|
+
test_groups = list(itertools.combinations(range(n_groups), n_test_groups))
|
|
239
|
+
splits = []
|
|
240
|
+
for chosen in test_groups:
|
|
241
|
+
test = np.concatenate([groups[g] for g in chosen])
|
|
242
|
+
keep = _train_mask(starts, ends, _contiguous_blocks(test), h)
|
|
243
|
+
splits.append(Split(train=np.flatnonzero(keep).astype(np.int64), test=test))
|
|
244
|
+
|
|
245
|
+
# Path p takes, for each group g, the p-th split (in order) that tests g.
|
|
246
|
+
n_paths = math.comb(n_groups - 1, n_test_groups - 1)
|
|
247
|
+
paths = np.empty((n_paths, n_groups), dtype=np.int64)
|
|
248
|
+
for g in range(n_groups):
|
|
249
|
+
testing_g = [i for i, chosen in enumerate(test_groups) if g in chosen]
|
|
250
|
+
paths[:, g] = testing_g
|
|
251
|
+
return CPCVResult(splits=splits, test_groups=test_groups, groups=groups, paths=paths)
|
algobacktesting/pbo.py
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
"""Probability of Backtest Overfitting (PBO) via combinatorially symmetric cross-validation.
|
|
2
|
+
|
|
3
|
+
You tried N strategy configurations and kept the one with the best backtest. PBO estimates
|
|
4
|
+
how often that selection procedure picks a configuration that then performs *below the
|
|
5
|
+
median* of the N configurations out of sample. A PBO near 0 means the selection procedure
|
|
6
|
+
generalizes; near 0.5 or above means it is mostly picking noise.
|
|
7
|
+
|
|
8
|
+
Reference
|
|
9
|
+
---------
|
|
10
|
+
[BBLZ] Bailey, D. H., Borwein, J. M., López de Prado, M. and Zhu, Q. J. (2017). "The
|
|
11
|
+
Probability of Backtest Overfitting." *Journal of Computational Finance* 20(4).
|
|
12
|
+
SSRN 2326253 (revised February 2015). Algorithm 2.3 (CSCV), pp. 11-12; Section 3,
|
|
13
|
+
pp. 13-14.
|
|
14
|
+
|
|
15
|
+
Implementation choices the paper leaves open (documented, deliberate):
|
|
16
|
+
|
|
17
|
+
* PBO is the share of combinations whose logit is <= 0, the paper's estimator
|
|
18
|
+
phi = integral of f(lambda) from -inf to 0 (Section 3.1). Definition 2.2 states a strict
|
|
19
|
+
"rank < N/2"; the two differ only when the selected strategy lands exactly on the median.
|
|
20
|
+
Consequence worth knowing: with an **odd** number of strategies N, the exact median rank
|
|
21
|
+
counts as overfit, so pure noise gives PBO = ((N + 1) / 2) / N on average instead of
|
|
22
|
+
0.5. That is 2/3 for N = 3 and 0.6 for N = 5, but negligible for large N. For even N it
|
|
23
|
+
is exactly 0.5. Identical strategies all tie at the median, giving PBO = 1.
|
|
24
|
+
* Ranks are ascending (rank N = best), as in the paper's example on p. 9. Ties in a
|
|
25
|
+
ranking get the average of the tied ranks. If several strategies tie for best in
|
|
26
|
+
sample, the first column is selected.
|
|
27
|
+
* The rows must split into S blocks of exactly equal length, as the paper requires;
|
|
28
|
+
otherwise a ``ValueError`` asks you to trim the series.
|
|
29
|
+
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
from __future__ import annotations
|
|
33
|
+
|
|
34
|
+
import itertools
|
|
35
|
+
import math
|
|
36
|
+
from collections.abc import Callable
|
|
37
|
+
from dataclasses import dataclass
|
|
38
|
+
from typing import TypeAlias
|
|
39
|
+
|
|
40
|
+
import numpy as np
|
|
41
|
+
from numpy.typing import ArrayLike, NDArray
|
|
42
|
+
|
|
43
|
+
__all__ = [
|
|
44
|
+
"PBOResult",
|
|
45
|
+
"average_ranks",
|
|
46
|
+
"column_sharpe_ratios",
|
|
47
|
+
"probability_of_backtest_overfitting",
|
|
48
|
+
]
|
|
49
|
+
|
|
50
|
+
Metric: TypeAlias = Callable[[NDArray[np.float64]], NDArray[np.float64]]
|
|
51
|
+
|
|
52
|
+
MAX_COMBINATIONS = 1_000_000 # C(22, 11) = 705,432 fits; C(24, 12) = 2,704,156 does not
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass(frozen=True)
|
|
56
|
+
class PBOResult:
|
|
57
|
+
"""Output of :func:`probability_of_backtest_overfitting`.
|
|
58
|
+
|
|
59
|
+
All arrays have one entry per train/test combination, in the same order.
|
|
60
|
+
|
|
61
|
+
Attributes:
|
|
62
|
+
pbo: Probability of backtest overfitting: share of combinations whose logit <= 0.
|
|
63
|
+
logits: lambda_c = ln(w_c / (1 - w_c)) for each combination.
|
|
64
|
+
relative_ranks: w_c = OOS rank of the in-sample winner / (N + 1), in (0, 1).
|
|
65
|
+
is_performance: In-sample performance of the in-sample winner.
|
|
66
|
+
oos_performance: Out-of-sample performance of that same strategy.
|
|
67
|
+
degradation_slope: OLS slope of ``oos_performance`` on ``is_performance``
|
|
68
|
+
([BBLZ] Section 3.2). Negative means better IS results foretell worse OOS
|
|
69
|
+
results. NaN if in-sample performance never varies.
|
|
70
|
+
degradation_intercept: OLS intercept of that regression (NaN likewise).
|
|
71
|
+
prob_oos_loss: Share of combinations where the in-sample winner has negative
|
|
72
|
+
out-of-sample performance ([BBLZ] Section 3.2).
|
|
73
|
+
n_partitions: S, the number of row blocks.
|
|
74
|
+
n_strategies: N, the number of strategy columns.
|
|
75
|
+
n_combinations: C(S, S/2), the number of train/test splits evaluated.
|
|
76
|
+
|
|
77
|
+
"""
|
|
78
|
+
|
|
79
|
+
pbo: float
|
|
80
|
+
logits: NDArray[np.float64]
|
|
81
|
+
relative_ranks: NDArray[np.float64]
|
|
82
|
+
is_performance: NDArray[np.float64]
|
|
83
|
+
oos_performance: NDArray[np.float64]
|
|
84
|
+
degradation_slope: float
|
|
85
|
+
degradation_intercept: float
|
|
86
|
+
prob_oos_loss: float
|
|
87
|
+
n_partitions: int
|
|
88
|
+
n_strategies: int
|
|
89
|
+
n_combinations: int
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def column_sharpe_ratios(returns: NDArray[np.float64]) -> NDArray[np.float64]:
|
|
93
|
+
"""Return the per-period Sharpe ratio of each column (mean / std with ddof=1).
|
|
94
|
+
|
|
95
|
+
This is the default performance metric for
|
|
96
|
+
:func:`probability_of_backtest_overfitting`.
|
|
97
|
+
"""
|
|
98
|
+
return np.asarray(returns.mean(axis=0) / returns.std(axis=0, ddof=1), dtype=np.float64)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def average_ranks(values: NDArray[np.float64]) -> NDArray[np.float64]:
|
|
102
|
+
"""Rank values ascending from 1 to N; tied values share the average of their ranks.
|
|
103
|
+
|
|
104
|
+
>>> average_ranks(np.array([0.5, 1.1, 0.7])) # [BBLZ] p. 9 example
|
|
105
|
+
array([1., 3., 2.])
|
|
106
|
+
|
|
107
|
+
"""
|
|
108
|
+
_, inverse, counts = np.unique(values, return_inverse=True, return_counts=True)
|
|
109
|
+
below = np.cumsum(counts) - counts # how many values are strictly smaller
|
|
110
|
+
return np.asarray((below + (counts + 1) / 2.0)[inverse], dtype=np.float64)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _validate(matrix: NDArray[np.float64], n_partitions: int) -> None:
|
|
114
|
+
if matrix.ndim != 2:
|
|
115
|
+
raise ValueError("returns must be a 2-D array: rows = time, columns = strategies")
|
|
116
|
+
t, n = matrix.shape
|
|
117
|
+
if n < 2:
|
|
118
|
+
raise ValueError("need at least 2 strategy columns to rank")
|
|
119
|
+
if n_partitions < 2 or n_partitions % 2:
|
|
120
|
+
raise ValueError("n_partitions (S) must be an even number >= 2")
|
|
121
|
+
n_combinations = math.comb(n_partitions, n_partitions // 2)
|
|
122
|
+
if n_combinations > MAX_COMBINATIONS:
|
|
123
|
+
raise ValueError(
|
|
124
|
+
f"n_partitions={n_partitions} means {n_combinations:,} train/test splits "
|
|
125
|
+
f"(limit {MAX_COMBINATIONS:,}); use S <= 22. The paper's example uses S = 16"
|
|
126
|
+
)
|
|
127
|
+
if t % n_partitions:
|
|
128
|
+
raise ValueError(
|
|
129
|
+
f"{t} rows do not split into {n_partitions} equal blocks; "
|
|
130
|
+
f"trim {t % n_partitions} row(s) from the start or end of the series"
|
|
131
|
+
)
|
|
132
|
+
if t // 2 < 2:
|
|
133
|
+
raise ValueError("each half of the sample needs at least 2 rows")
|
|
134
|
+
if not np.all(np.isfinite(matrix)):
|
|
135
|
+
raise ValueError("returns contain NaN or infinite values")
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def probability_of_backtest_overfitting(
|
|
139
|
+
returns: ArrayLike,
|
|
140
|
+
n_partitions: int = 16,
|
|
141
|
+
*,
|
|
142
|
+
metric: Metric | None = None,
|
|
143
|
+
) -> PBOResult:
|
|
144
|
+
"""Estimate the probability of backtest overfitting with CSCV ([BBLZ] Algorithm 2.3).
|
|
145
|
+
|
|
146
|
+
The rows of ``returns`` are split into ``n_partitions`` (S) equal, consecutive blocks.
|
|
147
|
+
For every way of choosing S/2 blocks as the training set (and the other S/2 as the
|
|
148
|
+
test set), the strategy with the best in-sample performance is found, and its
|
|
149
|
+
out-of-sample rank among all N strategies is recorded. Blocks are joined in their
|
|
150
|
+
original time order on both sides.
|
|
151
|
+
|
|
152
|
+
Args:
|
|
153
|
+
returns: Matrix of shape (T, N): T synchronized observations (rows, oldest first)
|
|
154
|
+
of N strategy configurations (columns), e.g. daily P&L or returns.
|
|
155
|
+
n_partitions: S, an even number of equal row blocks. The number of combinations
|
|
156
|
+
evaluated is C(S, S/2), e.g. 12,870 for S = 16.
|
|
157
|
+
metric: Function mapping a (rows, N) array to N performance numbers, higher is
|
|
158
|
+
better. Defaults to :func:`column_sharpe_ratios`. Order-dependent metrics
|
|
159
|
+
(e.g. drawdown-based) receive the rows in time order.
|
|
160
|
+
|
|
161
|
+
Returns:
|
|
162
|
+
A :class:`PBOResult`.
|
|
163
|
+
|
|
164
|
+
Raises:
|
|
165
|
+
ValueError: Bad shape, odd or too small S, rows not divisible by S, non-finite
|
|
166
|
+
input, or a performance value that is NaN or infinite.
|
|
167
|
+
|
|
168
|
+
"""
|
|
169
|
+
matrix = np.asarray(returns, dtype=np.float64)
|
|
170
|
+
_validate(matrix, n_partitions)
|
|
171
|
+
t, n = matrix.shape
|
|
172
|
+
s = n_partitions
|
|
173
|
+
blocks = matrix.reshape(s, t // s, n) # consecutive blocks, time order preserved
|
|
174
|
+
|
|
175
|
+
if metric is None:
|
|
176
|
+
evaluate = _block_sharpe_evaluator(blocks)
|
|
177
|
+
else:
|
|
178
|
+
user_metric = metric
|
|
179
|
+
|
|
180
|
+
def evaluate(chosen: tuple[int, ...]) -> NDArray[np.float64]:
|
|
181
|
+
rows = blocks[list(chosen)].reshape(-1, n) # chosen is sorted: time order
|
|
182
|
+
return np.asarray(user_metric(rows), dtype=np.float64)
|
|
183
|
+
|
|
184
|
+
combos = list(itertools.combinations(range(s), s // 2))
|
|
185
|
+
is_perf = np.empty(len(combos))
|
|
186
|
+
oos_perf = np.empty(len(combos))
|
|
187
|
+
omega = np.empty(len(combos))
|
|
188
|
+
all_blocks = frozenset(range(s))
|
|
189
|
+
|
|
190
|
+
for i, train in enumerate(combos):
|
|
191
|
+
test = tuple(sorted(all_blocks.difference(train)))
|
|
192
|
+
r_is, r_oos = evaluate(train), evaluate(test)
|
|
193
|
+
for label, values in (("in-sample", r_is), ("out-of-sample", r_oos)):
|
|
194
|
+
if values.shape != (n,) or not np.all(np.isfinite(values)):
|
|
195
|
+
raise ValueError(
|
|
196
|
+
f"{label} performance must be {n} finite numbers; got {values!r}. "
|
|
197
|
+
"A strategy may have zero variance within a block selection."
|
|
198
|
+
)
|
|
199
|
+
best = int(np.argmax(r_is)) # first column wins an in-sample tie
|
|
200
|
+
is_perf[i] = r_is[best]
|
|
201
|
+
oos_perf[i] = r_oos[best]
|
|
202
|
+
omega[i] = average_ranks(r_oos)[best] / (n + 1)
|
|
203
|
+
|
|
204
|
+
logits = np.log(omega / (1.0 - omega))
|
|
205
|
+
slope, intercept = _ols(is_perf, oos_perf)
|
|
206
|
+
return PBOResult(
|
|
207
|
+
pbo=float(np.mean(logits <= 0.0)),
|
|
208
|
+
logits=logits,
|
|
209
|
+
relative_ranks=omega,
|
|
210
|
+
is_performance=is_perf,
|
|
211
|
+
oos_performance=oos_perf,
|
|
212
|
+
degradation_slope=slope,
|
|
213
|
+
degradation_intercept=intercept,
|
|
214
|
+
prob_oos_loss=float(np.mean(oos_perf < 0.0)),
|
|
215
|
+
n_partitions=s,
|
|
216
|
+
n_strategies=n,
|
|
217
|
+
n_combinations=len(combos),
|
|
218
|
+
)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _block_sharpe_evaluator(
|
|
222
|
+
blocks: NDArray[np.float64],
|
|
223
|
+
) -> Callable[[tuple[int, ...]], NDArray[np.float64]]:
|
|
224
|
+
"""Fast exact column Sharpe ratios for any union of blocks, from per-block sums.
|
|
225
|
+
|
|
226
|
+
Data are centred on each column's overall mean first, so the sums of squares stay well
|
|
227
|
+
conditioned. The result equals ``column_sharpe_ratios`` on the joined rows.
|
|
228
|
+
"""
|
|
229
|
+
shift = blocks.mean(axis=(0, 1))
|
|
230
|
+
centred = blocks - shift
|
|
231
|
+
sums = centred.sum(axis=1) # (S, N)
|
|
232
|
+
squares = (centred**2).sum(axis=1) # (S, N)
|
|
233
|
+
rows_per_block = blocks.shape[1]
|
|
234
|
+
|
|
235
|
+
def evaluate(chosen: tuple[int, ...]) -> NDArray[np.float64]:
|
|
236
|
+
idx = list(chosen)
|
|
237
|
+
count = rows_per_block * len(idx)
|
|
238
|
+
mean_c = sums[idx].sum(axis=0) / count
|
|
239
|
+
var = (squares[idx].sum(axis=0) - count * mean_c**2) / (count - 1)
|
|
240
|
+
with np.errstate(divide="ignore", invalid="ignore"):
|
|
241
|
+
return np.asarray((mean_c + shift) / np.sqrt(var), dtype=np.float64)
|
|
242
|
+
|
|
243
|
+
return evaluate
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _ols(x: NDArray[np.float64], y: NDArray[np.float64]) -> tuple[float, float]:
|
|
247
|
+
"""Return (slope, intercept) of y on x, or NaNs if x has no variation."""
|
|
248
|
+
x_var = float(np.var(x))
|
|
249
|
+
if x_var == 0.0 or math.isclose(x_var, 0.0, abs_tol=1e-300):
|
|
250
|
+
return math.nan, math.nan
|
|
251
|
+
slope = float(np.mean((x - x.mean()) * (y - y.mean())) / x_var)
|
|
252
|
+
return slope, float(y.mean() - slope * x.mean())
|
algobacktesting/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
"""Is a Sharpe ratio statistically real? Probabilistic and Deflated Sharpe Ratios.
|
|
2
|
+
|
|
3
|
+
Every Sharpe ratio in this module is **per period** (not annualized): if you have daily
|
|
4
|
+
returns, pass the daily Sharpe ratio and the number of daily observations. Use
|
|
5
|
+
:func:`deannualize_sharpe` to convert an annual figure. The variance of trial Sharpe
|
|
6
|
+
ratios passed to :func:`expected_max_sharpe` and :func:`deflated_sharpe_ratio` must be in
|
|
7
|
+
the same per-period units.
|
|
8
|
+
|
|
9
|
+
Kurtosis is the raw (non-excess) kurtosis, so a Normal distribution has kurtosis 3.
|
|
10
|
+
|
|
11
|
+
References
|
|
12
|
+
----------
|
|
13
|
+
[BLdP2012] Bailey, D. H. and López de Prado, M. (2012). "The Sharpe Ratio Efficient
|
|
14
|
+
Frontier." *Journal of Risk* 15(2). SSRN 1821643.
|
|
15
|
+
|
|
16
|
+
[BLdP2014] Bailey, D. H. and López de Prado, M. (2014). "The Deflated Sharpe Ratio:
|
|
17
|
+
Correcting for Selection Bias, Backtest Overfitting and Non-Normality." *Journal of
|
|
18
|
+
Portfolio Management* 40(5). SSRN 2460551.
|
|
19
|
+
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import math
|
|
25
|
+
from dataclasses import dataclass
|
|
26
|
+
from statistics import NormalDist
|
|
27
|
+
|
|
28
|
+
import numpy as np
|
|
29
|
+
from numpy.typing import ArrayLike
|
|
30
|
+
|
|
31
|
+
__all__ = [
|
|
32
|
+
"EULER_GAMMA",
|
|
33
|
+
"ReturnStats",
|
|
34
|
+
"annualize_sharpe",
|
|
35
|
+
"deannualize_sharpe",
|
|
36
|
+
"deflated_sharpe_ratio",
|
|
37
|
+
"expected_max_sharpe",
|
|
38
|
+
"min_track_record_length",
|
|
39
|
+
"probabilistic_sharpe_ratio",
|
|
40
|
+
"return_stats",
|
|
41
|
+
"sharpe_ratio",
|
|
42
|
+
]
|
|
43
|
+
|
|
44
|
+
EULER_GAMMA = 0.5772156649015329
|
|
45
|
+
_NORMAL = NormalDist()
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass(frozen=True)
|
|
49
|
+
class ReturnStats:
|
|
50
|
+
"""Moments of a return series needed to judge its Sharpe ratio.
|
|
51
|
+
|
|
52
|
+
Attributes:
|
|
53
|
+
sharpe: Per-period Sharpe ratio, mean / sample standard deviation (ddof=1).
|
|
54
|
+
n_obs: Number of return observations.
|
|
55
|
+
skew: Sample skewness, m3 / m2**1.5 with population central moments
|
|
56
|
+
(0 for a symmetric distribution).
|
|
57
|
+
kurtosis: Sample raw kurtosis, m4 / m2**2 with population central moments
|
|
58
|
+
(3 for a Normal distribution).
|
|
59
|
+
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
sharpe: float
|
|
63
|
+
n_obs: int
|
|
64
|
+
skew: float
|
|
65
|
+
kurtosis: float
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def return_stats(returns: ArrayLike) -> ReturnStats:
|
|
69
|
+
"""Compute the Sharpe ratio, length, skewness and kurtosis of a return series.
|
|
70
|
+
|
|
71
|
+
Args:
|
|
72
|
+
returns: Per-period returns (e.g. daily), in excess of the risk-free rate if
|
|
73
|
+
relevant.
|
|
74
|
+
|
|
75
|
+
Raises:
|
|
76
|
+
ValueError: Fewer than 2 observations, non-finite values, or zero variance.
|
|
77
|
+
|
|
78
|
+
>>> s = return_stats([1.0, 2.0, 3.0, 4.0, 5.0])
|
|
79
|
+
>>> round(s.sharpe, 4), s.n_obs, round(s.skew, 4), round(s.kurtosis, 4)
|
|
80
|
+
(1.8974, 5, 0.0, 1.7)
|
|
81
|
+
|
|
82
|
+
"""
|
|
83
|
+
x = np.asarray(returns, dtype=float)
|
|
84
|
+
if x.ndim != 1:
|
|
85
|
+
raise ValueError(
|
|
86
|
+
f"returns must be a single 1-D series, got shape {x.shape}; "
|
|
87
|
+
"for several strategies, call this once per column"
|
|
88
|
+
)
|
|
89
|
+
if x.size < 2:
|
|
90
|
+
raise ValueError("need at least 2 returns")
|
|
91
|
+
if not np.all(np.isfinite(x)):
|
|
92
|
+
raise ValueError("returns contain NaN or infinite values")
|
|
93
|
+
n = x.size
|
|
94
|
+
dev = x - x.mean()
|
|
95
|
+
m2 = float(np.mean(dev**2))
|
|
96
|
+
if m2 == 0.0:
|
|
97
|
+
raise ValueError("returns have zero variance; the Sharpe ratio is undefined")
|
|
98
|
+
std = math.sqrt(m2 * n / (n - 1))
|
|
99
|
+
return ReturnStats(
|
|
100
|
+
sharpe=float(x.mean()) / std,
|
|
101
|
+
n_obs=n,
|
|
102
|
+
skew=float(np.mean(dev**3)) / m2**1.5,
|
|
103
|
+
kurtosis=float(np.mean(dev**4)) / m2**2,
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def sharpe_ratio(returns: ArrayLike) -> float:
|
|
108
|
+
"""Return the per-period Sharpe ratio: mean / sample standard deviation (ddof=1)."""
|
|
109
|
+
return return_stats(returns).sharpe
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def annualize_sharpe(sharpe: float, periods_per_year: float) -> float:
|
|
113
|
+
"""Scale a per-period Sharpe ratio to annual, assuming i.i.d. returns.
|
|
114
|
+
|
|
115
|
+
>>> round(annualize_sharpe(0.4576, 12), 3) # [BLdP2012] Figure 6: monthly -> 1.585
|
|
116
|
+
1.585
|
|
117
|
+
|
|
118
|
+
"""
|
|
119
|
+
_require_finite(sharpe=sharpe)
|
|
120
|
+
_require_positive_periods(periods_per_year)
|
|
121
|
+
return sharpe * math.sqrt(periods_per_year)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def deannualize_sharpe(annual_sharpe: float, periods_per_year: float) -> float:
|
|
125
|
+
"""Convert an annual Sharpe ratio to per-period, assuming i.i.d. returns.
|
|
126
|
+
|
|
127
|
+
>>> round(deannualize_sharpe(2.5, 250), 4)
|
|
128
|
+
0.1581
|
|
129
|
+
|
|
130
|
+
"""
|
|
131
|
+
_require_finite(annual_sharpe=annual_sharpe)
|
|
132
|
+
_require_positive_periods(periods_per_year)
|
|
133
|
+
return annual_sharpe / math.sqrt(periods_per_year)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _require_finite(**values: float) -> None:
|
|
137
|
+
for name, value in values.items():
|
|
138
|
+
if not math.isfinite(value):
|
|
139
|
+
raise ValueError(f"{name} must be a finite number, got {value!r}")
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _require_positive_periods(periods_per_year: float) -> None:
|
|
143
|
+
if not (math.isfinite(periods_per_year) and periods_per_year > 0):
|
|
144
|
+
raise ValueError(f"periods_per_year must be positive, got {periods_per_year!r}")
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _check_moments(skew: float, kurtosis: float) -> None:
|
|
148
|
+
"""Reject moment pairs no distribution can have (Pearson: kurtosis >= 1 + skew^2).
|
|
149
|
+
|
|
150
|
+
The most common way to break this is passing *excess* kurtosis (Normal = 0) where raw
|
|
151
|
+
kurtosis (Normal = 3) is expected.
|
|
152
|
+
"""
|
|
153
|
+
_require_finite(skew=skew, kurtosis=kurtosis)
|
|
154
|
+
if kurtosis < 1.0 + skew**2 - 1e-9:
|
|
155
|
+
raise ValueError(
|
|
156
|
+
f"impossible moments: kurtosis {kurtosis} < 1 + skew^2 = {1 + skew**2:.6g}. "
|
|
157
|
+
"kurtosis must be raw (Normal = 3); did you pass excess kurtosis?"
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _sharpe_dispersion(sharpe: float, skew: float, kurtosis: float) -> float:
|
|
162
|
+
"""Return sqrt(1 - skew*SR + (kurtosis-1)/4 * SR^2), the PSR denominator's shape term.
|
|
163
|
+
|
|
164
|
+
With valid moments (kurtosis >= 1 + skew^2) the radicand is at least
|
|
165
|
+
(1 - skew*SR/2)^2 >= 0, so it can only reach zero on that boundary.
|
|
166
|
+
"""
|
|
167
|
+
_check_moments(skew, kurtosis)
|
|
168
|
+
value = 1.0 - skew * sharpe + (kurtosis - 1.0) / 4.0 * sharpe**2
|
|
169
|
+
if value <= 0.0:
|
|
170
|
+
raise ValueError(
|
|
171
|
+
"skew, kurtosis and Sharpe ratio give a zero standard error "
|
|
172
|
+
"(a degenerate two-point distribution); PSR is undefined"
|
|
173
|
+
)
|
|
174
|
+
return math.sqrt(value)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def probabilistic_sharpe_ratio(
|
|
178
|
+
sharpe: float,
|
|
179
|
+
n_obs: float,
|
|
180
|
+
*,
|
|
181
|
+
benchmark: float = 0.0,
|
|
182
|
+
skew: float = 0.0,
|
|
183
|
+
kurtosis: float = 3.0,
|
|
184
|
+
) -> float:
|
|
185
|
+
"""Return the probability that the true Sharpe ratio exceeds ``benchmark`` (PSR).
|
|
186
|
+
|
|
187
|
+
Implements [BLdP2012] Eq. (11)::
|
|
188
|
+
|
|
189
|
+
PSR = Z[ (SR - SR*) * sqrt(n - 1) / sqrt(1 - skew*SR + (kurtosis - 1)/4 * SR^2) ]
|
|
190
|
+
|
|
191
|
+
where Z is the standard Normal CDF. Longer track records raise PSR; negative skew and
|
|
192
|
+
fat tails lower it, because they make a given Sharpe ratio less reliable.
|
|
193
|
+
|
|
194
|
+
Args:
|
|
195
|
+
sharpe: Observed per-period Sharpe ratio.
|
|
196
|
+
n_obs: Number of return observations behind it (the paper's n; at least 2).
|
|
197
|
+
benchmark: Per-period Sharpe ratio to beat (0 asks "is there any skill at all?").
|
|
198
|
+
skew: Skewness of the returns.
|
|
199
|
+
kurtosis: Raw kurtosis of the returns (Normal = 3).
|
|
200
|
+
|
|
201
|
+
Returns:
|
|
202
|
+
A probability in [0, 1].
|
|
203
|
+
|
|
204
|
+
[BLdP2012] p. 9: a monthly SR of 0.458 over two years, assuming Normal returns.
|
|
205
|
+
|
|
206
|
+
>>> round(probabilistic_sharpe_ratio(0.458, 24), 3)
|
|
207
|
+
0.982
|
|
208
|
+
|
|
209
|
+
"""
|
|
210
|
+
_require_finite(sharpe=sharpe, n_obs=n_obs, benchmark=benchmark)
|
|
211
|
+
if n_obs < 2:
|
|
212
|
+
raise ValueError("n_obs must be at least 2")
|
|
213
|
+
z = (sharpe - benchmark) * math.sqrt(n_obs - 1) / _sharpe_dispersion(sharpe, skew, kurtosis)
|
|
214
|
+
return _NORMAL.cdf(z)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def expected_max_sharpe(n_trials: float, sharpe_variance: float) -> float:
|
|
218
|
+
"""Return the expected best Sharpe ratio among ``n_trials`` skill-less strategies (SR0).
|
|
219
|
+
|
|
220
|
+
Even if every strategy tried has a true Sharpe ratio of zero, the best of them looks
|
|
221
|
+
good by luck. [BLdP2014] Eq. (2), from the extreme-value result in Appendix A.1,
|
|
222
|
+
Eq. (6) with mean zero::
|
|
223
|
+
|
|
224
|
+
SR0 = sqrt(V) * ( (1 - g) * Z^-1[1 - 1/N] + g * Z^-1[1 - 1/(N e)] )
|
|
225
|
+
|
|
226
|
+
where g is the Euler-Mascheroni constant. The approximation slightly overestimates the
|
|
227
|
+
exact expected maximum for N >= 10 and converges as N grows ([BLdP2014] A.2).
|
|
228
|
+
|
|
229
|
+
The closed form is an approximation for large N. Between 1 and 2 trials it is not
|
|
230
|
+
usable (it turns negative near N = 1, which would *reward* selection), so a
|
|
231
|
+
fractional N in that range is rejected: pass 1 for "no selection" or N >= 2.
|
|
232
|
+
``Z^-1[1 - p]`` is evaluated as ``-Z^-1[p]`` so very large N stays accurate.
|
|
233
|
+
|
|
234
|
+
Args:
|
|
235
|
+
n_trials: Number of independent strategy configurations tried: exactly 1, or at
|
|
236
|
+
least 2 (may be fractional, e.g. an effective number of trials).
|
|
237
|
+
sharpe_variance: Variance of the Sharpe ratios across those trials (V), in the
|
|
238
|
+
same per-period units as the Sharpe ratio it will be compared against.
|
|
239
|
+
|
|
240
|
+
>>> round(expected_max_sharpe(100, 1 / (2 * 250)), 4) # [BLdP2014] p. 10
|
|
241
|
+
0.1132
|
|
242
|
+
|
|
243
|
+
"""
|
|
244
|
+
_require_finite(n_trials=n_trials, sharpe_variance=sharpe_variance)
|
|
245
|
+
if n_trials < 1:
|
|
246
|
+
raise ValueError("n_trials must be at least 1")
|
|
247
|
+
if 1 < n_trials < 2:
|
|
248
|
+
raise ValueError(
|
|
249
|
+
"n_trials between 1 and 2 is outside the closed form's valid range "
|
|
250
|
+
"(it turns negative near 1); use 1 for no selection or a value >= 2"
|
|
251
|
+
)
|
|
252
|
+
if sharpe_variance < 0:
|
|
253
|
+
raise ValueError("sharpe_variance cannot be negative")
|
|
254
|
+
if n_trials == 1:
|
|
255
|
+
return 0.0 # a single trial involves no selection, so no selection bias
|
|
256
|
+
g = EULER_GAMMA
|
|
257
|
+
return math.sqrt(sharpe_variance) * -(
|
|
258
|
+
(1 - g) * _NORMAL.inv_cdf(1 / n_trials) + g * _NORMAL.inv_cdf(1 / (n_trials * math.e))
|
|
259
|
+
)
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def deflated_sharpe_ratio(
|
|
263
|
+
sharpe: float,
|
|
264
|
+
n_obs: float,
|
|
265
|
+
*,
|
|
266
|
+
n_trials: float,
|
|
267
|
+
sharpe_variance: float,
|
|
268
|
+
skew: float = 0.0,
|
|
269
|
+
kurtosis: float = 3.0,
|
|
270
|
+
) -> float:
|
|
271
|
+
"""Return the probability that the best of ``n_trials`` strategies is real (DSR).
|
|
272
|
+
|
|
273
|
+
[BLdP2014] Eq. (2): the PSR of the selected strategy, measured against
|
|
274
|
+
:func:`expected_max_sharpe` instead of zero, so the strategy is penalized for every
|
|
275
|
+
alternative tried before it was picked.
|
|
276
|
+
|
|
277
|
+
Args:
|
|
278
|
+
sharpe: Per-period Sharpe ratio of the selected strategy.
|
|
279
|
+
n_obs: Number of return observations behind it (the paper's T).
|
|
280
|
+
n_trials: Number of independent configurations tried during research (N).
|
|
281
|
+
sharpe_variance: Variance of the per-period Sharpe ratios across those trials.
|
|
282
|
+
skew: Skewness of the selected strategy's returns.
|
|
283
|
+
kurtosis: Raw kurtosis of the selected strategy's returns (Normal = 3).
|
|
284
|
+
|
|
285
|
+
[BLdP2014] p. 10 example: N = 100, annualized SR variance 1/2, annualized SR 2.5
|
|
286
|
+
over T = 1250 daily observations (250 per year), skew -3, kurtosis 10.
|
|
287
|
+
|
|
288
|
+
>>> dsr = deflated_sharpe_ratio(
|
|
289
|
+
... deannualize_sharpe(2.5, 250), 1250,
|
|
290
|
+
... n_trials=100, sharpe_variance=1 / (2 * 250), skew=-3, kurtosis=10,
|
|
291
|
+
... )
|
|
292
|
+
>>> round(dsr, 4)
|
|
293
|
+
0.9004
|
|
294
|
+
|
|
295
|
+
"""
|
|
296
|
+
return probabilistic_sharpe_ratio(
|
|
297
|
+
sharpe,
|
|
298
|
+
n_obs,
|
|
299
|
+
benchmark=expected_max_sharpe(n_trials, sharpe_variance),
|
|
300
|
+
skew=skew,
|
|
301
|
+
kurtosis=kurtosis,
|
|
302
|
+
)
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def min_track_record_length(
|
|
306
|
+
sharpe: float,
|
|
307
|
+
*,
|
|
308
|
+
benchmark: float = 0.0,
|
|
309
|
+
skew: float = 0.0,
|
|
310
|
+
kurtosis: float = 3.0,
|
|
311
|
+
confidence: float = 0.95,
|
|
312
|
+
) -> float:
|
|
313
|
+
"""Return how many observations are needed before ``sharpe`` beats ``benchmark`` (MinTRL).
|
|
314
|
+
|
|
315
|
+
Implements [BLdP2012] Eq. (13)::
|
|
316
|
+
|
|
317
|
+
MinTRL = 1 + [1 - skew*SR + (kurtosis - 1)/4 * SR^2] * (Z_alpha / (SR - SR*))^2
|
|
318
|
+
|
|
319
|
+
with Z_alpha the standard Normal quantile at ``confidence``. The result is a number of
|
|
320
|
+
observations at the frequency of the per-period Sharpe ratio, not years.
|
|
321
|
+
|
|
322
|
+
``confidence`` must be at least 0.5: Eq. (13) squares Z_alpha, so below 0.5 it would
|
|
323
|
+
silently return the answer for ``1 - confidence``.
|
|
324
|
+
|
|
325
|
+
[BLdP2012] p. 11: annualized SR 2 against 1 at 95%, daily Normal returns, is 2.73 years.
|
|
326
|
+
|
|
327
|
+
>>> round(min_track_record_length(2 / 252**0.5, benchmark=1 / 252**0.5) / 252, 2)
|
|
328
|
+
2.73
|
|
329
|
+
|
|
330
|
+
"""
|
|
331
|
+
_require_finite(sharpe=sharpe, benchmark=benchmark, confidence=confidence)
|
|
332
|
+
if not 0.5 <= confidence < 1.0:
|
|
333
|
+
raise ValueError("confidence must be at least 0.5 and below 1")
|
|
334
|
+
if sharpe <= benchmark:
|
|
335
|
+
raise ValueError("sharpe must exceed benchmark; otherwise no track record suffices")
|
|
336
|
+
z = _NORMAL.inv_cdf(confidence)
|
|
337
|
+
return 1.0 + _sharpe_dispersion(sharpe, skew, kurtosis) ** 2 * (z / (sharpe - benchmark)) ** 2
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: algobacktesting
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Is your backtest real? Deflated Sharpe Ratio, Probability of Backtest Overfitting, and purged cross-validation for trading research.
|
|
5
|
+
Keywords: backtesting,overfitting,deflated sharpe ratio,probability of backtest overfitting,quantitative finance,cross-validation
|
|
6
|
+
Author: Daniel Heidary
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Classifier: Development Status :: 3 - Alpha
|
|
10
|
+
Classifier: Intended Audience :: Financial and Insurance Industry
|
|
11
|
+
Classifier: Intended Audience :: Science/Research
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
18
|
+
Classifier: Topic :: Office/Business :: Financial :: Investment
|
|
19
|
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
|
20
|
+
Classifier: Typing :: Typed
|
|
21
|
+
Requires-Dist: numpy>=1.26
|
|
22
|
+
Requires-Python: >=3.11
|
|
23
|
+
Project-URL: Homepage, https://algobacktesting.com/
|
|
24
|
+
Project-URL: Repository, https://github.com/TheMarketMakerHoldings/algobacktesting
|
|
25
|
+
Project-URL: Documentation, https://github.com/TheMarketMakerHoldings/algobacktesting/blob/main/docs/api.md
|
|
26
|
+
Project-URL: Changelog, https://github.com/TheMarketMakerHoldings/algobacktesting/blob/main/CHANGELOG.md
|
|
27
|
+
Project-URL: Issues, https://github.com/TheMarketMakerHoldings/algobacktesting/issues
|
|
28
|
+
Description-Content-Type: text/markdown
|
|
29
|
+
|
|
30
|
+
# algobacktesting
|
|
31
|
+
|
|
32
|
+
[](https://pypi.org/project/algobacktesting/)
|
|
33
|
+
[](https://github.com/TheMarketMakerHoldings/algobacktesting/actions/workflows/ci.yml)
|
|
34
|
+
[](https://github.com/TheMarketMakerHoldings/algobacktesting/blob/main/LICENSE)
|
|
35
|
+

|
|
36
|
+

|
|
37
|
+
|
|
38
|
+
**Is your backtest real? Overfitting checks for trading research.**
|
|
39
|
+
|
|
40
|
+
> The Sharpe and PBO modules are verified against their source papers. The cross-validation
|
|
41
|
+
> module is built from the standard definitions and is awaiting review against the book.
|
|
42
|
+
|
|
43
|
+
Try enough strategy variations and one of them will look brilliant by luck alone.
|
|
44
|
+
`algobacktesting` implements statistical tests from Bailey & López de Prado's research that
|
|
45
|
+
tell a real edge apart from an overfit one.
|
|
46
|
+
|
|
47
|
+
**Not a programmer?** The [online check](https://algobacktesting.com/)
|
|
48
|
+
asks one question: are you actually profitable, or just lucky? Import a strategy's trades from
|
|
49
|
+
TradingView, TopstepX, Quantower, NinjaTrader or thinkorswim, paste them, or enter a win rate. Its stop lab
|
|
50
|
+
replays your entries on your own price bars to test other stop sizes, and counts every size
|
|
51
|
+
tried so a lucky stop is not mistaken for a better one. A prop-firm simulator estimates your
|
|
52
|
+
chance of passing a funded-account evaluation from your own trades. A strategy builder tests a rule you
|
|
53
|
+
write as a sentence on your own bars, counting every version you try. Save strategies under a
|
|
54
|
+
name and compare any two side by side, and share a result with a link that holds no trades. It runs in the browser, and nothing is uploaded.
|
|
55
|
+
|
|
56
|
+
| Question | Tool |
|
|
57
|
+
| --- | --- |
|
|
58
|
+
| Is this Sharpe ratio still impressive after counting every strategy I tried? | `deflated_sharpe_ratio` (DSR), `probabilistic_sharpe_ratio` (PSR), `min_track_record_length` |
|
|
59
|
+
| How likely is it that my "best" strategy is just the luckiest one? | `probability_of_backtest_overfitting` (PBO, via combinatorially symmetric cross-validation) |
|
|
60
|
+
| How do I cross-validate on time series without leaking the future? | `purged_kfold` (with embargo), `combinatorial_purged_cv` (CPCV) |
|
|
61
|
+
|
|
62
|
+
## Why this matters
|
|
63
|
+
|
|
64
|
+
I've consistently struggled with trading setups that had amazing winning streaks. They
|
|
65
|
+
looked great, but my overall profitability was neglected because of my obsession with my
|
|
66
|
+
strategies. The problem was that I didn't realize how unreliable my strategies really were
|
|
67
|
+
until I started calculating them. My strategies had incredibly high reward-to-risk setups
|
|
68
|
+
that happened frequently, and I launched them on Quantower using Python algorithms I wrote in
|
|
69
|
+
Visual Studio 2022, so the code ran my strategies automatically. I would often watch around
|
|
70
|
+
the peak hours of my setups and sometimes see them take off, and I told myself the winning
|
|
71
|
+
trades would take care of the occasional losses. Little did I know I had a 33% win rate and
|
|
72
|
+
my account was turning very negative.
|
|
73
|
+
|
|
74
|
+
When I saw the numbers, I didn't believe them. I blamed my brokerage for counting breakevens
|
|
75
|
+
as negative, but in reality a breakeven is a negative trade: if your strategy has a real edge,
|
|
76
|
+
you shouldn't need to worry about breakevens counting against you. Seeing my win rate broke
|
|
77
|
+
my dreams. It made me feel like trading without professional experience is for losers. I
|
|
78
|
+
called myself "exit liquidity", the target market for day-trading gurus, even though I had
|
|
79
|
+
started with my own analysis of the market instead of listening to gurus who tell you that
|
|
80
|
+
you can draw random patterns on a chart and that watching level 2 tick data is stupid. They
|
|
81
|
+
say that to hide the truth: trading comes down to data.
|
|
82
|
+
|
|
83
|
+
Now, when I develop a strategy, I backtest it on historical market data and run the results
|
|
84
|
+
through `algobacktesting` to see whether the strategy really has an edge.
|
|
85
|
+
|
|
86
|
+
## Quickstart
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
import numpy as np
|
|
90
|
+
from algobacktesting import (
|
|
91
|
+
column_sharpe_ratios,
|
|
92
|
+
deflated_sharpe_ratio,
|
|
93
|
+
probability_of_backtest_overfitting,
|
|
94
|
+
return_stats,
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
returns = np.random.default_rng(42).normal(0, 0.01, size=(1008, 200)) # 200 strategies, no edge
|
|
98
|
+
|
|
99
|
+
sharpes = column_sharpe_ratios(returns) # per-day Sharpe of each strategy
|
|
100
|
+
best = return_stats(returns[:, sharpes.argmax()]) # the backtest you'd be tempted to trade
|
|
101
|
+
|
|
102
|
+
dsr = deflated_sharpe_ratio(
|
|
103
|
+
best.sharpe,
|
|
104
|
+
best.n_obs,
|
|
105
|
+
n_trials=200,
|
|
106
|
+
sharpe_variance=sharpes.var(ddof=1),
|
|
107
|
+
skew=best.skew,
|
|
108
|
+
kurtosis=best.kurtosis,
|
|
109
|
+
)
|
|
110
|
+
pbo = probability_of_backtest_overfitting(returns, n_partitions=16).pbo
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
`examples/overfit_demo.py` runs this for three worlds: no edge, a modest real edge, and a
|
|
114
|
+
strong real edge. Its output:
|
|
115
|
+
|
|
116
|
+
| World | Best backtest (annual Sharpe) | Deflated Sharpe | PBO |
|
|
117
|
+
| --- | --- | --- | --- |
|
|
118
|
+
| 200 strategies, no edge | 1.69 | 0.654 | 0.275 |
|
|
119
|
+
| plus one modest real edge (true Sharpe ~1.3) | 1.69 | 0.642 | 0.274 |
|
|
120
|
+
| plus one strong real edge (true Sharpe ~2.4) | 2.22 | 0.906 | 0.082 |
|
|
121
|
+
|
|
122
|
+
- **No edge:** pure luck produced a 1.69 Sharpe. DSR refuses to call it real.
|
|
123
|
+
- **Modest edge:** it exists, but the luckiest noise strategy still wins the search.
|
|
124
|
+
Searching 200 variants buries a 1.3 Sharpe edge.
|
|
125
|
+
- **Strong edge:** it wins, and PBO drops to 0.08, so the selection process works. DSR is
|
|
126
|
+
still below 0.95: after 200 tries, four years of data is not enough to *prove* it.
|
|
127
|
+
|
|
128
|
+
### Why purging matters
|
|
129
|
+
|
|
130
|
+
`examples/leakage_demo.py` cross-validates a model that has **no real skill**: a
|
|
131
|
+
nearest-neighbour model predicting 20-day returns from pure noise. Averaged over 200
|
|
132
|
+
datasets:
|
|
133
|
+
|
|
134
|
+
| Cross-validation scheme | Out-of-sample correlation (honest value: 0) |
|
|
135
|
+
| --- | --- |
|
|
136
|
+
| Shuffled k-fold | +0.816 (s.e. 0.002) |
|
|
137
|
+
| Contiguous k-fold, no purging | +0.050 (s.e. 0.005) |
|
|
138
|
+
| Purged k-fold | +0.000 (s.e. 0.005) |
|
|
139
|
+
| Purged k-fold with a 5% embargo | -0.001 (s.e. 0.005) |
|
|
140
|
+
| Leak removed by purging (paired difference) | +0.050 (s.e. 0.002) |
|
|
141
|
+
|
|
142
|
+
Shuffling makes a worthless model look excellent. Without purging, even unshuffled
|
|
143
|
+
folds leak at their edges. One dataset's score varies by about 0.07, so that leak is
|
|
144
|
+
invisible in a single backtest while it inflates every one of them. Purged k-fold
|
|
145
|
+
gives the honest answer.
|
|
146
|
+
|
|
147
|
+
Each function's docstring cites the equation and page it implements. `docs/explainers/`
|
|
148
|
+
has a plain-English guide to each module.
|
|
149
|
+
|
|
150
|
+
## Installation
|
|
151
|
+
|
|
152
|
+
```bash
|
|
153
|
+
pip install algobacktesting
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
Requires Python 3.11+ and NumPy, which installs with it. For the latest version from GitHub
|
|
157
|
+
instead (needs Git):
|
|
158
|
+
|
|
159
|
+
```bash
|
|
160
|
+
pip install git+https://github.com/TheMarketMakerHoldings/algobacktesting
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
## Verification
|
|
164
|
+
|
|
165
|
+
- **Paper numbers:** every number printed in the source papers that these functions
|
|
166
|
+
compute is reproduced in the tests at the paper's printed precision. For example: DSR
|
|
167
|
+
0.9004, PSR 0.982 / 0.913 / 0.953, and minimum track record 2.73 / 2.83 / 3.24 / 4.99
|
|
168
|
+
years.
|
|
169
|
+
- **Independent checks:** exact numerical integration, seeded Monte Carlo calibration,
|
|
170
|
+
and a brute-force reference implementation for cross-validation, run on hundreds of
|
|
171
|
+
random datasets.
|
|
172
|
+
- **Coverage and platforms:** 100% line and branch coverage. CI runs the tests on Python
|
|
173
|
+
3.11–3.14, on Linux, Windows and macOS, and on the oldest supported NumPy (1.26).
|
|
174
|
+
- **Documentation:** the code and numbers in this README are run and compared by the tests.
|
|
175
|
+
|
|
176
|
+
## Documentation
|
|
177
|
+
|
|
178
|
+
| If you want | Read |
|
|
179
|
+
| --- | --- |
|
|
180
|
+
| Every function and its signature | [API reference](https://github.com/TheMarketMakerHoldings/algobacktesting/blob/main/docs/api.md) |
|
|
181
|
+
| The ideas in plain English, with worked examples | [Explainers](https://github.com/TheMarketMakerHoldings/algobacktesting/tree/main/docs/explainers) |
|
|
182
|
+
| The evidence: proofs, replication tables and errata | [Verification report](https://github.com/TheMarketMakerHoldings/algobacktesting/blob/main/docs/paper/verification-report.md) |
|
|
183
|
+
| Runnable demonstrations | [`examples/`](https://github.com/TheMarketMakerHoldings/algobacktesting/tree/main/examples) |
|
|
184
|
+
| What changed | [Changelog](https://github.com/TheMarketMakerHoldings/algobacktesting/blob/main/CHANGELOG.md) |
|
|
185
|
+
| To contribute or report a wrong number | [Contributing](https://github.com/TheMarketMakerHoldings/algobacktesting/blob/main/CONTRIBUTING.md) |
|
|
186
|
+
|
|
187
|
+
## References
|
|
188
|
+
|
|
189
|
+
- Bailey, D. H. and López de Prado, M. (2012). The Sharpe Ratio Efficient Frontier.
|
|
190
|
+
*Journal of Risk* 15(2).
|
|
191
|
+
- Bailey, D. H. and López de Prado, M. (2014). The Deflated Sharpe Ratio: Correcting for
|
|
192
|
+
Selection Bias, Backtest Overfitting and Non-Normality. *Journal of Portfolio Management*
|
|
193
|
+
40(5).
|
|
194
|
+
- Bailey, D. H., Borwein, J., López de Prado, M. and Zhu, Q. J. (2017). The Probability of
|
|
195
|
+
Backtest Overfitting. *Journal of Computational Finance* 20(4).
|
|
196
|
+
- López de Prado, M. (2018). *Advances in Financial Machine Learning*. Wiley.
|
|
197
|
+
|
|
198
|
+
## Disclaimer
|
|
199
|
+
|
|
200
|
+
Statistical tools for research. Not investment advice.
|
|
201
|
+
|
|
202
|
+
## License
|
|
203
|
+
|
|
204
|
+
MIT © 2026 Daniel Heidary. Published by The Market Maker Holdings & Co.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
algobacktesting/__init__.py,sha256=oDaS6_5Z-QD4z4mJCV_mexqwgZ9H4gcU8gAfmKF4_yw,1129
|
|
2
|
+
algobacktesting/cv.py,sha256=FokWHZv4w-IOpsvA-bOLxzEL1YZb-EZco0Jggc800Wc,10597
|
|
3
|
+
algobacktesting/pbo.py,sha256=uUFMH8qsM_k2A8Cs7uVP3I0iGsubGQ-SZLKuTpMmEdo,10641
|
|
4
|
+
algobacktesting/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
algobacktesting/sharpe.py,sha256=3svVJ8V_kqNvZVvUQ7Hz2NZrQNbvOzKZyXftBX1eUJo,12265
|
|
6
|
+
algobacktesting-0.1.0.dist-info/licenses/LICENSE,sha256=g-9hlSx8KXn8LLIRbUgwffe-QtRe3KJQ3uMgBb8_3pw,1071
|
|
7
|
+
algobacktesting-0.1.0.dist-info/WHEEL,sha256=-gI5GRFdiNNn2CFz-ptlExISMINC-k8bFxeojAlHbrM,81
|
|
8
|
+
algobacktesting-0.1.0.dist-info/METADATA,sha256=EoB8e08StfjTCcH0X727Fm1YS5j4amo2kl8WC2t-4BE,10668
|
|
9
|
+
algobacktesting-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Daniel Heidary
|
|
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.
|