Algorithmic Trading Using Bollinger Bands & Python

Use Bollinger Bands to Determine When To Buy & Sell Stock

Image for post
Image for post

Disclaimer: The material in this article is purely educational and should not be taken as professional investment advice. Invest at your own discretion.

A Bollinger Band is a technical analysis tool defined by a set of trendlines plotted two standard deviations (positively and negatively) away from a moving average like a simple moving average (SMA) of a security’s price, this can be adjusted to a users preference however.-investepdia.com

Bollinger Bands: Three Main Components

  • Upper Band: The upper band is just two standard deviations above the moving average of a stock’s price.
  • Middle Band: The middle band is just the moving average of the stock’s price. There are many different types of moving averages, for this article I will be using a Simple 20-day Moving Average.
  • Lower Band: Two standard deviations below the moving average is the lower band.

When To Buy & Sell ?

A price movement such as the closing price of a stock above the upper band seemingly indicates a good time to sell the stock, while a price movement of the stock below the lower band seemingly indicates a good time to buy the stock.

If Close Price > Upper Band
Then Sell

If Close Price < Lower Band
Then Buy

If you prefer not to read this article and would like a video representation of it, you can check out the YouTube Video below. It goes through everything in this article with a little more detail, and will help make it easy for you to start programming . Or you can use both as supplementary materials for learning !

If you are interested in reading more on machine learning and/or algorithmic trading then you might want to read Hands-On Machine Learning for Algorithmic Trading: Design and implement investment strategies based on smart algorithms that learn from data using Python. The book will show you how to implement machine learning algorithms to build, train, and validate algorithmic models. It will also show you how to create your own algorithmic design process to apply probabilistic machine learning approaches to trading decisions, and the book will show you how to develop neural networks for algorithmic trading to perform time series forecasting and smart analytics.

Image for post
Image for post

Hands-On Machine Learning for Algorithmic Trading: Design and implement investment strategies based on smart algorithms that learn from data using Python

Programming

The first thing that I like to do before writing any code is to put a description of the program in comments.

#Description: This program uses the Bollinger Band strategy to determine when to buy and sell stock

Import the dependencies / libraries.

#Import the libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')

Next get the Tesla stock data from 2/1/2016 to 12/29/2017. Since I am using the website https://colab.research.google.com/ , I need to use that sites library to upload the data.

#Load the data
from google.colab import files # Use to load data on Google Colab
files.upload() # Use to load data on Google Colab

Store the data.

#Store the data
df = pd.read_csv('TSLA.csv')
#Set the date as the index
df = df.set_index(pd.DatetimeIndex(df['Date'].values))
#Show the data
df
Image for post
Image for post

Next, graph the data. First get the time period (20 days), then calculate the Simple Moving Average, Std Deviation, Upper Band and Lower Band. Remember the Upper band is just two positive standard deviations away from the Moving Average, and the Lower band is just two negative standard deviations away from the Moving Average.

#Graph the data
#Get the time period (20 days)
period = 20
# Calculate the 20 Day Simple Moving Average, Std Deviation, Upper Band and Lower Band
#Calculating the Simple Moving Average
df['SMA'] = df['Close'].rolling(window=period).mean()
# Get the standard deviation
df['STD'] = df['Close'].rolling(window=period).std()
#Calculate the Upper Bollinger Band
df['Upper'] = df['SMA'] + (df['STD'] * 2)
#Calculate the Lower Bollinger Band
df['Lower'] = df['SMA'] - (df['STD'] * 2)
#Create a list of columns to keep
column_list = ['Close', 'SMA', 'Upper', 'Lower']
df[column_list].plot(figsize=(12.2,6.4)) #Plot the data
plt.title('Bollinger Band for Tesla')
plt.ylabel('USD Price ($)')
plt.show();
Image for post
Image for post

The above chart looks good, now let’s plot and shade the area between the two Bollinger bands.

#Plot and shade the area between the two Bollinger bands
#Get the figure and the figure size

fig = plt.figure(figsize=(12.2,6.4)) #width = 12.2 inches and height = 6.4 inches
#Add the subplot
ax = fig.add_subplot(1,1,1) #Number of rows, cols, & index
# Get the index values of the DataFrame
x_axis = df.index
# Plot and shade the area between the upper band and the lower band Grey
ax.fill_between(x_axis, df['Upper'], df['Lower'], color='grey')
# Plot the Closing Price and Moving Average
ax.plot(x_axis, df['Close'], color='gold', lw=3, label = 'Close Price') #lw = line width
ax.plot(x_axis, df['SMA'], color='blue', lw=3, label = 'Simple Moving Average')
# Set the Title & Show the Image
ax.set_title('Bollinger Band For Tesla')
ax.set_xlabel('Date')
ax.set_ylabel('USD Price ($)')
plt.xticks(rotation = 45)
ax.legend()
plt.show();
Image for post
Image for post

