INTRODUCTION:
Investment Analysis and Portfolio Management has been one of the key areas of interest among all sorts of investors, portfolio managers since long.
Investment Analysis involves evaluating different classes of financial instruments across sectors, markets, geographies and asset classes. It includes analyzing the past historical data like % Daily Return, 20 DMA, 50 DMA (Daily Moving Average), Cumulative Returns, Weighted Returns, Bollinger’s Bands etc in equities, the % change, yields, cumulative total returns, total market cap, z spread etc in bonds) to understand the performance so far as well as to come up with models to predict/forecast future performance, manage risks and adjust the investments for higher yields.
In this particular post we would be focusing on understanding the basics of Bollinger Band and how we can plot it using Python code.
Bollinger Band is used a technical analysis tool that can be used to track the price movements in the stock over a period of time and make decisions based on that. In general it consists of a plot showcasing the Simple Moving Average (SMA) for the price of a security against a set of 2 lines plotted against this SMA line generally with a +2/-2 Standard Deviations against the actual price. Any other numeric value can also be used depending on one’s personal preference.
As Standard Deviation helps to determine the Volatility of a particular stock, these plots can be used to assess the volatility of the stock as well as to figure out opportunities for buying/selling a particular stock based on the average price movements over the period of time.
Thus Bollinger Bands consists of 3 different charts:
1. Middle chart/band which may be either be a 20 day SMA, 50 day SMA etc depending on what we want to plot. Here SMA is the Simple Moving Average for our stock prices.
2. If the middle band is 20 SMA, Upper Band would be:
20 day SMA + (20 day standard deviation of price * 2) This signifies that the upper band is 2 Standard Deviations away from the middle on the positive side.
3. Similarly, if the middle band is 20 SMA, Lower Band would be:
20 day SMA – (20 day standard deviation of price * 2) This signifies that the upper band is 2 Standard Deviations away from the middle on the negative side.
The focus of this article is only to showcase how Bollinger Bands can be plotted using Python code. One is advised to do proper research and study before taking any sort of decisions based on this technical indicator.
We would be using data for the stock Maruti Suzuki available via Yahoo Finance using the yfinance module. So let’s get started.
# import the required libraries
import yfinance as yf
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
import warnings
warnings.filterwarnings("ignore")
import matplotlib.style as style
style.use('seaborn-poster') #sets the size of the charts
style.use('ggplot')
stock_ticker = 'MARUTI.BO'
start_date = '2019-03-25'
end_date = '2020-03-25'
period = 20 # consider for a 20 Day Mean
price_field = 'Adj Close'
# fetch the data for the required duration
# the fetched data has Date column set as the DateTimeIndex by default
data = yf.download(stock_ticker, start=start_date, end=end_date)
# Fill in the missing data using forward fill and backward fill
data.fillna(method='ffill', inplace=True)
data.fillna(method='bfill', inplace=True)
#data['Adj Close'].plot(figsize=(16,8), title='Adjusted Closing Prices');
# create a final dataframe df_final
# assign the Adj Close as one of the columns in Data Frame
df_final = data[[price_field]]
# CAlculate and assign the 20 Day Moving Average for each of the price points
df_final[str(price_field) + ' : ' + str(period) + ' Day Mean'] = df_final.rolling(window=period).mean()
# CAlculate and assign the Upper and Lower band based on the Bollinger Band formula
df_final['Upper'] = df_final[str(price_field) + ' : ' + str(period) + ' Day Mean'] + 2 * df_final[price_field].rolling(window=period).std()
df_final['Lower'] = df_final[str(price_field) + ' : ' + str(period) + ' Day Mean'] - 2 * df_final[price_field].rolling(window=period).std()
# plot the Bollinger Bands
df_final.plot(figsize = (16,8), title = stock_ticker)

So that’s it. Go ahead and run this piece of code in your favorite python editor and Voila you can see the chart plotted.
See you until next time. Happy Learning !