From 6a41faf474350edf8165811b939d08967963747a Mon Sep 17 00:00:00 2001 From: Thomas Wiecki Date: Wed, 22 Oct 2014 09:22:43 +0200 Subject: [PATCH] MAINT: Make beta calculation robust to missing values. Risk calculations are robust to nans, except for beta which calls numpy with the complete list of algorithm_returns. If nans are present the result of covar will be nan. This is fixed by filtering out nans in algorithm_returns. --- zipline/finance/risk/cumulative.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/zipline/finance/risk/cumulative.py b/zipline/finance/risk/cumulative.py index 1d92afce..21269ef9 100644 --- a/zipline/finance/risk/cumulative.py +++ b/zipline/finance/risk/cumulative.py @@ -441,8 +441,13 @@ algorithm_returns ({algo_count}) in range {start} : {end} on {dt}" if len(self.annualized_mean_returns) < 2: return 0.0 - returns_matrix = np.vstack([self.algorithm_returns, - self.benchmark_returns]) + # Drop nans if there are gaps in the data + algorithm_returns = self.algorithm_returns.dropna() + benchmark_returns = \ + self.benchmark_returns.loc[algorithm_returns.index] + + returns_matrix = np.vstack([algorithm_returns, + benchmark_returns]) C = np.cov(returns_matrix, ddof=1) algorithm_covariance = C[0][1] benchmark_variance = C[1][1]