我正在尝试编写代码块,以使我能够确定投资组合中资产的风险贡献。协方差矩阵是一个6x6的熊猫数据帧。
我的代码如下:
import numpy as np
import pandas as pd
weights = np.array([.1,.2,.05,.25,.1,.3])
data = pd.DataFrame(np.random.randn(1000,6),columns = 'a','b','c','d','e','f'])
covariance = data.cov()
portfolio_variance = (weights*covariance*weights.T)[0,0]
sigma = np.sqrt(portfolio_variance)
marginal_risk = covariance*weights.T
risk_contribution = np.multiply(marginal_risk, weights.T)/sigma
print(risk_contribution)
当我尝试运行代码时,出现KeyError,并且如果从
[0,0]
中删除portfolio_variance
,则会得到似乎没有意义的输出。有人可以指出我的错误吗?
最佳答案
您的代码存在三个问题:
在第6行上打开列表运算符方括号:
data = pd.DataFrame(np.random.randn(1000,6),columns = ['a','b','c','d','e','f'])
您正在使用二维索引运算符错误。您不能说
[0,0]
,而必须说[0][0]
。最后,由于为列命名,因此在索引时必须使用它们,因此实际上是
['a'][0]
:portfolio_variance = (weights*covariance*weights.T)['a'][0]
最终的工作代码:
import numpy as np
import pandas as pd
weights = np.array([.1,.2,.05,.25,.1,.3])
data = pd.DataFrame(np.random.randn(1000,6),columns = ['a','b','c','d','e','f'])
covariance = data.cov()
portfolio_variance = (weights*covariance*weights.T)['a'][0]
sigma = np.sqrt(portfolio_variance)
marginal_risk = covariance*weights.T
risk_contribution = np.multiply(marginal_risk, weights.T)/sigma
print(risk_contribution)