How To Plot Stock Bollinger Band Using Python

Bollinger Bands use 2 parameters, Period and Standard Deviations, StdDev. The default values are 20 for period, and 2 for standard deviations.

Let us import the necessary packages.

In [1]:
import matplotlib.pyplot as plt
import pandas as pd
%matplotlib inline
import numpy as np
plt.rcParams.update({'figure.max_open_warning': 0})

I will use yfinance to access the stock data.

Let us try to plot the Bollinger Band for APPLE stock.

In [2]:
import yfinance as yf
In [3]:
aapl = yf.Ticker("AAPL")
In [4]:
dfdata = aapl.history(period="6mo")
In [5]:
dfdata.head()
Out[5]:
Open High Low Close Volume Dividends Stock Splits
Date
2022-03-17 158.157619 160.540802 157.180418 160.161880 75615400 0.0 0
2022-03-18 160.052194 164.010873 159.304333 163.512299 123511700 0.0 0
2022-03-21 163.043633 165.875545 162.545059 164.908310 95811400 0.0 0
2022-03-22 165.037929 168.936781 164.439649 168.338501 81532000 0.0 0
2022-03-23 167.510879 172.147610 167.171837 169.724548 98062700 0.0 0

We just need the closing price.

In [6]:
series = dfdata['Close']

In below code snippet, I am calculating the 20 day simple moving average, deviation and lower, upper bound for the bollinger band.

In [7]:
scale = 2
window = 20
sma = series.rolling(window).mean()
deviation = series.rolling(window).std()
lower_bound = sma - scale * deviation
upper_bound = sma + scale * deviation

Let us plot the bollinger band now.

In [8]:
plt.figure(figsize=(15,5))
plt.plot(upper_bound, "r--", label="Upper Bollinger Bound / Lower Bollinger Bound")
plt.plot(lower_bound, "r--")
    
plt.title("Moving average\n window size = {}".format(window))
plt.plot(series[window:], label="Actual values")
plt.legend(loc="upper left")
plt.grid(True)