我正在尝试计算股票投资组合的标准差。但是,我在代码的最后一行收到以下错误
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))
答案 0 :(得分:0)
看起来您并不是从quandl(21而不是25)中得到所有股票,这就是为什么权重向量和协方差矩阵的维数不匹配的原因。 这样设置noa:
noa = len(returns_daily.columns)
您将得到结果