Skip to content

Commit 84e685a

Browse files
authored
BUG: Fix RuntimeWarning on dummy compute_stats call (#1253)
Fixes #1251: covariance calculation for insufficient data points
1 parent b1a869c commit 84e685a

File tree

1 file changed

+5
-2
lines changed

1 file changed

+5
-2
lines changed

backtesting/_stats.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -154,8 +154,11 @@ def _round_timedelta(value, _period=_data_period(index)):
154154
s.loc['Calmar Ratio'] = annualized_return / (-max_dd or np.nan)
155155
equity_log_returns = np.log(equity[1:] / equity[:-1])
156156
market_log_returns = np.log(c[1:] / c[:-1])
157-
cov_matrix = np.cov(equity_log_returns, market_log_returns)
158-
beta = cov_matrix[0, 1] / cov_matrix[1, 1]
157+
beta = np.nan
158+
if len(equity_log_returns) > 1 and len(market_log_returns) > 1:
159+
# len == 0 on dummy call `stats_keys = compute_stats(...)` pre optimization
160+
cov_matrix = np.cov(equity_log_returns, market_log_returns)
161+
beta = cov_matrix[0, 1] / cov_matrix[1, 1]
159162
# Jensen CAPM Alpha: can be strongly positive when beta is negative and B&H Return is large
160163
s.loc['Alpha [%]'] = s.loc['Return [%]'] - risk_free_rate * 100 - beta * (s.loc['Buy & Hold Return [%]'] - risk_free_rate * 100) # noqa: E501
161164
s.loc['Beta'] = beta

0 commit comments

Comments
 (0)