Bollinger Bands® for identifying overbought and oversold conditions in market— Python implementation

In this article, I have demonstrated how to use Python for plotting and visualizing Bollinger Bands® and derive insights from it.

Pratik Nabriya
DataDrivenInvestor

--

What are Bollinger Bands®

Bollinger Bands® are a technical analysis tool created by John Bollinger in the early 1980s for generating oversold or overbought signals. They arose from the need for adaptive trading bands and the observation that volatility was dynamic, not static as was widely believed at the time.

Bollinger Bands® can be applied in all the financial markets including equities, commodities, forex, and futures. Bollinger Bands® can be used in most time frames, from very short-term periods, to hourly, daily, weekly or monthly. Since their introduction 30 years ago they have become one of the most widely used technical indicators worldwide.

​Understanding Bollinger Bands®

Bollinger Bands® consists of three lines:

  1. A moving average band (typically 20-day SMA)
  2. Upper Bollinger band
  3. Lower Bollinger band

The upper and lower bands are typically 2 standard deviations +/- from the middle simple moving average band.

The bands widen and narrow when the volatility of the price is higher or lower, respectively. Bollinger Bands® do not, in themselves, generate buy or sell signals; they are an indicator of overbought or oversold conditions. When the price is near the upper or lower band it indicates that a reversal may be imminent. The middle band becomes a support or resistance level.

How To Calculate Bollinger Bands®

Step 1: Calculate simple moving average of the security under consideration

For example, a 20-day moving average would average out the closing prices for the first 20 days as the first data point. The next data point would drop the earliest price, add the price on day 21 and take the average, and so on.

Step 2: Calculate the standard deviation

The standard deviation measures how spread out numbers are from an average value. Standard deviation is calculated by taking the square root of the variance, which itself is an average of squared differences of the mean.

Note that, here we calculate the standard deviation with respect to the rolling mean of the closing price (moving average price) that we computed in the previous step.

Step 3: Calculate Upper band and Lower band

Next, multiply the standard deviation value by a factor of 1.5 or 2 (depending upon how many standard deviations we wish to consider the spread of the price). For obtaining the upper band, add the product to the moving average. For the lower band, subtract the product from the moving average.

Typical values used —

  • Short term: 10-day moving average, bands at 1.5 standard deviations
    (1.5*std dev +/- SMA)
  • Medium term: 20-day moving average, bands at 2 standard deviations.
  • Long term: 50-day moving average, bands at 2.5 standard deviations.

Plotting and Visualization with Python

Now that we have accustomed ourselves with the fundamentals, let us proceed towards the python code. If you are overwhelmed with the theory, trust me, it’s way easier to carry out all the above mentioned steps using Python.

For the demonstration, I have selected the ITC Limited stock for the period of 2 years i.e. from 28th Jan 2019 to 28th Jan 2021. You are free to select your own company and the time-period.

Importing necessary libraries —

# import necessary libraries 
%matplotlib inline
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import datetime
import warnings
warnings.filterwarnings(‘ignore’)

We are going to extract the stock price for the given period from Yahoo Finance by using Pandas-datareader API.

import pandas_datareader.data as webstart = datetime.datetime(2019, 1, 28)
end = datetime.datetime(2021, 1, 28)
itc_df = web.DataReader([‘ITC.NS’], ‘yahoo’, start = start, end = end)[‘Close’]
itc_df.columns = {‘Close Price’}
itc_df.head()

Output —

Next, we check if there are any null values—

itc_df.isnull().sum()

Output —

Let’s proceed to observe general price variation of the closing price for the given period.

itc_df[‘Close Price’].plot(figsize = (15, 8), fontsize = 12)
plt.ylabel(‘Price in INR(₹)’)
plt.grid()
plt.show()

Output —

As it can be seen, there is a steep fall in the price of the stock around the month of April. That is due to the meltdown in the global financial markets at the peak of Covid-19 pandemic.

