Technical Analysis Bollinger Bands with Python

During this article, I would like to show you how to calculate and plot Bollinger bands with Python. Technical Analysis is a great tool use by investors and ana

Technical Analysis Bollinger Bands with Python

Sep 11, 2023 5:45 PM - Rajnish Katharotiya

blog post cover photo

Image credit: Campaign Creators

During this article, I would like to show you how to calculate and plot Bollinger bands with Python. Technical Analysis is a great tool use by investors and analysts to find out interesting stocks to add to the portfolio.

By the end of the article, we will have a Python script where we only need to input the name of the company. Then, within seconds, the stock's Bollinger bands will be calculated and plotted for our analysis. As we will see, this analysis is super easy to build.

Photo by Adeolu Eletu on Unsplash

Technical Analysis Bollinger Bands

Bollinger bands are used as technical analysis tool. They were first developed by John Bollinger. As we will see, Bollinger Bands are computed based on standard deviations on the Moving Average.

An analyst would calculate a number n of standard deviations (most common is to use two times the standard deviation) above and below the moving average. That is, the upper and lower band will be two times +/- from the single moving average.

We need to calculate four elements for our analysis:

  • Closing Price. We will use financialmodelingprep endpoint with historically stock price data to get stock prices into Pandas.

  • 20 days moving Average. We will use the Pandas function rolling to calculate 20 days moving average.

  • Upper Band. We can easily calculate the upper band by getting the 20 days standard deviation and adding it to the 20 days moving average.

  • Lower Band. Upper band will be obtained by getting the 20 days standard deviation and extracting it to the 20 days moving average.

Let's see how we can do all of this with Python.

Calculating Bollinger Bands with Python

First let's create our bollingerbands function and make a request to the API end point to get the historical closing prices. The API url takes the ticker of the company as a parameter.

Next, we parse the response to extract the latest 150 days (feel free to change the number of days).

Then, we convert the API response dictionary into a Pandas DataFrame using the Pandas from_dict()method.

import requests

import pandas as pd

import matplotlib.pyplot as plt

api_key= 'your api key'

def bollingerbands(stock):

stockprices = requests.get(f'{stock}?serietype=line&apikey={api_key}')

stockprices = stockprices.json()

#Parse the response and select only last 150 days of prices

stockprices = stockprices['historical'][-150:]

stockprices = pd.DataFrame.from_dict(stockprices)

stockprices = stockprices.set_index('date')

Now that we have our closing prices in a Pandas DataFrame, we can move to calculate the Moving Average, Upper Bollinger band and Lower Bollinger band:

stockprices['MA20'] = stockprices['close'].rolling(window=20).mean()

stockprices['20dSTD'] = stockprices['close'].rolling(window=20).std()

stockprices['Upper'] = stockprices['MA20'] + (stockprices['20dSTD'] * 2)

stockprices['Lower'] = stockprices['MA20'] - (stockprices['20dSTD'] * 2)

Plotting Bollinger Bands with Python

Finally we have computed the Bollinger bands. Next, we can move to plot them using Python and matplotlib. We would like to plot the closing price, 20 days moving average, upper Rollinger Band and lower Rollinger Band in a single chart:



plt.title(stock + ' Bollinger Bands')



And by running the whole script and passing the ticker of the selected company, for instance Apple, we obtain the graphical representation and calculation of the Bollinger bands:


Bollinger Band Interpretation

Closing prices above the upper Bollinger band may indicate that currently the stock price is too high and price may decrease soon. The market is said to be overbought.

Closing prices below the lower Bollinger band may be seen as a sign that prices are too low and they may be moving up soon. At this point the market for the stock is said to be oversold.

By looking into our Bollinger band graph for Apple, we can see, for example, that recently the closing price was below the lower Bollinger band. This can be taken as a sign to invest in Apple.

However, before taking any investment decision, we should further perform fundamental analysis to support our investment decision.

Wrapping up

In conclusion, we can say that Bollinger bands are a power tool to identify interesting stocks. During this post, we have learnt how to calculate and plot Bollinger bands with Python using only a few lines of codes. Of course, we always need to support our findings with more robust fundamental analysis before taking any investment decisions.

Other Blogs

Sep 11, 2023 - Rajnish Katharotiya

P/E Ratios Using Normalized Earnings

Price to Earnings is one of the key metrics use to value companies using multiples. The P/E ratio and other multiples are relative valuation metrics and they cannot be looked at in isolation. One of the problems with the P/E metric is the fact that if we are in the peak of a business cycle, earni...

blog post title

Sep 11, 2023 - Rajnish Katharotiya

What is Price To Earnings Ratio and How to Calculate it using Python

Price-to-Earnings ratio is a relative valuation tool. It is used by investors to find great companies at low prices. In this post, we will build a Python script to calculate Price Earnings Ratio for comparable companies. Photo by Skitterphoto on Pexels Price Earnings Ratio and Comparable Compa...

blog post title

Oct 17, 2023 - Davit Kirakosyan

VMware Stock Drops 12% as China May Hold Up the Broadcom Acquisition

Shares of VMware (NYSE:VMW) witnessed a sharp drop of 12% intra-day today due to rising concerns about China's review of the company's significant sale deal to Broadcom. Consequently, Broadcom's shares also saw a dip of around 4%. Even though there aren’t any apparent problems with the proposed solu...

blog post title


Financial Modeling Prep API provides real time stock price, company financial statements, major index prices, stock historical data, forex real time rate and cryptocurrencies. Financial Modeling Prep stock price API is in real time, the company reports can be found in quarter or annual format, and goes back 30 years in history.
2017-2023 © Financial Modeling Prep