FMP
Sep 11, 2023 6:45 PM - Rajnish Katharotiya
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
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.
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)
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')
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.
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.
May 14, 2024 11:41 AM - Sanzhi Kobzhan
A stock's target price, also known as its fair value, is an indication of what a share can cost based on the company’s forecasted financial statements. It is important to know a stock's fair value to find undervalued stocks with great growth potential. Let's consider how investment analysts calculat...
May 24, 2024 9:30 AM - Rajnish Katharotiya
Earnings call transcripts are invaluable resources for investors, analysts, and financial enthusiasts. They provide insights into a company's performance, strategy, and future outlook, making them essential for making informed investment decisions. With Financial Modeling Prep, Earnings Call Transcr...
May 27, 2024 3:30 PM - Rajnish Katharotiya
In the ever-evolving world of technology, certain sectors have consistently demonstrated exceptional growth and innovation. The graphics processing units (GPUs) industry is one such sector, offering investors a golden opportunity for potentially high returns. In this blog, we'll delve into why inves...