如何解决未指定位置时如何查找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])
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。