1

I am using the backtrader library.

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()

I want dynamically adjust the fast and slow parameters. I tried adding **kwargs to class definition, but it doesn't work.

Borut Flis
  • 15,715
  • 30
  • 92
  • 119

1 Answers1

1

Yes, you can pass the parameters to backtrader strategy dynamically. You have to modify the __init__ function of the strategy class to get the parameters passed in during object creation. Here's an example:

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()

While adding the strategy to backtrader cerebro, you can pass in a dictionary of parameters.

strat_params = {'fast': 9, 'slow': 20}
cerebro.addstrategy(MA_CrossOver, strat_params)
krskara
  • 162
  • 1
  • 8
  • Thanks. I was making a mistake including **kwargs in the class definition, while I should have added it to __init__, basically I didn't know Python classes well enough – Borut Flis Jun 03 '22 at 09:54