Supported Indicators

Bollinger Bands

Introduction

This indicator creates a moving average (middle band) with an upper band and lower band fixed at k standard deviations above and below the moving average.

To view the implementation of this indicator, see the LEAN GitHub repository.

Using BB Indicator

To create an automatic indicator for BollingerBands, call the BBbb helper method from the QCAlgorithm class. The BBbb method creates a BollingerBands object, hooks it up for automatic updates, and returns it so you can used it in your algorithm. In most cases, you should call the helper method in the Initializeinitialize method.

public class BollingerBandsAlgorithm : QCAlgorithm
{
    private Symbol _symbol;
    private BollingerBands _bb;

    public override void Initialize()
    {
        _symbol = AddEquity("SPY", Resolution.Daily).Symbol;
        _bb = BB(_symbol, 30, 2m);
    }

    public override void OnData(Slice data)
    {

        if (_bb.IsReady)
        {
            // The current value of _bb is represented by itself (_bb)
            // or _bb.Current.Value
            Plot("BollingerBands", "bb", _bb);
            // Plot all properties of abands
            Plot("BollingerBands", "standarddeviation", _bb.StandardDeviation);
            Plot("BollingerBands", "middleband", _bb.MiddleBand);
            Plot("BollingerBands", "upperband", _bb.UpperBand);
            Plot("BollingerBands", "lowerband", _bb.LowerBand);
            Plot("BollingerBands", "bandwidth", _bb.BandWidth);
            Plot("BollingerBands", "percentb", _bb.PercentB);
            Plot("BollingerBands", "price", _bb.Price);
        }
    }
}
class BollingerBandsAlgorithm(QCAlgorithm):
    def initialize(self) -> None:
        self._symbol = self.add_equity("SPY", Resolution.DAILY).symbol
        self._bb = self.bb(self._symbol, 30, 2)

    def on_data(self, slice: Slice) -> None:

        if self._bb.is_ready:
            # The current value of self._bb is represented by self._bb.current.value
            self.plot("BollingerBands", "bb", self._bb.current.value)
            # Plot all attributes of self._bb
            self.plot("BollingerBands", "standard_deviation", self._bb.standard_deviation.current.value)
            self.plot("BollingerBands", "middle_band", self._bb.middle_band.current.value)
            self.plot("BollingerBands", "upper_band", self._bb.upper_band.current.value)
            self.plot("BollingerBands", "lower_band", self._bb.lower_band.current.value)
            self.plot("BollingerBands", "band_width", self._bb.band_width.current.value)
            self.plot("BollingerBands", "percent_b", self._bb.percent_b.current.value)
            self.plot("BollingerBands", "price", self._bb.price.current.value)

For more information about this method, see the QCAlgorithm classQCAlgorithm class.

You can manually create a BollingerBands indicator, so it doesn't automatically update. Manual indicators let you update their values with any data you choose.

Updating your indicator manually enables you to control when the indicator is updated and what data you use to update it. To manually update the indicator, call the Updateupdate method. The indicator will only be ready after you prime it with enough data.

public class BollingerBandsAlgorithm : QCAlgorithm
{
    private Symbol _symbol;
    private BollingerBands _bollingerbands;

    public override void Initialize()
    {
        _symbol = AddEquity("SPY", Resolution.Daily).Symbol;
        _bollingerbands = new BollingerBands(30, 2m);
    }

