There's more...

It is worth mentioning that backtrader has parameter optimization capabilities, which we present in the code that follows. The code is a modified version of the strategy from this recipe, in which we optimize the number of days in the SMA.

The following list provides details of modifications to the code (we only show the relevant ones, as the bulk of the code is identical to that using bt.Strategy):

  • We add an extra attribute called stop to the class definition—it returns the Terminal portfolio value for each parameter:
def stop(self):
self.log(f'(ma_period = {self.params.ma_period:2d}) --- Terminal Value: {self.broker.getvalue():.2f}')
  • Instead of using cerebro.addstrategy(), we use cerebro.optstrategy(), and provide the strategy name and parameter values:
cerebro.optstrategy(SmaStrategy, ma_period=range(10, 31))
  • We increase the number of CPU cores when running the backtesting: cerebro.run(maxcpus=4)

We present the results in the following summary (the order of parameters is not preserved, as the testing was carried out on four cores):

We see that the strategy performed best for ma_period = 22.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.86.121