For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See:

Attempting to create Bollinger Band indicator from scratch, am I missing studies? (SMA, StdDev)

  • from future import (absolute_import, division, print_function,

    import datetime # For datetime objects
    import os.path # To manage paths
    import sys # To find out the script name (in argv[0])

    Import the backtrader platform

    import backtrader as bt
    class BollingerBand(bt.Strategy):

    params = (('period', 5),
        ('devfactor', 3.0),)
    def __init__(self):
        self.period = self.params.period
        self.devfactor = self.params.devfactor
        self.close = self.datas[0].close
        self.midband = bt.indicators.SimpleMovingAverage(self.close,self.period)
        self.topband = self.midband + self.devfactor*StandardDeviation(data,period)
        self.botband = self.midband - self.devfactor*StandardDeviation(data,period)
    def next(self):
        self.log('Close, %.2f' % self.close[0])
        if self.order:
        if not self.position:
            if self.close[0] > self.topband:
                self.log('Short/Sale, %.2f' % self.close)
                self.order = self.sell()
            if self.close[0] < self.botband:
                self.log('Buy, %.2f' % self.close)
                self.order =

    if name == 'main':
    cerebro = bt.Cerebro()
    modpath = os.path.dirname(os.path.abspath(sys.argv[0]))
    datapath = os.path.join(modpath, 'RICK.csv')
    data = bt.feeds.YahooFinanceCSVData(
    # Do not pass values before this date
    fromdate=datetime.datetime(2019, 11, 13),
    # Do not pass values before this date
    todate=datetime.datetime(2020, 11, 13),
    # Do not pass values after this date
    cerebro.addsizer(bt.sizers.FixedSize, stake =10)
    print('Starting Portfolio Value: %.2f' %
    print('Final Portfolio Value: %.2f' %

  • There is alread a built in Bollinger Bands. If you feel the need to recreate it, you should extend the class bt.Indicators not bt.Strategy. Then instantiate the indicator in your strategy.

    If developing bespoke you might consider looking at the Bollinger Band code ( in the indicators class in backtrader to see the original code.

  • @run-out Thank you, I tried to delete this post but couldn't find the option.

  • @earlcharles1 Yes all of our thoughts are recorded forever here. :)

Log in to reply