algobacktesting 0.1.0__tar.gz → 0.1.1__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: algobacktesting
3
- Version: 0.1.0
3
+ Version: 0.1.1
4
4
  Summary: Is your backtest real? Deflated Sharpe Ratio, Probability of Backtest Overfitting, and purged cross-validation for trading research.
5
5
  Keywords: backtesting,overfitting,deflated sharpe ratio,probability of backtest overfitting,quantitative finance,cross-validation
6
6
  Author: Daniel Heidary
@@ -40,23 +40,27 @@ Description-Content-Type: text/markdown
40
40
  > The Sharpe and PBO modules are verified against their source papers. The cross-validation
41
41
  > module is built from the standard definitions and is awaiting review against the book.
42
42
 
43
- Try enough strategy variations and one of them will look brilliant by luck alone.
43
+ Try enough strategy variations and one of them will look brilliant by chance alone.
44
44
  `algobacktesting` implements statistical tests from Bailey & López de Prado's research that
45
45
  tell a real edge apart from an overfit one.
46
46
 
47
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
48
+ asks one question: what is the probability your edge is real? Import a strategy's trades from
49
+ TradingView, Tradovate, 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 and target sizes, and counts every
51
+ size tried so one that merely fits the past is not mistaken for a better one. A prop-firm simulator
52
+ estimates your probability of passing a funded-account evaluation from your own trades. A strategy builder tests a rule you
53
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.
54
+ name and compare any two side by side, set your older trades against your newer ones, and share a
55
+ result with a link that holds no trades. It runs in the browser, and nothing is uploaded. Guides:
56
+ [Deflated Sharpe Ratio](https://algobacktesting.com/guides/deflated-sharpe-ratio.html),
57
+ [backtest overfitting](https://algobacktesting.com/guides/backtest-overfitting.html) and the
58
+ [odds of passing a prop evaluation](https://algobacktesting.com/guides/prop-firm-evaluation-odds.html).
55
59
 
56
60
  | Question | Tool |
57
61
  | --- | --- |
58
62
  | 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) |
63
+ | What is the probability that my "best" strategy is overfit? | `probability_of_backtest_overfitting` (PBO, via combinatorially symmetric cross-validation) |
60
64
  | How do I cross-validate on time series without leaking the future? | `purged_kfold` (with embargo), `combinatorial_purged_cv` (CPCV) |
61
65
 
62
66
  ## Why this matters
@@ -119,8 +123,8 @@ strong real edge. Its output:
119
123
  | plus one modest real edge (true Sharpe ~1.3) | 1.69 | 0.642 | 0.274 |
120
124
  | plus one strong real edge (true Sharpe ~2.4) | 2.22 | 0.906 | 0.082 |
121
125
 
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.
126
+ - **No edge:** pure noise produced a 1.69 Sharpe. DSR refuses to call it real.
127
+ - **Modest edge:** it exists, but the best noise strategy still wins the search.
124
128
  Searching 200 variants buries a 1.3 Sharpe edge.
125
129
  - **Strong edge:** it wins, and PBO drops to 0.08, so the selection process works. DSR is
126
130
  still below 0.95: after 200 tries, four years of data is not enough to *prove* it.
@@ -11,23 +11,27 @@
11
11
  > The Sharpe and PBO modules are verified against their source papers. The cross-validation
12
12
  > module is built from the standard definitions and is awaiting review against the book.
13
13
 
14
- Try enough strategy variations and one of them will look brilliant by luck alone.
14
+ Try enough strategy variations and one of them will look brilliant by chance alone.
15
15
  `algobacktesting` implements statistical tests from Bailey & López de Prado's research that
16
16
  tell a real edge apart from an overfit one.
17
17
 
18
18
  **Not a programmer?** The [online check](https://algobacktesting.com/)
19
- asks one question: are you actually profitable, or just lucky? Import a strategy's trades from
20
- TradingView, TopstepX, Quantower, NinjaTrader or thinkorswim, paste them, or enter a win rate. Its stop lab
21
- replays your entries on your own price bars to test other stop sizes, and counts every size
22
- tried so a lucky stop is not mistaken for a better one. A prop-firm simulator estimates your
23
- chance of passing a funded-account evaluation from your own trades. A strategy builder tests a rule you
19
+ asks one question: what is the probability your edge is real? Import a strategy's trades from
20
+ TradingView, Tradovate, TopstepX, Quantower, NinjaTrader or thinkorswim, paste them, or enter a win rate. Its stop lab
21
+ replays your entries on your own price bars to test other stop and target sizes, and counts every
22
+ size tried so one that merely fits the past is not mistaken for a better one. A prop-firm simulator
23
+ estimates your probability of passing a funded-account evaluation from your own trades. A strategy builder tests a rule you
24
24
  write as a sentence on your own bars, counting every version you try. Save strategies under a
25
- 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.
25
+ name and compare any two side by side, set your older trades against your newer ones, and share a
26
+ result with a link that holds no trades. It runs in the browser, and nothing is uploaded. Guides:
27
+ [Deflated Sharpe Ratio](https://algobacktesting.com/guides/deflated-sharpe-ratio.html),
28
+ [backtest overfitting](https://algobacktesting.com/guides/backtest-overfitting.html) and the
29
+ [odds of passing a prop evaluation](https://algobacktesting.com/guides/prop-firm-evaluation-odds.html).
26
30
 
27
31
  | Question | Tool |
28
32
  | --- | --- |
29
33
  | Is this Sharpe ratio still impressive after counting every strategy I tried? | `deflated_sharpe_ratio` (DSR), `probabilistic_sharpe_ratio` (PSR), `min_track_record_length` |
30
- | How likely is it that my "best" strategy is just the luckiest one? | `probability_of_backtest_overfitting` (PBO, via combinatorially symmetric cross-validation) |
34
+ | What is the probability that my "best" strategy is overfit? | `probability_of_backtest_overfitting` (PBO, via combinatorially symmetric cross-validation) |
31
35
  | How do I cross-validate on time series without leaking the future? | `purged_kfold` (with embargo), `combinatorial_purged_cv` (CPCV) |
32
36
 
33
37
  ## Why this matters
@@ -90,8 +94,8 @@ strong real edge. Its output:
90
94
  | plus one modest real edge (true Sharpe ~1.3) | 1.69 | 0.642 | 0.274 |
91
95
  | plus one strong real edge (true Sharpe ~2.4) | 2.22 | 0.906 | 0.082 |
92
96
 
93
- - **No edge:** pure luck produced a 1.69 Sharpe. DSR refuses to call it real.
94
- - **Modest edge:** it exists, but the luckiest noise strategy still wins the search.
97
+ - **No edge:** pure noise produced a 1.69 Sharpe. DSR refuses to call it real.
98
+ - **Modest edge:** it exists, but the best noise strategy still wins the search.
95
99
  Searching 200 variants buries a 1.3 Sharpe edge.
96
100
  - **Strong edge:** it wins, and PBO drops to 0.08, so the selection process works. DSR is
97
101
  still below 0.95: after 200 tries, four years of data is not enough to *prove* it.
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "algobacktesting"
3
- version = "0.1.0"
3
+ version = "0.1.1"
4
4
  description = "Is your backtest real? Deflated Sharpe Ratio, Probability of Backtest Overfitting, and purged cross-validation for trading research."
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -87,6 +87,7 @@ ignore = [
87
87
  "ANN",
88
88
  "S101",
89
89
  ]
90
+ "docs/build_guides.py" = ["E501"]
90
91
 
91
92
  [tool.mypy]
92
93
  strict = true
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "algobacktesting"
3
- version = "0.1.0"
3
+ version = "0.1.1"
4
4
  description = "Is your backtest real? Deflated Sharpe Ratio, Probability of Backtest Overfitting, and purged cross-validation for trading research."
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -62,6 +62,7 @@ ignore = ["D203", "D213", "D105", "D107"]
62
62
 
63
63
  [tool.ruff.lint.per-file-ignores]
64
64
  "tests/**" = ["D", "ANN", "S101"]
65
+ "docs/build_guides.py" = ["E501"]
65
66
 
66
67
  [tool.mypy]
67
68
  strict = true
@@ -27,7 +27,7 @@ from algobacktesting.sharpe import (
27
27
  sharpe_ratio,
28
28
  )
29
29
 
30
- __version__ = "0.1.0"
30
+ __version__ = "0.1.1"
31
31
 
32
32
  __all__ = [
33
33
  "EULER_GAMMA",
@@ -93,9 +93,15 @@ def column_sharpe_ratios(returns: NDArray[np.float64]) -> NDArray[np.float64]:
93
93
  """Return the per-period Sharpe ratio of each column (mean / std with ddof=1).
94
94
 
95
95
  This is the default performance metric for
96
- :func:`probability_of_backtest_overfitting`.
96
+ :func:`probability_of_backtest_overfitting`. A column that never changes has no Sharpe
97
+ ratio: NaN is returned for it.
97
98
  """
98
- return np.asarray(returns.mean(axis=0) / returns.std(axis=0, ddof=1), dtype=np.float64)
99
+ values = np.asarray(returns, dtype=np.float64)
100
+ constant = values.max(axis=0) == values.min(axis=0)
101
+ with np.errstate(divide="ignore", invalid="ignore"):
102
+ ratios = values.mean(axis=0) / values.std(axis=0, ddof=1)
103
+ # Rounding can leave a constant column a tiny standard deviation, hence a huge ratio.
104
+ return np.where(constant, np.nan, ratios)
99
105
 
100
106
 
101
107
  def average_ranks(values: NDArray[np.float64]) -> NDArray[np.float64]:
@@ -221,24 +227,34 @@ def probability_of_backtest_overfitting(
221
227
  def _block_sharpe_evaluator(
222
228
  blocks: NDArray[np.float64],
223
229
  ) -> Callable[[tuple[int, ...]], NDArray[np.float64]]:
224
- """Fast exact column Sharpe ratios for any union of blocks, from per-block sums.
230
+ """Fast column Sharpe ratios for any union of blocks, without re-reading the rows.
225
231
 
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.
232
+ The sum of squares about the joined mean splits into the part inside each block and the
233
+ part between the blocks' means (the analysis-of-variance identity)::
234
+
235
+ sum (x - mean)^2 = sum_b sum_(x in b) (x - mean_b)^2 + rows * sum_b (mean_b - mean)^2
236
+
237
+ Every term is positive, so nothing large cancels: a bad tick or a jump in level in one
238
+ block cannot spoil the variance of the blocks around it. The result equals
239
+ ``column_sharpe_ratios`` on the joined rows up to rounding, including NaN for a column that
240
+ never changes there: that is read from each block's smallest and largest value, because
241
+ rounding can leave such a column a tiny variance and a huge ratio.
228
242
  """
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)
243
+ means = blocks.mean(axis=1) # (S, N)
244
+ within = ((blocks - means[:, np.newaxis, :]) ** 2).sum(axis=1) # (S, N)
245
+ lows, highs = blocks.min(axis=1), blocks.max(axis=1) # (S, N)
233
246
  rows_per_block = blocks.shape[1]
234
247
 
235
248
  def evaluate(chosen: tuple[int, ...]) -> NDArray[np.float64]:
236
249
  idx = list(chosen)
237
250
  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)
251
+ mean = means[idx].mean(axis=0)
252
+ between = rows_per_block * ((means[idx] - mean) ** 2).sum(axis=0)
253
+ var = (within[idx].sum(axis=0) + between) / (count - 1)
240
254
  with np.errstate(divide="ignore", invalid="ignore"):
241
- return np.asarray((mean_c + shift) / np.sqrt(var), dtype=np.float64)
255
+ ratios = mean / np.sqrt(var)
256
+ constant = highs[idx].max(axis=0) == lows[idx].min(axis=0)
257
+ return np.where(constant, np.nan, ratios)
242
258
 
243
259
  return evaluate
244
260
 
@@ -93,7 +93,8 @@ def return_stats(returns: ArrayLike) -> ReturnStats:
93
93
  n = x.size
94
94
  dev = x - x.mean()
95
95
  m2 = float(np.mean(dev**2))
96
- if m2 == 0.0:
96
+ # Rounding the mean can leave identical returns a tiny variance, so compare them directly.
97
+ if m2 == 0.0 or x.max() == x.min():
97
98
  raise ValueError("returns have zero variance; the Sharpe ratio is undefined")
98
99
  std = math.sqrt(m2 * n / (n - 1))
99
100
  return ReturnStats(
@@ -218,7 +219,7 @@ def expected_max_sharpe(n_trials: float, sharpe_variance: float) -> float:
218
219
  """Return the expected best Sharpe ratio among ``n_trials`` skill-less strategies (SR0).
219
220
 
220
221
  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
+ good by chance. [BLdP2014] Eq. (2), from the extreme-value result in Appendix A.1,
222
223
  Eq. (6) with mean zero::
223
224
 
224
225
  SR0 = sqrt(V) * ( (1 - g) * Z^-1[1 - 1/N] + g * Z^-1[1 - 1/(N e)] )
File without changes