# Algorithmic Trading Using Bollinger Bands & Python

Use Bollinger Bands to Determine When To Buy & Sell Stock

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

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.

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 librariesimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltplt.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 datafrom google.colab import files # Use to load data on Google Colabfiles.upload() # Use to load data on Google Colab`

Store the data.

`#Store the datadf = pd.read_csv('TSLA.csv')#Set the date as the indexdf = df.set_index(pd.DatetimeIndex(df['Date'].values))#Show the datadf`

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 Averagedf['SMA'] = df['Close'].rolling(window=period).mean()# Get the standard deviationdf['STD'] = df['Close'].rolling(window=period).std() #Calculate the Upper Bollinger Banddf['Upper'] = df['SMA'] + (df['STD'] * 2)#Calculate the Lower Bollinger Banddf['Lower'] = df['SMA'] - (df['STD'] * 2)#Create a list of columns to keepcolumn_list = ['Close', 'SMA', 'Upper', 'Lower']df[column_list].plot(figsize=(12.2,6.4)) #Plot the dataplt.title('Bollinger Band for Tesla')plt.ylabel('USD Price (\$)')plt.show();`

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 sizefig = plt.figure(figsize=(12.2,6.4)) #width = 12.2 inches and height = 6.4 inches#Add the subplotax = fig.add_subplot(1,1,1) #Number of rows, cols, & index# Get the index values of the DataFramex_axis = df.index# Plot and shade the area between the upper band and the lower band Greyax.fill_between(x_axis, df['Upper'], df['Lower'], color='grey')# Plot the Closing Price and Moving Averageax.plot(x_axis, df['Close'], color='gold', lw=3, label = 'Close Price') #lw = line widthax.plot(x_axis, df['SMA'], color='blue', lw=3, label = 'Simple Moving Average')# Set the Title & Show the Imageax.set_title('Bollinger Band For Tesla')ax.set_xlabel('Date')ax.set_ylabel('USD Price (\$)')plt.xticks(rotation = 45)ax.legend()plt.show();`

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 framenew_df = df[period-1:]#Show the new data framenew_df`

Create a function to get the buy and sell signals.

`# Create a function to get the buy and sell signalsdef get_signal(data):  buy_signal = [] #buy list  sell_signal = [] #sell listfor 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 signalsnew_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 sizefig = plt.figure(figsize=(12.2,6.4)) #width = 12.2 inches and height = 6.4 inches#Add the subplotax = fig.add_subplot(1,1,1) #Number of rows, cols, & index# Get the index values of the DataFramex_axis = new_df.index# Plot and shade the area between the upper band and the lower band Greyax.fill_between(x_axis, new_df['Upper'], new_df['Lower'], color='grey')# Plot the Closing Price and Moving Averageax.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 Imageax.set_title('Bollinger Band For Tesla')ax.set_xlabel('Date')ax.set_ylabel('USD Price (\$)')plt.xticks(rotation = 45)ax.legend()plt.show();`

# Analysis & Conclusion:

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.