Create and show a new data frame to plot everything including the buy and sell signals. This data set will eventually contain everything needed to create the final plot.

#Create a new data frame
new_df = df[period-1:]
#Show the new data frame
new_df
Image for post
Image for post

Create a function to get the buy and sell signals.

# Create a function to get the buy and sell signals
def get_signal(data):
buy_signal = [] #buy list
sell_signal = [] #sell list
for i in range(len(data['Close'])):
if data['Close'][i] > data['Upper'][i]: #Then you should sell
#print('SELL')
buy_signal.append(np.nan)
sell_signal.append(data['Close'][i])
elif data['Close'][i] < data['Lower'][i]: #Then you should buy
#print('BUY')
sell_signal.append(np.nan)
buy_signal.append(data['Close'][i])
else:
buy_signal.append(np.nan)
sell_signal.append(np.nan)
return (buy_signal, sell_signal)

Create two new columns to store the buy and sell signals.

#Create new columns for the buy and sell signals
new_df['Buy'] = get_signal(new_df)[0]
new_df['Sell'] = get_signal(new_df)[1]

Put it all together and plot all of the data.

#Plot all of the data
#Get the figure and the figure size

fig = plt.figure(figsize=(12.2,6.4)) #width = 12.2 inches and height = 6.4 inches
#Add the subplot
ax = fig.add_subplot(1,1,1) #Number of rows, cols, & index
# Get the index values of the DataFrame
x_axis = new_df.index
# Plot and shade the area between the upper band and the lower band Grey
ax.fill_between(x_axis, new_df['Upper'], new_df['Lower'], color='grey')
# Plot the Closing Price and Moving Average
ax.plot(x_axis, new_df['Close'], color='gold', lw=3, label = 'Close Price',alpha = 0.5)
ax.plot(x_axis, new_df['SMA'], color='blue', lw=3, label = 'Moving Average',alpha = 0.5)
ax.scatter(x_axis, new_df['Buy'] , color='green', lw=3, label = 'Buy',marker = '^', alpha = 1)
ax.scatter(x_axis, new_df['Sell'] , color='red', lw=3, label = 'Sell',marker = 'v', alpha = 1)
# Set the Title & Show the Image
ax.set_title('Bollinger Band For Tesla')
ax.set_xlabel('Date')
ax.set_ylabel('USD Price ($)')
plt.xticks(rotation = 45)
ax.legend()
plt.show();
Image for post
Image for post

Analysis & Conclusion:

Image for post
Image for post

Looking at the chart above, we can see some instances where this strategy didn’t work to the fullest. If we used this strategy and bought stock in Tesla at around $48 and then sold it for a little less at about $47 between the dates April 2016 and July 2016 where the buy and sell signals told us to do so, then we would have lost money (about $1 per share). However, if we would’ve bought the stock around $42 , where one of the buy signals tells us to buy and sold where either one of the sell signals tells us to sell, then we would’ve made about $5 per share.

Similar situations can be seen between the dates July 2016 and October 2016, where the indicator initially tells us to buy the stock at a higher price than it tells us to sell, but we can also see other lower buy signals that we would’ve made profit from. I also noticed that the initial buy signal wasn’t to far from the initial sell signal in price, so I wouldn’t have lost much money per share.

Interestingly, the graph shows many sell signals while rising to its peak price from January 2017 to before the start of July 2017 and not once does the strategy tell us to buy the stock until a significant drop occurs a little after July 2017 which was a good time to buy.

With this strategy it seems best to wait for a second or third buy signal before actually buying the stock as that would’ve been a more profitable strategy with little to no loss in money. Like most trading strategies, you will probably want to use other indicators with this strategy and do more testing before using it.

If you want to start an investment portfolio, then sign up with WeBull using this link, deposit $100 or more and get 2 extra FREE stocks worth up to $1600 USD! It’s free stocks that you can either sell, play with or create your own trading strategy with.

Thanks for reading this article I hope its helpful to you all! If you enjoyed this article and found it helpful please leave some claps to show your appreciation. Keep up the learning, and if you like machine learning, mathematics, computer science, programming or algorithm analysis, please visit and subscribe to my YouTube channels (randerson112358 & compsci112358 ).

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store