未指定位置时如何查找TypeError?

问题描述

我正在测试我发现的一些代码片段,但无法识别错误

代码

import datetime as dt
from datetime import date
import pandas as pd
import pandas_datareader.data as web
import numpy as np
import time
import math
import scipy.optimize as optimize


start = dt.datetime(2016,12,1)
end = dt.datetime(2020,1)


tick = ['GOOG','AAPL','AMZN']


#pandas dataframe
data = web.DataReader(tick,'yahoo',start,end)['Adj Close']
data = np.log(data/data.shift(1))


def sharpetest(wts,returns):
  weights = np.array(wts)
  port_return = np.sum(returns.mean() * weights) * 252
  port_vol = np.sqrt(np.dot(weights.T,np.dot(returns.cov() * 252,weights)))
  sharpe = port_return/port_vol
  sharpe = np.array(sharpe)
  return sharpe
  

num_assets = len(tick)

constraints = ({'type' : 'eq','fun': lambda x: np.sum(x) -1})
bounds = tuple((0,1) for x in range(num_assets))
args = (num_assets * [1./num_assets,],data)


optimal_sharpe=optimize.minimize(sharpetest,args,method = 'SLSQP',bounds = bounds,constraints = constraints)
print(optimal_sharpe)

输出

   /usr/local/lib/python3.9/site-packages/numpy/core/_asarray.py:83:
   VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list- 
   or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If 
   you meant to do this,you must specify 'dtype=object' when creating the ndarray
   return array(a,dtype,copy=False,order=order)
   TypeError: float() argument must be a string or a number,not 'list'

如您所见,未指定 TypeError 的行。我如何找到错误

我很抱歉问这样一个基本的问题。

解决方法

类型错误来自函数 sharpetest 的应用程序。它来自将权重与数据相结合。以下是如何更正代码的示例。

constraints = ({'type' : 'eq','fun': lambda x: np.sum(x) -1})
bounds = tuple((0,1) for x in range(num_assets))
x0 = num_assets * [1./num_assets,]
args =  (data)

print(sharpetest(num_assets * [1./num_assets,],data))

optimal_sharpe=optimize.minimize(sharpetest,x0,args,method = 'SLSQP',bounds = bounds,constraints = constraints)
print(optimal_sharpe)

您可以看到 x0 被分解为它自己的参数,然后附加数据(股票的回报)作为参数传入。你有一个非常有趣的例子!

我得到的输出是

     fun: array(0.79108107)
     jac: array([-7.45058060e-09,7.86704488e-01,7.25132324e-01])
 message: 'Optimization terminated successfully'
    nfev: 12
     nit: 3
    njev: 3
  status: 0
 success: True
       x: array([1.00000000e+00,1.38777878e-16,0.00000000e+00])