python - 修复 Python 中的 ValueError 以计算投资组合标准差
问题描述
我正在尝试计算股票投资组合的标准差。但是,我在最后一行代码中收到以下错误
ValueError: shapes (21,21) and (25,) not aligned: 21 (dim 1) != 25 (dim 0)
任何有关如何解决此错误的建议将不胜感激:)
import quandl
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#get adjusted closing prices of selected companies with Quandl
quandl.ApiConfig.api_key = 'ENTER KEY HERE'
stocks = ['KHC', 'HPE', 'AAPL', 'GOOG', 'MSFT', 'GE', 'WMT', 'KO',
'XOM', 'IBM', 'MO', 'JNJ', 'CVX', 'MRK', 'WFC', 'HD', 'ORCL',
'MMM', 'FB', 'F', 'T', 'BA', 'CSCO','HPQ', 'GILD']
#length of stocks
noa = len(stocks)
#obtain data from quandl
data = quandl.get_table('WIKI/PRICES', ticker = stocks,
qopts = { 'columns': ['date', 'ticker','adj_close']},
date = { 'gte': '1995-1-1', 'lte': '2010-12-31' }, paginate=True)
data.head()
#sort the adjusted closing prices by tickers
#reorganise data pulled by setting date as index with
#columns of tickers and their corresponding adjusted prices
table = data.pivot(index = 'date', columns='ticker')
table.head()
#calculate daily and annual returns of the stocks
returns_daily = np.log(table / table.shift(1))
#factor of 252 trading days to annualise
returns_annual = returns_daily.mean() * 252
#covariance of returns of the stock
cov = returns_daily.cov() * 252
#generates random numbers between 0 and 1 and then
#normalises the values such that the sum of all values equals 1
weights = np.random.random(noa)
weights /= np.sum(weights)
#expected portfolio return
returns = np.sum(returns_daily.mean()[:, None] * weights)
#expected portfolio standard deviation
np.dot(weights.T, np.dot(cov() * 252, weights))
解决方案
看起来您并非从 quandl 获得所有股票(21 而不是 25),这就是为什么权重向量和协方差矩阵的维度不匹配的原因。这样设置 noa :
noa = len(returns_daily.columns)
你会得到结果
推荐阅读
- python - 无法使用pyqt5显示秒表
- c# - 关注 CefSharp WPF 组件中错误处理方法的问题
- c# - 如何在本地机器上运行.net项目
- visual-studio - VS2019 Pre 和 Post 构建事件总是以代码 1 失败
- amazon-web-services - 通过 CloudFormation 部署 AWS UserPool 并更新属性
- jsonschema - 在 json 模式项中具有多个属性
- android - 旋转可绘制/渐变
- node.js - 需要帮助来确定问题
- embedded - Segger Embedded Studio 链接错误 STM32F7
- python - 无法查看 allauth 登录和注册页面