FMP

FMP

Enter

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

Jul 10, 2024 2:34 AM - Parth Sanghvi

Capital Budgeting Techniques: NPV, IRR, and More - A Comprehensive Guide

Capital budgeting is a critical financial process that companies use to evaluate and select long-term investments or projects. It involves assessing potential expenditures and determining their profitability to ensure that resources are allocated effectively. This comprehensive guide covers essentia...

blog post title

Aug 7, 2024 3:53 AM - Parth Sanghvi

The Impact of Interest Rates on the Economy and Financial Markets: A Comprehensive Analysis

Interest rates play a crucial role in the economy and financial markets, influencing everything from consumer behavior to investment decisions. Understanding their impact is essential for making informed financial and investment decisions. This comprehensive analysis delves into how interest rates a...

blog post title

Aug 31, 2024 10:27 AM - Sanzhi Kobzhan

What are API endpoints and how can traders use them?

Dear traders, how do you obtain stock market data? Everyone should access fresh and accurate data to analyze investments and define great trading strategies. As you may know, buying a stock based on its price level is not the best option because buying a stock is all about buying a company. You shou...

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.
twitterlinkedin
2017-2025 © Financial Modeling Prep