【问题标题】:Portfolio Variance of a Portfolio of N Assets in PythonPython中N资产投资组合的投资组合方差
【发布时间】:2011-11-16 13:40:59
【问题描述】:

投资组合方差计算如下:

port_var = W'_p * S * W_p

对于具有 N 资产的投资组合,其中

W'_p = transpose of vector of weights of stocks in portfolios
S = sample covariance matrix
W_p = vector of weights of stocks in portfolios

我有以下 numpy 矩阵。

投资组合中股票权重的数组(向量)(共有 10 只股票):

weights = np.array(
     [[ 0.09],
      [ 0.05],
      [ 0.15],
      [ 0.10],
      [ 0.15],
      [ 0.15],
      [ 0.08],
      [ 0.08],
      [ 0.1 ],
      [ 0.05]])

股票收益的协方差矩阵:

covar = np.array([[ 0.00154474  0.00079555  0.00099691  0.00052596  0.0005363   0.00062005
0.00064031  0.00037494  0.00018826  0.00132809],
[ 0.00079555  0.00287429  0.00058536  0.00091774  0.00046885  0.00110434
0.00137141  0.00046724  0.00030414  0.0016615 ],
[ 0.00099691  0.00058536  0.00155757  0.00056336  0.00052395  0.00060104
0.00057223  0.00021365  0.00017057  0.00130247],
[ 0.00052596  0.00091774  0.00056336  0.00126312  0.00031941  0.00088137
0.00024493  0.00025136  0.00011519  0.00135475],
[ 0.0005363   0.00046885  0.00052395  0.00031941  0.00054093  0.00045649
0.00042927  0.00021928  0.00016835  0.00093471],
[ 0.00062005  0.00110434  0.00060104  0.00088137  0.00045649  0.00133081
0.00060353  0.0003967   0.00024983  0.00168281],
[ 0.00064031  0.00137141  0.00057223  0.00024493  0.00042927  0.00060353
0.00468731  0.00059557  0.00020384  0.00078669],
[ 0.00037494  0.00046724  0.00021365  0.00025136  0.00021928  0.0003967
0.00059557  0.00082333  0.00017191  0.00066816],
[ 0.00018826  0.00030414  0.00017057  0.00011519  0.00016835  0.00024983
0.00020384  0.00017191  0.00036348  0.0004505 ],
[ 0.00132809  0.0016615   0.00130247  0.00135475  0.00093471  0.00168281
0.00078669  0.00066816  0.0004505   0.00530036]])

当我计算时

weights.T * covar * weights

结果是一个与 covar 大小相同的数组。我是投资组合理论的新手,但我认为投资组合的方差应该是一个标量(单值)。

有没有人有这方面的经验可能会有所帮助?

【问题讨论】:

    标签: python arrays numpy portfolio variance


    【解决方案1】:
    np.dot(weights.T,np.dot(covar,weights))
    # array([[ 0.00064654]])
    

    对于二维 numpy 数组,np.dot 等价于矩阵乘法。

    对于 2D 数组 np.dotted 与 1D 数组,np.dot 等价于矩阵向量乘法。

    对于一维数组,np.dot 等价于内积。

    对于 numpy 数组,* 执行逐元素乘法(必要时使用 broadcasting)。


    weights.T*np.matrix(covar)*weights
    #matrix([[ 0.00064654]])
    

    或者,如果您将covar 转换为np.matrix,则* 等效于矩阵乘法。

    【讨论】:

    • @strimp099 - 作为旁注,使用较新版本的 numpy(>= 1.5,我认为?)dot 也是一种 ndarray 方法。也就是说,你可以把unutbu的例子中的第一个例子写成weights.T.dot(covar.dot(weights))。对于某些事情,这种风格更简洁一些,尽管向后兼容的程度稍差。
    猜你喜欢
    • 2017-12-04
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-26
    • 1970-01-01
    • 2021-04-22
    • 1970-01-01
    相关资源
    最近更新 更多