问题描述
嗨,我正在学习如何编写自动交易系统的代码,但在尝试使用 Scipy Optimize Brute 时遇到了一些问题
import pandas as pd
import numpy as np
from pandas_datareader import data as pdr
import yfinance as yf
yf.pdr_override()
from scipy.optimize import brute
data = pdr.get_data_yahoo("GOOG",interval = "5m",period = "1mo")
def run_strategy(boll):
close = data.drop(columns = ['Open','High','Low','Adj Close','Volume'],axis =1)
close["returns"] = np.log(close.div(close.shift(1)))
close.dropna(inplace =True)
close["SMA"] = close["Close"].rolling(boll[0]).mean()
close["Lower"] = close["SMA"] - close["Close"].rolling(boll[0]).std()*boll[1]
close["Upper"] = close["SMA"] + close["Close"].rolling(boll[0]).std()*boll[1]
data.dropna(inplace = True)
close["distance"] = close.Close - close.SMA
close["position"] = np.where(close.Close< close.Lower,1,np.nan)#over sold,go long
close["position"] = np.where(close.Close> close.Lower,-1,close["position"])#overbought,go short
#go neutral
close["position"] = np.where(close.distance* close.distance.shift(1) <0,close["position"])#crossing SMA,go neutral
close.position = close.position.ffill().fillna(0)
close.position.value_counts()
close["strategy"] = close.position.shift(1) * close["returns"]
close.dropna(inplace = True)
return close[["returns","strategy"]].sum().apply(np.exp)
brute(run_strategy,((20,100,1),(1,5,1)),finish = None)
我得到的错误是
Traceback (most recent call last):
File "<pyshell#24>",line 1,in <module>
brute(run_strategy,finish = None)
File "C:\Program Files\python39\lib\site-packages\scipy\optimize\optimize.py",line 3234,in brute
Jout = np.reshape(Jout,inpt_shape[1:])
File "<__array_function__ internals>",line 5,in reshape
File "C:\Users\TYS\AppData\Roaming\Python\python39\site-packages\numpy\core\fromnumeric.py",line 299,in reshape
return _wrapfunc(a,'reshape',newshape,order=order)
File "C:\Users\TYS\AppData\Roaming\Python\python39\site-packages\numpy\core\fromnumeric.py",line 58,in _wrapfunc
return bound(*args,**kwds)
ValueError: cannot reshape array of size 640 into shape (80,4)
任何关于如何使用 scipy.optimize brute 的帮助都会很棒
我使用的是 Python 3.9、Windows 10 和 Scipy 1.5.4
我已经用 brute 测试了一些基本的代码示例,它似乎有效,所以不确定为什么在这种情况下它不起作用。
谢谢
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)