Bollinger Bands for stock trading — Theory and practice in Python | by Gianluca Malato | Towards Data Science

Quantitative traders often look for trading tools that can spot trends or reversals. Such tools should self-adapt to market conditions and try to describe the current situation in the most accurate way.
In this article, I’ll talk about Bollinger Bands and how to work with them in Python.
Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details.
Bollinger Bands are a tool introduced by the quantitative trader John Bollinger in the 1980s. They are made by two lines that wrap the price time series in a way that is related to volatility. The higher the volatility, the wider the bands.
They are usually drawn in this way:
Higher band: a 20-period Simple Moving Average plus 2 times the 20-period rolling standard deviation, both calculated on the close price
Lower band: a 20-period Simple Moving Average minus 2 times the 20-period rolling standard deviation, both calculated on the close price
This is the result applied to the SPX ETF of the S&P 500 index:
As you can see, the bands try to wrap the price, but some particular events occur when the price breaks them and we can use such events for building many trading strategies.
Let’s see some trading setups that can be spotted with Bollinger Bands.
The most common approach, often used by binary options traders, is to consider Bollinger Bands as dynamic supports and resistances. Once the price has broken a band, it’s generally thought that it will likely return back towards the SMA.
However, while this approach could seem good, Bollinger himself usually suggests using the Bands together with another indicator, for example, an oscillator. We’re going to see that breaking the bands is not often a reverse signal.
If the trend is strong, the price will likely move near a band for some candles. That’s because a strong trend means high volatility, so the bands expand and the price follows them.
A very used set of patterns is the W-M pattern. The former is the opposite of the latter. W pattern occurs when the price breaks the lower band, then rises, then falls again, and finally rises without breaking the band again. It really seems to draw a W letter.
The M pattern occurs when the price breaks the upper band, then makes a new maximum without breaking the band again.
These patterns are usually considered as a decrease of momentum, so they are used in a reversal way. W patterns are bullish, M patterns are bearish.
Don’t forget that market volatility changes over time and there are some periods of low volatility that prelude a huge directional burst of the market. Bollinger Bands can spot such situations very easily. You have to look for a market condition in which the bands are flat and their width is constant. This is called “squeeze” because the volatility is lowering. Then you have to look for a breakout made by a huge candle. That is the prelude of the directional explosion of the price and you could trade following the direction of the breakout.
Bollinger Bands have 2 parameters: the period of the moving average and of the standard deviation (which is the same) and the multiplier of the standard deviation.
The 20-period SMA is often used to catch medium-term movements, so the value of 20 periods has been chosen empirically.
Let’s talk about the multiplier of the standard deviation. According to the normal distribution, there is a probability of nearly 95% that the value of a normal variable is more than 2 standard deviations far from the mean value. That’s where the 2 number comes from.
In reality, we know that prices don’t follow a normal distribution. According to the Geometric Brownian Motion model, a good approximation of the price distribution is the Lognormal distribution. Moreover, according to Chebyshev’s inequality, the probability of having a value of any random variable with a finite variance that is more than 2 standard deviations far from the mean value is less than 25%. So, it’s quite high and very different from the 5% of the normal case.
John Bollinger himself suggests using a slightly different set of parameters, changing the multiplier and the period according to some particular situations.
Nevertheless, the 20–2 combination is widely considered almost like a standard in trading.
Calculating Bollinger Bands in Python is very easy. We’re going to see how to do it using S&P 500 historical data. The whole code can be found in my GitHub repository: https://github.com/gianlucamalato/machinelearning/blob/master/Bollinger_Bands.ipynb
First, let’s install yfinance:
!pip install yfinance
Then let’s import some libraries:
import yfinanceimport pandas as pdimport matplotlib.pyplot as plt
Let’s import some data from S&P 500 index:
name = "SPY"ticker = yfinance.Ticker(name)df = ticker.history(interval="1d",start="2020-01-15",end="2020-07-15")
We can define the period and the multiplier:
period = 20multiplier = 2
Then, we can finally calculate the bands:
df['UpperBand'] = df['Close'].rolling(period).mean() + df['Close'].rolling(period).std() * multiplierdf['LowerBand'] = df['Close'].rolling(period).mean() - df['Close'].rolling(period).std() * multiplier
The final chart is:
As you can see, the bands wrap the price just like expected.
Bollinger Bands are very useful to use in trading and very simple to calculate. Different strategies using such a dynamic tool can lead to different results, so a good backtest of a trading strategy should always be done to fine-tune the parameters of the indicators.