如何滚动地从数据框中获取逆协方差矩阵 [英] How to get an inverted covariance matrix from a dataframe on a rolling basis

查看:83
本文介绍了如何滚动地从数据框中获取逆协方差矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有十个不同的投资组合的DataFrame返回12904天.我正在尝试获取每个日期的滚动倒排协方差矩阵.我用.rolling()函数得到协方差矩阵.不幸的是,采用相反的方法会产生错误.任何帮助,我们将不胜感激!

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!

DataFrame extra_return(12904行×10列):

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 

我尝试的代码:

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

我收到的错误:

LinAlgError: Last 2 dimensions of the array must be square

我也尝试过:

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

错误消息在这里:

'Rolling' object has no attribute 'np'

每天的预期输出是10x10的矩阵.

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

非常感谢!

推荐答案

我认为您快到了.以下代码返回一个序列,其中每个日期对应于750个观察周期内的协方差矩阵:

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))

这篇关于如何滚动地从数据框中获取逆协方差矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