您可以向 backtrader 策略添加参数吗?
Can you add parameters to backtrader strategy?
我正在使用 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 添加到 class 定义中,但它不起作用。
是的,您可以将参数动态传递给 backtrader 策略。必须修改策略class的__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)
我正在使用 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 添加到 class 定义中,但它不起作用。
是的,您可以将参数动态传递给 backtrader 策略。必须修改策略class的__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)