How to create Bollinger Bands in python
Here’s a step-by-step guide on how to create Bollinger bands on python. Little bit about bollinger bands first before we move on to coding. Bollinger Bands are a type of technical analysis tool that can help investors identify when an asset is oversold or overbought1. They consist of three lines: a simple moving average (SMA) of the asset’s price, and an upper and lower band that are typically two standard deviations away from the SMA. The bands widen and narrow depending on the volatility of the price movements. When the price touches the upper band, it can indicate that the asset is overbought and may reverse its direction. When the price touches the lower band, it can indicate that the asset is oversold and may bounce back.
Now, onto the coding bit.
Import the yahoo finance and pandas libraries.
import yfinance as yf
import pandas as pd
We are going to create Bollinger bands for Tesla. Download data from yahoo finance.
TSLA = yf.download('TSLA','2020-01-01','2023-01-01')
TSLA.head()
Date Open High Low Close Adj Close Volume
2020-01-02 28.299999 28.713333 28.114000 28.684000 28.684000 142981500
2020-01-03 29.366667 30.266666 29.128000 29.534000 29.534000 266677500
2020-01-06 29.364668 30.104000 29.333332 30.102667 30.102667 151995000
2020-01-07 30.760000 31.441999 30.224001 31.270666 31.270666 268231500
2020-01-08 31.580000 33.232666 31.215334 32.809334 32.809334 467164500
Create a function for Bollinger Bands.
def Bollinger_Bands(data,n):
MA = data['Close'].rolling(window=n).mean()
SD = data['Close'].rolling(window=n).std()
data['Upper_BB'] = MA + (2*SD)
data['Lower_BB'] = MA - (2*SD)
return data
n=21
tsla_bb = Bollinger_Bands(TSLA,n)
tsla_bb.tail()
Date Open High Low Close Adj Close Volume Upper_BB Lower_BB
2022-12-23 126.370003 128.619995 121.019997 123.150002 123.150002 166989700 210.328186 121.755624
2022-12-27 117.500000 119.669998 108.760002 109.099998 109.099998 208643400 212.543187 112.515861
2022-12-28 110.349998 116.269997 108.239998 112.709999 112.709999 221070500 212.736747 105.635634
2022-12-29 120.389999 123.570000 117.500000 121.820000 121.820000 221923300 211.331209 101.421172
2022-12-30 119.949997 124.480003 119.750000 123.180000 123.180000 157777300 206.803489 99.137464
Create a graph to plot the close, and the upper, lower bands.
import matplotlib.pyplot as plt
plt.figure(figsize=(10,6))
plt.plot(tsla_bb.Close,color='k')
plt.plot(tsla_bb.Upper_BB,color='g')
plt.plot(tsla_bb.Lower_BB,color='r')
plt.grid(linewidth=0.5, linestyle='-.',color='k')
plt.title("TSLA Bollinger Bands",fontsize=12,color='k')
plt.ylabel("Price")
plt.xlabel("Time")
plt.show()
Voila! Download data for any stock you like, choose any time frame and create bollinger bands. Fascinating how you can do so much with so little lines of code. We live in exciting times!