quantstats-pro 0.4.1__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.
- quantstats/__init__.py +163 -0
- quantstats/_compat.py +431 -0
- quantstats/_montecarlo.py +296 -0
- quantstats/_numpy_compat.py +289 -0
- quantstats/_plotting/__init__.py +0 -0
- quantstats/_plotting/core.py +2173 -0
- quantstats/_plotting/wrappers.py +2109 -0
- quantstats/_reporting/__init__.py +12 -0
- quantstats/_reporting/engine.py +37 -0
- quantstats/_reporting/sections.py +223 -0
- quantstats/alphadecay/__init__.py +25 -0
- quantstats/alphadecay/core.py +712 -0
- quantstats/alphadecay/plotting.py +206 -0
- quantstats/montecarlo/__init__.py +34 -0
- quantstats/montecarlo/analytics.py +291 -0
- quantstats/montecarlo/base.py +92 -0
- quantstats/montecarlo/core.py +175 -0
- quantstats/montecarlo/models/__init__.py +15 -0
- quantstats/montecarlo/models/bayesian.py +88 -0
- quantstats/montecarlo/models/block_bootstrap.py +108 -0
- quantstats/montecarlo/models/bootstrap.py +38 -0
- quantstats/montecarlo/models/garch.py +83 -0
- quantstats/montecarlo/models/gbm.py +44 -0
- quantstats/montecarlo/models/heston.py +103 -0
- quantstats/montecarlo/models/jump_diffusion.py +86 -0
- quantstats/montecarlo/models/shuffle.py +49 -0
- quantstats/montecarlo/models/trimmed.py +50 -0
- quantstats/montecarlo/plotting.py +324 -0
- quantstats/montecarlo/registry.py +34 -0
- quantstats/plots.py +27 -0
- quantstats/py.typed +0 -0
- quantstats/report.html +64 -0
- quantstats/report_alpha_decay.html +43 -0
- quantstats/report_montecarlo.html +62 -0
- quantstats/report_simple.html +58 -0
- quantstats/reports.py +3502 -0
- quantstats/stats.py +3321 -0
- quantstats/utils.py +1011 -0
- quantstats/version.py +1 -0
- quantstats_pro-0.4.1.dist-info/METADATA +509 -0
- quantstats_pro-0.4.1.dist-info/RECORD +43 -0
- quantstats_pro-0.4.1.dist-info/WHEEL +4 -0
- quantstats_pro-0.4.1.dist-info/licenses/LICENSE.txt +202 -0
quantstats/stats.py
ADDED
|
@@ -0,0 +1,3321 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
#
|
|
3
|
+
# QuantStats: Portfolio analytics for quants
|
|
4
|
+
# https://github.com/ranaroussi/quantstats
|
|
5
|
+
#
|
|
6
|
+
# Copyright 2019-2025 Ran Aroussi
|
|
7
|
+
#
|
|
8
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
9
|
+
# you may not use this file except in compliance with the License.
|
|
10
|
+
# You may obtain a copy of the License at
|
|
11
|
+
#
|
|
12
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
13
|
+
#
|
|
14
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
15
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
16
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
17
|
+
# See the License for the specific language governing permissions and
|
|
18
|
+
# limitations under the License.
|
|
19
|
+
|
|
20
|
+
"""
|
|
21
|
+
Portfolio Statistics Module
|
|
22
|
+
|
|
23
|
+
This module provides comprehensive statistical analysis functions for portfolio
|
|
24
|
+
performance evaluation, risk assessment, and benchmarking. It includes functions
|
|
25
|
+
for calculating various return metrics, risk ratios, drawdown analysis, and
|
|
26
|
+
comparison with benchmarks.
|
|
27
|
+
|
|
28
|
+
The module is designed to work with pandas Series and DataFrames containing
|
|
29
|
+
return data, price data, or performance metrics.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
from math import ceil as _ceil
|
|
33
|
+
from math import sqrt as _sqrt
|
|
34
|
+
from warnings import warn
|
|
35
|
+
|
|
36
|
+
import numpy as _np
|
|
37
|
+
import pandas as _pd
|
|
38
|
+
from scipy.stats import linregress as _linregress
|
|
39
|
+
from scipy.stats import norm as _norm
|
|
40
|
+
|
|
41
|
+
from . import utils as _utils
|
|
42
|
+
from ._compat import safe_concat
|
|
43
|
+
from .utils import validate_input
|
|
44
|
+
|
|
45
|
+
# Type aliases for common types (Python 3.10+ syntax)
|
|
46
|
+
Returns = _pd.Series | _pd.DataFrame
|
|
47
|
+
"""Type alias for returns data: can be a pandas Series or DataFrame."""
|
|
48
|
+
|
|
49
|
+
# ======== STATS ========
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def pct_rank(prices: _pd.Series, window: int = 60) -> _pd.Series:
|
|
53
|
+
"""
|
|
54
|
+
Calculate the percentile rank of prices over a rolling window.
|
|
55
|
+
|
|
56
|
+
This function computes the percentile rank (0-100) of each price point
|
|
57
|
+
within a rolling window, useful for identifying relative position of
|
|
58
|
+
current prices compared to recent history.
|
|
59
|
+
|
|
60
|
+
Args:
|
|
61
|
+
prices (pd.Series): Series of price data
|
|
62
|
+
window (int): Rolling window size for rank calculation (default: 60)
|
|
63
|
+
|
|
64
|
+
Returns:
|
|
65
|
+
pd.Series: Percentile ranks (0-100 scale)
|
|
66
|
+
|
|
67
|
+
Example:
|
|
68
|
+
>>> prices = pd.Series([100, 105, 110, 95, 120])
|
|
69
|
+
>>> ranks = pct_rank(prices, window=3)
|
|
70
|
+
>>> print(ranks)
|
|
71
|
+
"""
|
|
72
|
+
# Create rolling window shifts and transpose for ranking
|
|
73
|
+
rank = _utils.multi_shift(prices, window).T.rank(pct=True).T
|
|
74
|
+
# Extract first column and convert to percentage scale
|
|
75
|
+
return rank.iloc[:, 0] * 100.0
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def compsum(returns: Returns) -> Returns:
|
|
79
|
+
"""
|
|
80
|
+
Calculate rolling compounded returns (cumulative product).
|
|
81
|
+
|
|
82
|
+
This function computes the cumulative compounded returns by adding 1
|
|
83
|
+
to each return, taking the cumulative product, and subtracting 1.
|
|
84
|
+
|
|
85
|
+
Args:
|
|
86
|
+
returns: Series or DataFrame of returns
|
|
87
|
+
|
|
88
|
+
Returns:
|
|
89
|
+
Cumulative compounded returns (same type as input)
|
|
90
|
+
|
|
91
|
+
Example:
|
|
92
|
+
>>> returns = pd.Series([0.01, 0.02, -0.01, 0.03])
|
|
93
|
+
>>> cumulative = compsum(returns)
|
|
94
|
+
>>> print(cumulative)
|
|
95
|
+
"""
|
|
96
|
+
# Add 1 to convert returns to growth factors, then cumulative product
|
|
97
|
+
return returns.add(1).cumprod(axis=0) - 1
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def comp(returns: Returns) -> _pd.Series | float:
|
|
101
|
+
"""
|
|
102
|
+
Calculate total compounded returns (final cumulative return).
|
|
103
|
+
|
|
104
|
+
This function computes the total compounded return over the entire period
|
|
105
|
+
by converting returns to growth factors and taking their product.
|
|
106
|
+
|
|
107
|
+
Args:
|
|
108
|
+
returns (pd.Series): Series of returns
|
|
109
|
+
|
|
110
|
+
Returns:
|
|
111
|
+
float: Total compounded return
|
|
112
|
+
|
|
113
|
+
Example:
|
|
114
|
+
>>> returns = pd.Series([0.01, 0.02, -0.01, 0.03])
|
|
115
|
+
>>> total_return = comp(returns)
|
|
116
|
+
>>> print(total_return)
|
|
117
|
+
"""
|
|
118
|
+
# Convert returns to growth factors, take product, subtract 1
|
|
119
|
+
return returns.add(1).prod(axis=0) - 1
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def distribution(
|
|
123
|
+
returns: Returns,
|
|
124
|
+
compounded: bool = True,
|
|
125
|
+
prepare_returns: bool = True,
|
|
126
|
+
) -> dict:
|
|
127
|
+
"""
|
|
128
|
+
Analyze return distributions across different time periods.
|
|
129
|
+
|
|
130
|
+
This function calculates return distributions (including outliers) for
|
|
131
|
+
daily, weekly, monthly, quarterly, and yearly periods. It identifies
|
|
132
|
+
outliers using the IQR method (1.5 * IQR beyond Q1/Q3).
|
|
133
|
+
|
|
134
|
+
Args:
|
|
135
|
+
returns (pd.Series): Return series to analyze
|
|
136
|
+
compounded (bool): Whether to compound returns (default: True)
|
|
137
|
+
prepare_returns (bool): Whether to prepare returns first (default: True)
|
|
138
|
+
|
|
139
|
+
Returns:
|
|
140
|
+
dict: Dictionary containing distribution data for each period
|
|
141
|
+
|
|
142
|
+
Example:
|
|
143
|
+
>>> returns = pd.Series([0.01, 0.02, -0.01],
|
|
144
|
+
... index=pd.date_range('2023-01-01', periods=3))
|
|
145
|
+
>>> dist = distribution(returns)
|
|
146
|
+
>>> print(dist['Daily']['values'])
|
|
147
|
+
"""
|
|
148
|
+
def get_outliers(data):
|
|
149
|
+
"""
|
|
150
|
+
Identify outliers using the IQR method.
|
|
151
|
+
|
|
152
|
+
Uses 1.5 * IQR rule: values beyond Q1 - 1.5*IQR or Q3 + 1.5*IQR
|
|
153
|
+
are considered outliers.
|
|
154
|
+
"""
|
|
155
|
+
# https://datascience.stackexchange.com/a/57199
|
|
156
|
+
Q1 = data.quantile(0.25) # First quartile
|
|
157
|
+
Q3 = data.quantile(0.75) # Third quartile
|
|
158
|
+
IQR = Q3 - Q1 # Interquartile range
|
|
159
|
+
|
|
160
|
+
# Create filter for non-outlier values
|
|
161
|
+
filtered = (data >= Q1 - 1.5 * IQR) & (data <= Q3 + 1.5 * IQR)
|
|
162
|
+
|
|
163
|
+
return {
|
|
164
|
+
"values": data.loc[filtered].tolist(),
|
|
165
|
+
"outliers": data.loc[~filtered].tolist(),
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
# Handle DataFrame input by selecting appropriate column
|
|
169
|
+
if isinstance(returns, _pd.DataFrame):
|
|
170
|
+
warn(
|
|
171
|
+
"Pandas DataFrame was passed (Series expected). "
|
|
172
|
+
"Only first column will be used.", stacklevel=2
|
|
173
|
+
)
|
|
174
|
+
returns = returns.copy()
|
|
175
|
+
returns.columns = map(str.lower, returns.columns)
|
|
176
|
+
if len(returns.columns) > 1 and "close" in returns.columns:
|
|
177
|
+
returns = returns["close"]
|
|
178
|
+
else:
|
|
179
|
+
returns = returns[returns.columns[0]]
|
|
180
|
+
|
|
181
|
+
# Choose aggregation function based on compounded parameter
|
|
182
|
+
apply_fnc = comp if compounded else _np.sum
|
|
183
|
+
daily = returns.dropna()
|
|
184
|
+
|
|
185
|
+
# Prepare returns if requested
|
|
186
|
+
if prepare_returns:
|
|
187
|
+
daily = _utils._prepare_returns(daily)
|
|
188
|
+
|
|
189
|
+
# Calculate distributions for different time periods
|
|
190
|
+
return {
|
|
191
|
+
"Daily": get_outliers(daily),
|
|
192
|
+
"Weekly": get_outliers(daily.resample("W-MON").apply(apply_fnc)),
|
|
193
|
+
"Monthly": get_outliers(daily.resample("ME").apply(apply_fnc)),
|
|
194
|
+
"Quarterly": get_outliers(daily.resample("QE").apply(apply_fnc)),
|
|
195
|
+
"Yearly": get_outliers(daily.resample("YE").apply(apply_fnc)),
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def expected_return(
|
|
200
|
+
returns: Returns,
|
|
201
|
+
aggregate: str | None = None,
|
|
202
|
+
compounded: bool = True,
|
|
203
|
+
prepare_returns: bool = True,
|
|
204
|
+
) -> float:
|
|
205
|
+
"""
|
|
206
|
+
Calculate the expected return (geometric mean) for a given period.
|
|
207
|
+
|
|
208
|
+
This function computes the geometric holding period return, which represents
|
|
209
|
+
the expected return per period based on historical data. It's calculated
|
|
210
|
+
as the nth root of the product of (1 + returns) minus 1.
|
|
211
|
+
|
|
212
|
+
Args:
|
|
213
|
+
returns (pd.Series): Return series
|
|
214
|
+
aggregate (str): Aggregation period ('D', 'W', 'M', 'Q', 'Y')
|
|
215
|
+
compounded (bool): Whether to compound returns (default: True)
|
|
216
|
+
prepare_returns (bool): Whether to prepare returns first (default: True)
|
|
217
|
+
|
|
218
|
+
Returns:
|
|
219
|
+
float: Expected return per period
|
|
220
|
+
|
|
221
|
+
Example:
|
|
222
|
+
>>> returns = pd.Series([0.01, 0.02, -0.01, 0.03])
|
|
223
|
+
>>> expected = expected_return(returns)
|
|
224
|
+
>>> print(f"Expected return: {expected:.4f}")
|
|
225
|
+
"""
|
|
226
|
+
if prepare_returns:
|
|
227
|
+
returns = _utils._prepare_returns(returns)
|
|
228
|
+
|
|
229
|
+
# Aggregate returns if period specified
|
|
230
|
+
returns = _utils.aggregate_returns(returns, aggregate, compounded)
|
|
231
|
+
|
|
232
|
+
# Calculate geometric mean: (product of (1 + returns))^(1/n) - 1
|
|
233
|
+
return _np.prod(1 + returns, axis=0) ** (1 / len(returns)) - 1
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def geometric_mean(
|
|
237
|
+
returns: Returns,
|
|
238
|
+
aggregate: str | None = None,
|
|
239
|
+
compounded: bool = True,
|
|
240
|
+
) -> float:
|
|
241
|
+
"""
|
|
242
|
+
Calculate geometric mean of returns.
|
|
243
|
+
|
|
244
|
+
This is a shorthand function for expected_return() with the same parameters.
|
|
245
|
+
|
|
246
|
+
Args:
|
|
247
|
+
returns (pd.Series): Return series
|
|
248
|
+
aggregate (str): Aggregation period ('D', 'W', 'M', 'Q', 'Y')
|
|
249
|
+
compounded (bool): Whether to compound returns (default: True)
|
|
250
|
+
|
|
251
|
+
Returns:
|
|
252
|
+
float: Geometric mean of returns
|
|
253
|
+
"""
|
|
254
|
+
return expected_return(returns, aggregate, compounded)
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def ghpr(
|
|
258
|
+
returns: Returns,
|
|
259
|
+
aggregate: str | None = None,
|
|
260
|
+
compounded: bool = True,
|
|
261
|
+
) -> float:
|
|
262
|
+
"""
|
|
263
|
+
Calculate Geometric Holding Period Return.
|
|
264
|
+
|
|
265
|
+
This is a shorthand function for expected_return() with the same parameters.
|
|
266
|
+
GHPR represents the average rate of return per period.
|
|
267
|
+
|
|
268
|
+
Args:
|
|
269
|
+
returns (pd.Series): Return series
|
|
270
|
+
aggregate (str): Aggregation period ('D', 'W', 'M', 'Q', 'Y')
|
|
271
|
+
compounded (bool): Whether to compound returns (default: True)
|
|
272
|
+
|
|
273
|
+
Returns:
|
|
274
|
+
float: Geometric holding period return
|
|
275
|
+
"""
|
|
276
|
+
return expected_return(returns, aggregate, compounded)
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def outliers(returns: Returns, quantile: float = 0.95) -> Returns:
|
|
280
|
+
"""
|
|
281
|
+
Identify and return outlier returns above a specified quantile.
|
|
282
|
+
|
|
283
|
+
This function filters returns to show only those above the specified
|
|
284
|
+
quantile threshold, helping identify extreme positive performance periods.
|
|
285
|
+
|
|
286
|
+
Args:
|
|
287
|
+
returns (pd.Series): Return series to analyze
|
|
288
|
+
quantile (float): Quantile threshold (default: 0.95 for 95th percentile)
|
|
289
|
+
|
|
290
|
+
Returns:
|
|
291
|
+
pd.Series: Returns above the quantile threshold
|
|
292
|
+
|
|
293
|
+
Example:
|
|
294
|
+
>>> returns = pd.Series([0.01, 0.02, 0.05, -0.01, 0.10])
|
|
295
|
+
>>> outlier_returns = outliers(returns, quantile=0.90)
|
|
296
|
+
>>> print(outlier_returns)
|
|
297
|
+
"""
|
|
298
|
+
# Filter returns above the specified quantile and remove NaN values
|
|
299
|
+
return returns[returns > returns.quantile(quantile)].dropna(how="all")
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def remove_outliers(returns: Returns, quantile: float = 0.95) -> Returns:
|
|
303
|
+
"""
|
|
304
|
+
Remove outlier returns above a specified quantile.
|
|
305
|
+
|
|
306
|
+
This function filters out extreme returns above the quantile threshold,
|
|
307
|
+
useful for robust statistical analysis by removing extreme values.
|
|
308
|
+
|
|
309
|
+
Args:
|
|
310
|
+
returns (pd.Series): Return series to filter
|
|
311
|
+
quantile (float): Quantile threshold (default: 0.95 for 95th percentile)
|
|
312
|
+
|
|
313
|
+
Returns:
|
|
314
|
+
pd.Series: Returns below the quantile threshold
|
|
315
|
+
|
|
316
|
+
Example:
|
|
317
|
+
>>> returns = pd.Series([0.01, 0.02, 0.05, -0.01, 0.10])
|
|
318
|
+
>>> filtered = remove_outliers(returns, quantile=0.90)
|
|
319
|
+
>>> print(filtered)
|
|
320
|
+
"""
|
|
321
|
+
# Keep only returns below the specified quantile threshold
|
|
322
|
+
return returns[returns < returns.quantile(quantile)]
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def best(
|
|
326
|
+
returns: Returns,
|
|
327
|
+
aggregate: str | None = None,
|
|
328
|
+
compounded: bool = True,
|
|
329
|
+
prepare_returns: bool = True,
|
|
330
|
+
) -> float:
|
|
331
|
+
"""
|
|
332
|
+
Find the best (highest) return for a given period.
|
|
333
|
+
|
|
334
|
+
This function identifies the maximum return over the specified aggregation
|
|
335
|
+
period, helping identify the best performing period in the dataset.
|
|
336
|
+
|
|
337
|
+
Args:
|
|
338
|
+
returns (pd.Series): Return series to analyze
|
|
339
|
+
aggregate (str): Aggregation period ('D', 'W', 'M', 'Q', 'Y')
|
|
340
|
+
compounded (bool): Whether to compound returns (default: True)
|
|
341
|
+
prepare_returns (bool): Whether to prepare returns first (default: True)
|
|
342
|
+
|
|
343
|
+
Returns:
|
|
344
|
+
float: Best (maximum) return for the period
|
|
345
|
+
|
|
346
|
+
Example:
|
|
347
|
+
>>> returns = pd.Series([0.01, 0.02, -0.01, 0.03])
|
|
348
|
+
>>> best_return = best(returns)
|
|
349
|
+
>>> print(f"Best return: {best_return:.4f}")
|
|
350
|
+
"""
|
|
351
|
+
if prepare_returns:
|
|
352
|
+
returns = _utils._prepare_returns(returns)
|
|
353
|
+
|
|
354
|
+
# Aggregate returns and find maximum
|
|
355
|
+
return _utils.aggregate_returns(returns, aggregate, compounded).max()
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def worst(
|
|
359
|
+
returns: Returns,
|
|
360
|
+
aggregate: str | None = None,
|
|
361
|
+
compounded: bool = True,
|
|
362
|
+
prepare_returns: bool = True,
|
|
363
|
+
) -> float:
|
|
364
|
+
"""
|
|
365
|
+
Find the worst (lowest) return for a given period.
|
|
366
|
+
|
|
367
|
+
This function identifies the minimum return over the specified aggregation
|
|
368
|
+
period, helping identify the worst performing period in the dataset.
|
|
369
|
+
|
|
370
|
+
Args:
|
|
371
|
+
returns (pd.Series): Return series to analyze
|
|
372
|
+
aggregate (str): Aggregation period ('D', 'W', 'M', 'Q', 'Y')
|
|
373
|
+
compounded (bool): Whether to compound returns (default: True)
|
|
374
|
+
prepare_returns (bool): Whether to prepare returns first (default: True)
|
|
375
|
+
|
|
376
|
+
Returns:
|
|
377
|
+
float: Worst (minimum) return for the period
|
|
378
|
+
|
|
379
|
+
Example:
|
|
380
|
+
>>> returns = pd.Series([0.01, 0.02, -0.01, 0.03])
|
|
381
|
+
>>> worst_return = worst(returns)
|
|
382
|
+
>>> print(f"Worst return: {worst_return:.4f}")
|
|
383
|
+
"""
|
|
384
|
+
if prepare_returns:
|
|
385
|
+
returns = _utils._prepare_returns(returns)
|
|
386
|
+
|
|
387
|
+
# Aggregate returns and find minimum
|
|
388
|
+
return _utils.aggregate_returns(returns, aggregate, compounded).min()
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def consecutive_wins(
|
|
392
|
+
returns: Returns,
|
|
393
|
+
aggregate: str | None = None,
|
|
394
|
+
compounded: bool = True,
|
|
395
|
+
prepare_returns: bool = True,
|
|
396
|
+
) -> int:
|
|
397
|
+
"""
|
|
398
|
+
Calculate the maximum number of consecutive winning periods.
|
|
399
|
+
|
|
400
|
+
This function identifies the longest streak of positive returns, which
|
|
401
|
+
helps assess the consistency of positive performance.
|
|
402
|
+
|
|
403
|
+
Args:
|
|
404
|
+
returns (pd.Series): Return series to analyze
|
|
405
|
+
aggregate (str): Aggregation period ('D', 'W', 'M', 'Q', 'Y')
|
|
406
|
+
compounded (bool): Whether to compound returns (default: True)
|
|
407
|
+
prepare_returns (bool): Whether to prepare returns first (default: True)
|
|
408
|
+
|
|
409
|
+
Returns:
|
|
410
|
+
int: Maximum number of consecutive winning periods
|
|
411
|
+
|
|
412
|
+
Example:
|
|
413
|
+
>>> returns = pd.Series([0.01, 0.02, 0.03, -0.01, 0.02])
|
|
414
|
+
>>> max_wins = consecutive_wins(returns)
|
|
415
|
+
>>> print(f"Max consecutive wins: {max_wins}")
|
|
416
|
+
"""
|
|
417
|
+
if prepare_returns:
|
|
418
|
+
returns = _utils._prepare_returns(returns)
|
|
419
|
+
|
|
420
|
+
# Aggregate returns and convert to boolean (positive = True)
|
|
421
|
+
returns = _utils.aggregate_returns(returns, aggregate, compounded) > 0
|
|
422
|
+
|
|
423
|
+
# Count consecutive True values and return maximum
|
|
424
|
+
return _utils._count_consecutive(returns).max()
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def consecutive_losses(
|
|
428
|
+
returns: Returns,
|
|
429
|
+
aggregate: str | None = None,
|
|
430
|
+
compounded: bool = True,
|
|
431
|
+
prepare_returns: bool = True,
|
|
432
|
+
) -> int:
|
|
433
|
+
"""
|
|
434
|
+
Calculate the maximum number of consecutive losing periods.
|
|
435
|
+
|
|
436
|
+
This function identifies the longest streak of negative returns, which
|
|
437
|
+
helps assess the potential for extended drawdown periods.
|
|
438
|
+
|
|
439
|
+
Args:
|
|
440
|
+
returns (pd.Series): Return series to analyze
|
|
441
|
+
aggregate (str): Aggregation period ('D', 'W', 'M', 'Q', 'Y')
|
|
442
|
+
compounded (bool): Whether to compound returns (default: True)
|
|
443
|
+
prepare_returns (bool): Whether to prepare returns first (default: True)
|
|
444
|
+
|
|
445
|
+
Returns:
|
|
446
|
+
int: Maximum number of consecutive losing periods
|
|
447
|
+
|
|
448
|
+
Example:
|
|
449
|
+
>>> returns = pd.Series([0.01, -0.02, -0.01, -0.01, 0.02])
|
|
450
|
+
>>> max_losses = consecutive_losses(returns)
|
|
451
|
+
>>> print(f"Max consecutive losses: {max_losses}")
|
|
452
|
+
"""
|
|
453
|
+
if prepare_returns:
|
|
454
|
+
returns = _utils._prepare_returns(returns)
|
|
455
|
+
|
|
456
|
+
# Aggregate returns and convert to boolean (negative = True)
|
|
457
|
+
returns = _utils.aggregate_returns(returns, aggregate, compounded) < 0
|
|
458
|
+
|
|
459
|
+
# Count consecutive True values and return maximum
|
|
460
|
+
return _utils._count_consecutive(returns).max()
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
def exposure(
|
|
464
|
+
returns: Returns,
|
|
465
|
+
prepare_returns: bool = True,
|
|
466
|
+
) -> float | _pd.Series:
|
|
467
|
+
"""
|
|
468
|
+
Calculate market exposure time as percentage of periods with non-zero returns.
|
|
469
|
+
|
|
470
|
+
This function measures how often the strategy was actually invested
|
|
471
|
+
(had non-zero returns) versus being in cash or having zero positions.
|
|
472
|
+
|
|
473
|
+
Args:
|
|
474
|
+
returns (pd.Series or pd.DataFrame): Return series or DataFrame
|
|
475
|
+
prepare_returns (bool): Whether to prepare returns first (default: True)
|
|
476
|
+
|
|
477
|
+
Returns:
|
|
478
|
+
float or pd.Series: Exposure percentage (0-1 scale)
|
|
479
|
+
|
|
480
|
+
Example:
|
|
481
|
+
>>> returns = pd.Series([0.01, 0.00, 0.02, 0.00, 0.03])
|
|
482
|
+
>>> exp = exposure(returns)
|
|
483
|
+
>>> print(f"Market exposure: {exp:.2%}")
|
|
484
|
+
"""
|
|
485
|
+
if prepare_returns:
|
|
486
|
+
returns = _utils._prepare_returns(returns)
|
|
487
|
+
|
|
488
|
+
def _exposure(ret):
|
|
489
|
+
"""
|
|
490
|
+
Calculate exposure for a single return series.
|
|
491
|
+
|
|
492
|
+
Counts non-NaN, non-zero returns and divides by total periods.
|
|
493
|
+
Rounds up to nearest percent to avoid zero exposure from rounding.
|
|
494
|
+
"""
|
|
495
|
+
# Count non-NaN and non-zero returns
|
|
496
|
+
ex = len(ret[(~_np.isnan(ret)) & (ret != 0)]) / len(ret)
|
|
497
|
+
# Round up to nearest percent
|
|
498
|
+
return _ceil(ex * 100) / 100
|
|
499
|
+
|
|
500
|
+
# Handle DataFrame input by calculating exposure for each column
|
|
501
|
+
if isinstance(returns, _pd.DataFrame):
|
|
502
|
+
_df = {}
|
|
503
|
+
for col in returns.columns:
|
|
504
|
+
_df[col] = _exposure(returns[col])
|
|
505
|
+
return _pd.Series(_df)
|
|
506
|
+
|
|
507
|
+
return _exposure(returns)
|
|
508
|
+
|
|
509
|
+
|
|
510
|
+
def win_rate(
|
|
511
|
+
returns: Returns,
|
|
512
|
+
aggregate: str | None = None,
|
|
513
|
+
compounded: bool = True,
|
|
514
|
+
prepare_returns: bool = True,
|
|
515
|
+
) -> float | _pd.Series:
|
|
516
|
+
"""
|
|
517
|
+
Calculate the win rate (percentage of profitable periods).
|
|
518
|
+
|
|
519
|
+
This function computes the ratio of positive returns to total non-zero
|
|
520
|
+
returns, providing a measure of how often the strategy generates profits.
|
|
521
|
+
|
|
522
|
+
Args:
|
|
523
|
+
returns (pd.Series or pd.DataFrame): Return series or DataFrame
|
|
524
|
+
aggregate (str): Aggregation period ('D', 'W', 'M', 'Q', 'Y')
|
|
525
|
+
compounded (bool): Whether to compound returns (default: True)
|
|
526
|
+
prepare_returns (bool): Whether to prepare returns first (default: True)
|
|
527
|
+
|
|
528
|
+
Returns:
|
|
529
|
+
float or pd.Series: Win rate as decimal (0-1 scale)
|
|
530
|
+
|
|
531
|
+
Example:
|
|
532
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
533
|
+
>>> wr = win_rate(returns)
|
|
534
|
+
>>> print(f"Win rate: {wr:.2%}")
|
|
535
|
+
"""
|
|
536
|
+
def _win_rate(series):
|
|
537
|
+
"""
|
|
538
|
+
Calculate win rate for a single return series.
|
|
539
|
+
|
|
540
|
+
Handles edge cases like no non-zero returns and provides
|
|
541
|
+
error handling for calculation issues.
|
|
542
|
+
"""
|
|
543
|
+
try:
|
|
544
|
+
# Filter out zero returns (periods with no trading)
|
|
545
|
+
non_zero_returns = series[series != 0]
|
|
546
|
+
if len(non_zero_returns) == 0:
|
|
547
|
+
warn("No non-zero returns found for win rate calculation, returning 0.0", stacklevel=2)
|
|
548
|
+
return 0.0
|
|
549
|
+
|
|
550
|
+
# Calculate ratio of positive returns to non-zero returns
|
|
551
|
+
return len(series[series > 0]) / len(non_zero_returns)
|
|
552
|
+
except (ValueError, TypeError) as e:
|
|
553
|
+
warn(f"Error calculating win rate: {e}, returning 0.0", stacklevel=2)
|
|
554
|
+
return 0.0
|
|
555
|
+
|
|
556
|
+
if prepare_returns:
|
|
557
|
+
returns = _utils._prepare_returns(returns)
|
|
558
|
+
|
|
559
|
+
# Aggregate returns if period specified
|
|
560
|
+
if aggregate:
|
|
561
|
+
returns = _utils.aggregate_returns(returns, aggregate, compounded)
|
|
562
|
+
|
|
563
|
+
# Handle DataFrame input by calculating win rate for each column
|
|
564
|
+
if isinstance(returns, _pd.DataFrame):
|
|
565
|
+
_df = {}
|
|
566
|
+
for col in returns.columns:
|
|
567
|
+
_df[col] = _win_rate(returns[col])
|
|
568
|
+
return _pd.Series(_df)
|
|
569
|
+
|
|
570
|
+
return _win_rate(returns)
|
|
571
|
+
|
|
572
|
+
|
|
573
|
+
def avg_return(
|
|
574
|
+
returns: Returns,
|
|
575
|
+
aggregate: str | None = None,
|
|
576
|
+
compounded: bool = True,
|
|
577
|
+
prepare_returns: bool = True,
|
|
578
|
+
) -> float:
|
|
579
|
+
"""
|
|
580
|
+
Calculate the average return per period (excluding zero returns).
|
|
581
|
+
|
|
582
|
+
This function computes the mean of non-zero returns, providing insight
|
|
583
|
+
into the typical magnitude of returns when the strategy is active.
|
|
584
|
+
|
|
585
|
+
Args:
|
|
586
|
+
returns (pd.Series): Return series to analyze
|
|
587
|
+
aggregate (str): Aggregation period ('D', 'W', 'M', 'Q', 'Y')
|
|
588
|
+
compounded (bool): Whether to compound returns (default: True)
|
|
589
|
+
prepare_returns (bool): Whether to prepare returns first (default: True)
|
|
590
|
+
|
|
591
|
+
Returns:
|
|
592
|
+
float: Average return per period
|
|
593
|
+
|
|
594
|
+
Example:
|
|
595
|
+
>>> returns = pd.Series([0.01, 0.00, 0.02, -0.01, 0.03])
|
|
596
|
+
>>> avg_ret = avg_return(returns)
|
|
597
|
+
>>> print(f"Average return: {avg_ret:.4f}")
|
|
598
|
+
"""
|
|
599
|
+
if prepare_returns:
|
|
600
|
+
returns = _utils._prepare_returns(returns)
|
|
601
|
+
|
|
602
|
+
# Aggregate returns if period specified
|
|
603
|
+
if aggregate:
|
|
604
|
+
returns = _utils.aggregate_returns(returns, aggregate, compounded)
|
|
605
|
+
|
|
606
|
+
# Calculate mean of non-zero returns
|
|
607
|
+
return returns[returns != 0].dropna().mean()
|
|
608
|
+
|
|
609
|
+
|
|
610
|
+
def avg_win(
|
|
611
|
+
returns: Returns,
|
|
612
|
+
aggregate: str | None = None,
|
|
613
|
+
compounded: bool = True,
|
|
614
|
+
prepare_returns: bool = True,
|
|
615
|
+
) -> float:
|
|
616
|
+
"""
|
|
617
|
+
Calculate the average winning return (mean of positive returns).
|
|
618
|
+
|
|
619
|
+
This function computes the mean of positive returns only, showing
|
|
620
|
+
the typical magnitude of profitable periods.
|
|
621
|
+
|
|
622
|
+
Args:
|
|
623
|
+
returns (pd.Series): Return series to analyze
|
|
624
|
+
aggregate (str): Aggregation period ('D', 'W', 'M', 'Q', 'Y')
|
|
625
|
+
compounded (bool): Whether to compound returns (default: True)
|
|
626
|
+
prepare_returns (bool): Whether to prepare returns first (default: True)
|
|
627
|
+
|
|
628
|
+
Returns:
|
|
629
|
+
float: Average winning return
|
|
630
|
+
|
|
631
|
+
Example:
|
|
632
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
633
|
+
>>> avg_win_ret = avg_win(returns)
|
|
634
|
+
>>> print(f"Average win: {avg_win_ret:.4f}")
|
|
635
|
+
"""
|
|
636
|
+
if prepare_returns:
|
|
637
|
+
returns = _utils._prepare_returns(returns)
|
|
638
|
+
|
|
639
|
+
# Aggregate returns if period specified
|
|
640
|
+
if aggregate:
|
|
641
|
+
returns = _utils.aggregate_returns(returns, aggregate, compounded)
|
|
642
|
+
|
|
643
|
+
# Calculate mean of positive returns only
|
|
644
|
+
return returns[returns > 0].dropna().mean()
|
|
645
|
+
|
|
646
|
+
|
|
647
|
+
def avg_loss(
|
|
648
|
+
returns: Returns,
|
|
649
|
+
aggregate: str | None = None,
|
|
650
|
+
compounded: bool = True,
|
|
651
|
+
prepare_returns: bool = True,
|
|
652
|
+
) -> float:
|
|
653
|
+
"""
|
|
654
|
+
Calculate the average losing return (mean of negative returns).
|
|
655
|
+
|
|
656
|
+
This function computes the mean of negative returns only, showing
|
|
657
|
+
the typical magnitude of losing periods.
|
|
658
|
+
|
|
659
|
+
Args:
|
|
660
|
+
returns (pd.Series): Return series to analyze
|
|
661
|
+
aggregate (str): Aggregation period ('D', 'W', 'M', 'Q', 'Y')
|
|
662
|
+
compounded (bool): Whether to compound returns (default: True)
|
|
663
|
+
prepare_returns (bool): Whether to prepare returns first (default: True)
|
|
664
|
+
|
|
665
|
+
Returns:
|
|
666
|
+
float: Average losing return (negative value)
|
|
667
|
+
|
|
668
|
+
Example:
|
|
669
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
670
|
+
>>> avg_loss_ret = avg_loss(returns)
|
|
671
|
+
>>> print(f"Average loss: {avg_loss_ret:.4f}")
|
|
672
|
+
"""
|
|
673
|
+
if prepare_returns:
|
|
674
|
+
returns = _utils._prepare_returns(returns)
|
|
675
|
+
|
|
676
|
+
# Aggregate returns if period specified
|
|
677
|
+
if aggregate:
|
|
678
|
+
returns = _utils.aggregate_returns(returns, aggregate, compounded)
|
|
679
|
+
|
|
680
|
+
# Calculate mean of negative returns only
|
|
681
|
+
return returns[returns < 0].dropna().mean()
|
|
682
|
+
|
|
683
|
+
|
|
684
|
+
def volatility(
|
|
685
|
+
returns: Returns,
|
|
686
|
+
periods: int = 252,
|
|
687
|
+
annualize: bool = True,
|
|
688
|
+
prepare_returns: bool = True,
|
|
689
|
+
) -> float | _pd.Series:
|
|
690
|
+
"""
|
|
691
|
+
Calculate volatility (standard deviation) of returns.
|
|
692
|
+
|
|
693
|
+
This function computes the volatility of returns, which measures the
|
|
694
|
+
degree of variation in returns over time. Higher volatility indicates
|
|
695
|
+
more uncertainty and risk.
|
|
696
|
+
|
|
697
|
+
Args:
|
|
698
|
+
returns: Return series or DataFrame to analyze
|
|
699
|
+
periods: Number of periods per year for annualization (default: 252)
|
|
700
|
+
annualize: Whether to annualize the volatility (default: True)
|
|
701
|
+
prepare_returns: Whether to prepare returns first (default: True)
|
|
702
|
+
|
|
703
|
+
Returns:
|
|
704
|
+
Volatility (annualized if annualize=True)
|
|
705
|
+
|
|
706
|
+
Example:
|
|
707
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
708
|
+
>>> vol = volatility(returns)
|
|
709
|
+
>>> print(f"Annualized volatility: {vol:.4f}")
|
|
710
|
+
"""
|
|
711
|
+
validate_input(returns)
|
|
712
|
+
|
|
713
|
+
if prepare_returns:
|
|
714
|
+
returns = _utils._prepare_returns(returns)
|
|
715
|
+
|
|
716
|
+
# Calculate standard deviation of returns
|
|
717
|
+
std = returns.std()
|
|
718
|
+
|
|
719
|
+
# Annualize by multiplying by square root of periods per year
|
|
720
|
+
if annualize:
|
|
721
|
+
return std * _np.sqrt(periods)
|
|
722
|
+
|
|
723
|
+
return std
|
|
724
|
+
|
|
725
|
+
|
|
726
|
+
def rolling_volatility(
|
|
727
|
+
returns: Returns,
|
|
728
|
+
rolling_period: int = 126,
|
|
729
|
+
periods_per_year: int = 252,
|
|
730
|
+
prepare_returns: bool = True,
|
|
731
|
+
) -> _pd.Series:
|
|
732
|
+
"""
|
|
733
|
+
Calculate rolling volatility over a specified window.
|
|
734
|
+
|
|
735
|
+
This function computes volatility using a rolling window, providing
|
|
736
|
+
a time-varying measure of risk that adapts to changing market conditions.
|
|
737
|
+
|
|
738
|
+
Args:
|
|
739
|
+
returns (pd.Series): Return series to analyze
|
|
740
|
+
rolling_period (int): Rolling window size (default: 126, ~6 months)
|
|
741
|
+
periods_per_year (int): Periods per year for annualization (default: 252)
|
|
742
|
+
prepare_returns (bool): Whether to prepare returns first (default: True)
|
|
743
|
+
|
|
744
|
+
Returns:
|
|
745
|
+
pd.Series: Rolling volatility series (annualized)
|
|
746
|
+
|
|
747
|
+
Example:
|
|
748
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
749
|
+
>>> rolling_vol = rolling_volatility(returns, rolling_period=3)
|
|
750
|
+
>>> print(rolling_vol)
|
|
751
|
+
"""
|
|
752
|
+
if prepare_returns:
|
|
753
|
+
returns = _utils._prepare_returns(returns, rolling_period)
|
|
754
|
+
|
|
755
|
+
# Calculate rolling standard deviation and annualize
|
|
756
|
+
return returns.rolling(rolling_period).std() * _np.sqrt(periods_per_year)
|
|
757
|
+
|
|
758
|
+
|
|
759
|
+
def implied_volatility(
|
|
760
|
+
returns: Returns,
|
|
761
|
+
periods: int = 252,
|
|
762
|
+
annualize: bool = True,
|
|
763
|
+
) -> float | _pd.Series:
|
|
764
|
+
"""
|
|
765
|
+
Calculate implied volatility using log returns.
|
|
766
|
+
|
|
767
|
+
This function computes volatility using log returns instead of simple
|
|
768
|
+
returns, which is mathematically more appropriate for continuous compounding.
|
|
769
|
+
|
|
770
|
+
Args:
|
|
771
|
+
returns (pd.Series): Return series to analyze
|
|
772
|
+
periods (int): Number of periods for rolling calculation (default: 252)
|
|
773
|
+
annualize (bool): Whether to annualize the volatility (default: True)
|
|
774
|
+
|
|
775
|
+
Returns:
|
|
776
|
+
float or pd.Series: Implied volatility
|
|
777
|
+
|
|
778
|
+
Example:
|
|
779
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
780
|
+
>>> impl_vol = implied_volatility(returns)
|
|
781
|
+
>>> print(f"Implied volatility: {impl_vol:.4f}")
|
|
782
|
+
"""
|
|
783
|
+
# Convert to log returns for continuous compounding
|
|
784
|
+
logret = _utils.log_returns(returns)
|
|
785
|
+
|
|
786
|
+
if annualize:
|
|
787
|
+
# Calculate rolling volatility and annualize
|
|
788
|
+
return logret.rolling(periods).std() * _np.sqrt(periods)
|
|
789
|
+
|
|
790
|
+
# Return simple standard deviation
|
|
791
|
+
return logret.std()
|
|
792
|
+
|
|
793
|
+
|
|
794
|
+
def autocorr_penalty(
|
|
795
|
+
returns: Returns,
|
|
796
|
+
prepare_returns: bool = False,
|
|
797
|
+
) -> float:
|
|
798
|
+
"""
|
|
799
|
+
Calculate autocorrelation penalty for risk-adjusted metrics.
|
|
800
|
+
|
|
801
|
+
This function computes a penalty factor that accounts for autocorrelation
|
|
802
|
+
in returns, which can inflate risk-adjusted ratios. Used to adjust
|
|
803
|
+
Sharpe and Sortino ratios for more realistic risk assessment.
|
|
804
|
+
|
|
805
|
+
Args:
|
|
806
|
+
returns (pd.Series): Return series to analyze
|
|
807
|
+
prepare_returns (bool): Whether to prepare returns first (default: False)
|
|
808
|
+
|
|
809
|
+
Returns:
|
|
810
|
+
float: Autocorrelation penalty factor (>= 1)
|
|
811
|
+
|
|
812
|
+
Example:
|
|
813
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
814
|
+
>>> penalty = autocorr_penalty(returns)
|
|
815
|
+
>>> print(f"Autocorrelation penalty: {penalty:.4f}")
|
|
816
|
+
"""
|
|
817
|
+
if prepare_returns:
|
|
818
|
+
returns = _utils._prepare_returns(returns)
|
|
819
|
+
|
|
820
|
+
# Handle DataFrame input by selecting first column
|
|
821
|
+
if isinstance(returns, _pd.DataFrame):
|
|
822
|
+
returns = returns[returns.columns[0]]
|
|
823
|
+
|
|
824
|
+
# returns.to_csv('/Users/ran/Desktop/test.csv')
|
|
825
|
+
num = len(returns)
|
|
826
|
+
|
|
827
|
+
# Calculate autocorrelation coefficient between consecutive returns
|
|
828
|
+
coef = _np.abs(_np.corrcoef(returns[:-1], returns[1:])[0, 1])
|
|
829
|
+
|
|
830
|
+
# Vectorized calculation instead of list comprehension
|
|
831
|
+
x = _np.arange(1, num)
|
|
832
|
+
# Calculate weighted correlation effects over time
|
|
833
|
+
corr = ((num - x) / num) * (coef**x)
|
|
834
|
+
|
|
835
|
+
# Return penalty factor (square root of 1 + 2 * sum of correlations)
|
|
836
|
+
return _np.sqrt(1 + 2 * _np.sum(corr))
|
|
837
|
+
|
|
838
|
+
|
|
839
|
+
# ======= METRICS =======
|
|
840
|
+
|
|
841
|
+
|
|
842
|
+
def sharpe(
|
|
843
|
+
returns: Returns,
|
|
844
|
+
rf: float = 0.0,
|
|
845
|
+
periods: int = 252,
|
|
846
|
+
annualize: bool = True,
|
|
847
|
+
smart: bool = False,
|
|
848
|
+
) -> float | _pd.Series:
|
|
849
|
+
"""
|
|
850
|
+
Calculate the Sharpe ratio of excess returns.
|
|
851
|
+
|
|
852
|
+
The Sharpe ratio measures risk-adjusted returns by dividing excess returns
|
|
853
|
+
(returns - risk-free rate) by the standard deviation of returns.
|
|
854
|
+
Higher values indicate better risk-adjusted performance.
|
|
855
|
+
|
|
856
|
+
Args:
|
|
857
|
+
returns: Return series or DataFrame to analyze
|
|
858
|
+
rf: Risk-free rate (annualized if periods specified, default: 0.0)
|
|
859
|
+
periods: Periods per year for annualization (default: 252)
|
|
860
|
+
annualize: Whether to annualize the ratio (default: True)
|
|
861
|
+
smart: Whether to apply autocorrelation penalty (default: False)
|
|
862
|
+
|
|
863
|
+
Returns:
|
|
864
|
+
Sharpe ratio (float for Series input, Series for DataFrame input)
|
|
865
|
+
|
|
866
|
+
Raises:
|
|
867
|
+
ValueError: If rf is non-zero but periods is None
|
|
868
|
+
|
|
869
|
+
Example:
|
|
870
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
871
|
+
>>> sharpe_ratio = sharpe(returns, rf=0.02)
|
|
872
|
+
>>> print(f"Sharpe ratio: {sharpe_ratio:.4f}")
|
|
873
|
+
"""
|
|
874
|
+
validate_input(returns)
|
|
875
|
+
|
|
876
|
+
# Validate parameters for risk-free rate handling
|
|
877
|
+
if rf != 0 and periods is None:
|
|
878
|
+
raise ValueError("periods parameter is required when risk-free rate (rf) is non-zero. "
|
|
879
|
+
"This is needed to properly annualize the risk-free rate.")
|
|
880
|
+
|
|
881
|
+
# Prepare returns (subtract risk-free rate if applicable)
|
|
882
|
+
returns = _utils._prepare_returns(returns, rf, periods)
|
|
883
|
+
|
|
884
|
+
# Calculate standard deviation as denominator
|
|
885
|
+
divisor = returns.std(ddof=1)
|
|
886
|
+
|
|
887
|
+
# Apply autocorrelation penalty if smart mode enabled
|
|
888
|
+
if smart:
|
|
889
|
+
# penalize sharpe with auto correlation
|
|
890
|
+
divisor = divisor * autocorr_penalty(returns)
|
|
891
|
+
|
|
892
|
+
# Calculate base Sharpe ratio
|
|
893
|
+
res = returns.mean() / divisor
|
|
894
|
+
|
|
895
|
+
# Annualize if requested
|
|
896
|
+
if annualize:
|
|
897
|
+
return res * _np.sqrt(1 if periods is None else periods)
|
|
898
|
+
|
|
899
|
+
return res
|
|
900
|
+
|
|
901
|
+
|
|
902
|
+
def smart_sharpe(
|
|
903
|
+
returns: Returns,
|
|
904
|
+
rf: float = 0.0,
|
|
905
|
+
periods: int = 252,
|
|
906
|
+
annualize: bool = True,
|
|
907
|
+
) -> float | _pd.Series:
|
|
908
|
+
"""
|
|
909
|
+
Calculate the Smart Sharpe ratio (Sharpe with autocorrelation penalty).
|
|
910
|
+
|
|
911
|
+
This is a wrapper for the sharpe() function with smart=True, which
|
|
912
|
+
applies an autocorrelation penalty to provide more realistic risk-adjusted
|
|
913
|
+
returns for strategies with autocorrelated returns.
|
|
914
|
+
|
|
915
|
+
Args:
|
|
916
|
+
returns (pd.Series): Return series to analyze
|
|
917
|
+
rf (float): Risk-free rate (annualized, default: 0.0)
|
|
918
|
+
periods (int): Periods per year for annualization (default: 252)
|
|
919
|
+
annualize (bool): Whether to annualize the ratio (default: True)
|
|
920
|
+
|
|
921
|
+
Returns:
|
|
922
|
+
float: Smart Sharpe ratio
|
|
923
|
+
|
|
924
|
+
Example:
|
|
925
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
926
|
+
>>> smart_sharpe_ratio = smart_sharpe(returns)
|
|
927
|
+
>>> print(f"Smart Sharpe ratio: {smart_sharpe_ratio:.4f}")
|
|
928
|
+
"""
|
|
929
|
+
return sharpe(returns, rf, periods, annualize, True)
|
|
930
|
+
|
|
931
|
+
|
|
932
|
+
def rolling_sharpe(
|
|
933
|
+
returns: Returns,
|
|
934
|
+
rf: float = 0.0,
|
|
935
|
+
rolling_period: int = 126,
|
|
936
|
+
annualize: bool = True,
|
|
937
|
+
periods_per_year: int = 252,
|
|
938
|
+
prepare_returns: bool = True,
|
|
939
|
+
) -> _pd.Series:
|
|
940
|
+
"""
|
|
941
|
+
Calculate rolling Sharpe ratio over a specified window.
|
|
942
|
+
|
|
943
|
+
This function computes the Sharpe ratio using a rolling window, providing
|
|
944
|
+
a time-varying measure of risk-adjusted performance that adapts to
|
|
945
|
+
changing market conditions.
|
|
946
|
+
|
|
947
|
+
Args:
|
|
948
|
+
returns (pd.Series): Return series to analyze
|
|
949
|
+
rf (float): Risk-free rate (annualized, default: 0.0)
|
|
950
|
+
rolling_period (int): Rolling window size (default: 126, ~6 months)
|
|
951
|
+
annualize (bool): Whether to annualize the ratio (default: True)
|
|
952
|
+
periods_per_year (int): Periods per year for annualization (default: 252)
|
|
953
|
+
prepare_returns (bool): Whether to prepare returns first (default: True)
|
|
954
|
+
|
|
955
|
+
Returns:
|
|
956
|
+
pd.Series: Rolling Sharpe ratio series
|
|
957
|
+
|
|
958
|
+
Raises:
|
|
959
|
+
Exception: If rf != 0 and rolling_period is None
|
|
960
|
+
|
|
961
|
+
Example:
|
|
962
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
963
|
+
>>> rolling_sharpe_ratio = rolling_sharpe(returns, rolling_period=3)
|
|
964
|
+
>>> print(rolling_sharpe_ratio)
|
|
965
|
+
"""
|
|
966
|
+
# Validate parameters for risk-free rate handling
|
|
967
|
+
if rf != 0 and rolling_period is None:
|
|
968
|
+
raise Exception("Must provide periods if rf != 0")
|
|
969
|
+
|
|
970
|
+
if prepare_returns:
|
|
971
|
+
returns = _utils._prepare_returns(returns, rf, rolling_period)
|
|
972
|
+
|
|
973
|
+
# Calculate rolling mean and standard deviation
|
|
974
|
+
res = returns.rolling(rolling_period).mean() / returns.rolling(rolling_period).std()
|
|
975
|
+
|
|
976
|
+
# Annualize if requested
|
|
977
|
+
if annualize:
|
|
978
|
+
res = res * _np.sqrt(1 if periods_per_year is None else periods_per_year)
|
|
979
|
+
|
|
980
|
+
return res
|
|
981
|
+
|
|
982
|
+
|
|
983
|
+
def sortino(
|
|
984
|
+
returns: Returns,
|
|
985
|
+
rf: float = 0,
|
|
986
|
+
periods: int = 252,
|
|
987
|
+
annualize: bool = True,
|
|
988
|
+
smart: bool = False,
|
|
989
|
+
) -> float | _pd.Series:
|
|
990
|
+
"""
|
|
991
|
+
Calculate the Sortino ratio of excess returns.
|
|
992
|
+
|
|
993
|
+
The Sortino ratio is similar to the Sharpe ratio but uses downside deviation
|
|
994
|
+
instead of total volatility, focusing only on harmful volatility.
|
|
995
|
+
This provides a more accurate measure of risk-adjusted returns.
|
|
996
|
+
|
|
997
|
+
Args:
|
|
998
|
+
returns (pd.Series): Return series to analyze
|
|
999
|
+
rf (float): Risk-free rate (annualized, default: 0.0)
|
|
1000
|
+
periods (int): Periods per year for annualization (default: 252)
|
|
1001
|
+
annualize (bool): Whether to annualize the ratio (default: True)
|
|
1002
|
+
smart (bool): Whether to apply autocorrelation penalty (default: False)
|
|
1003
|
+
|
|
1004
|
+
Returns:
|
|
1005
|
+
float: Sortino ratio
|
|
1006
|
+
|
|
1007
|
+
Raises:
|
|
1008
|
+
ValueError: If rf is non-zero but periods is None
|
|
1009
|
+
|
|
1010
|
+
Example:
|
|
1011
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
1012
|
+
>>> sortino_ratio = sortino(returns, rf=0.02)
|
|
1013
|
+
>>> print(f"Sortino ratio: {sortino_ratio:.4f}")
|
|
1014
|
+
|
|
1015
|
+
Note:
|
|
1016
|
+
Calculation is based on this paper by Red Rock Capital:
|
|
1017
|
+
http://www.redrockcapital.com/Sortino__A__Sharper__Ratio_Red_Rock_Capital.pdf
|
|
1018
|
+
"""
|
|
1019
|
+
validate_input(returns)
|
|
1020
|
+
|
|
1021
|
+
# Validate parameters for risk-free rate handling
|
|
1022
|
+
if rf != 0 and periods is None:
|
|
1023
|
+
raise ValueError("periods parameter is required when risk-free rate (rf) is non-zero. "
|
|
1024
|
+
"This is needed to properly annualize the risk-free rate.")
|
|
1025
|
+
|
|
1026
|
+
# Prepare returns (subtract risk-free rate if applicable)
|
|
1027
|
+
returns = _utils._prepare_returns(returns, rf, periods)
|
|
1028
|
+
|
|
1029
|
+
# Calculate downside deviation (only negative returns)
|
|
1030
|
+
downside = _np.sqrt((returns[returns < 0] ** 2).sum() / len(returns))
|
|
1031
|
+
|
|
1032
|
+
# Apply autocorrelation penalty if smart mode enabled
|
|
1033
|
+
if smart:
|
|
1034
|
+
# penalize sortino with auto correlation
|
|
1035
|
+
downside = downside * autocorr_penalty(returns)
|
|
1036
|
+
|
|
1037
|
+
# Calculate base Sortino ratio
|
|
1038
|
+
# Handle both Series (DataFrame input) and scalar (Series input) cases
|
|
1039
|
+
if isinstance(downside, _pd.Series):
|
|
1040
|
+
res = returns.mean() / downside.replace(0, _np.nan)
|
|
1041
|
+
else:
|
|
1042
|
+
if downside == 0:
|
|
1043
|
+
res = _np.nan
|
|
1044
|
+
else:
|
|
1045
|
+
res = returns.mean() / downside
|
|
1046
|
+
|
|
1047
|
+
# Annualize if requested
|
|
1048
|
+
if annualize:
|
|
1049
|
+
return res * _np.sqrt(1 if periods is None else periods)
|
|
1050
|
+
|
|
1051
|
+
return res
|
|
1052
|
+
|
|
1053
|
+
|
|
1054
|
+
def smart_sortino(
|
|
1055
|
+
returns: Returns,
|
|
1056
|
+
rf: float = 0,
|
|
1057
|
+
periods: int = 252,
|
|
1058
|
+
annualize: bool = True,
|
|
1059
|
+
) -> float | _pd.Series:
|
|
1060
|
+
"""
|
|
1061
|
+
Calculate the Smart Sortino ratio (Sortino with autocorrelation penalty).
|
|
1062
|
+
|
|
1063
|
+
This is a wrapper for the sortino() function with smart=True, which
|
|
1064
|
+
applies an autocorrelation penalty to provide more realistic risk-adjusted
|
|
1065
|
+
returns for strategies with autocorrelated returns.
|
|
1066
|
+
|
|
1067
|
+
Args:
|
|
1068
|
+
returns (pd.Series): Return series to analyze
|
|
1069
|
+
rf (float): Risk-free rate (annualized, default: 0.0)
|
|
1070
|
+
periods (int): Periods per year for annualization (default: 252)
|
|
1071
|
+
annualize (bool): Whether to annualize the ratio (default: True)
|
|
1072
|
+
|
|
1073
|
+
Returns:
|
|
1074
|
+
float: Smart Sortino ratio
|
|
1075
|
+
|
|
1076
|
+
Example:
|
|
1077
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
1078
|
+
>>> smart_sortino_ratio = smart_sortino(returns)
|
|
1079
|
+
>>> print(f"Smart Sortino ratio: {smart_sortino_ratio:.4f}")
|
|
1080
|
+
"""
|
|
1081
|
+
return sortino(returns, rf, periods, annualize, True)
|
|
1082
|
+
|
|
1083
|
+
|
|
1084
|
+
def rolling_sortino(
|
|
1085
|
+
returns: Returns,
|
|
1086
|
+
rf: float = 0,
|
|
1087
|
+
rolling_period: int = 126,
|
|
1088
|
+
annualize: bool = True,
|
|
1089
|
+
periods_per_year: int = 252,
|
|
1090
|
+
**kwargs,
|
|
1091
|
+
) -> _pd.Series:
|
|
1092
|
+
"""
|
|
1093
|
+
Calculate rolling Sortino ratio over a specified window.
|
|
1094
|
+
|
|
1095
|
+
This function computes the Sortino ratio using a rolling window, providing
|
|
1096
|
+
a time-varying measure of downside risk-adjusted performance.
|
|
1097
|
+
|
|
1098
|
+
Args:
|
|
1099
|
+
returns (pd.Series): Return series to analyze
|
|
1100
|
+
rf (float): Risk-free rate (annualized, default: 0.0)
|
|
1101
|
+
rolling_period (int): Rolling window size (default: 126, ~6 months)
|
|
1102
|
+
annualize (bool): Whether to annualize the ratio (default: True)
|
|
1103
|
+
periods_per_year (int): Periods per year for annualization (default: 252)
|
|
1104
|
+
**kwargs: Additional keyword arguments (e.g., prepare_returns)
|
|
1105
|
+
|
|
1106
|
+
Returns:
|
|
1107
|
+
pd.Series: Rolling Sortino ratio series
|
|
1108
|
+
|
|
1109
|
+
Raises:
|
|
1110
|
+
Exception: If rf != 0 and rolling_period is None
|
|
1111
|
+
|
|
1112
|
+
Example:
|
|
1113
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
1114
|
+
>>> rolling_sortino_ratio = rolling_sortino(returns, rolling_period=3)
|
|
1115
|
+
>>> print(rolling_sortino_ratio)
|
|
1116
|
+
"""
|
|
1117
|
+
# Validate parameters for risk-free rate handling
|
|
1118
|
+
if rf != 0 and rolling_period is None:
|
|
1119
|
+
raise Exception("Must provide periods if rf != 0")
|
|
1120
|
+
|
|
1121
|
+
if kwargs.get("prepare_returns", True):
|
|
1122
|
+
returns = _utils._prepare_returns(returns, rf, rolling_period)
|
|
1123
|
+
|
|
1124
|
+
# Optimized downside calculation using vectorized operations
|
|
1125
|
+
def calc_downside(x):
|
|
1126
|
+
"""
|
|
1127
|
+
Calculate downside variance more efficiently.
|
|
1128
|
+
|
|
1129
|
+
This function computes the sum of squared negative returns,
|
|
1130
|
+
which is used to calculate downside deviation.
|
|
1131
|
+
"""
|
|
1132
|
+
negative_returns = x[x < 0]
|
|
1133
|
+
return (negative_returns**2).sum() if len(negative_returns) > 0 else 0
|
|
1134
|
+
|
|
1135
|
+
# Calculate rolling downside deviation
|
|
1136
|
+
downside = (
|
|
1137
|
+
returns.rolling(rolling_period).apply(calc_downside, raw=True) / rolling_period
|
|
1138
|
+
)
|
|
1139
|
+
|
|
1140
|
+
# Calculate rolling Sortino ratio
|
|
1141
|
+
res = returns.rolling(rolling_period).mean() / _np.sqrt(downside)
|
|
1142
|
+
|
|
1143
|
+
# Annualize if requested
|
|
1144
|
+
if annualize:
|
|
1145
|
+
res = res * _np.sqrt(1 if periods_per_year is None else periods_per_year)
|
|
1146
|
+
|
|
1147
|
+
return res
|
|
1148
|
+
|
|
1149
|
+
|
|
1150
|
+
def adjusted_sortino(
|
|
1151
|
+
returns: Returns,
|
|
1152
|
+
rf: float = 0,
|
|
1153
|
+
periods: int = 252,
|
|
1154
|
+
annualize: bool = True,
|
|
1155
|
+
smart: bool = False,
|
|
1156
|
+
) -> float | _pd.Series:
|
|
1157
|
+
"""
|
|
1158
|
+
Calculate Jack Schwager's adjusted Sortino ratio.
|
|
1159
|
+
|
|
1160
|
+
This version of the Sortino ratio is adjusted by dividing by sqrt(2)
|
|
1161
|
+
to allow for direct comparisons with the Sharpe ratio. This adjustment
|
|
1162
|
+
accounts for the difference in calculation methods.
|
|
1163
|
+
|
|
1164
|
+
Args:
|
|
1165
|
+
returns (pd.Series): Return series to analyze
|
|
1166
|
+
rf (float): Risk-free rate (annualized, default: 0.0)
|
|
1167
|
+
periods (int): Periods per year for annualization (default: 252)
|
|
1168
|
+
annualize (bool): Whether to annualize the ratio (default: True)
|
|
1169
|
+
smart (bool): Whether to apply autocorrelation penalty (default: False)
|
|
1170
|
+
|
|
1171
|
+
Returns:
|
|
1172
|
+
float: Adjusted Sortino ratio
|
|
1173
|
+
|
|
1174
|
+
Example:
|
|
1175
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
1176
|
+
>>> adj_sortino = adjusted_sortino(returns)
|
|
1177
|
+
>>> print(f"Adjusted Sortino ratio: {adj_sortino:.4f}")
|
|
1178
|
+
|
|
1179
|
+
Note:
|
|
1180
|
+
See here for more info: https://archive.is/wip/2rwFW
|
|
1181
|
+
"""
|
|
1182
|
+
# Calculate standard Sortino ratio
|
|
1183
|
+
data = sortino(returns, rf, periods=periods, annualize=annualize, smart=smart)
|
|
1184
|
+
|
|
1185
|
+
# Apply Schwager's adjustment factor
|
|
1186
|
+
return data / _sqrt(2)
|
|
1187
|
+
|
|
1188
|
+
|
|
1189
|
+
def probabilistic_ratio(
|
|
1190
|
+
series: Returns,
|
|
1191
|
+
rf: float = 0.0,
|
|
1192
|
+
base: str = "sharpe",
|
|
1193
|
+
periods: int = 252,
|
|
1194
|
+
annualize: bool = False,
|
|
1195
|
+
smart: bool = False,
|
|
1196
|
+
) -> float:
|
|
1197
|
+
"""
|
|
1198
|
+
Calculate the probabilistic ratio for a given base metric.
|
|
1199
|
+
|
|
1200
|
+
This function computes the probabilistic version of risk-adjusted ratios,
|
|
1201
|
+
which accounts for the statistical uncertainty in the ratio estimation.
|
|
1202
|
+
It considers skewness and kurtosis to provide more robust estimates.
|
|
1203
|
+
|
|
1204
|
+
Args:
|
|
1205
|
+
series (pd.Series): Return series to analyze
|
|
1206
|
+
rf (float): Risk-free rate (annualized, default: 0.0)
|
|
1207
|
+
base (str): Base metric ('sharpe', 'sortino', 'adjusted_sortino')
|
|
1208
|
+
periods (int): Periods per year for annualization (default: 252)
|
|
1209
|
+
annualize (bool): Whether to annualize the result (default: False)
|
|
1210
|
+
smart (bool): Whether to apply autocorrelation penalty (default: False)
|
|
1211
|
+
|
|
1212
|
+
Returns:
|
|
1213
|
+
float: Probabilistic ratio (0-1 scale representing probability)
|
|
1214
|
+
|
|
1215
|
+
Raises:
|
|
1216
|
+
ValueError: If invalid base metric is provided
|
|
1217
|
+
|
|
1218
|
+
Example:
|
|
1219
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
1220
|
+
>>> prob_ratio = probabilistic_ratio(returns, base="sharpe")
|
|
1221
|
+
>>> print(f"Probabilistic Sharpe ratio: {prob_ratio:.4f}")
|
|
1222
|
+
"""
|
|
1223
|
+
# Calculate the base ratio depending on the selected metric
|
|
1224
|
+
if base.lower() == "sharpe":
|
|
1225
|
+
base = sharpe(series, periods=periods, annualize=False, smart=smart)
|
|
1226
|
+
elif base.lower() == "sortino":
|
|
1227
|
+
base = sortino(series, periods=periods, annualize=False, smart=smart)
|
|
1228
|
+
elif base.lower() == "adjusted_sortino":
|
|
1229
|
+
base = adjusted_sortino(series, periods=periods, annualize=False, smart=smart)
|
|
1230
|
+
else:
|
|
1231
|
+
raise ValueError(
|
|
1232
|
+
f"Invalid metric '{base}'. Must be one of: 'sharpe', 'sortino', or 'adjusted_sortino'"
|
|
1233
|
+
)
|
|
1234
|
+
|
|
1235
|
+
# Calculate higher moments for adjustment
|
|
1236
|
+
skew_no = skew(series, prepare_returns=False)
|
|
1237
|
+
kurtosis_no = kurtosis(series, prepare_returns=False)
|
|
1238
|
+
|
|
1239
|
+
n = len(series)
|
|
1240
|
+
|
|
1241
|
+
# Calculate standard error of the ratio incorporating higher moments
|
|
1242
|
+
# Formula accounts for skewness and kurtosis effects on ratio distribution
|
|
1243
|
+
sigma_sr = _np.sqrt(
|
|
1244
|
+
(1 + (0.5 * base**2) - (skew_no * base) + (((kurtosis_no - 3) / 4) * base**2))
|
|
1245
|
+
/ (n - 1)
|
|
1246
|
+
)
|
|
1247
|
+
|
|
1248
|
+
# Calculate standardized ratio and convert to probability
|
|
1249
|
+
ratio = (base - rf) / sigma_sr
|
|
1250
|
+
psr = _norm.cdf(ratio)
|
|
1251
|
+
|
|
1252
|
+
# Annualize if requested
|
|
1253
|
+
if annualize:
|
|
1254
|
+
return psr * (252**0.5)
|
|
1255
|
+
|
|
1256
|
+
return psr
|
|
1257
|
+
|
|
1258
|
+
|
|
1259
|
+
def probabilistic_sharpe_ratio(
|
|
1260
|
+
series: Returns,
|
|
1261
|
+
rf: float = 0.0,
|
|
1262
|
+
periods: int = 252,
|
|
1263
|
+
annualize: bool = False,
|
|
1264
|
+
smart: bool = False,
|
|
1265
|
+
) -> float:
|
|
1266
|
+
"""
|
|
1267
|
+
Calculate the Probabilistic Sharpe Ratio (PSR).
|
|
1268
|
+
|
|
1269
|
+
This function computes the PSR, which represents the probability that
|
|
1270
|
+
the observed Sharpe ratio is statistically greater than a benchmark.
|
|
1271
|
+
It accounts for higher moments to provide more robust estimates.
|
|
1272
|
+
|
|
1273
|
+
Args:
|
|
1274
|
+
series (pd.Series): Return series to analyze
|
|
1275
|
+
rf (float): Risk-free rate (annualized, default: 0.0)
|
|
1276
|
+
periods (int): Periods per year for annualization (default: 252)
|
|
1277
|
+
annualize (bool): Whether to annualize the result (default: False)
|
|
1278
|
+
smart (bool): Whether to apply autocorrelation penalty (default: False)
|
|
1279
|
+
|
|
1280
|
+
Returns:
|
|
1281
|
+
float: Probabilistic Sharpe ratio (0-1 scale)
|
|
1282
|
+
|
|
1283
|
+
Example:
|
|
1284
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
1285
|
+
>>> psr = probabilistic_sharpe_ratio(returns)
|
|
1286
|
+
>>> print(f"Probabilistic Sharpe ratio: {psr:.4f}")
|
|
1287
|
+
"""
|
|
1288
|
+
return probabilistic_ratio(
|
|
1289
|
+
series, rf, base="sharpe", periods=periods, annualize=annualize, smart=smart
|
|
1290
|
+
)
|
|
1291
|
+
|
|
1292
|
+
|
|
1293
|
+
def probabilistic_sortino_ratio(
|
|
1294
|
+
series, rf=0.0, periods=252, annualize=False, smart=False
|
|
1295
|
+
):
|
|
1296
|
+
"""
|
|
1297
|
+
Calculate the Probabilistic Sortino Ratio.
|
|
1298
|
+
|
|
1299
|
+
This function computes the probabilistic version of the Sortino ratio,
|
|
1300
|
+
which accounts for statistical uncertainty in the ratio estimation.
|
|
1301
|
+
|
|
1302
|
+
Args:
|
|
1303
|
+
series (pd.Series): Return series to analyze
|
|
1304
|
+
rf (float): Risk-free rate (annualized, default: 0.0)
|
|
1305
|
+
periods (int): Periods per year for annualization (default: 252)
|
|
1306
|
+
annualize (bool): Whether to annualize the result (default: False)
|
|
1307
|
+
smart (bool): Whether to apply autocorrelation penalty (default: False)
|
|
1308
|
+
|
|
1309
|
+
Returns:
|
|
1310
|
+
float: Probabilistic Sortino ratio (0-1 scale)
|
|
1311
|
+
|
|
1312
|
+
Example:
|
|
1313
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
1314
|
+
>>> psr = probabilistic_sortino_ratio(returns)
|
|
1315
|
+
>>> print(f"Probabilistic Sortino ratio: {psr:.4f}")
|
|
1316
|
+
"""
|
|
1317
|
+
return probabilistic_ratio(
|
|
1318
|
+
series, rf, base="sortino", periods=periods, annualize=annualize, smart=smart
|
|
1319
|
+
)
|
|
1320
|
+
|
|
1321
|
+
|
|
1322
|
+
def probabilistic_adjusted_sortino_ratio(
|
|
1323
|
+
series, rf=0.0, periods=252, annualize=False, smart=False
|
|
1324
|
+
):
|
|
1325
|
+
"""
|
|
1326
|
+
Calculate the Probabilistic Adjusted Sortino Ratio.
|
|
1327
|
+
|
|
1328
|
+
This function computes the probabilistic version of the adjusted Sortino
|
|
1329
|
+
ratio, accounting for statistical uncertainty in the ratio estimation.
|
|
1330
|
+
|
|
1331
|
+
Args:
|
|
1332
|
+
series (pd.Series): Return series to analyze
|
|
1333
|
+
rf (float): Risk-free rate (annualized, default: 0.0)
|
|
1334
|
+
periods (int): Periods per year for annualization (default: 252)
|
|
1335
|
+
annualize (bool): Whether to annualize the result (default: False)
|
|
1336
|
+
smart (bool): Whether to apply autocorrelation penalty (default: False)
|
|
1337
|
+
|
|
1338
|
+
Returns:
|
|
1339
|
+
float: Probabilistic adjusted Sortino ratio (0-1 scale)
|
|
1340
|
+
|
|
1341
|
+
Example:
|
|
1342
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
1343
|
+
>>> psr = probabilistic_adjusted_sortino_ratio(returns)
|
|
1344
|
+
>>> print(f"Probabilistic adjusted Sortino ratio: {psr:.4f}")
|
|
1345
|
+
"""
|
|
1346
|
+
return probabilistic_ratio(
|
|
1347
|
+
series,
|
|
1348
|
+
rf,
|
|
1349
|
+
base="adjusted_sortino",
|
|
1350
|
+
periods=periods,
|
|
1351
|
+
annualize=annualize,
|
|
1352
|
+
smart=smart,
|
|
1353
|
+
)
|
|
1354
|
+
|
|
1355
|
+
|
|
1356
|
+
def treynor_ratio(returns, benchmark, periods=252.0, rf=0.0):
|
|
1357
|
+
"""
|
|
1358
|
+
Calculate the Treynor ratio.
|
|
1359
|
+
|
|
1360
|
+
The Treynor ratio measures risk-adjusted returns relative to systematic risk
|
|
1361
|
+
(beta) rather than total risk (volatility). It's calculated as excess return
|
|
1362
|
+
divided by beta, useful for comparing portfolios with different market exposure.
|
|
1363
|
+
|
|
1364
|
+
Args:
|
|
1365
|
+
returns (pd.Series): Return series to analyze
|
|
1366
|
+
benchmark (pd.Series): Benchmark return series for beta calculation
|
|
1367
|
+
periods (float): Periods per year for annualization (default: 252.0)
|
|
1368
|
+
rf (float): Risk-free rate (annualized, default: 0.0)
|
|
1369
|
+
|
|
1370
|
+
Returns:
|
|
1371
|
+
float: Treynor ratio
|
|
1372
|
+
|
|
1373
|
+
Example:
|
|
1374
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
1375
|
+
>>> benchmark = pd.Series([0.005, -0.01, 0.02, -0.005, 0.015])
|
|
1376
|
+
>>> treynor = treynor_ratio(returns, benchmark)
|
|
1377
|
+
>>> print(f"Treynor ratio: {treynor:.4f}")
|
|
1378
|
+
"""
|
|
1379
|
+
# Handle DataFrame input by selecting first column
|
|
1380
|
+
if isinstance(returns, _pd.DataFrame):
|
|
1381
|
+
returns = returns[returns.columns[0]]
|
|
1382
|
+
|
|
1383
|
+
# Calculate beta from the Greeks (alpha, beta analysis)
|
|
1384
|
+
beta = greeks(returns, benchmark, periods=periods).to_dict().get("beta", 0)
|
|
1385
|
+
|
|
1386
|
+
# Prevent division by zero
|
|
1387
|
+
if beta == 0:
|
|
1388
|
+
warn("Beta is zero, cannot calculate Treynor ratio, returning 0", stacklevel=2)
|
|
1389
|
+
return 0
|
|
1390
|
+
|
|
1391
|
+
# Calculate excess return over risk-free rate divided by beta
|
|
1392
|
+
return (comp(returns) - rf) / beta
|
|
1393
|
+
|
|
1394
|
+
|
|
1395
|
+
def omega(
|
|
1396
|
+
returns: Returns,
|
|
1397
|
+
rf: float = 0.0,
|
|
1398
|
+
required_return: float = 0.0,
|
|
1399
|
+
periods: int = 252,
|
|
1400
|
+
) -> float:
|
|
1401
|
+
"""
|
|
1402
|
+
Calculate the Omega ratio of a strategy.
|
|
1403
|
+
|
|
1404
|
+
The Omega ratio measures the probability-weighted ratio of gains to losses
|
|
1405
|
+
above and below a threshold return. It provides a comprehensive view of
|
|
1406
|
+
the return distribution's characteristics.
|
|
1407
|
+
|
|
1408
|
+
Args:
|
|
1409
|
+
returns (pd.Series): Return series to analyze
|
|
1410
|
+
rf (float): Risk-free rate (annualized, default: 0.0)
|
|
1411
|
+
required_return (float): Required return threshold (default: 0.0)
|
|
1412
|
+
periods (int): Periods per year for annualization (default: 252)
|
|
1413
|
+
|
|
1414
|
+
Returns:
|
|
1415
|
+
float: Omega ratio
|
|
1416
|
+
|
|
1417
|
+
Example:
|
|
1418
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
1419
|
+
>>> omega_ratio = omega(returns, required_return=0.01)
|
|
1420
|
+
>>> print(f"Omega ratio: {omega_ratio:.4f}")
|
|
1421
|
+
|
|
1422
|
+
Note:
|
|
1423
|
+
See https://en.wikipedia.org/wiki/Omega_ratio for more details.
|
|
1424
|
+
"""
|
|
1425
|
+
validate_input(returns)
|
|
1426
|
+
|
|
1427
|
+
# Validate minimum data requirements
|
|
1428
|
+
if len(returns) < 2:
|
|
1429
|
+
warn("Insufficient data for omega ratio calculation (need at least 2 returns), returning NaN", stacklevel=2)
|
|
1430
|
+
return _np.nan
|
|
1431
|
+
|
|
1432
|
+
# Validate required return parameter
|
|
1433
|
+
if required_return <= -1:
|
|
1434
|
+
warn(f"Invalid required_return ({required_return}) for omega ratio, must be > -1, returning NaN", stacklevel=2)
|
|
1435
|
+
return _np.nan
|
|
1436
|
+
|
|
1437
|
+
# Prepare returns (subtract risk-free rate if applicable)
|
|
1438
|
+
returns = _utils._prepare_returns(returns, rf, periods)
|
|
1439
|
+
|
|
1440
|
+
# Convert annualized required return to per-period if needed
|
|
1441
|
+
if periods == 1:
|
|
1442
|
+
return_threshold = required_return
|
|
1443
|
+
else:
|
|
1444
|
+
return_threshold = (1 + required_return) ** (1.0 / periods) - 1
|
|
1445
|
+
|
|
1446
|
+
# Calculate deviations from threshold
|
|
1447
|
+
returns_less_thresh = returns - return_threshold
|
|
1448
|
+
|
|
1449
|
+
# Sum of positive deviations (gains above threshold)
|
|
1450
|
+
numer = returns_less_thresh[returns_less_thresh > 0.0].sum()
|
|
1451
|
+
|
|
1452
|
+
# Sum of negative deviations (losses below threshold)
|
|
1453
|
+
denom = -1.0 * returns_less_thresh[returns_less_thresh < 0.0].sum()
|
|
1454
|
+
|
|
1455
|
+
# Handle both Series and scalar cases
|
|
1456
|
+
if isinstance(denom, _pd.Series):
|
|
1457
|
+
result = numer / denom
|
|
1458
|
+
# Return NaN where denominator is zero
|
|
1459
|
+
result = result.where(denom > 0.0, _np.nan)
|
|
1460
|
+
return result
|
|
1461
|
+
else:
|
|
1462
|
+
if denom > 0.0:
|
|
1463
|
+
return numer / denom
|
|
1464
|
+
return _np.nan
|
|
1465
|
+
|
|
1466
|
+
|
|
1467
|
+
def gain_to_pain_ratio(returns, rf=0, resolution="D"):
|
|
1468
|
+
"""
|
|
1469
|
+
Calculate Jack Schwager's Gain-to-Pain Ratio (GPR).
|
|
1470
|
+
|
|
1471
|
+
This ratio measures the total gains divided by the total losses,
|
|
1472
|
+
providing a simple measure of how much profit is generated per
|
|
1473
|
+
unit of loss. Higher values indicate better performance.
|
|
1474
|
+
|
|
1475
|
+
Args:
|
|
1476
|
+
returns (pd.Series): Return series to analyze
|
|
1477
|
+
rf (float): Risk-free rate (default: 0)
|
|
1478
|
+
resolution (str): Resampling frequency ('D', 'W', 'M', etc.)
|
|
1479
|
+
|
|
1480
|
+
Returns:
|
|
1481
|
+
float: Gain-to-Pain ratio
|
|
1482
|
+
|
|
1483
|
+
Example:
|
|
1484
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
1485
|
+
>>> gpr = gain_to_pain_ratio(returns)
|
|
1486
|
+
>>> print(f"Gain-to-Pain ratio: {gpr:.4f}")
|
|
1487
|
+
|
|
1488
|
+
Note:
|
|
1489
|
+
See here for more info: https://archive.is/wip/2rwFW
|
|
1490
|
+
"""
|
|
1491
|
+
# Prepare returns and resample to specified frequency
|
|
1492
|
+
returns = _utils._prepare_returns(returns, rf).resample(resolution).sum()
|
|
1493
|
+
|
|
1494
|
+
# Calculate absolute sum of negative returns (pain)
|
|
1495
|
+
downside = abs(returns[returns < 0].sum())
|
|
1496
|
+
|
|
1497
|
+
# Handle both Series (DataFrame input) and scalar (Series input) cases
|
|
1498
|
+
if isinstance(downside, _pd.Series):
|
|
1499
|
+
# DataFrame input - element-wise division with zero protection
|
|
1500
|
+
return returns.sum() / downside.replace(0, _np.nan)
|
|
1501
|
+
else:
|
|
1502
|
+
# Series input - scalar division
|
|
1503
|
+
if downside == 0:
|
|
1504
|
+
return _np.nan
|
|
1505
|
+
return returns.sum() / downside
|
|
1506
|
+
|
|
1507
|
+
|
|
1508
|
+
def cagr(
|
|
1509
|
+
returns: Returns,
|
|
1510
|
+
rf: float = 0.0,
|
|
1511
|
+
compounded: bool = True,
|
|
1512
|
+
periods: int = 252,
|
|
1513
|
+
) -> float | _pd.Series:
|
|
1514
|
+
"""
|
|
1515
|
+
Calculate the Compound Annual Growth Rate (CAGR) of excess returns.
|
|
1516
|
+
|
|
1517
|
+
CAGR represents the geometric mean annual growth rate, providing a
|
|
1518
|
+
smoothed annualized return that accounts for compounding effects.
|
|
1519
|
+
|
|
1520
|
+
Args:
|
|
1521
|
+
returns (pd.Series): Return series to analyze
|
|
1522
|
+
rf (float): Risk-free rate (annualized, default: 0.0)
|
|
1523
|
+
compounded (bool): Whether to compound returns (default: True)
|
|
1524
|
+
periods (int): Periods per year for annualization (default: 252)
|
|
1525
|
+
|
|
1526
|
+
Returns:
|
|
1527
|
+
float or pd.Series: CAGR percentage
|
|
1528
|
+
|
|
1529
|
+
Example:
|
|
1530
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02],
|
|
1531
|
+
... index=pd.date_range('2023-01-01', periods=5))
|
|
1532
|
+
>>> cagr_value = cagr(returns)
|
|
1533
|
+
>>> print(f"CAGR: {cagr_value:.4f}")
|
|
1534
|
+
"""
|
|
1535
|
+
validate_input(returns)
|
|
1536
|
+
|
|
1537
|
+
# Prepare returns (subtract risk-free rate if applicable)
|
|
1538
|
+
total = _utils._prepare_returns(returns, rf)
|
|
1539
|
+
|
|
1540
|
+
# Calculate total return
|
|
1541
|
+
if compounded:
|
|
1542
|
+
total = comp(total)
|
|
1543
|
+
else:
|
|
1544
|
+
total = _np.sum(total, axis=0)
|
|
1545
|
+
|
|
1546
|
+
# Calculate time period in years using trading periods
|
|
1547
|
+
# This is consistent with how Sharpe, Sortino, and other metrics
|
|
1548
|
+
# handle annualization in quantstats
|
|
1549
|
+
years = len(returns) / periods
|
|
1550
|
+
|
|
1551
|
+
# Calculate CAGR using geometric mean formula
|
|
1552
|
+
res = abs(total + 1.0) ** (1.0 / years) - 1
|
|
1553
|
+
|
|
1554
|
+
# Handle DataFrame input
|
|
1555
|
+
if isinstance(returns, _pd.DataFrame):
|
|
1556
|
+
res = _pd.Series(res)
|
|
1557
|
+
res.index = returns.columns
|
|
1558
|
+
|
|
1559
|
+
return res
|
|
1560
|
+
|
|
1561
|
+
|
|
1562
|
+
def rar(returns, rf=0.0, periods=252):
|
|
1563
|
+
"""
|
|
1564
|
+
Calculate the Risk-Adjusted Return (RAR).
|
|
1565
|
+
|
|
1566
|
+
RAR is calculated as CAGR divided by exposure, taking into account
|
|
1567
|
+
the time the strategy was actually invested. This provides a more
|
|
1568
|
+
accurate measure of returns adjusted for actual market participation.
|
|
1569
|
+
|
|
1570
|
+
Args:
|
|
1571
|
+
returns (pd.Series): Return series to analyze
|
|
1572
|
+
rf (float): Risk-free rate (annualized, default: 0.0)
|
|
1573
|
+
periods (int): Periods per year for CAGR annualization (default: 252)
|
|
1574
|
+
|
|
1575
|
+
Returns:
|
|
1576
|
+
float: Risk-adjusted return
|
|
1577
|
+
|
|
1578
|
+
Example:
|
|
1579
|
+
>>> returns = pd.Series([0.01, 0.00, 0.03, 0.00, 0.02])
|
|
1580
|
+
>>> rar_value = rar(returns)
|
|
1581
|
+
>>> print(f"Risk-adjusted return: {rar_value:.4f}")
|
|
1582
|
+
"""
|
|
1583
|
+
# Prepare returns (subtract risk-free rate if applicable)
|
|
1584
|
+
returns = _utils._prepare_returns(returns, rf)
|
|
1585
|
+
|
|
1586
|
+
# Calculate CAGR and divide by exposure time
|
|
1587
|
+
return cagr(returns, periods=periods) / exposure(returns)
|
|
1588
|
+
|
|
1589
|
+
|
|
1590
|
+
def skew(returns, prepare_returns=True):
|
|
1591
|
+
"""
|
|
1592
|
+
Calculate returns' skewness.
|
|
1593
|
+
|
|
1594
|
+
Skewness measures the degree of asymmetry of a distribution around its mean.
|
|
1595
|
+
Positive skewness indicates a longer tail on the positive side,
|
|
1596
|
+
while negative skewness indicates a longer tail on the negative side.
|
|
1597
|
+
|
|
1598
|
+
Args:
|
|
1599
|
+
returns (pd.Series): Return series to analyze
|
|
1600
|
+
prepare_returns (bool): Whether to prepare returns first (default: True)
|
|
1601
|
+
|
|
1602
|
+
Returns:
|
|
1603
|
+
float: Skewness value
|
|
1604
|
+
|
|
1605
|
+
Example:
|
|
1606
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
1607
|
+
>>> skewness = skew(returns)
|
|
1608
|
+
>>> print(f"Skewness: {skewness:.4f}")
|
|
1609
|
+
"""
|
|
1610
|
+
if prepare_returns:
|
|
1611
|
+
returns = _utils._prepare_returns(returns)
|
|
1612
|
+
|
|
1613
|
+
# Calculate skewness using pandas built-in method
|
|
1614
|
+
return returns.skew()
|
|
1615
|
+
|
|
1616
|
+
|
|
1617
|
+
def kurtosis(returns, prepare_returns=True):
|
|
1618
|
+
"""
|
|
1619
|
+
Calculate returns' kurtosis.
|
|
1620
|
+
|
|
1621
|
+
Kurtosis measures the degree to which a distribution is peaked compared
|
|
1622
|
+
to a normal distribution. Higher kurtosis indicates more extreme returns
|
|
1623
|
+
(fat tails), while lower kurtosis indicates fewer extreme returns.
|
|
1624
|
+
|
|
1625
|
+
Args:
|
|
1626
|
+
returns (pd.Series): Return series to analyze
|
|
1627
|
+
prepare_returns (bool): Whether to prepare returns first (default: True)
|
|
1628
|
+
|
|
1629
|
+
Returns:
|
|
1630
|
+
float: Kurtosis value (excess kurtosis, normal distribution = 0)
|
|
1631
|
+
|
|
1632
|
+
Example:
|
|
1633
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
1634
|
+
>>> kurt = kurtosis(returns)
|
|
1635
|
+
>>> print(f"Kurtosis: {kurt:.4f}")
|
|
1636
|
+
"""
|
|
1637
|
+
if prepare_returns:
|
|
1638
|
+
returns = _utils._prepare_returns(returns)
|
|
1639
|
+
|
|
1640
|
+
# Calculate kurtosis using pandas built-in method (excess kurtosis)
|
|
1641
|
+
return returns.kurtosis()
|
|
1642
|
+
|
|
1643
|
+
|
|
1644
|
+
def calmar(
|
|
1645
|
+
returns: Returns,
|
|
1646
|
+
prepare_returns: bool = True,
|
|
1647
|
+
periods: int = 252,
|
|
1648
|
+
) -> float:
|
|
1649
|
+
"""
|
|
1650
|
+
Calculate the Calmar ratio (CAGR / Maximum Drawdown).
|
|
1651
|
+
|
|
1652
|
+
The Calmar ratio measures risk-adjusted returns by dividing the CAGR
|
|
1653
|
+
by the absolute value of the maximum drawdown. It provides insight
|
|
1654
|
+
into returns relative to the worst-case scenario.
|
|
1655
|
+
|
|
1656
|
+
Args:
|
|
1657
|
+
returns (pd.Series): Return series to analyze
|
|
1658
|
+
prepare_returns (bool): Whether to prepare returns first (default: True)
|
|
1659
|
+
periods (int): Periods per year for annualization (default: 252)
|
|
1660
|
+
|
|
1661
|
+
Returns:
|
|
1662
|
+
float: Calmar ratio
|
|
1663
|
+
|
|
1664
|
+
Example:
|
|
1665
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
1666
|
+
>>> calmar_ratio = calmar(returns)
|
|
1667
|
+
>>> print(f"Calmar ratio: {calmar_ratio:.4f}")
|
|
1668
|
+
"""
|
|
1669
|
+
validate_input(returns)
|
|
1670
|
+
|
|
1671
|
+
if prepare_returns:
|
|
1672
|
+
returns = _utils._prepare_returns(returns)
|
|
1673
|
+
|
|
1674
|
+
# Calculate CAGR and maximum drawdown
|
|
1675
|
+
cagr_ratio = cagr(returns, periods=periods)
|
|
1676
|
+
max_dd = max_drawdown(returns)
|
|
1677
|
+
|
|
1678
|
+
# Return ratio of CAGR to absolute maximum drawdown
|
|
1679
|
+
return cagr_ratio / abs(max_dd)
|
|
1680
|
+
|
|
1681
|
+
|
|
1682
|
+
def ulcer_index(returns):
|
|
1683
|
+
"""
|
|
1684
|
+
Calculate the Ulcer Index (downside risk measurement).
|
|
1685
|
+
|
|
1686
|
+
The Ulcer Index measures the depth and duration of drawdowns,
|
|
1687
|
+
providing a comprehensive measure of downside risk. It's calculated
|
|
1688
|
+
as the square root of the mean of squared drawdowns.
|
|
1689
|
+
|
|
1690
|
+
Args:
|
|
1691
|
+
returns (pd.Series): Return series to analyze
|
|
1692
|
+
|
|
1693
|
+
Returns:
|
|
1694
|
+
float: Ulcer Index value
|
|
1695
|
+
|
|
1696
|
+
Example:
|
|
1697
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
1698
|
+
>>> ulcer = ulcer_index(returns)
|
|
1699
|
+
>>> print(f"Ulcer Index: {ulcer:.4f}")
|
|
1700
|
+
"""
|
|
1701
|
+
# Convert returns to drawdown series
|
|
1702
|
+
dd = to_drawdown_series(returns)
|
|
1703
|
+
|
|
1704
|
+
# Calculate root mean square of drawdowns
|
|
1705
|
+
return _np.sqrt(_np.divide((dd**2).sum(), returns.shape[0] - 1))
|
|
1706
|
+
|
|
1707
|
+
|
|
1708
|
+
def ulcer_performance_index(returns, rf=0):
|
|
1709
|
+
"""
|
|
1710
|
+
Calculate the Ulcer Performance Index (UPI).
|
|
1711
|
+
|
|
1712
|
+
The UPI measures risk-adjusted returns using the Ulcer Index as the
|
|
1713
|
+
risk measure instead of standard deviation. It provides a better
|
|
1714
|
+
measure for strategies with significant drawdowns.
|
|
1715
|
+
|
|
1716
|
+
Args:
|
|
1717
|
+
returns (pd.Series): Return series to analyze
|
|
1718
|
+
rf (float): Risk-free rate (default: 0)
|
|
1719
|
+
|
|
1720
|
+
Returns:
|
|
1721
|
+
float: Ulcer Performance Index
|
|
1722
|
+
|
|
1723
|
+
Example:
|
|
1724
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
1725
|
+
>>> upi_value = ulcer_performance_index(returns)
|
|
1726
|
+
>>> print(f"Ulcer Performance Index: {upi_value:.4f}")
|
|
1727
|
+
"""
|
|
1728
|
+
# Calculate excess return divided by Ulcer Index
|
|
1729
|
+
ulcer = ulcer_index(returns)
|
|
1730
|
+
|
|
1731
|
+
# Handle both Series (DataFrame input) and scalar (Series input) cases
|
|
1732
|
+
if isinstance(ulcer, _pd.Series):
|
|
1733
|
+
# DataFrame input - element-wise division with zero protection
|
|
1734
|
+
return (comp(returns) - rf) / ulcer.replace(0, _np.nan)
|
|
1735
|
+
else:
|
|
1736
|
+
# Series input - scalar division
|
|
1737
|
+
if ulcer == 0:
|
|
1738
|
+
return _np.nan
|
|
1739
|
+
return (comp(returns) - rf) / ulcer
|
|
1740
|
+
|
|
1741
|
+
|
|
1742
|
+
def upi(returns, rf=0):
|
|
1743
|
+
"""
|
|
1744
|
+
Calculate the Ulcer Performance Index (UPI).
|
|
1745
|
+
|
|
1746
|
+
This is a shorthand function for ulcer_performance_index() with
|
|
1747
|
+
the same parameters and functionality.
|
|
1748
|
+
|
|
1749
|
+
Args:
|
|
1750
|
+
returns (pd.Series): Return series to analyze
|
|
1751
|
+
rf (float): Risk-free rate (default: 0)
|
|
1752
|
+
|
|
1753
|
+
Returns:
|
|
1754
|
+
float: Ulcer Performance Index
|
|
1755
|
+
"""
|
|
1756
|
+
return ulcer_performance_index(returns, rf)
|
|
1757
|
+
|
|
1758
|
+
|
|
1759
|
+
def serenity_index(returns, rf=0):
|
|
1760
|
+
"""
|
|
1761
|
+
Calculate the Serenity Index.
|
|
1762
|
+
|
|
1763
|
+
The Serenity Index is a comprehensive risk-adjusted return measure
|
|
1764
|
+
that combines the Ulcer Index with downside risk considerations.
|
|
1765
|
+
It provides a more holistic view of strategy performance.
|
|
1766
|
+
|
|
1767
|
+
Args:
|
|
1768
|
+
returns (pd.Series): Return series to analyze
|
|
1769
|
+
rf (float): Risk-free rate (default: 0)
|
|
1770
|
+
|
|
1771
|
+
Returns:
|
|
1772
|
+
float: Serenity Index
|
|
1773
|
+
|
|
1774
|
+
Example:
|
|
1775
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
1776
|
+
>>> serenity = serenity_index(returns)
|
|
1777
|
+
>>> print(f"Serenity Index: {serenity:.4f}")
|
|
1778
|
+
|
|
1779
|
+
Note:
|
|
1780
|
+
Based on KeyQuant whitepaper:
|
|
1781
|
+
https://www.keyquant.com/Download/GetFile?Filename=%5CPublications%5CKeyQuant_WhitePaper_APT_Part1.pdf
|
|
1782
|
+
"""
|
|
1783
|
+
# Convert returns to drawdown series
|
|
1784
|
+
dd = to_drawdown_series(returns)
|
|
1785
|
+
|
|
1786
|
+
# Calculate pitfall measure using conditional value at risk of drawdowns
|
|
1787
|
+
std_returns = returns.std()
|
|
1788
|
+
|
|
1789
|
+
# Handle both Series (DataFrame input) and scalar (Series input) cases
|
|
1790
|
+
if isinstance(std_returns, _pd.Series):
|
|
1791
|
+
# DataFrame input - element-wise operations
|
|
1792
|
+
pitfall = -cvar(dd) / std_returns.replace(0, _np.nan)
|
|
1793
|
+
denominator = ulcer_index(returns) * pitfall
|
|
1794
|
+
return (returns.sum() - rf) / denominator.replace(0, _np.nan)
|
|
1795
|
+
else:
|
|
1796
|
+
# Series input - scalar operations
|
|
1797
|
+
if std_returns == 0:
|
|
1798
|
+
return _np.nan
|
|
1799
|
+
|
|
1800
|
+
cvar_val = cvar(dd)
|
|
1801
|
+
ulcer_val = ulcer_index(returns)
|
|
1802
|
+
|
|
1803
|
+
# Handle cases where these might return Series/array
|
|
1804
|
+
if hasattr(cvar_val, '__len__') and len(cvar_val) == 1:
|
|
1805
|
+
cvar_val = float(cvar_val.iloc[0] if hasattr(cvar_val, 'iloc') else cvar_val[0])
|
|
1806
|
+
if hasattr(ulcer_val, '__len__') and len(ulcer_val) == 1:
|
|
1807
|
+
ulcer_val = float(ulcer_val.iloc[0] if hasattr(ulcer_val, 'iloc') else ulcer_val[0])
|
|
1808
|
+
|
|
1809
|
+
pitfall = -cvar_val / std_returns
|
|
1810
|
+
denominator = ulcer_val * pitfall
|
|
1811
|
+
|
|
1812
|
+
if denominator == 0:
|
|
1813
|
+
return _np.nan
|
|
1814
|
+
return (returns.sum() - rf) / denominator
|
|
1815
|
+
|
|
1816
|
+
|
|
1817
|
+
def risk_of_ruin(returns, prepare_returns=True):
|
|
1818
|
+
"""
|
|
1819
|
+
Calculate the risk of ruin (probability of losing all capital).
|
|
1820
|
+
|
|
1821
|
+
This function estimates the likelihood of losing all investment capital
|
|
1822
|
+
based on the win rate and the number of trades/periods. It's useful
|
|
1823
|
+
for position sizing and risk management.
|
|
1824
|
+
|
|
1825
|
+
Args:
|
|
1826
|
+
returns (pd.Series): Return series to analyze
|
|
1827
|
+
prepare_returns (bool): Whether to prepare returns first (default: True)
|
|
1828
|
+
|
|
1829
|
+
Returns:
|
|
1830
|
+
float: Risk of ruin probability (0-1 scale)
|
|
1831
|
+
|
|
1832
|
+
Example:
|
|
1833
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
1834
|
+
>>> ror_value = risk_of_ruin(returns)
|
|
1835
|
+
>>> print(f"Risk of ruin: {ror_value:.4f}")
|
|
1836
|
+
"""
|
|
1837
|
+
if prepare_returns:
|
|
1838
|
+
returns = _utils._prepare_returns(returns)
|
|
1839
|
+
|
|
1840
|
+
# Calculate win rate
|
|
1841
|
+
wins = win_rate(returns)
|
|
1842
|
+
|
|
1843
|
+
# Calculate risk of ruin using gambler's ruin formula
|
|
1844
|
+
return ((1 - wins) / (1 + wins)) ** len(returns)
|
|
1845
|
+
|
|
1846
|
+
|
|
1847
|
+
def ror(returns):
|
|
1848
|
+
"""
|
|
1849
|
+
Calculate the risk of ruin (probability of losing all capital).
|
|
1850
|
+
|
|
1851
|
+
This is a shorthand function for risk_of_ruin() with the same
|
|
1852
|
+
parameters and functionality.
|
|
1853
|
+
|
|
1854
|
+
Args:
|
|
1855
|
+
returns (pd.Series): Return series to analyze
|
|
1856
|
+
|
|
1857
|
+
Returns:
|
|
1858
|
+
float: Risk of ruin probability (0-1 scale)
|
|
1859
|
+
"""
|
|
1860
|
+
return risk_of_ruin(returns)
|
|
1861
|
+
|
|
1862
|
+
|
|
1863
|
+
def value_at_risk(
|
|
1864
|
+
returns: Returns,
|
|
1865
|
+
sigma: float = 1,
|
|
1866
|
+
confidence: float = 0.95,
|
|
1867
|
+
prepare_returns: bool = True,
|
|
1868
|
+
) -> float | _pd.Series:
|
|
1869
|
+
"""
|
|
1870
|
+
Calculate the daily Value at Risk (VaR).
|
|
1871
|
+
|
|
1872
|
+
VaR estimates the maximum expected loss over a given time horizon
|
|
1873
|
+
at a specified confidence level, using the variance-covariance method.
|
|
1874
|
+
|
|
1875
|
+
Args:
|
|
1876
|
+
returns (pd.Series): Return series to analyze
|
|
1877
|
+
sigma (float): Volatility multiplier (default: 1)
|
|
1878
|
+
confidence (float): Confidence level (0.95 = 95%, default: 0.95)
|
|
1879
|
+
prepare_returns (bool): Whether to prepare returns first (default: True)
|
|
1880
|
+
|
|
1881
|
+
Returns:
|
|
1882
|
+
float: Value at Risk (negative value representing loss)
|
|
1883
|
+
|
|
1884
|
+
Example:
|
|
1885
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
1886
|
+
>>> var_value = value_at_risk(returns, confidence=0.95)
|
|
1887
|
+
>>> print(f"95% VaR: {var_value:.4f}")
|
|
1888
|
+
"""
|
|
1889
|
+
if prepare_returns:
|
|
1890
|
+
returns = _utils._prepare_returns(returns)
|
|
1891
|
+
|
|
1892
|
+
# Calculate mean and adjust volatility
|
|
1893
|
+
mu = returns.mean()
|
|
1894
|
+
sigma *= returns.std()
|
|
1895
|
+
|
|
1896
|
+
# Convert percentage confidence to decimal if needed
|
|
1897
|
+
if confidence > 1:
|
|
1898
|
+
confidence = confidence / 100
|
|
1899
|
+
|
|
1900
|
+
# Calculate VaR using normal distribution inverse CDF
|
|
1901
|
+
return _norm.ppf(1 - confidence, mu, sigma)
|
|
1902
|
+
|
|
1903
|
+
|
|
1904
|
+
def var(returns, sigma=1, confidence=0.95, prepare_returns=True):
|
|
1905
|
+
"""
|
|
1906
|
+
Calculate the daily Value at Risk (VaR).
|
|
1907
|
+
|
|
1908
|
+
This is a shorthand function for value_at_risk() with the same
|
|
1909
|
+
parameters and functionality.
|
|
1910
|
+
|
|
1911
|
+
Args:
|
|
1912
|
+
returns (pd.Series): Return series to analyze
|
|
1913
|
+
sigma (float): Volatility multiplier (default: 1)
|
|
1914
|
+
confidence (float): Confidence level (0.95 = 95%, default: 0.95)
|
|
1915
|
+
prepare_returns (bool): Whether to prepare returns first (default: True)
|
|
1916
|
+
|
|
1917
|
+
Returns:
|
|
1918
|
+
float: Value at Risk (negative value representing loss)
|
|
1919
|
+
"""
|
|
1920
|
+
return value_at_risk(returns, sigma, confidence, prepare_returns)
|
|
1921
|
+
|
|
1922
|
+
|
|
1923
|
+
def conditional_value_at_risk(
|
|
1924
|
+
returns: Returns,
|
|
1925
|
+
sigma: float = 1,
|
|
1926
|
+
confidence: float = 0.95,
|
|
1927
|
+
prepare_returns: bool = True,
|
|
1928
|
+
) -> float | _pd.Series:
|
|
1929
|
+
"""
|
|
1930
|
+
Calculate the Conditional Value at Risk (CVaR), also known as Expected Shortfall.
|
|
1931
|
+
|
|
1932
|
+
CVaR measures the expected loss given that a loss exceeds the VaR threshold.
|
|
1933
|
+
It quantifies the amount of tail risk an investment faces, providing a more
|
|
1934
|
+
comprehensive risk measure than VaR alone.
|
|
1935
|
+
|
|
1936
|
+
Args:
|
|
1937
|
+
returns (pd.Series): Return series to analyze
|
|
1938
|
+
sigma (float): Volatility multiplier (default: 1)
|
|
1939
|
+
confidence (float): Confidence level (0.95 = 95%, default: 0.95)
|
|
1940
|
+
prepare_returns (bool): Whether to prepare returns first (default: True)
|
|
1941
|
+
|
|
1942
|
+
Returns:
|
|
1943
|
+
float: Conditional Value at Risk (expected loss beyond VaR)
|
|
1944
|
+
|
|
1945
|
+
Example:
|
|
1946
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
1947
|
+
>>> cvar_value = conditional_value_at_risk(returns, confidence=0.95)
|
|
1948
|
+
>>> print(f"95% CVaR: {cvar_value:.4f}")
|
|
1949
|
+
"""
|
|
1950
|
+
if prepare_returns:
|
|
1951
|
+
returns = _utils._prepare_returns(returns)
|
|
1952
|
+
|
|
1953
|
+
# Handle both Series and DataFrame inputs
|
|
1954
|
+
if isinstance(returns, _pd.DataFrame):
|
|
1955
|
+
# For DataFrame, calculate CVaR for each column separately
|
|
1956
|
+
result = {}
|
|
1957
|
+
for col in returns.columns:
|
|
1958
|
+
col_returns = returns[col]
|
|
1959
|
+
# Calculate VaR for this specific column
|
|
1960
|
+
col_var = value_at_risk(col_returns, sigma, confidence, prepare_returns=False)
|
|
1961
|
+
below_var = col_returns[col_returns < col_var]
|
|
1962
|
+
c_var_col = below_var.mean() if len(below_var) > 0 else _np.nan
|
|
1963
|
+
result[col] = c_var_col if not _np.isnan(c_var_col) else col_var
|
|
1964
|
+
return _pd.Series(result)
|
|
1965
|
+
else:
|
|
1966
|
+
# For Series, calculate VaR threshold
|
|
1967
|
+
var = value_at_risk(returns, sigma, confidence)
|
|
1968
|
+
c_var = returns[returns < var].values.mean()
|
|
1969
|
+
# Return CVaR if valid, otherwise return VaR
|
|
1970
|
+
return c_var if ~_np.isnan(c_var) else var
|
|
1971
|
+
|
|
1972
|
+
|
|
1973
|
+
def cvar(returns, sigma=1, confidence=0.95, prepare_returns=True):
|
|
1974
|
+
"""
|
|
1975
|
+
Calculate the Conditional Value at Risk (CVaR).
|
|
1976
|
+
|
|
1977
|
+
This is a shorthand function for conditional_value_at_risk() with
|
|
1978
|
+
the same parameters and functionality.
|
|
1979
|
+
|
|
1980
|
+
Args:
|
|
1981
|
+
returns (pd.Series): Return series to analyze
|
|
1982
|
+
sigma (float): Volatility multiplier (default: 1)
|
|
1983
|
+
confidence (float): Confidence level (0.95 = 95%, default: 0.95)
|
|
1984
|
+
prepare_returns (bool): Whether to prepare returns first (default: True)
|
|
1985
|
+
|
|
1986
|
+
Returns:
|
|
1987
|
+
float: Conditional Value at Risk
|
|
1988
|
+
"""
|
|
1989
|
+
return conditional_value_at_risk(returns, sigma, confidence, prepare_returns)
|
|
1990
|
+
|
|
1991
|
+
|
|
1992
|
+
def expected_shortfall(returns, sigma=1, confidence=0.95):
|
|
1993
|
+
"""
|
|
1994
|
+
Calculate the Expected Shortfall (ES), also known as CVaR.
|
|
1995
|
+
|
|
1996
|
+
This is a shorthand function for conditional_value_at_risk() with
|
|
1997
|
+
the same parameters and functionality.
|
|
1998
|
+
|
|
1999
|
+
Args:
|
|
2000
|
+
returns (pd.Series): Return series to analyze
|
|
2001
|
+
sigma (float): Volatility multiplier (default: 1)
|
|
2002
|
+
confidence (float): Confidence level (0.95 = 95%, default: 0.95)
|
|
2003
|
+
|
|
2004
|
+
Returns:
|
|
2005
|
+
float: Expected Shortfall
|
|
2006
|
+
"""
|
|
2007
|
+
return conditional_value_at_risk(returns, sigma, confidence)
|
|
2008
|
+
|
|
2009
|
+
|
|
2010
|
+
def tail_ratio(returns, cutoff=0.95, prepare_returns=True):
|
|
2011
|
+
"""
|
|
2012
|
+
Calculate the tail ratio between right and left tails.
|
|
2013
|
+
|
|
2014
|
+
This function measures the ratio between the right (95%) and left (5%) tails
|
|
2015
|
+
of the return distribution, providing insight into the asymmetry of extreme
|
|
2016
|
+
returns. Higher values indicate more favorable tail characteristics.
|
|
2017
|
+
|
|
2018
|
+
Args:
|
|
2019
|
+
returns (pd.Series): Return series to analyze
|
|
2020
|
+
cutoff (float): Percentile cutoff for tail analysis (default: 0.95)
|
|
2021
|
+
prepare_returns (bool): Whether to prepare returns first (default: True)
|
|
2022
|
+
|
|
2023
|
+
Returns:
|
|
2024
|
+
float: Tail ratio (right tail / left tail)
|
|
2025
|
+
|
|
2026
|
+
Example:
|
|
2027
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
2028
|
+
>>> tail_r = tail_ratio(returns)
|
|
2029
|
+
>>> print(f"Tail ratio: {tail_r:.4f}")
|
|
2030
|
+
"""
|
|
2031
|
+
if prepare_returns:
|
|
2032
|
+
returns = _utils._prepare_returns(returns)
|
|
2033
|
+
|
|
2034
|
+
# Calculate ratio of right tail to left tail
|
|
2035
|
+
upper_quantile = returns.quantile(cutoff)
|
|
2036
|
+
lower_quantile = returns.quantile(1 - cutoff)
|
|
2037
|
+
|
|
2038
|
+
# Handle edge cases: NaN values or zero denominator
|
|
2039
|
+
# Check if result is a Series (DataFrame input) or scalar (Series input)
|
|
2040
|
+
if isinstance(upper_quantile, _pd.Series):
|
|
2041
|
+
# Handle DataFrame input - apply element-wise
|
|
2042
|
+
result = _pd.Series(index=upper_quantile.index, dtype=float)
|
|
2043
|
+
for col in upper_quantile.index:
|
|
2044
|
+
if _pd.isna(upper_quantile[col]) or _pd.isna(lower_quantile[col]) or lower_quantile[col] == 0:
|
|
2045
|
+
result[col] = _np.nan
|
|
2046
|
+
else:
|
|
2047
|
+
result[col] = abs(upper_quantile[col] / lower_quantile[col])
|
|
2048
|
+
return result
|
|
2049
|
+
else:
|
|
2050
|
+
# Handle Series input - scalar values
|
|
2051
|
+
if _pd.isna(upper_quantile) or _pd.isna(lower_quantile) or lower_quantile == 0:
|
|
2052
|
+
return _np.nan
|
|
2053
|
+
return abs(upper_quantile / lower_quantile)
|
|
2054
|
+
|
|
2055
|
+
|
|
2056
|
+
def payoff_ratio(returns, prepare_returns=True):
|
|
2057
|
+
"""
|
|
2058
|
+
Calculate the payoff ratio (average win / average loss).
|
|
2059
|
+
|
|
2060
|
+
This function measures the ratio of average winning returns to average
|
|
2061
|
+
losing returns, providing insight into the reward-to-risk profile
|
|
2062
|
+
of individual trades or periods.
|
|
2063
|
+
|
|
2064
|
+
Args:
|
|
2065
|
+
returns (pd.Series): Return series to analyze
|
|
2066
|
+
prepare_returns (bool): Whether to prepare returns first (default: True)
|
|
2067
|
+
|
|
2068
|
+
Returns:
|
|
2069
|
+
float: Payoff ratio (average win / absolute average loss)
|
|
2070
|
+
|
|
2071
|
+
Example:
|
|
2072
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
2073
|
+
>>> payoff_r = payoff_ratio(returns)
|
|
2074
|
+
>>> print(f"Payoff ratio: {payoff_r:.4f}")
|
|
2075
|
+
"""
|
|
2076
|
+
if prepare_returns:
|
|
2077
|
+
returns = _utils._prepare_returns(returns)
|
|
2078
|
+
|
|
2079
|
+
# Calculate ratio of average win to absolute average loss
|
|
2080
|
+
avg_loss_val = avg_loss(returns)
|
|
2081
|
+
avg_win_val = avg_win(returns)
|
|
2082
|
+
|
|
2083
|
+
# Handle both Series (DataFrame input) and scalar (Series input) cases
|
|
2084
|
+
if isinstance(avg_loss_val, _pd.Series):
|
|
2085
|
+
# DataFrame input - element-wise division with zero protection
|
|
2086
|
+
# Use abs() before replace to handle negative values properly
|
|
2087
|
+
return avg_win_val / abs(avg_loss_val).replace(0, _np.nan)
|
|
2088
|
+
else:
|
|
2089
|
+
# Series input - scalar division
|
|
2090
|
+
if avg_loss_val == 0:
|
|
2091
|
+
return _np.nan
|
|
2092
|
+
return avg_win_val / abs(avg_loss_val)
|
|
2093
|
+
|
|
2094
|
+
|
|
2095
|
+
def win_loss_ratio(returns, prepare_returns=True):
|
|
2096
|
+
"""
|
|
2097
|
+
Calculate the win-loss ratio (average win / average loss).
|
|
2098
|
+
|
|
2099
|
+
This is a shorthand function for payoff_ratio() with the same
|
|
2100
|
+
parameters and functionality.
|
|
2101
|
+
|
|
2102
|
+
Args:
|
|
2103
|
+
returns (pd.Series): Return series to analyze
|
|
2104
|
+
prepare_returns (bool): Whether to prepare returns first (default: True)
|
|
2105
|
+
|
|
2106
|
+
Returns:
|
|
2107
|
+
float: Win-loss ratio
|
|
2108
|
+
"""
|
|
2109
|
+
return payoff_ratio(returns, prepare_returns)
|
|
2110
|
+
|
|
2111
|
+
|
|
2112
|
+
def profit_ratio(returns, prepare_returns=True):
|
|
2113
|
+
"""
|
|
2114
|
+
Calculate the profit ratio (win ratio / loss ratio).
|
|
2115
|
+
|
|
2116
|
+
This function measures the ratio of win frequency to loss frequency,
|
|
2117
|
+
providing insight into the consistency of profitable periods.
|
|
2118
|
+
|
|
2119
|
+
Args:
|
|
2120
|
+
returns (pd.Series or pd.DataFrame): Return series to analyze
|
|
2121
|
+
prepare_returns (bool): Whether to prepare returns first (default: True)
|
|
2122
|
+
|
|
2123
|
+
Returns:
|
|
2124
|
+
float or pd.Series: Profit ratio
|
|
2125
|
+
|
|
2126
|
+
Example:
|
|
2127
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
2128
|
+
>>> profit_r = profit_ratio(returns)
|
|
2129
|
+
>>> print(f"Profit ratio: {profit_r:.4f}")
|
|
2130
|
+
"""
|
|
2131
|
+
if prepare_returns:
|
|
2132
|
+
returns = _utils._prepare_returns(returns)
|
|
2133
|
+
|
|
2134
|
+
def _profit_ratio(ret):
|
|
2135
|
+
# Separate wins and losses
|
|
2136
|
+
wins = ret[ret >= 0]
|
|
2137
|
+
loss = ret[ret < 0]
|
|
2138
|
+
|
|
2139
|
+
# Handle edge cases
|
|
2140
|
+
win_count = len(wins)
|
|
2141
|
+
loss_count = len(loss)
|
|
2142
|
+
|
|
2143
|
+
if win_count == 0:
|
|
2144
|
+
return 0.0
|
|
2145
|
+
if loss_count == 0:
|
|
2146
|
+
return _np.nan
|
|
2147
|
+
|
|
2148
|
+
# Calculate win and loss ratios
|
|
2149
|
+
win_ratio = abs(wins.mean() / win_count) if win_count > 0 else 0
|
|
2150
|
+
loss_ratio = abs(loss.mean() / loss_count) if loss_count > 0 else 0
|
|
2151
|
+
|
|
2152
|
+
if loss_ratio == 0:
|
|
2153
|
+
return _np.nan
|
|
2154
|
+
return win_ratio / loss_ratio
|
|
2155
|
+
|
|
2156
|
+
# Handle DataFrame by applying to each column
|
|
2157
|
+
if isinstance(returns, _pd.DataFrame):
|
|
2158
|
+
return returns.apply(_profit_ratio)
|
|
2159
|
+
|
|
2160
|
+
return _profit_ratio(returns)
|
|
2161
|
+
|
|
2162
|
+
|
|
2163
|
+
def profit_factor(returns, prepare_returns=True):
|
|
2164
|
+
"""
|
|
2165
|
+
Calculate the profit factor (total wins / total losses).
|
|
2166
|
+
|
|
2167
|
+
This function measures the ratio of total winning returns to total
|
|
2168
|
+
losing returns, providing insight into the overall profitability
|
|
2169
|
+
of the strategy.
|
|
2170
|
+
|
|
2171
|
+
Args:
|
|
2172
|
+
returns (pd.Series): Return series to analyze
|
|
2173
|
+
prepare_returns (bool): Whether to prepare returns first (default: True)
|
|
2174
|
+
|
|
2175
|
+
Returns:
|
|
2176
|
+
float: Profit factor (total wins / total losses)
|
|
2177
|
+
|
|
2178
|
+
Example:
|
|
2179
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
2180
|
+
>>> pf = profit_factor(returns)
|
|
2181
|
+
>>> print(f"Profit factor: {pf:.4f}")
|
|
2182
|
+
"""
|
|
2183
|
+
if prepare_returns:
|
|
2184
|
+
returns = _utils._prepare_returns(returns)
|
|
2185
|
+
|
|
2186
|
+
# Calculate total wins and losses
|
|
2187
|
+
wins_sum = returns[returns >= 0].sum()
|
|
2188
|
+
losses_sum = abs(returns[returns < 0].sum())
|
|
2189
|
+
|
|
2190
|
+
# Handle both Series and scalar cases
|
|
2191
|
+
if isinstance(losses_sum, _pd.Series):
|
|
2192
|
+
result = wins_sum / losses_sum
|
|
2193
|
+
# Replace infinite values with 0
|
|
2194
|
+
result = result.replace([_np.inf, -_np.inf], 0)
|
|
2195
|
+
return result
|
|
2196
|
+
else:
|
|
2197
|
+
# Handle division by zero case
|
|
2198
|
+
if losses_sum == 0:
|
|
2199
|
+
return 0.0 if wins_sum == 0 else float('inf')
|
|
2200
|
+
return wins_sum / losses_sum
|
|
2201
|
+
|
|
2202
|
+
|
|
2203
|
+
def cpc_index(returns, prepare_returns=True):
|
|
2204
|
+
"""
|
|
2205
|
+
Calculate the CPC Index (Profit Factor * Win Rate * Win-Loss Ratio).
|
|
2206
|
+
|
|
2207
|
+
The CPC Index is a comprehensive performance measure that combines
|
|
2208
|
+
profit factor, win rate, and win-loss ratio to provide a single
|
|
2209
|
+
metric for strategy evaluation.
|
|
2210
|
+
|
|
2211
|
+
Args:
|
|
2212
|
+
returns (pd.Series): Return series to analyze
|
|
2213
|
+
prepare_returns (bool): Whether to prepare returns first (default: True)
|
|
2214
|
+
|
|
2215
|
+
Returns:
|
|
2216
|
+
float: CPC Index
|
|
2217
|
+
|
|
2218
|
+
Example:
|
|
2219
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
2220
|
+
>>> cpc = cpc_index(returns)
|
|
2221
|
+
>>> print(f"CPC Index: {cpc:.4f}")
|
|
2222
|
+
"""
|
|
2223
|
+
if prepare_returns:
|
|
2224
|
+
returns = _utils._prepare_returns(returns)
|
|
2225
|
+
|
|
2226
|
+
# Calculate composite metric
|
|
2227
|
+
return profit_factor(returns) * win_rate(returns) * win_loss_ratio(returns)
|
|
2228
|
+
|
|
2229
|
+
|
|
2230
|
+
def common_sense_ratio(returns, prepare_returns=True):
|
|
2231
|
+
"""
|
|
2232
|
+
Calculate the Common Sense Ratio (Profit Factor * Tail Ratio).
|
|
2233
|
+
|
|
2234
|
+
This ratio combines profit factor with tail ratio to provide a
|
|
2235
|
+
measure that considers both profitability and tail risk characteristics.
|
|
2236
|
+
|
|
2237
|
+
Args:
|
|
2238
|
+
returns (pd.Series): Return series to analyze
|
|
2239
|
+
prepare_returns (bool): Whether to prepare returns first (default: True)
|
|
2240
|
+
|
|
2241
|
+
Returns:
|
|
2242
|
+
float: Common Sense Ratio
|
|
2243
|
+
|
|
2244
|
+
Example:
|
|
2245
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
2246
|
+
>>> csr = common_sense_ratio(returns)
|
|
2247
|
+
>>> print(f"Common Sense Ratio: {csr:.4f}")
|
|
2248
|
+
"""
|
|
2249
|
+
if prepare_returns:
|
|
2250
|
+
returns = _utils._prepare_returns(returns)
|
|
2251
|
+
|
|
2252
|
+
# Calculate composite metric
|
|
2253
|
+
return profit_factor(returns) * tail_ratio(returns)
|
|
2254
|
+
|
|
2255
|
+
|
|
2256
|
+
def outlier_win_ratio(returns, quantile=0.99, prepare_returns=True):
|
|
2257
|
+
"""
|
|
2258
|
+
Calculate the outlier winners ratio.
|
|
2259
|
+
|
|
2260
|
+
This function computes the ratio of the 99th percentile of returns
|
|
2261
|
+
to the mean positive return, showing how much outlier wins contribute
|
|
2262
|
+
to overall performance.
|
|
2263
|
+
|
|
2264
|
+
Args:
|
|
2265
|
+
returns (pd.Series): Return series to analyze
|
|
2266
|
+
quantile (float): Quantile for outlier threshold (default: 0.99)
|
|
2267
|
+
prepare_returns (bool): Whether to prepare returns first (default: True)
|
|
2268
|
+
|
|
2269
|
+
Returns:
|
|
2270
|
+
float: Outlier win ratio
|
|
2271
|
+
|
|
2272
|
+
Example:
|
|
2273
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
2274
|
+
>>> outlier_win_r = outlier_win_ratio(returns)
|
|
2275
|
+
>>> print(f"Outlier win ratio: {outlier_win_r:.4f}")
|
|
2276
|
+
"""
|
|
2277
|
+
if prepare_returns:
|
|
2278
|
+
returns = _utils._prepare_returns(returns)
|
|
2279
|
+
|
|
2280
|
+
# Calculate ratio of high quantile to mean positive return
|
|
2281
|
+
positive_mean = returns[returns >= 0].mean()
|
|
2282
|
+
quantile_val = returns.quantile(quantile) # Series for DataFrame, scalar for Series
|
|
2283
|
+
|
|
2284
|
+
# Handle both Series (DataFrame input) and scalar (Series input) cases
|
|
2285
|
+
if isinstance(positive_mean, _pd.Series):
|
|
2286
|
+
# DataFrame input - element-wise division with zero protection
|
|
2287
|
+
return quantile_val / positive_mean.replace(0, _np.nan)
|
|
2288
|
+
else:
|
|
2289
|
+
# Series input - scalar division
|
|
2290
|
+
if _pd.isna(positive_mean) or positive_mean == 0:
|
|
2291
|
+
return _np.nan
|
|
2292
|
+
return quantile_val / positive_mean
|
|
2293
|
+
|
|
2294
|
+
|
|
2295
|
+
def outlier_loss_ratio(returns, quantile=0.01, prepare_returns=True):
|
|
2296
|
+
"""
|
|
2297
|
+
Calculate the outlier losers ratio.
|
|
2298
|
+
|
|
2299
|
+
This function computes the ratio of the 1st percentile of returns
|
|
2300
|
+
to the mean negative return, showing how much outlier losses contribute
|
|
2301
|
+
to overall risk.
|
|
2302
|
+
|
|
2303
|
+
Args:
|
|
2304
|
+
returns (pd.Series): Return series to analyze
|
|
2305
|
+
quantile (float): Quantile for outlier threshold (default: 0.01)
|
|
2306
|
+
prepare_returns (bool): Whether to prepare returns first (default: True)
|
|
2307
|
+
|
|
2308
|
+
Returns:
|
|
2309
|
+
float: Outlier loss ratio
|
|
2310
|
+
|
|
2311
|
+
Example:
|
|
2312
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
2313
|
+
>>> outlier_loss_r = outlier_loss_ratio(returns)
|
|
2314
|
+
>>> print(f"Outlier loss ratio: {outlier_loss_r:.4f}")
|
|
2315
|
+
"""
|
|
2316
|
+
if prepare_returns:
|
|
2317
|
+
returns = _utils._prepare_returns(returns)
|
|
2318
|
+
|
|
2319
|
+
# Calculate ratio of low quantile to mean negative return
|
|
2320
|
+
negative_mean = returns[returns < 0].mean()
|
|
2321
|
+
quantile_val = returns.quantile(quantile) # Series for DataFrame, scalar for Series
|
|
2322
|
+
|
|
2323
|
+
# Handle both Series (DataFrame input) and scalar (Series input) cases
|
|
2324
|
+
if isinstance(negative_mean, _pd.Series):
|
|
2325
|
+
# DataFrame input - element-wise division with zero protection
|
|
2326
|
+
return quantile_val / negative_mean.replace(0, _np.nan)
|
|
2327
|
+
else:
|
|
2328
|
+
# Series input - scalar division
|
|
2329
|
+
if _pd.isna(negative_mean) or negative_mean == 0:
|
|
2330
|
+
return _np.nan
|
|
2331
|
+
return quantile_val / negative_mean
|
|
2332
|
+
|
|
2333
|
+
|
|
2334
|
+
def recovery_factor(returns, rf=0.0, prepare_returns=True):
|
|
2335
|
+
"""
|
|
2336
|
+
Calculate the recovery factor (total returns / maximum drawdown).
|
|
2337
|
+
|
|
2338
|
+
This function measures how fast the strategy recovers from drawdowns
|
|
2339
|
+
by comparing total returns to the maximum drawdown experienced.
|
|
2340
|
+
Higher values indicate better recovery characteristics.
|
|
2341
|
+
|
|
2342
|
+
Args:
|
|
2343
|
+
returns (pd.Series): Return series to analyze
|
|
2344
|
+
rf (float): Risk-free rate (default: 0.0)
|
|
2345
|
+
prepare_returns (bool): Whether to prepare returns first (default: True)
|
|
2346
|
+
|
|
2347
|
+
Returns:
|
|
2348
|
+
float: Recovery factor
|
|
2349
|
+
|
|
2350
|
+
Example:
|
|
2351
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
2352
|
+
>>> rf_value = recovery_factor(returns)
|
|
2353
|
+
>>> print(f"Recovery factor: {rf_value:.4f}")
|
|
2354
|
+
"""
|
|
2355
|
+
if prepare_returns:
|
|
2356
|
+
returns = _utils._prepare_returns(returns)
|
|
2357
|
+
|
|
2358
|
+
# Calculate total excess returns
|
|
2359
|
+
total_returns = returns.sum() - rf
|
|
2360
|
+
|
|
2361
|
+
# Calculate maximum drawdown
|
|
2362
|
+
max_dd = max_drawdown(returns)
|
|
2363
|
+
|
|
2364
|
+
# Handle both Series (DataFrame input) and scalar (Series input) cases
|
|
2365
|
+
if isinstance(max_dd, _pd.Series):
|
|
2366
|
+
# DataFrame input - element-wise division with zero protection
|
|
2367
|
+
return abs(total_returns) / abs(max_dd).replace(0, _np.nan)
|
|
2368
|
+
else:
|
|
2369
|
+
# Series input - scalar division
|
|
2370
|
+
if max_dd == 0:
|
|
2371
|
+
return _np.nan
|
|
2372
|
+
return abs(total_returns) / abs(max_dd)
|
|
2373
|
+
|
|
2374
|
+
|
|
2375
|
+
def risk_return_ratio(returns, prepare_returns=True):
|
|
2376
|
+
"""
|
|
2377
|
+
Calculate the risk-return ratio (mean return / standard deviation).
|
|
2378
|
+
|
|
2379
|
+
This function calculates the Sharpe ratio without factoring in the
|
|
2380
|
+
risk-free rate, providing a simple measure of return per unit of risk.
|
|
2381
|
+
|
|
2382
|
+
Args:
|
|
2383
|
+
returns (pd.Series): Return series to analyze
|
|
2384
|
+
prepare_returns (bool): Whether to prepare returns first (default: True)
|
|
2385
|
+
|
|
2386
|
+
Returns:
|
|
2387
|
+
float: Risk-return ratio
|
|
2388
|
+
|
|
2389
|
+
Example:
|
|
2390
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
2391
|
+
>>> rrr = risk_return_ratio(returns)
|
|
2392
|
+
>>> print(f"Risk-return ratio: {rrr:.4f}")
|
|
2393
|
+
"""
|
|
2394
|
+
if prepare_returns:
|
|
2395
|
+
returns = _utils._prepare_returns(returns)
|
|
2396
|
+
|
|
2397
|
+
# Calculate mean return divided by standard deviation
|
|
2398
|
+
std = returns.std()
|
|
2399
|
+
|
|
2400
|
+
# Handle both Series (DataFrame input) and scalar (Series input) cases
|
|
2401
|
+
if isinstance(std, _pd.Series):
|
|
2402
|
+
# DataFrame input - element-wise division with zero protection
|
|
2403
|
+
return returns.mean() / std.replace(0, _np.nan)
|
|
2404
|
+
else:
|
|
2405
|
+
# Series input - scalar division
|
|
2406
|
+
if std == 0:
|
|
2407
|
+
return _np.nan
|
|
2408
|
+
return returns.mean() / std
|
|
2409
|
+
|
|
2410
|
+
|
|
2411
|
+
def _get_baseline_value(prices):
|
|
2412
|
+
"""
|
|
2413
|
+
Determine the appropriate baseline value for drawdown calculations.
|
|
2414
|
+
|
|
2415
|
+
This function analyzes the price series to determine the correct baseline
|
|
2416
|
+
value that should represent "no drawdown" (i.e., the starting equity).
|
|
2417
|
+
|
|
2418
|
+
Args:
|
|
2419
|
+
prices (pd.Series): Price series
|
|
2420
|
+
|
|
2421
|
+
Returns:
|
|
2422
|
+
float: Baseline value for drawdown calculations
|
|
2423
|
+
"""
|
|
2424
|
+
if len(prices) == 0:
|
|
2425
|
+
return 1.0
|
|
2426
|
+
|
|
2427
|
+
# Handle both Series and DataFrame cases
|
|
2428
|
+
if isinstance(prices, _pd.DataFrame):
|
|
2429
|
+
# If prices is a DataFrame, ensure it has at least one column
|
|
2430
|
+
if prices.shape[1] == 0:
|
|
2431
|
+
return 1.0 # Default baseline for empty DataFrame with no columns
|
|
2432
|
+
# Get the first value of the first column
|
|
2433
|
+
first_price = prices.iat[0, 0]
|
|
2434
|
+
else:
|
|
2435
|
+
# If prices is a Series, get the first value directly
|
|
2436
|
+
first_price = prices.iloc[0]
|
|
2437
|
+
|
|
2438
|
+
# If the first price is much larger than 1, it's likely from to_prices conversion
|
|
2439
|
+
# The to_prices function uses base * (1 + compsum), so we determine the appropriate baseline
|
|
2440
|
+
if first_price > 1000:
|
|
2441
|
+
# This suggests it came from to_prices with a large base (default 1e5)
|
|
2442
|
+
# However, we should use a more reasonable baseline for drawdown calculations
|
|
2443
|
+
# We'll use the same scale as the prices but represent the "no loss" baseline
|
|
2444
|
+
return 1e5
|
|
2445
|
+
elif first_price > 10:
|
|
2446
|
+
# Smaller base value scale
|
|
2447
|
+
return 100.0
|
|
2448
|
+
else:
|
|
2449
|
+
# Normal price scale, use 1.0 as baseline
|
|
2450
|
+
return 1.0
|
|
2451
|
+
|
|
2452
|
+
|
|
2453
|
+
def max_drawdown(prices: Returns) -> float:
|
|
2454
|
+
"""
|
|
2455
|
+
Calculate the maximum drawdown from peak to trough.
|
|
2456
|
+
|
|
2457
|
+
This function calculates the maximum observed loss from a peak to a
|
|
2458
|
+
subsequent trough, expressed as a percentage. It handles the edge case
|
|
2459
|
+
where the first return is negative by establishing a proper baseline.
|
|
2460
|
+
|
|
2461
|
+
Args:
|
|
2462
|
+
prices (pd.Series): Price series or cumulative returns
|
|
2463
|
+
|
|
2464
|
+
Returns:
|
|
2465
|
+
float: Maximum drawdown (negative value)
|
|
2466
|
+
|
|
2467
|
+
Example:
|
|
2468
|
+
>>> prices = pd.Series([100, 110, 105, 120, 115])
|
|
2469
|
+
>>> max_dd = max_drawdown(prices)
|
|
2470
|
+
>>> print(f"Maximum drawdown: {max_dd:.4f}")
|
|
2471
|
+
"""
|
|
2472
|
+
validate_input(prices)
|
|
2473
|
+
|
|
2474
|
+
# Prepare prices (convert from returns if needed)
|
|
2475
|
+
prices = _utils._prepare_prices(prices)
|
|
2476
|
+
|
|
2477
|
+
if len(prices) == 0:
|
|
2478
|
+
return 0.0
|
|
2479
|
+
|
|
2480
|
+
# Handle edge case: if first value represents a loss from baseline
|
|
2481
|
+
# Add a phantom baseline value to ensure proper drawdown calculation
|
|
2482
|
+
try:
|
|
2483
|
+
time_delta = prices.index.freq or _pd.Timedelta(days=1)
|
|
2484
|
+
except Exception:
|
|
2485
|
+
time_delta = _pd.Timedelta(days=1)
|
|
2486
|
+
|
|
2487
|
+
phantom_date = prices.index[0] - time_delta
|
|
2488
|
+
|
|
2489
|
+
# Determine appropriate baseline value
|
|
2490
|
+
baseline_value = _get_baseline_value(prices)
|
|
2491
|
+
|
|
2492
|
+
# Create extended series with phantom baseline
|
|
2493
|
+
extended_prices = prices.copy()
|
|
2494
|
+
extended_prices.loc[phantom_date] = baseline_value
|
|
2495
|
+
extended_prices = extended_prices.sort_index()
|
|
2496
|
+
|
|
2497
|
+
# Calculate drawdown with phantom baseline
|
|
2498
|
+
return (extended_prices / extended_prices.expanding(min_periods=0).max()).min() - 1
|
|
2499
|
+
|
|
2500
|
+
|
|
2501
|
+
def to_drawdown_series(returns):
|
|
2502
|
+
"""
|
|
2503
|
+
Convert returns series to drawdown series.
|
|
2504
|
+
|
|
2505
|
+
This function converts a return series to a drawdown series showing
|
|
2506
|
+
the decline from peak equity at each point in time. It handles the
|
|
2507
|
+
edge case where the first return is negative by establishing a proper baseline.
|
|
2508
|
+
|
|
2509
|
+
Args:
|
|
2510
|
+
returns (pd.Series): Return series to convert
|
|
2511
|
+
|
|
2512
|
+
Returns:
|
|
2513
|
+
pd.Series: Drawdown series (negative values showing decline from peak)
|
|
2514
|
+
|
|
2515
|
+
Example:
|
|
2516
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
2517
|
+
>>> dd_series = to_drawdown_series(returns)
|
|
2518
|
+
>>> print(dd_series)
|
|
2519
|
+
"""
|
|
2520
|
+
validate_input(returns)
|
|
2521
|
+
|
|
2522
|
+
# Convert returns to prices
|
|
2523
|
+
prices = _utils._prepare_prices(returns)
|
|
2524
|
+
|
|
2525
|
+
if len(prices) == 0:
|
|
2526
|
+
return _pd.Series([], dtype=float, index=returns.index)
|
|
2527
|
+
|
|
2528
|
+
# Handle edge case: if first value represents a loss from baseline
|
|
2529
|
+
# Add a phantom baseline value to ensure proper drawdown calculation
|
|
2530
|
+
try:
|
|
2531
|
+
time_delta = prices.index.freq or _pd.Timedelta(days=1)
|
|
2532
|
+
except Exception:
|
|
2533
|
+
time_delta = _pd.Timedelta(days=1)
|
|
2534
|
+
|
|
2535
|
+
phantom_date = prices.index[0] - time_delta
|
|
2536
|
+
|
|
2537
|
+
# Determine appropriate baseline value
|
|
2538
|
+
baseline_value = _get_baseline_value(prices)
|
|
2539
|
+
|
|
2540
|
+
# Create extended series with phantom baseline
|
|
2541
|
+
extended_prices = prices.copy()
|
|
2542
|
+
extended_prices.loc[phantom_date] = baseline_value
|
|
2543
|
+
extended_prices = extended_prices.sort_index()
|
|
2544
|
+
|
|
2545
|
+
# Calculate drawdown series with phantom baseline
|
|
2546
|
+
dd = extended_prices / _np.maximum.accumulate(extended_prices) - 1.0
|
|
2547
|
+
|
|
2548
|
+
# Remove phantom point and return original time series
|
|
2549
|
+
dd = dd.drop(phantom_date)
|
|
2550
|
+
|
|
2551
|
+
# Clean up infinite and zero values
|
|
2552
|
+
return dd.replace([_np.inf, -_np.inf, -0], 0) # type: ignore[attr-defined]
|
|
2553
|
+
|
|
2554
|
+
|
|
2555
|
+
def kelly_criterion(returns, prepare_returns=True):
|
|
2556
|
+
"""
|
|
2557
|
+
Calculates the recommended maximum amount of capital that
|
|
2558
|
+
should be allocated to the given strategy, based on the
|
|
2559
|
+
Kelly Criterion (http://en.wikipedia.org/wiki/Kelly_criterion)
|
|
2560
|
+
"""
|
|
2561
|
+
if prepare_returns:
|
|
2562
|
+
returns = _utils._prepare_returns(returns)
|
|
2563
|
+
win_loss_ratio = payoff_ratio(returns)
|
|
2564
|
+
win_prob = win_rate(returns)
|
|
2565
|
+
lose_prob = 1 - win_prob
|
|
2566
|
+
|
|
2567
|
+
# Handle both Series (DataFrame input) and scalar (Series input) cases
|
|
2568
|
+
if isinstance(win_loss_ratio, _pd.Series):
|
|
2569
|
+
# DataFrame input - element-wise operations with zero/nan protection
|
|
2570
|
+
# Replace 0 and NaN values with NaN to avoid division issues
|
|
2571
|
+
win_loss_ratio_safe = win_loss_ratio.replace(0, _np.nan)
|
|
2572
|
+
return ((win_loss_ratio_safe * win_prob) - lose_prob) / win_loss_ratio_safe
|
|
2573
|
+
else:
|
|
2574
|
+
# Series input - scalar operations
|
|
2575
|
+
if win_loss_ratio == 0 or _pd.isna(win_loss_ratio):
|
|
2576
|
+
return _np.nan
|
|
2577
|
+
return ((win_loss_ratio * win_prob) - lose_prob) / win_loss_ratio
|
|
2578
|
+
|
|
2579
|
+
|
|
2580
|
+
# ==== VS. BENCHMARK ====
|
|
2581
|
+
|
|
2582
|
+
|
|
2583
|
+
def r_squared(returns, benchmark, prepare_returns=True):
|
|
2584
|
+
"""
|
|
2585
|
+
Calculate the R-squared (coefficient of determination) versus benchmark.
|
|
2586
|
+
|
|
2587
|
+
R-squared measures how well the returns fit a straight line relationship
|
|
2588
|
+
with the benchmark. Values closer to 1 indicate higher correlation with
|
|
2589
|
+
the benchmark, while values closer to 0 indicate more independent movement.
|
|
2590
|
+
|
|
2591
|
+
Args:
|
|
2592
|
+
returns (pd.Series): Return series to analyze
|
|
2593
|
+
benchmark (pd.Series): Benchmark return series for comparison
|
|
2594
|
+
prepare_returns (bool): Whether to prepare returns first (default: True)
|
|
2595
|
+
|
|
2596
|
+
Returns:
|
|
2597
|
+
float: R-squared value (0-1 scale)
|
|
2598
|
+
|
|
2599
|
+
Example:
|
|
2600
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
2601
|
+
>>> benchmark = pd.Series([0.005, -0.01, 0.02, -0.005, 0.015])
|
|
2602
|
+
>>> r_sq = r_squared(returns, benchmark)
|
|
2603
|
+
>>> print(f"R-squared: {r_sq:.4f}")
|
|
2604
|
+
"""
|
|
2605
|
+
if prepare_returns:
|
|
2606
|
+
returns = _utils._prepare_returns(returns)
|
|
2607
|
+
|
|
2608
|
+
# Prepare benchmark to match returns index
|
|
2609
|
+
benchmark = _utils._prepare_benchmark(benchmark, returns.index)
|
|
2610
|
+
|
|
2611
|
+
# Perform linear regression and extract correlation coefficient
|
|
2612
|
+
_, _, r_val, _, _ = _linregress(
|
|
2613
|
+
returns, _utils._prepare_benchmark(benchmark, returns.index)
|
|
2614
|
+
)
|
|
2615
|
+
|
|
2616
|
+
# Square the correlation coefficient to get R-squared
|
|
2617
|
+
return r_val**2
|
|
2618
|
+
|
|
2619
|
+
|
|
2620
|
+
def r2(returns, benchmark):
|
|
2621
|
+
"""
|
|
2622
|
+
Calculate the R-squared (coefficient of determination) versus benchmark.
|
|
2623
|
+
|
|
2624
|
+
This is a shorthand function for r_squared() with the same parameters
|
|
2625
|
+
and functionality.
|
|
2626
|
+
|
|
2627
|
+
Args:
|
|
2628
|
+
returns (pd.Series): Return series to analyze
|
|
2629
|
+
benchmark (pd.Series): Benchmark return series for comparison
|
|
2630
|
+
|
|
2631
|
+
Returns:
|
|
2632
|
+
float: R-squared value (0-1 scale)
|
|
2633
|
+
"""
|
|
2634
|
+
return r_squared(returns, benchmark)
|
|
2635
|
+
|
|
2636
|
+
|
|
2637
|
+
def information_ratio(returns, benchmark, prepare_returns=True):
|
|
2638
|
+
"""
|
|
2639
|
+
Calculate the Information Ratio.
|
|
2640
|
+
|
|
2641
|
+
The Information Ratio measures the risk-adjusted excess return of a
|
|
2642
|
+
portfolio relative to a benchmark. It's calculated as the active return
|
|
2643
|
+
(return - benchmark) divided by the tracking error (standard deviation
|
|
2644
|
+
of active returns).
|
|
2645
|
+
|
|
2646
|
+
Args:
|
|
2647
|
+
returns (pd.Series): Return series to analyze
|
|
2648
|
+
benchmark (pd.Series): Benchmark return series for comparison
|
|
2649
|
+
prepare_returns (bool): Whether to prepare returns first (default: True)
|
|
2650
|
+
|
|
2651
|
+
Returns:
|
|
2652
|
+
float: Information Ratio
|
|
2653
|
+
|
|
2654
|
+
Example:
|
|
2655
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
2656
|
+
>>> benchmark = pd.Series([0.005, -0.01, 0.02, -0.005, 0.015])
|
|
2657
|
+
>>> info_ratio = information_ratio(returns, benchmark)
|
|
2658
|
+
>>> print(f"Information Ratio: {info_ratio:.4f}")
|
|
2659
|
+
"""
|
|
2660
|
+
if prepare_returns:
|
|
2661
|
+
returns = _utils._prepare_returns(returns)
|
|
2662
|
+
|
|
2663
|
+
# Prepare benchmark to match returns index
|
|
2664
|
+
benchmark = _utils._prepare_benchmark(benchmark, returns.index)
|
|
2665
|
+
|
|
2666
|
+
# Calculate active returns (returns - benchmark)
|
|
2667
|
+
diff_rets = returns - _utils._prepare_benchmark(benchmark, returns.index)
|
|
2668
|
+
|
|
2669
|
+
# Calculate tracking error (standard deviation of active returns)
|
|
2670
|
+
std = diff_rets.std()
|
|
2671
|
+
|
|
2672
|
+
# Return Information Ratio (active return / tracking error)
|
|
2673
|
+
if std != 0:
|
|
2674
|
+
return diff_rets.mean() / diff_rets.std()
|
|
2675
|
+
return 0
|
|
2676
|
+
|
|
2677
|
+
|
|
2678
|
+
def greeks(returns, benchmark, periods=252.0, prepare_returns=True):
|
|
2679
|
+
"""
|
|
2680
|
+
Calculate portfolio Greeks (alpha and beta) relative to benchmark.
|
|
2681
|
+
|
|
2682
|
+
This function calculates the key portfolio metrics for benchmark comparison:
|
|
2683
|
+
- Alpha: Excess return after adjusting for systematic risk (beta)
|
|
2684
|
+
- Beta: Sensitivity to benchmark movements (systematic risk)
|
|
2685
|
+
|
|
2686
|
+
Args:
|
|
2687
|
+
returns (pd.Series): Return series to analyze
|
|
2688
|
+
benchmark (pd.Series): Benchmark return series for comparison
|
|
2689
|
+
periods (float): Periods per year for alpha annualization (default: 252.0)
|
|
2690
|
+
prepare_returns (bool): Whether to prepare returns first (default: True)
|
|
2691
|
+
|
|
2692
|
+
Returns:
|
|
2693
|
+
pd.Series: Series containing 'alpha' and 'beta' values
|
|
2694
|
+
|
|
2695
|
+
Example:
|
|
2696
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
2697
|
+
>>> benchmark = pd.Series([0.005, -0.01, 0.02, -0.005, 0.015])
|
|
2698
|
+
>>> portfolio_greeks = greeks(returns, benchmark)
|
|
2699
|
+
>>> print(f"Alpha: {portfolio_greeks['alpha']:.4f}")
|
|
2700
|
+
>>> print(f"Beta: {portfolio_greeks['beta']:.4f}")
|
|
2701
|
+
"""
|
|
2702
|
+
# Data preparation
|
|
2703
|
+
if prepare_returns:
|
|
2704
|
+
returns = _utils._prepare_returns(returns)
|
|
2705
|
+
benchmark = _utils._prepare_benchmark(benchmark, returns.index)
|
|
2706
|
+
# ----------------------------
|
|
2707
|
+
|
|
2708
|
+
# Calculate covariance matrix between returns and benchmark
|
|
2709
|
+
matrix = _np.cov(returns, benchmark)
|
|
2710
|
+
|
|
2711
|
+
# Calculate beta (sensitivity to benchmark movements)
|
|
2712
|
+
if matrix[1, 1] == 0:
|
|
2713
|
+
beta = _np.nan
|
|
2714
|
+
else:
|
|
2715
|
+
beta = matrix[0, 1] / matrix[1, 1]
|
|
2716
|
+
|
|
2717
|
+
# Calculate alpha (excess return after adjusting for beta)
|
|
2718
|
+
alpha = returns.mean() - beta * benchmark.mean()
|
|
2719
|
+
|
|
2720
|
+
# Annualize alpha
|
|
2721
|
+
alpha = alpha * periods
|
|
2722
|
+
|
|
2723
|
+
# Return results as Series
|
|
2724
|
+
return _pd.Series(
|
|
2725
|
+
{
|
|
2726
|
+
"beta": beta,
|
|
2727
|
+
"alpha": alpha,
|
|
2728
|
+
# "vol": _np.sqrt(matrix[0, 0]) * _np.sqrt(periods)
|
|
2729
|
+
}
|
|
2730
|
+
).fillna(0)
|
|
2731
|
+
|
|
2732
|
+
|
|
2733
|
+
def rolling_greeks(returns, benchmark, periods=252, prepare_returns=True):
|
|
2734
|
+
"""
|
|
2735
|
+
Calculate rolling Greeks (alpha and beta) over time.
|
|
2736
|
+
|
|
2737
|
+
This function calculates time-varying alpha and beta using a rolling
|
|
2738
|
+
window, showing how portfolio sensitivity to the benchmark changes
|
|
2739
|
+
over time. Useful for analyzing strategy stability and regime changes.
|
|
2740
|
+
|
|
2741
|
+
Args:
|
|
2742
|
+
returns (pd.Series): Return series to analyze
|
|
2743
|
+
benchmark (pd.Series): Benchmark return series for comparison
|
|
2744
|
+
periods (int): Rolling window size (default: 252, ~1 year)
|
|
2745
|
+
prepare_returns (bool): Whether to prepare returns first (default: True)
|
|
2746
|
+
|
|
2747
|
+
Returns:
|
|
2748
|
+
pd.DataFrame: DataFrame with 'alpha' and 'beta' columns over time
|
|
2749
|
+
|
|
2750
|
+
Example:
|
|
2751
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
2752
|
+
>>> benchmark = pd.Series([0.005, -0.01, 0.02, -0.005, 0.015])
|
|
2753
|
+
>>> rolling_greeks_df = rolling_greeks(returns, benchmark, periods=3)
|
|
2754
|
+
>>> print(rolling_greeks_df)
|
|
2755
|
+
"""
|
|
2756
|
+
if prepare_returns:
|
|
2757
|
+
returns = _utils._prepare_returns(returns)
|
|
2758
|
+
|
|
2759
|
+
# Create combined DataFrame for rolling calculations
|
|
2760
|
+
df = _pd.DataFrame(
|
|
2761
|
+
data={
|
|
2762
|
+
"returns": returns,
|
|
2763
|
+
"benchmark": _utils._prepare_benchmark(benchmark, returns.index),
|
|
2764
|
+
}
|
|
2765
|
+
)
|
|
2766
|
+
|
|
2767
|
+
# Fill NaN values with 0 for calculation stability
|
|
2768
|
+
df = df.fillna(0)
|
|
2769
|
+
|
|
2770
|
+
# Calculate rolling correlation and standard deviations
|
|
2771
|
+
corr = df.rolling(int(periods)).corr().unstack()["returns"]["benchmark"]
|
|
2772
|
+
std = df.rolling(int(periods)).std()
|
|
2773
|
+
|
|
2774
|
+
# Calculate rolling beta (protect against division by zero)
|
|
2775
|
+
beta = corr * std["returns"] / std["benchmark"].replace(0, _np.nan)
|
|
2776
|
+
|
|
2777
|
+
# Calculate rolling alpha (not annualized for rolling version)
|
|
2778
|
+
alpha = df["returns"].mean() - beta * df["benchmark"].mean()
|
|
2779
|
+
|
|
2780
|
+
# Return DataFrame with rolling Greeks
|
|
2781
|
+
return _pd.DataFrame(index=returns.index, data={"beta": beta, "alpha": alpha})
|
|
2782
|
+
|
|
2783
|
+
|
|
2784
|
+
def compare(
|
|
2785
|
+
returns,
|
|
2786
|
+
benchmark,
|
|
2787
|
+
aggregate=None,
|
|
2788
|
+
compounded=True,
|
|
2789
|
+
round_vals=None,
|
|
2790
|
+
prepare_returns=True,
|
|
2791
|
+
):
|
|
2792
|
+
"""
|
|
2793
|
+
Compare returns to benchmark across different time periods.
|
|
2794
|
+
|
|
2795
|
+
This function provides a comprehensive comparison of portfolio returns
|
|
2796
|
+
versus benchmark performance across various aggregation periods
|
|
2797
|
+
(daily, weekly, monthly, quarterly, yearly).
|
|
2798
|
+
|
|
2799
|
+
Args:
|
|
2800
|
+
returns (pd.Series or pd.DataFrame): Return series to analyze
|
|
2801
|
+
benchmark (pd.Series): Benchmark return series for comparison
|
|
2802
|
+
aggregate (str): Aggregation period ('D', 'W', 'M', 'Q', 'Y')
|
|
2803
|
+
compounded (bool): Whether to compound returns (default: True)
|
|
2804
|
+
round_vals (int): Number of decimal places to round (default: None)
|
|
2805
|
+
prepare_returns (bool): Whether to prepare returns first (default: True)
|
|
2806
|
+
|
|
2807
|
+
Returns:
|
|
2808
|
+
pd.DataFrame: Comparison DataFrame with columns:
|
|
2809
|
+
- Benchmark: Benchmark returns for each period
|
|
2810
|
+
- Returns: Portfolio returns for each period
|
|
2811
|
+
- Multiplier: Portfolio return / Benchmark return
|
|
2812
|
+
- Won: '+' if portfolio outperformed, '-' if underperformed
|
|
2813
|
+
|
|
2814
|
+
Example:
|
|
2815
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
2816
|
+
>>> benchmark = pd.Series([0.005, -0.01, 0.02, -0.005, 0.015])
|
|
2817
|
+
>>> comparison = compare(returns, benchmark)
|
|
2818
|
+
>>> print(comparison)
|
|
2819
|
+
"""
|
|
2820
|
+
# Normalize timezone for returns to ensure consistent comparisons
|
|
2821
|
+
# Convert to UTC if timezone-aware, then make naive
|
|
2822
|
+
# This must happen before prepare_returns to avoid issues
|
|
2823
|
+
if hasattr(returns.index, 'tz') and returns.index.tz is not None:
|
|
2824
|
+
returns = returns.tz_convert('UTC').tz_localize(None)
|
|
2825
|
+
|
|
2826
|
+
if prepare_returns:
|
|
2827
|
+
returns = _utils._prepare_returns(returns)
|
|
2828
|
+
|
|
2829
|
+
# Normalize benchmark timezone first if it's not a string
|
|
2830
|
+
if (
|
|
2831
|
+
benchmark is not None
|
|
2832
|
+
and not isinstance(benchmark, str)
|
|
2833
|
+
and hasattr(
|
|
2834
|
+
benchmark.index
|
|
2835
|
+
if isinstance(benchmark, _pd.Series)
|
|
2836
|
+
else benchmark[benchmark.columns[0]].index,
|
|
2837
|
+
"tz",
|
|
2838
|
+
)
|
|
2839
|
+
):
|
|
2840
|
+
if isinstance(benchmark, _pd.Series) and benchmark.index.tz is not None:
|
|
2841
|
+
benchmark = benchmark.tz_convert("UTC").tz_localize(None)
|
|
2842
|
+
elif (
|
|
2843
|
+
isinstance(benchmark, _pd.DataFrame)
|
|
2844
|
+
and benchmark[benchmark.columns[0]].index.tz is not None
|
|
2845
|
+
):
|
|
2846
|
+
for col in benchmark.columns:
|
|
2847
|
+
benchmark[col] = benchmark[col].tz_convert("UTC").tz_localize(None)
|
|
2848
|
+
|
|
2849
|
+
# Store original benchmark for proper aggregation
|
|
2850
|
+
# This preserves returns that may fall on non-trading days
|
|
2851
|
+
if isinstance(benchmark, str):
|
|
2852
|
+
benchmark_original = _utils.download_returns(benchmark)
|
|
2853
|
+
elif isinstance(benchmark, _pd.DataFrame):
|
|
2854
|
+
benchmark_original = benchmark[benchmark.columns[0]].copy()
|
|
2855
|
+
else:
|
|
2856
|
+
benchmark_original = benchmark.copy() if benchmark is not None else None
|
|
2857
|
+
|
|
2858
|
+
# Normalize timezone for benchmark_original as well (in case it was downloaded)
|
|
2859
|
+
if benchmark_original is not None and hasattr(benchmark_original.index, 'tz') and benchmark_original.index.tz is not None:
|
|
2860
|
+
benchmark_original = benchmark_original.tz_convert('UTC').tz_localize(None)
|
|
2861
|
+
|
|
2862
|
+
# Prepare benchmark to match returns index for other calculations
|
|
2863
|
+
benchmark = _utils._prepare_benchmark(benchmark, returns.index)
|
|
2864
|
+
|
|
2865
|
+
# Handle Series input
|
|
2866
|
+
if isinstance(returns, _pd.Series):
|
|
2867
|
+
# Aggregate returns and use original benchmark for aggregation
|
|
2868
|
+
# This ensures we don't lose benchmark returns on non-trading days
|
|
2869
|
+
if benchmark_original is not None:
|
|
2870
|
+
benchmark_agg = _utils.aggregate_returns(benchmark_original, aggregate, compounded) * 100
|
|
2871
|
+
else:
|
|
2872
|
+
benchmark_agg = _utils.aggregate_returns(benchmark, aggregate, compounded) * 100
|
|
2873
|
+
returns_agg = _utils.aggregate_returns(returns, aggregate, compounded) * 100
|
|
2874
|
+
|
|
2875
|
+
# Create comparison DataFrame
|
|
2876
|
+
data = _pd.DataFrame(
|
|
2877
|
+
data={
|
|
2878
|
+
"Benchmark": benchmark_agg,
|
|
2879
|
+
"Returns": returns_agg,
|
|
2880
|
+
}
|
|
2881
|
+
)
|
|
2882
|
+
|
|
2883
|
+
# Calculate performance multiplier and win/loss indicator
|
|
2884
|
+
# Protect against division by zero in benchmark
|
|
2885
|
+
data["Multiplier"] = data["Returns"] / data["Benchmark"].replace(0, _np.nan)
|
|
2886
|
+
data["Won"] = _np.where(data["Returns"] >= data["Benchmark"], "+", "-")
|
|
2887
|
+
|
|
2888
|
+
# Handle DataFrame input (multiple strategies)
|
|
2889
|
+
elif isinstance(returns, _pd.DataFrame):
|
|
2890
|
+
# Aggregate benchmark using original data to preserve non-trading day returns
|
|
2891
|
+
if benchmark_original is not None:
|
|
2892
|
+
bench = {
|
|
2893
|
+
"Benchmark": _utils.aggregate_returns(benchmark_original, aggregate, compounded) * 100
|
|
2894
|
+
}
|
|
2895
|
+
else:
|
|
2896
|
+
bench = {
|
|
2897
|
+
"Benchmark": _utils.aggregate_returns(benchmark, aggregate, compounded) * 100
|
|
2898
|
+
}
|
|
2899
|
+
|
|
2900
|
+
# Aggregate each strategy column
|
|
2901
|
+
strategy = {
|
|
2902
|
+
"Returns_" + str(i): _utils.aggregate_returns(returns[col], aggregate, compounded) * 100
|
|
2903
|
+
for i, col in enumerate(returns.columns)
|
|
2904
|
+
}
|
|
2905
|
+
|
|
2906
|
+
# Combine into single DataFrame
|
|
2907
|
+
data = _pd.DataFrame(data={**bench, **strategy})
|
|
2908
|
+
|
|
2909
|
+
# Apply rounding if specified
|
|
2910
|
+
if round_vals is not None:
|
|
2911
|
+
return _np.round(data, round_vals)
|
|
2912
|
+
|
|
2913
|
+
return data
|
|
2914
|
+
|
|
2915
|
+
|
|
2916
|
+
def monthly_returns(returns, eoy=True, compounded=True, prepare_returns=True):
|
|
2917
|
+
"""
|
|
2918
|
+
Calculate monthly returns in a pivot table format.
|
|
2919
|
+
|
|
2920
|
+
This function creates a matrix showing returns for each month across
|
|
2921
|
+
different years, making it easy to identify seasonal patterns and
|
|
2922
|
+
compare performance across time periods.
|
|
2923
|
+
|
|
2924
|
+
Args:
|
|
2925
|
+
returns (pd.Series or pd.DataFrame): Return series to analyze
|
|
2926
|
+
eoy (bool): Whether to include end-of-year totals (default: True)
|
|
2927
|
+
compounded (bool): Whether to compound returns (default: True)
|
|
2928
|
+
prepare_returns (bool): Whether to prepare returns first (default: True)
|
|
2929
|
+
|
|
2930
|
+
Returns:
|
|
2931
|
+
pd.DataFrame: Monthly returns matrix with years as rows and months
|
|
2932
|
+
as columns. If eoy=True, includes 'EOY' column with
|
|
2933
|
+
annual returns.
|
|
2934
|
+
|
|
2935
|
+
Example:
|
|
2936
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02],
|
|
2937
|
+
... index=pd.date_range('2023-01-01', periods=5, freq='M'))
|
|
2938
|
+
>>> monthly_rets = monthly_returns(returns)
|
|
2939
|
+
>>> print(monthly_rets)
|
|
2940
|
+
"""
|
|
2941
|
+
# Handle DataFrame input by selecting appropriate column
|
|
2942
|
+
if isinstance(returns, _pd.DataFrame):
|
|
2943
|
+
warn(
|
|
2944
|
+
"Pandas DataFrame was passed (Series expected). "
|
|
2945
|
+
"Only first column will be used.", stacklevel=2
|
|
2946
|
+
)
|
|
2947
|
+
returns = returns.copy()
|
|
2948
|
+
returns.columns = map(str.lower, returns.columns)
|
|
2949
|
+
if len(returns.columns) > 1 and "close" in returns.columns:
|
|
2950
|
+
returns = returns["close"]
|
|
2951
|
+
else:
|
|
2952
|
+
returns = returns[returns.columns[0]]
|
|
2953
|
+
|
|
2954
|
+
if prepare_returns:
|
|
2955
|
+
returns = _utils._prepare_returns(returns)
|
|
2956
|
+
|
|
2957
|
+
# Store original returns for end-of-year calculations
|
|
2958
|
+
original_returns = returns.copy()
|
|
2959
|
+
|
|
2960
|
+
# Group returns by month-year and aggregate
|
|
2961
|
+
returns = _pd.DataFrame(
|
|
2962
|
+
_utils.group_returns(returns, returns.index.strftime("%Y-%m-01"), compounded)
|
|
2963
|
+
)
|
|
2964
|
+
|
|
2965
|
+
# Set up DataFrame structure
|
|
2966
|
+
returns.columns = ["Returns"]
|
|
2967
|
+
returns.index = _pd.to_datetime(returns.index)
|
|
2968
|
+
|
|
2969
|
+
# Extract year and month for pivot table
|
|
2970
|
+
returns["Year"] = returns.index.strftime("%Y")
|
|
2971
|
+
returns["Month"] = returns.index.strftime("%b")
|
|
2972
|
+
|
|
2973
|
+
# Create pivot table with years as rows and months as columns
|
|
2974
|
+
returns = returns.pivot(index="Year", columns="Month", values="Returns").fillna(0)
|
|
2975
|
+
|
|
2976
|
+
# Ensure all months are present in the DataFrame
|
|
2977
|
+
for month in [
|
|
2978
|
+
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
|
|
2979
|
+
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
|
|
2980
|
+
]:
|
|
2981
|
+
if month not in returns.columns:
|
|
2982
|
+
returns.loc[:, month] = 0
|
|
2983
|
+
|
|
2984
|
+
# Order columns by calendar month
|
|
2985
|
+
returns = returns[
|
|
2986
|
+
[
|
|
2987
|
+
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
|
|
2988
|
+
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
|
|
2989
|
+
]
|
|
2990
|
+
]
|
|
2991
|
+
|
|
2992
|
+
# Add end-of-year totals if requested
|
|
2993
|
+
if eoy:
|
|
2994
|
+
returns["eoy"] = _utils.group_returns(
|
|
2995
|
+
original_returns, original_returns.index.year, compounded=compounded # type: ignore
|
|
2996
|
+
).values
|
|
2997
|
+
|
|
2998
|
+
# Format column names to uppercase
|
|
2999
|
+
returns.columns = map(lambda x: str(x).upper(), returns.columns) # type: ignore
|
|
3000
|
+
returns.index.name = None
|
|
3001
|
+
|
|
3002
|
+
return returns
|
|
3003
|
+
|
|
3004
|
+
|
|
3005
|
+
def drawdown_details(drawdown):
|
|
3006
|
+
"""
|
|
3007
|
+
Calculate detailed drawdown statistics for each drawdown period.
|
|
3008
|
+
|
|
3009
|
+
This function analyzes a drawdown series to provide comprehensive statistics
|
|
3010
|
+
for each individual drawdown period, including start/end dates, duration,
|
|
3011
|
+
maximum drawdown, and 99th percentile drawdown.
|
|
3012
|
+
|
|
3013
|
+
Args:
|
|
3014
|
+
drawdown (pd.Series or pd.DataFrame): Drawdown series to analyze
|
|
3015
|
+
|
|
3016
|
+
Returns:
|
|
3017
|
+
pd.DataFrame: Detailed drawdown statistics with columns:
|
|
3018
|
+
- start: Start date of drawdown period
|
|
3019
|
+
- valley: Date of maximum drawdown
|
|
3020
|
+
- end: End date of drawdown period
|
|
3021
|
+
- days: Duration in days
|
|
3022
|
+
- max drawdown: Maximum drawdown percentage
|
|
3023
|
+
- 99% max drawdown: 99th percentile drawdown (excludes outliers)
|
|
3024
|
+
|
|
3025
|
+
Example:
|
|
3026
|
+
>>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
|
|
3027
|
+
>>> dd_series = to_drawdown_series(returns)
|
|
3028
|
+
>>> dd_details = drawdown_details(dd_series)
|
|
3029
|
+
>>> print(dd_details)
|
|
3030
|
+
"""
|
|
3031
|
+
|
|
3032
|
+
def _drawdown_details(drawdown):
|
|
3033
|
+
"""
|
|
3034
|
+
Calculate drawdown details for a single drawdown series.
|
|
3035
|
+
|
|
3036
|
+
This internal function processes a single drawdown series to extract
|
|
3037
|
+
detailed statistics about each drawdown period.
|
|
3038
|
+
"""
|
|
3039
|
+
# Mark periods with no drawdown (drawdown = 0)
|
|
3040
|
+
no_dd = drawdown == 0
|
|
3041
|
+
|
|
3042
|
+
# Extract drawdown start dates (first date of each drawdown period)
|
|
3043
|
+
starts = ~no_dd & no_dd.shift(1)
|
|
3044
|
+
starts = list(starts[starts.values].index)
|
|
3045
|
+
|
|
3046
|
+
# Extract drawdown end dates (last date of each drawdown period)
|
|
3047
|
+
ends = no_dd & (~no_dd).shift(1)
|
|
3048
|
+
ends = ends.shift(-1, fill_value=False)
|
|
3049
|
+
ends = list(ends[ends.values].index)
|
|
3050
|
+
|
|
3051
|
+
# Return empty DataFrame if no drawdowns found
|
|
3052
|
+
if not starts:
|
|
3053
|
+
return _pd.DataFrame(
|
|
3054
|
+
index=[],
|
|
3055
|
+
columns=(
|
|
3056
|
+
"start",
|
|
3057
|
+
"valley",
|
|
3058
|
+
"end",
|
|
3059
|
+
"days",
|
|
3060
|
+
"max drawdown",
|
|
3061
|
+
"99% max drawdown",
|
|
3062
|
+
),
|
|
3063
|
+
)
|
|
3064
|
+
|
|
3065
|
+
# Handle edge case: drawdown series begins in a drawdown
|
|
3066
|
+
if ends and starts[0] > ends[0]:
|
|
3067
|
+
starts.insert(0, drawdown.index[0])
|
|
3068
|
+
|
|
3069
|
+
# Handle edge case: series ends in a drawdown
|
|
3070
|
+
if not ends or starts[-1] > ends[-1]:
|
|
3071
|
+
ends.append(drawdown.index[-1])
|
|
3072
|
+
|
|
3073
|
+
# Build detailed statistics for each drawdown period
|
|
3074
|
+
data = []
|
|
3075
|
+
for i, _ in enumerate(starts):
|
|
3076
|
+
# Extract drawdown for this period
|
|
3077
|
+
dd = drawdown[starts[i]:ends[i]]
|
|
3078
|
+
|
|
3079
|
+
# Calculate 99% drawdown (excluding outliers)
|
|
3080
|
+
clean_dd = -remove_outliers(-dd, 0.99)
|
|
3081
|
+
|
|
3082
|
+
# Compile statistics for this drawdown period
|
|
3083
|
+
data.append(
|
|
3084
|
+
(
|
|
3085
|
+
starts[i], # Start date
|
|
3086
|
+
dd.idxmin(), # Valley date (max drawdown)
|
|
3087
|
+
ends[i], # End date
|
|
3088
|
+
(ends[i] - starts[i]).days + 1, # Duration in days
|
|
3089
|
+
dd.min() * 100, # Max drawdown %
|
|
3090
|
+
clean_dd.min() * 100, # 99% max drawdown %
|
|
3091
|
+
)
|
|
3092
|
+
)
|
|
3093
|
+
|
|
3094
|
+
# Create DataFrame with results
|
|
3095
|
+
df = _pd.DataFrame(
|
|
3096
|
+
data=data,
|
|
3097
|
+
columns=(
|
|
3098
|
+
"start",
|
|
3099
|
+
"valley",
|
|
3100
|
+
"end",
|
|
3101
|
+
"days",
|
|
3102
|
+
"max drawdown",
|
|
3103
|
+
"99% max drawdown",
|
|
3104
|
+
),
|
|
3105
|
+
)
|
|
3106
|
+
|
|
3107
|
+
# Format data types
|
|
3108
|
+
df["days"] = df["days"].astype(int)
|
|
3109
|
+
df["max drawdown"] = df["max drawdown"].astype(float)
|
|
3110
|
+
df["99% max drawdown"] = df["99% max drawdown"].astype(float)
|
|
3111
|
+
|
|
3112
|
+
# Format dates as strings
|
|
3113
|
+
df["start"] = df["start"].dt.strftime("%Y-%m-%d")
|
|
3114
|
+
df["end"] = df["end"].dt.strftime("%Y-%m-%d")
|
|
3115
|
+
df["valley"] = df["valley"].dt.strftime("%Y-%m-%d")
|
|
3116
|
+
|
|
3117
|
+
return df
|
|
3118
|
+
|
|
3119
|
+
# Handle DataFrame input by processing each column separately
|
|
3120
|
+
if isinstance(drawdown, _pd.DataFrame):
|
|
3121
|
+
_dfs = {}
|
|
3122
|
+
for col in drawdown.columns:
|
|
3123
|
+
_dfs[col] = _drawdown_details(drawdown[col])
|
|
3124
|
+
return safe_concat(_dfs, axis=1)
|
|
3125
|
+
|
|
3126
|
+
return _drawdown_details(drawdown)
|
|
3127
|
+
|
|
3128
|
+
|
|
3129
|
+
# ======== MONTE CARLO ========
|
|
3130
|
+
|
|
3131
|
+
|
|
3132
|
+
def montecarlo(returns, sims=1000, bust=None, goal=None, seed=None):
|
|
3133
|
+
"""
|
|
3134
|
+
Run Monte Carlo simulation by shuffling returns.
|
|
3135
|
+
|
|
3136
|
+
This function creates multiple simulated return paths by randomly
|
|
3137
|
+
shuffling the historical returns. This preserves the return distribution
|
|
3138
|
+
while breaking any time-series dependencies, allowing probability-based
|
|
3139
|
+
risk assessment.
|
|
3140
|
+
|
|
3141
|
+
Args:
|
|
3142
|
+
returns (pd.Series or pd.DataFrame): Daily returns (not prices)
|
|
3143
|
+
sims (int): Number of simulations to run (default: 1000)
|
|
3144
|
+
bust (float, optional): Drawdown threshold for "bust" probability
|
|
3145
|
+
(e.g., -0.1 for -10% drawdown)
|
|
3146
|
+
goal (float, optional): Return threshold for "goal" probability
|
|
3147
|
+
(e.g., 1.0 for +100% return)
|
|
3148
|
+
seed (int, optional): Random seed for reproducibility
|
|
3149
|
+
|
|
3150
|
+
Returns:
|
|
3151
|
+
MonteCarloResult: Object containing simulation results with:
|
|
3152
|
+
- .data: DataFrame of all simulation paths
|
|
3153
|
+
- .stats: Terminal value statistics (min, max, mean, median, std)
|
|
3154
|
+
- .maxdd: Max drawdown statistics across simulations
|
|
3155
|
+
- .bust_probability: Probability of exceeding bust threshold
|
|
3156
|
+
- .goal_probability: Probability of reaching goal threshold
|
|
3157
|
+
- .plot(): Visualize simulation paths
|
|
3158
|
+
|
|
3159
|
+
Example:
|
|
3160
|
+
>>> import quantstats as qs
|
|
3161
|
+
>>> returns = qs.utils.download_returns("SPY")
|
|
3162
|
+
>>> mc = qs.stats.montecarlo(returns, sims=1000, bust=-0.2, goal=0.5)
|
|
3163
|
+
>>> print(mc.stats)
|
|
3164
|
+
>>> print(f"Bust probability: {mc.bust_probability:.1%}")
|
|
3165
|
+
>>> print(f"Goal probability: {mc.goal_probability:.1%}")
|
|
3166
|
+
>>> mc.plot()
|
|
3167
|
+
"""
|
|
3168
|
+
from ._montecarlo import run_montecarlo
|
|
3169
|
+
|
|
3170
|
+
# Validate and prepare returns
|
|
3171
|
+
validate_input(returns)
|
|
3172
|
+
returns = _utils._prepare_returns(returns)
|
|
3173
|
+
|
|
3174
|
+
# Handle DataFrame by processing first column (or extend for multi-column)
|
|
3175
|
+
if isinstance(returns, _pd.DataFrame):
|
|
3176
|
+
if returns.shape[1] == 1:
|
|
3177
|
+
returns = returns.iloc[:, 0]
|
|
3178
|
+
else:
|
|
3179
|
+
# For multi-column DataFrame, run on first column
|
|
3180
|
+
# Future: could return dict of MonteCarloResults
|
|
3181
|
+
returns = returns.iloc[:, 0]
|
|
3182
|
+
|
|
3183
|
+
return run_montecarlo(returns, sims=sims, bust=bust, goal=goal, seed=seed)
|
|
3184
|
+
|
|
3185
|
+
|
|
3186
|
+
def montecarlo_sharpe(returns, sims=1000, rf=0, periods=252, seed=None):
|
|
3187
|
+
"""
|
|
3188
|
+
Distribution of Sharpe ratios across Monte Carlo simulations.
|
|
3189
|
+
|
|
3190
|
+
This function runs Monte Carlo simulations and calculates the Sharpe
|
|
3191
|
+
ratio for each simulated path, providing a distribution of possible
|
|
3192
|
+
Sharpe ratio outcomes.
|
|
3193
|
+
|
|
3194
|
+
Args:
|
|
3195
|
+
returns (pd.Series): Daily returns
|
|
3196
|
+
sims (int): Number of simulations (default: 1000)
|
|
3197
|
+
rf (float): Risk-free rate (default: 0)
|
|
3198
|
+
periods (int): Periods per year for annualization (default: 252)
|
|
3199
|
+
seed (int, optional): Random seed for reproducibility
|
|
3200
|
+
|
|
3201
|
+
Returns:
|
|
3202
|
+
dict: Statistics of Sharpe ratio distribution including
|
|
3203
|
+
min, max, mean, median, std, percentile_5, percentile_95
|
|
3204
|
+
|
|
3205
|
+
Example:
|
|
3206
|
+
>>> sharpe_dist = qs.stats.montecarlo_sharpe(returns, sims=1000)
|
|
3207
|
+
>>> print(f"Expected Sharpe: {sharpe_dist['mean']:.2f}")
|
|
3208
|
+
>>> print(f"Sharpe range: {sharpe_dist['percentile_5']:.2f} to "
|
|
3209
|
+
... f"{sharpe_dist['percentile_95']:.2f}")
|
|
3210
|
+
"""
|
|
3211
|
+
from ._montecarlo import run_montecarlo
|
|
3212
|
+
|
|
3213
|
+
validate_input(returns)
|
|
3214
|
+
returns = _utils._prepare_returns(returns)
|
|
3215
|
+
|
|
3216
|
+
if isinstance(returns, _pd.DataFrame):
|
|
3217
|
+
returns = returns.iloc[:, 0]
|
|
3218
|
+
|
|
3219
|
+
mc = run_montecarlo(returns, sims=sims, seed=seed)
|
|
3220
|
+
|
|
3221
|
+
# Calculate Sharpe for each simulation path
|
|
3222
|
+
sharpe_values = []
|
|
3223
|
+
for col in mc.data.columns:
|
|
3224
|
+
# Convert cumulative returns back to simple returns
|
|
3225
|
+
cumret = mc.data[col] + 1
|
|
3226
|
+
sim_returns = cumret.pct_change().dropna()
|
|
3227
|
+
if len(sim_returns) > 0 and sim_returns.std() > 0:
|
|
3228
|
+
excess = sim_returns.mean() - rf / periods
|
|
3229
|
+
sharpe_val = excess / sim_returns.std() * _np.sqrt(periods)
|
|
3230
|
+
sharpe_values.append(sharpe_val)
|
|
3231
|
+
|
|
3232
|
+
sharpe_series = _pd.Series(sharpe_values)
|
|
3233
|
+
return {
|
|
3234
|
+
"min": sharpe_series.min(),
|
|
3235
|
+
"max": sharpe_series.max(),
|
|
3236
|
+
"mean": sharpe_series.mean(),
|
|
3237
|
+
"median": sharpe_series.median(),
|
|
3238
|
+
"std": sharpe_series.std(),
|
|
3239
|
+
"percentile_5": sharpe_series.quantile(0.05),
|
|
3240
|
+
"percentile_95": sharpe_series.quantile(0.95),
|
|
3241
|
+
}
|
|
3242
|
+
|
|
3243
|
+
|
|
3244
|
+
def montecarlo_drawdown(returns, sims=1000, seed=None):
|
|
3245
|
+
"""
|
|
3246
|
+
Distribution of maximum drawdowns across Monte Carlo simulations.
|
|
3247
|
+
|
|
3248
|
+
This function runs Monte Carlo simulations and returns statistics
|
|
3249
|
+
about the distribution of maximum drawdowns across all paths.
|
|
3250
|
+
|
|
3251
|
+
Args:
|
|
3252
|
+
returns (pd.Series): Daily returns
|
|
3253
|
+
sims (int): Number of simulations (default: 1000)
|
|
3254
|
+
seed (int, optional): Random seed for reproducibility
|
|
3255
|
+
|
|
3256
|
+
Returns:
|
|
3257
|
+
dict: Statistics of max drawdown distribution including
|
|
3258
|
+
min, max, mean, median, std, percentile_5, percentile_95
|
|
3259
|
+
|
|
3260
|
+
Example:
|
|
3261
|
+
>>> dd_dist = qs.stats.montecarlo_drawdown(returns, sims=1000)
|
|
3262
|
+
>>> print(f"Expected max drawdown: {dd_dist['mean']:.1%}")
|
|
3263
|
+
>>> print(f"Worst case (5th pct): {dd_dist['percentile_5']:.1%}")
|
|
3264
|
+
"""
|
|
3265
|
+
mc = montecarlo(returns, sims=sims, seed=seed)
|
|
3266
|
+
return mc.maxdd
|
|
3267
|
+
|
|
3268
|
+
|
|
3269
|
+
def montecarlo_cagr(returns, sims=1000, periods=252, seed=None):
|
|
3270
|
+
"""
|
|
3271
|
+
Distribution of CAGR across Monte Carlo simulations.
|
|
3272
|
+
|
|
3273
|
+
This function runs Monte Carlo simulations and calculates the
|
|
3274
|
+
Compound Annual Growth Rate for each simulated path.
|
|
3275
|
+
|
|
3276
|
+
Args:
|
|
3277
|
+
returns (pd.Series): Daily returns
|
|
3278
|
+
sims (int): Number of simulations (default: 1000)
|
|
3279
|
+
periods (int): Periods per year for annualization (default: 252)
|
|
3280
|
+
seed (int, optional): Random seed for reproducibility
|
|
3281
|
+
|
|
3282
|
+
Returns:
|
|
3283
|
+
dict: Statistics of CAGR distribution including
|
|
3284
|
+
min, max, mean, median, std, percentile_5, percentile_95
|
|
3285
|
+
|
|
3286
|
+
Example:
|
|
3287
|
+
>>> cagr_dist = qs.stats.montecarlo_cagr(returns, sims=1000)
|
|
3288
|
+
>>> print(f"Expected CAGR: {cagr_dist['mean']:.1%}")
|
|
3289
|
+
"""
|
|
3290
|
+
from ._montecarlo import run_montecarlo
|
|
3291
|
+
|
|
3292
|
+
validate_input(returns)
|
|
3293
|
+
returns = _utils._prepare_returns(returns)
|
|
3294
|
+
|
|
3295
|
+
if isinstance(returns, _pd.DataFrame):
|
|
3296
|
+
returns = returns.iloc[:, 0]
|
|
3297
|
+
|
|
3298
|
+
mc = run_montecarlo(returns, sims=sims, seed=seed)
|
|
3299
|
+
|
|
3300
|
+
# Calculate CAGR for each simulation path
|
|
3301
|
+
n_periods = len(mc.data)
|
|
3302
|
+
years = n_periods / periods
|
|
3303
|
+
|
|
3304
|
+
cagr_values = []
|
|
3305
|
+
for col in mc.data.columns:
|
|
3306
|
+
terminal = mc.data[col].iloc[-1]
|
|
3307
|
+
# CAGR = (1 + total_return)^(1/years) - 1
|
|
3308
|
+
if terminal > -1: # Avoid invalid values
|
|
3309
|
+
cagr_val = (1 + terminal) ** (1 / years) - 1
|
|
3310
|
+
cagr_values.append(cagr_val)
|
|
3311
|
+
|
|
3312
|
+
cagr_series = _pd.Series(cagr_values)
|
|
3313
|
+
return {
|
|
3314
|
+
"min": cagr_series.min(),
|
|
3315
|
+
"max": cagr_series.max(),
|
|
3316
|
+
"mean": cagr_series.mean(),
|
|
3317
|
+
"median": cagr_series.median(),
|
|
3318
|
+
"std": cagr_series.std(),
|
|
3319
|
+
"percentile_5": cagr_series.quantile(0.05),
|
|
3320
|
+
"percentile_95": cagr_series.quantile(0.95),
|
|
3321
|
+
}
|