python - 未指定位置时如何查找 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,12,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])
推荐阅读
- android - Jetpack Compose 滚动 LazyColumn with CoroutineScope 结果错误 A MonotonicFrameClock 在此 CoroutineContext 中不可用
- javascript - 准备文件时禁用按钮 - Jquery
- django - 如何在 django 模型中将字符串添加到主键
- flutter - 如何将所选滤波器芯片的数据传递到 Flutter 中的其他页面
- google-apps-script - 使用位于子文件夹中的文件调用谷歌应用脚本 htmlservice.createTemplateFromFile(file)
- c# - 使用 C# 从 AWS 检索机密,而不在代码库中存储访问凭证
- powerbi - Azure Percept 通过 PowerQuery 日历将分析流式传输到 PowerBI DirectQuery 连接
- python - 具有容量限制的 OR-Tools 作业车间
- powershell - 通过 powershell 为电子邮件添加敏感度标签
- excel - 跨不同的 VBAProjects 调用 VBA UDF