Bollinger Band for Beginners

Posted on August 17, 2022 by Quantplay Team ‐ 4 min read

Bollinger Band for Beginners

A case study of bollinger bands -

Today, we are going to back-test bollinger bands over a period of three years using Quantplay. But before we get into that, Let us try to understand bollinger bands first.

What Is a Bollinger Band? -

Bollinger Bands were developed and copyrighted by famous technical trader John Bollinger, designed to discover opportunities that give investors a higher probability of properly identifying when an asset is oversold or overbought.

This indicator is based on mean reversion model. Meaning, it says that whenever the price will hit the upper band it is more likely now, that the price will return back to its mean which is the middle band in this case and vise-versa.

Key details -

  • There are three lines that compose Bollinger Bands
  • A simple moving average (i.e middle band) and an upper and lower band
  • The upper and lower bands are typically 2 standard deviations +/- from a 20-day SMA (simple moving average)

How to use bollinger bands in trading -

  • If the price is near the upper Bollinger Band, it’s considered “expensive” because it is 2 standard deviation above the average (the 20-period moving average). As a trader, we should sell here and expect the price to fall till it reaches the middle band.

  • If the is price near the lower Bollinger Band, it’s considered “cheap” because it’s 2 standard deviation below the average. We should buy here expecting the price to rise till it reacher the middle band.

Let’s test the strategy using quantplay’s library -

  • Enter a trade at 9:20 AM (when the first 5-minute candle closes)
  • Exit the trade at 3:15 PM or whenever the stoploss triggers
  • Trade INR 1,00,000 in the stock
  • Filter stocks that are outside of bollinger bands using Quantplay’s library
  • Pick top 5 stocks based on the previous day performance
  • Trade with a stop loss of 3%

Strategy Code -

from quantplay.strategy.base import QuantplayAlgorithm
from quantplay.utils.constant import TickInterval
from quantplay.service import market
import numpy as np
import pandas as pd
import ta

class BollingerBands(QuantplayAlgorithm):
    def __init__(self):
        self.interval = "5minute"
        self.entry_time = "09:15"
        self.exit_time = "15:15"
        self.exchange_to_trade_on = "NSE"
        self.stream_symbols_by_security_type = {"EQ": market.symbols(universe="FNO_STOCKS")}
        self.strategy_type = "intraday"
        self.strategy_tag = "bband"

        super(BollingerBands, self).__init__()

    def get_trades(self, market_data):
        trades = market.get_trades(market_data, self.entry_time)
        trades.loc[:, 'last_day_return'] = trades.close/trades.close.shift(1) - 1

        bbands = ta.volatility.BollingerBands(close=trades.close,
                                         window=20,
                                         window_dev=2)

        trades["bb_high"] = bbands.bollinger_hband()

        trades = trades[trades.close > trades.bb_high]
        trades = trades.sort_values("last_day_return", ascending=False).groupby(['date']).head(5)

        trades.loc[:, 'tradingsymbol'] = trades.symbol
        trades.loc[:, "transaction_type"] = "SELL"
        trades.loc[:, "stoploss"] = 0.02
        trades.loc[:, "quantity"] = (100000/trades.close).astype(int)

        return trades
strategy = BollingerBands()
strategy.validate()
res, trades = strategy.backtest()

Performance -

Image

Fig: Balance progression from Jan-2019 till May-2022

Image

Fig: Profit gained on backtested data from 31st Jan 2019 till 31st May 2022

Image

Fig: Profit gained on back-tested data from the year 2019 till till the year 2022

Strategy statistics -

AttributeYear 2019Year 2020Year 2021Year 2022All (Combining all the years)
Total profit17302992725140776973455038745
Max drawdown2857571341575782587772393
Sharpe ratio9.043.145.1915.406.16
Max drawdown days48709915117
Losing streak6128312
Winning streak86468
Monthly pnl144197727117311946912290
Required exposure100000100000100000100000100000
Total signals964108211323053483
Total trading days22923424674783
Success ratio0.520.440.460.560.48
Avg. pnl17986124319145

Conclusion -

Using only the bands to trade is a risky strategy since the indicator focuses on price and volatility, while ignoring a lot of other relevant information.In our upcoming blogs we are going to discuss the right market conditions to trade bands and improve the strategy results.

Follow us on your favorite social media to know when we post a better version of the strategy. You can now execute strategies like this using Quantplay library within seconds!

I hope you enjoyed reading this blog. Happy trading!