如何修复TypeError:*:'method'和'float'不支持的操作数类型

时间:2019-04-18 18:24:39

标签: python

尝试运行此代码时,我一直收到此错误。我不是计算机科学专业的学生,​​没有编码背景,但是我的教授认为,为我们提供一个需要高级编码知识的项目是一个好主意。我不知道该如何解决。

TypeError                                 Traceback (most recent call last)
<ipython-input-11-851da82dbe8c> in <module>()
     18   weights /= np.sum(weights)
     19   portfolio_return = np.sum(mean_returns * weights) * 252
---> 20   portfolio_std_dev = np.sqrt(np.dot(weights.T,np.dot(cov_matrix, weights))) * np.sqrt(252)
     21   results[0,i] = portfolio_return
     22   results[1,i] = portfolio_std_dev

TypeError: unsupported operand type(s) for *: 'method' and 'float'

编辑:这是更完整的代码:

import pandas_datareader.data as web 
import numpy as np 
import pandas as pd
import matplotlib.pyplot as plt 

stocks = ['AMZN','V','K','GOOG','MSFT','JPM','GS','C','AMD','LOW','VZ','GE',
         'FB','AXP','AAPL','TSLA','PSX','NFLX','DG','BABA']
num_stocks = len(stocks)
data = web.DataReader(stocks,data_source='yahoo',start='01/01/2010')['Adj Close']
data = data.pct_change()
mean_returns = data.mean()
cov_matrix = data.cov
num_portfolios = 25000
results = np.zeros((3+num_stocks,num_portfolios))

for i in range(num_portfolios):
  weights = np.array(np.random.random(num_stocks))
  weights /= np.sum(weights)
  portfolio_return = np.sum(mean_returns * weights) * 252
  portfolio_std_dev = np.sqrt(np.dot(weights.T,np.dot(cov_matrix, weights))) * np.sqrt(252)
  results[0,i] = portfolio_return
  results[1,i] = portfolio_std_dev
  results[2,i] = results[0,i] / results[1,i]
  results[3:,i] = weights     

0 个答案:

没有答案