如何在Python中计算资产的风险贡献

时间:2019-11-21 21:46:37

标签: python pandas numpy

我正在尝试编写代码块,以使我能够确定投资组合中资产的风险贡献。协方差矩阵是一个6x6的熊猫数据框。

我的代码如下:

"cmd.exe /c start excel \"C:/Users/<username>/<filepath info>/TEST.xlsm\""

当我尝试运行代码时,出现KeyError,并且如果我从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) 中删除了[0,0],则会得到似乎没有意义的输出。

有人可以指出我的错误吗?

2 个答案:

答案 0 :(得分:2)

您的代码存在三个问题:

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

答案 1 :(得分:1)

portfolio_variance =(weights*covariance*weights.T)

portfolio_variance 应该是

portfolio_variance =(weights@covariance@weights.T) 

这将提供投资组合方差,它应该是一个数字。

对于边际风险来说,应该是

marginal_risk = covariance@weights.T