Now let’s build a function that computes the moving average of the day-to-day closing price, the upper band and lower band.

def bollinger_band(price, length = 20, num_stdev = 2):
mean_price = price.rolling(length).mean()
stdev = price.rolling(length).std()
upband = mean_price + num_stdev*stdev
dwnband = mean_price — num_stdev*stdev

return np.round(mean_price, 3), np.round(upband, 3), np.round(dwnband, 3)
itc_df[‘Moving_avg’], itc_df[‘Upper_band’], itc_df[‘Lower_band’] = bollinger_band(itc_df[‘Close Price’])

Let’s see last few rows of the dataframe —

itc_df.tail()

Output —

Now that we have obtained the the required values, lets plot the bollinger bands® chart —

itc_df[‘Close Price’].plot(c = ‘k’, figsize = (20,10), lw = 2)
itc_df[‘Moving_avg’].plot(c = ‘b’, figsize = (20, 10), lw = 1)
itc_df[‘Upper_band’].plot(c = ‘g’, figsize = (20, 10), lw = 1)
itc_df[‘Lower_band’].plot(c = ‘r’, figsize = (20, 10), lw = 1)
plt.title(‘Bollinger Bands’, fontsize = 20)
plt.ylabel(‘Price in INR(₹)’,fontsize = 15 )
plt.xlabel(‘Date’, fontsize = 15 )
plt.grid()
plt.show()

What Do Bollinger Bands® tell us ?

The reason why the upper and lower bands are two standard deviations away from the moving average is that this makes an envelope around the closing price and most of the price action is contained within these two bands. Statistically, two standard deviation includes 95% of price movement. Thus, any time the closing price goes below or above the Bollinger bands, there are high chances for breakout or price reversion, and hence it can be used a signal.

Because the standard deviation is also a measure of volatility, when the markets become more volatile the bands tend to widen. During the less volatile periods, the bands tend to contract. This is commonly referred as Bollinger bands squeeze and is considered by traders to be a potential sign of future increased volatility and possible trading opportunities.

Trading with Bollinger bands®

One strategy effective for the relatively low-risk individual who is content with low but safe returns on their investment is to trade by keeping an eye on the SMA as the signal to enter or exit the trade. If the closing price crosses SMA from below, it is an indication to go long. For more on the trading strategies based on moving averages please check my previous article —

A variation on the earlier strategy is that we enter the trade when the closing price it is inside the band and trending, and exit when it touches the other band. For example, if the closing price had touched the lower band before increasing again, and if we are confident that it will sustain the price increase, we buy the stock and exit when it touches the upper band.

In the above chart, you can see that price changing the direction once it touches the upper Bollinger Band and similarly changing its direction once again when it touches the lower Bollinger Band.

The Bottom Line

Bollinger Bands® are a good way to understand the price action of an asset and helps us in forming better decisions on when to enter a trade. Buying when stock prices cross below the lower Bollinger Band® often helps traders take advantage of oversold conditions and profit when the stock price moves back up toward the center moving-average line.

Note that Bollinger Bands® are not a standalone trading system. They are simply one indicator designed to provide traders with information regarding the price volatility. It is suggested using them with two or three other non-correlated indicators and techniques like moving average divergence/convergence (MACD), on-balance volume and relative strength index (RSI) that provide more direct market signals. You can use a combination of different indicators to create your own strategy.

References:

You may also want to check my other article —

— — — — — — — — — — — — — — — —
Disclaimer — The trading strategies and related information in this article is for the educational purpose only. All investments and trading in the stock market involve risk. Any decision related to buying/selling of stocks or other financial instruments should only be made after a thorough research and seeking a professional assistance if required.
— — — — — — — — — — — — — — — —

--

--

I’m passionate about using Statistics and Machine Learning on data to make Humans and Machines smarter. LinkedIn: linkedin.com/in/pratiknabriya/