From 9d71936f50ce54e8c68f3fb1a08288643e093acc Mon Sep 17 00:00:00 2001 From: Alexander Condello Date: Tue, 27 Jun 2023 10:08:14 -0700 Subject: [PATCH] Fix covariance calculation to not generate NaNs --- single_period.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/single_period.py b/single_period.py index 491fe06..c2317c9 100644 --- a/single_period.py +++ b/single_period.py @@ -189,7 +189,10 @@ def load_data(self, file_path='', dates=None, df=None, num=0): self.price = self.df.iloc[-1] self.monthly_returns = self.df[list(self.stocks)].pct_change().iloc[1:] self.avg_monthly_returns = self.monthly_returns.mean(axis=0) - self.covariance_matrix = self.monthly_returns.cov() + self.covariance_matrix = covariance_matrix = self.monthly_returns.cov() + + # convert any NaNs in the covariance matrix to 0s + covariance_matrix.replace(np.nan, 0) def build_cqm(self, max_risk=None, min_return=None, init_holdings=None): """Build and store a CQM.