你能给backtrader策略添加参数吗?



我正在使用backtrader库。

class MA_CrossOver(bt.Strategy):
alias = ('SMA_CrossOver',)
params = (
# period for the fast Moving Average
('fast', 10),
# period for the slow moving average
('slow', 30),
# moving average to use
('_movav', btind.MovAv.SMA)
)
def __init__(self):
sma_fast = self.p._movav(period=self.p.fast)
sma_slow = self.p._movav(period=self.p.slow)
self.buysig = btind.CrossOver(sma_fast, sma_slow)
def next(self):
if self.position.size:
if self.buysig < 0:
self.sell()
elif self.buysig > 0:
self.buy()

我想动态调整快慢参数。我试着在类定义中添加**kwargs,但它不起作用。

是的,您可以动态地将参数传递给backtrader策略。您必须修改策略类的__init__函数以获得在对象创建过程中传入的参数。下面是一个例子:

class MA_CrossOver(bt.Strategy):
alias = ('SMA_CrossOver',)
params = (
# period for the fast Moving Average
('fast', 10),
# period for the slow moving average
('slow', 30),
# moving average to use
('_movav', btind.MovAv.SMA)
)
def __init__(self, params=None):
if params != None:
for name, val in params.items():
setattr(self.params, name, val)
sma_fast = self.p._movav(period=self.p.fast)
sma_slow = self.p._movav(period=self.p.slow)
self.buysig = btind.CrossOver(sma_fast, sma_slow)
def next(self):
if self.position.size:
if self.buysig < 0:
self.sell()
elif self.buysig > 0:
self.buy()

将策略添加到backtrader cerebro时,可以传入一个参数字典。

strat_params = {'fast': 9, 'slow': 20}
cerebro.addstrategy(MA_CrossOver, strat_params)

相关内容

  • 没有找到相关文章

最新更新