【发布时间】: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,因为我只想优化窗口参数???:-如果是,你能展示一下吗? 如果你知道的话请帮帮我
【问题讨论】: