How to do it...

Execute the following steps to backtest a strategy based on the Bollinger Bands.

  1. Import the libraries:
import backtrader as btimport datetimeimport pandas as pd
  1. The template of the strategy is presented:
class BBand_Strategy(bt.Strategy):    params = (('period', 20),               ('devfactor', 2.0),)    def __init__(self):        # some code            def log(self, txt):        # some code    def notify_order(self, order):        # some code    def notify_trade(self, trade):        # some code    def next_open(self):        # some code

The __init__ block is defined as:

    def __init__(self):
        # keep track of close price in the series
        self.data_close = self.datas[0].close
        self.data_open = self.datas[0].open

        # keep track of pending orders/buy price/buy commission
        self.order = None
        self.price

Get Python for Finance Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.