FMP

FMP

Enter

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

-

twitterlinkedinfacebook
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'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')

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:

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

Nov 25, 2023 6:39 AM - Parth Sanghvi

DCF Valuation vs. Comparable Companies Analysis: Choosing the Right Valuation Method

Choosing the Right Valuation Method: DCF vs. Comparable Companies Analysis Introduction: Valuation methods play a pivotal role in determining the fair value of a company, aiding investors in making informed investment decisions. Two commonly used methods, DCF Valuation and Comparable Companies A...

blog post title

Dec 23, 2023 2:19 AM - Parth Sanghvi

Understanding the Limitations of DCF Analysis: A Guide to Overcoming Challenges

Introduction: Discounted Cash Flow (DCF) analysis stands as a cornerstone in valuing investments, yet its efficacy is contingent upon various assumptions and methodologies. While a powerful tool, DCF analysis comes with inherent limitations and challenges that investors must acknowledge to make i...

blog post title

Dec 25, 2023 2:28 AM - Parth Sanghvi

Integrating Sustainability into Valuations: Navigating ESG Factors within the Discounted Cash Flow (DCF) Model

Introduction: The investment landscape is undergoing a profound shift with a heightened emphasis on sustainability and responsible investing. In this blog post, we explore the intersection of Environmental, Social, and Governance (ESG) considerations within the Discounted Cash Flow (DCF) model, h...

blog post title
FMP

FMP

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.
twitterlinkedinfacebookinstagram
2017-2024 © Financial Modeling Prep