How to get an inverted covariance matrix from a dataframe on a rolling basis

Viewed 191

I have a DataFrame of ten different portfolio returns an 12904 days. I am trying to get the rolling inverted covariance matrix for each date. I get the covariance matrix with the .rolling() function. Taking the inverse of that unfortunately yields an error. Any help is greatly appreciated!

The DataFrame excess_return (12904 rows × 10 columns):

             NoDur  Durbl   Manuf   Enrgy   HiTec   Telcm   Shops   Hlth    Utils   Other
Date                                        
1970-01-02   0.0074 0.0188  0.0111  0.0175  0.0069  0.0162  0.0041  -0.0035 0.0159  0.0175
1970-01-05   0.0058 -0.0023 0.0049  0.0099  0.0066  0.0237  -0.0026 -0.0019 0.0122  0.0052
1970-01-06  -0.0032 -0.0135 -0.0085 -0.0107 -0.0050 -0.0002 0.0015  -0.0047 -0.0105 -0.0111
1970-01-07   0.0012 -0.0047 -0.0004 -0.0080 -0.0000 -0.0015 0.0042  0.0007  -0.0038 -0.0012
1970-01-08  -0.0024 -0.0035 0.0021  -0.0034 0.00255 -0.0057 0.0007  0.0062  0.0015  0.0011 

The code I tried:

rolling_cov_inv = np.linalg.inv(excess_return.rolling(750).cov().shift())

The error I received:

LinAlgError: Last 2 dimensions of the array must be square

I also tried:

rolling_cov_inv = excess_return.rolling(750).np.linalg.inv(cov()).shift())

The error message here:

'Rolling' object has no attribute 'np'

The expected output is a 10x10 matrix for every single day.

Many thanks in advance!

1 Answers

I think you are almost there. The following code returns a series where each date corresponds to the covariance matrix over a 750 observations period:

excess_return.rolling(750).cov().groupby('Date').apply(lambda g: pd.DataFrame(np.linalg.inv(g.values), index=g.index, columns=g.columns))
Related