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 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.

In my previous article, I already introduced technical analysis and Moving Averages with Python. I recommend you to also have a look.

Technical Analysis Bollinger Bands with Python
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, a free API 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 thing we need to do is to import all the required packages. We will use requests to make http requests to the API end point. In addition, we will also use Pandas and matplotlib to plot the Bollinger bands.

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.

Note that you need to sign up to financialmodelingprep to get an API key. It is free up to 250 API requests per month. If you choose to sign up for a paid subscription using my link, you get a 25% discount.

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"https://financialmodelingprep.com/api/v3/historical-price-full/{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')

#Outcome
             close
date              
2019-08-02  204.02
2019-08-05  193.34
2019-08-06  197.00
2019-08-07  199.04
2019-08-08  203.43

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)

# Outcome
             close      MA20     20dSTD       Upper       Lower
date                                                           
2020-03-02  298.81  310.6475  17.171900  344.991300  276.303700
2020-03-03  289.32  309.6805  17.821954  345.324409  274.036591
2020-03-04  302.74  308.8750  17.749623  344.374246  273.375754
2020-03-05  292.92  307.4485  17.832063  343.112625  271.784375
2020-03-06  289.03  305.6395  17.770448  341.180395  270.098605

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:

 stockprices[['close','MA20','Upper','Lower']].plot(figsize=(10,4))
 plt.grid(True)
 plt.title(stock + ' Bollinger Bands')
 plt.axis('tight')
 plt.ylabel('Price')

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:

bollingerbands('aapl')
Bollinger Bands with Python
Bollinger Bands with Python

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 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. Check my other posts to find out how to build some cool financial analysis tools.

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.

See below the whole scrip. Thank you for reading! If you enjoy reading my blog on Python for Finance, I would highly appreciate if you share the post on social media. Happy to continue the discussion in Twitter https://twitter.com/CodingandF

import requests
import pandas as pd
import matplotlib.pyplot as plt

api_key= 'your api key'
def bollingerbands(stock):
    stockprices = requests.get(f"https://financialmodelingprep.com/api/v3/historical-price-full/{stock}?serietype=line&apikey={api_key}")
    stockprices = stockprices.json()

    stockprices = stockprices['historical'][-150:]
    
    stockprices = pd.DataFrame.from_dict(stockprices)
    stockprices = stockprices.set_index('date')
    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)
    
    stockprices[['close','MA20','Upper','Lower']].plot(figsize=(10,4))
    plt.grid(True)
    plt.title(stock + ' Bollinger Bands')
    plt.axis('tight')
    plt.ylabel('Price')
    plt.savefig('apple.png', bbox_inches='tight')
    
bollingerbands('aapl')