A short tutorial on Bollinger Bands using Python
Image from dolphintrader.com
Introduction
Bollinger Bands® are a technical analysis tool developed by John Bollinger for generating oversold or overbought signals.
According to Investopedia a Bollinger Band®
…is a technical analysis tool defined by a set of trendlines plotted two standard deviations (positively and negatively) away from a simple moving average (SMA) of a security’s price, but which can be adjusted to user preferences.
They were developed and copyrighted by famous technical trader John Bollinger. They were designed to discover opportunities that give investors a higher probability of correctly identifying when an asset is oversold or overbought.
Bollinger Bands® belongs among popular stock and cryptocurrency trading indicators. Bollinger Bands® can also nicely visualize price volatility, its range expansion is followed by range contraction and vice versa, and can be used to anticipate breakouts.
In this tutorial we will learn how to download the data corresponding to a popular security which is Tesla (TSLA), then we will perform the calculation in a Jupyter Notebook using Python libraries, and additionally, we will use the downloaded data to generate the same calculation and interactive visualization in Tableau Public.
The Calculation
Basically consists of 3 lines:
The simple moving average (SMA) of the security in question is a window (typically 20 datapoints). The 20-day moving average would average out the closing prices for the first 20 days as the first data point. The next data point would drop the earliest price, add the price on day 21, and take the average, and so on. Next, the standard deviation [1] of the security price will be obtained.
Upper Bollinger Band is the value of the sigma (standard deviation) multiplied by 2 then added to the amount from each point along the SMA.
Lower Bollinger Band is the value of the sigma (standard deviation) multiplied by 2 then subtracted to the amount from each point along the SMA.
The following is the Bollinger Bands® formula:
Image from Investopedia
where:
BOLU = Upper Bollinger Band
BOLD = Lower Bollinger Band
MA = Moving Average
TP (typical price) = (High + Low + Close) / 3
n = Number of of days in smoothing period (typically 20)
m = Number of standard deviations (typically 2)
σ [TP,n] = Standard Deviation over last n periods of TP
Calculating Bollinger Bands® using Python
The first thing that we will need to make the calculation is oil, and when I talk about “oil” I mean data, which is the first thing that our “engine” will need to work.
In order to get the necessary data, we will make use of the pandas data reader API which connects to several stocks data providers such as Alpha Vantage, Quandl, Yahoo Finance, among others, to get financial data for standalone applications, in this opportunity we will use Yahoo Finance:
Image from Author
After that, we’ll set a list of stocks (tickers) like Apple, Google, Tesla, Netflix, etc., but I used for my analysis the Tesla one (TSLA). Then I set the period of time for the data to be downloaded and then connected to the API and stored the data in a pandas dataframe.
Image from Author
Then I created a function that will compute the Moving Average, Standard Deviation, and the Lower and Upper bands that will generate the graphs:
Image from Author
Feel free to replicate this calculation by cloning the GitHub repo, I recommend you install and run it inside Anaconda distribution.
Once you have run the notebook you will get an output like this one:
Image from Author
This graphical representation of the data contains the plot of the Moving Average, Standard Deviation, and the Lower and Upper bands, so the closer the prices move to the upper band the more overbought the market, and the closer the prices move to the lower band, the more oversold the market.
Most projects fail before they get to production. Check out our free ebook to learn how to implement an MLOps lifecycle to better monitor, train, and deploy your machine learning models to increase output and iteration.
Calculating Bollinger Bands® in Tableau Public
In order to know how to set and create a data visualization in Tableau Public, follow the steps in this article. In the Jupyter Notebook we have set up, we downloaded the Stocks data of Tesla (you can feel free to modify the code and download the data for another ticker). In the data
folder of the project, you will find the data that was downloaded using the pandas DataReader API corresponding to the high, low, open, and close prices of 377 days between 01/01/2021 to the days when this article was written:
Image from Author
In the following Tableau Public repository, you can find the same graph that was generated in the Jupyter Notebook:
Image from Author
The difference is that there is more interactivity in this graph as you can play around with different filters as the number of Standard Deviations parameter or the Rolling Windows.
Image from Author
In the thedata
folder there is also a Tableau Workbook file that you can upload and analyze in Tableau Desktop.
Conclusions
In this article we have learned the basic theory that involves the Bollinger Bands and seen a step-by-step of how this analysis tool is calculated in Python and also in Tableau, as well as how you can use it to interpret the performance of a security in the stock market.
Sources:
[What Is a Bollinger Band® in Technical Analysis?
A Bollinger Band® is a technical analysis tool defined by a set of trendlines plotted two standard deviations…investopedia.com](https://www.investopedia.com/terms/b/bollingerbands.asp "investopedia.com/terms/b/bollingerbands.asp")
[Bollinger Bands for stock trading. Theory and practice in Python
Let’s see a simple but effective trading tool in Pythontowardsdatascience.com](https://towardsdatascience.com/bollinger-bands-for-stock-trading-theory-and-practice-in-python-7d3e79d30e02 "towardsdatascience.com/bollinger-bands-for-..")
[1] For a given data set, the standard deviation measures how spread out numbers are from an average value.
Editor’s Note: Heartbeat is a contributor-driven online publication and community dedicated to providing premier educational resources for data science, machine learning, and deep learning practitioners. We’re committed to supporting and inspiring developers and engineers from all walks of life.
Editorially independent, Heartbeat is sponsored and published by Comet, an MLOps platform that enables data scientists & ML teams to track, compare, explain, & optimize their experiments. We pay our contributors, and we don’t sell ads.
If you’d like to contribute, head on over to our call for contributors. You can also sign up to receive our weekly newsletter (Deep Learning Weekly), check out the Comet blog, join us on Slack, and follow Comet on Twitter and LinkedIn for resources, events, and much more that will help you build better ML models, faster.