    public override void OnData(Slice data)
    {
        if (data.Bars.TryGetValue(_symbol, out var bar))
            _bollingerbands.Update(bar.EndTime, bar.Close);

        if (_bollingerbands.IsReady)
        {
            // The current value of _bollingerbands is represented by itself (_bollingerbands)
            // or _bollingerbands.Current.Value
            Plot("BollingerBands", "bollingerbands", _bollingerbands);
            // Plot all properties of abands
            Plot("BollingerBands", "standarddeviation", _bollingerbands.StandardDeviation);
            Plot("BollingerBands", "middleband", _bollingerbands.MiddleBand);
            Plot("BollingerBands", "upperband", _bollingerbands.UpperBand);
            Plot("BollingerBands", "lowerband", _bollingerbands.LowerBand);
            Plot("BollingerBands", "bandwidth", _bollingerbands.BandWidth);
            Plot("BollingerBands", "percentb", _bollingerbands.PercentB);
            Plot("BollingerBands", "price", _bollingerbands.Price);
        }
    }
}
class BollingerBandsAlgorithm(QCAlgorithm):
    def initialize(self) -> None:
        self._symbol = self.add_equity("SPY", Resolution.DAILY).symbol
        self._bollingerbands = BollingerBands(30, 2)

    def on_data(self, slice: Slice) -> None:
        bar = slice.bars.get(self._symbol)
        if bar:
            self._bollingerbands.update(bar.end_time, bar.close)

        if self._bollingerbands.is_ready:
            # The current value of self._bollingerbands is represented by self._bollingerbands.current.value
            self.plot("BollingerBands", "bollingerbands", self._bollingerbands.current.value)
            # Plot all attributes of self._bollingerbands
            self.plot("BollingerBands", "standard_deviation", self._bollingerbands.standard_deviation.current.value)
            self.plot("BollingerBands", "middle_band", self._bollingerbands.middle_band.current.value)
            self.plot("BollingerBands", "upper_band", self._bollingerbands.upper_band.current.value)
            self.plot("BollingerBands", "lower_band", self._bollingerbands.lower_band.current.value)
            self.plot("BollingerBands", "band_width", self._bollingerbands.band_width.current.value)
            self.plot("BollingerBands", "percent_b", self._bollingerbands.percent_b.current.value)
            self.plot("BollingerBands", "price", self._bollingerbands.price.current.value)

For more information about this indicator, see its referencereference.

Visualization

The following plot shows values for some of the BollingerBands indicator properties:

BollingerBands line plot.

Indicator History

To get the historical data of the BollingerBands indicator, call the IndicatorHistoryself.indicator_history method. This method resets your indicator, makes a history request, and updates the indicator with the historical data. Just like with regular history requests, the IndicatorHistoryindicator_history method supports time periods based on a trailing number of bars, a trailing period of time, or a defined period of time. If you don't provide a resolution argument, it defaults to match the resolution of the security subscription.

public class BollingerBandsAlgorithm : QCAlgorithm
{
    private Symbol _symbol;
    private BollingerBands _bb;

    public override void Initialize()
    {
        _symbol = AddEquity("SPY", Resolution.Daily).Symbol;
        _bb = BB(_symbol, 30, 2m);

        var indicatorHistory = IndicatorHistory(_bb, _symbol, 100, Resolution.Minute);
        var timeSpanIndicatorHistory = IndicatorHistory(_bb, _symbol, TimeSpan.FromDays(10), Resolution.Minute);
        var timePeriodIndicatorHistory = IndicatorHistory(_bb, _symbol, new DateTime(2024, 7, 1), new DateTime(2024, 7, 5), Resolution.Minute);

        // Access all attributes of indicatorHistory
        var standardDeviation = indicatorHistory.Select(x => ((dynamic)x).StandardDeviation).ToList();
        var middleBand = indicatorHistory.Select(x => ((dynamic)x).MiddleBand).ToList();
        var upperBand = indicatorHistory.Select(x => ((dynamic)x).UpperBand).ToList();
        var lowerBand = indicatorHistory.Select(x => ((dynamic)x).LowerBand).ToList();
        var bandWidth = indicatorHistory.Select(x => ((dynamic)x).BandWidth).ToList();
        var percentB = indicatorHistory.Select(x => ((dynamic)x).PercentB).ToList();
        var price = indicatorHistory.Select(x => ((dynamic)x).Price).ToList();
    }
}
class BollingerBandsAlgorithm(QCAlgorithm):
    def initialize(self) -> None:
        self._symbol = self.add_equity("SPY", Resolution.DAILY).symbol
        self._bb = self.bb(self._symbol, 30, 2)

        indicator_history = self.indicator_history(self._bb, self._symbol, 100, Resolution.MINUTE)
        timedelta_indicator_history = self.indicator_history(self._bb, self._symbol, timedelta(days=10), Resolution.MINUTE)
        time_period_indicator_history = self.indicator_history(self._bb, self._symbol, datetime(2024, 7, 1), datetime(2024, 7, 5), Resolution.MINUTE)
    
        # Access all attributes of indicator_history
        indicator_history_df = indicator_history.data_frame
        standard_deviation = indicator_history_df["standarddeviation"]
        middle_band = indicator_history_df["middleband"]
        upper_band = indicator_history_df["upperband"]
        lower_band = indicator_history_df["lowerband"]
        band_width = indicator_history_df["bandwidth"]
        percent_b = indicator_history_df["percentb"]
        price = indicator_history_df["price"]

You can also see our Videos. You can also get in touch with us via Discord.

Did you find this page helpful?

Contribute to the documentation: