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

你会得到结果

最新更新