【问题标题】:ValueError: setting an array element with a sequence. cant be solvedValueError:使用序列设置数组元素。无法解决
【发布时间】:2021-01-28 15:58:35
【问题描述】:
import pandas as pd
import numpy as np
import yfinance as yf
import matplotlib.pyplot as plt
from scipy.optimize import brute

class contrarian_strategy():
    def __init__(self,ticker):
        self.ticker=ticker
        self.get_data()
        #self.test_strategy()
    def get_data(self):
        data=yf.download(self.ticker)["Close"].to_frame()
        data["returns"]=np.log(data.Close.div(data.Close.shift(1)))
        self.data=data
        return data
    def test_strategy(self,window):
        self.window=window
        self.data["positions"]= -np.sign(self.data["returns"].rolling(int(window)).mean())
        self.data["strategy"]= self.data["positions"]*self.data["returns"]
        self.data["creturns"]=self.data["returns"].cumsum().apply(np.exp)
        self.data["cstrategy"]=self.data["strategy"].cumsum().apply(np.exp)
        self.results=self.data
        #absolute strategy performance
        perf_strat=self.data["cstrategy"].iloc[-1]
        #buy and hold absolute performance
        perf_buy_and_hold=self.data["creturns"].iloc[-1]
        return perf_strat,perf_buy_and_hold
    def plot_returns(self):
        title="{}".format(self.ticker)
        
        return self.results.plot(figsize=(15,15),title=title)
        
        plt.show()
    def optimize_results(self,windowrange):#,windowrangehigh,step):
        opt=brute(self.test_strategy,[windowrange])#,windowrangehigh,step))
        return opt

我应该使用 scipy 最小化而不是 brute,因为我只想优化窗口参数???:-如果是,你能展示一下吗? 如果你知道,请帮帮我 当我通过 tsla.optimize_results((10,50,1)) 方法运行此代码时,我得到:-

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
TypeError: float() argument must be a string or a number, not 'tuple'

The above exception was the direct cause of the following exception:

ValueError                                Traceback (most recent call last)
<ipython-input-99-31e36e1901a4> in <module>
----> 1 aapl.optimize_results((10,50,1))

<ipython-input-97-b3ff81b5303c> in optimize_results(self, windowrange)
     34         plt.show()
     35     def optimize_results(self,windowrange):#,windowrangehigh,step):
---> 36         opt=brute(self.test_strategy,[windowrange])#,windowrangehigh,step))
     37         return opt

~\anaconda3\lib\site-packages\scipy\optimize\optimize.py in brute(func, ranges, args, Ns, full_output, finish, disp, workers)
   3266 
   3267         # run minimizer
-> 3268         res = finish(func, xmin, args=args, **finish_kwargs)
   3269 
   3270         if isinstance(res, OptimizeResult):

~\anaconda3\lib\site-packages\scipy\optimize\optimize.py in fmin(func, x0, args, xtol, ftol, maxiter, maxfun, full_output, disp, retall, callback, initial_simplex)
    541             'initial_simplex': initial_simplex}
    542 
--> 543     res = _minimize_neldermead(func, x0, args, callback=callback, **opts)
    544     if full_output:
    545         retlist = res['x'], res['fun'], res['nit'], res['nfev'], res['status']

~\anaconda3\lib\site-packages\scipy\optimize\optimize.py in _minimize_neldermead(func, x0, args, callback, maxiter, maxfev, disp, return_all, initial_simplex, xatol, fatol, adaptive, **unknown_options)
    687 
    688     for k in range(N + 1):
--> 689         fsim[k] = func(sim[k])
    690 
    691     ind = np.argsort(fsim)

ValueError: setting an array element with a sequence.

我应该使用 scipy 最小化而不是 brute,因为我只想优化窗口参数???:-如果是,你能展示一下吗? 如果你知道的话请帮帮我

【问题讨论】:

    标签: python numpy scipy


    【解决方案1】:

    我没有使用过brute,甚至没有看过它的文档,但我怀疑问题在于你的函数的返回

    self.test_strategy
    ...
    return perf_strat,perf_buy_and_hold
    

    这是一个元组。 brute 需要什么?看起来它需要一个浮点数。

    fsim[k] = func(sim[k])
    

    在随机尝试其他优化功能之前,请确保您了解该功能需要什么。这意味着阅读和必要的重读文档。确保您理解示例(如果有)。您不能作弊 - 优化器将以非常特定的方式调用您的函数,并期望返回特定类型的 - 例如标量,或者可能是与输入形状匹配的数组。

    【讨论】:

      猜你喜欢
      • 2018-06-26
      • 2011-06-08
      • 2018-08-04
      • 2019-08-04
      相关资源
      最近更新 更多