Investing with Python: Bollinger Bands

Download the accompanying IPython Notebook for this Tutorial from Github. 

 

Python streamlines tasks requiring multiple steps in a single block of code. For this reason, it is a great tool for querying and performing analysis on data.

Last post, we outlined steps for calculating MACD Signal Line & Centerline Crossovers.

In this post, we introduce a new technical indicator,  Bollinger Bands.

Bollinger Bands

Developed by John Bollinger, Bollinger Bands® are volatility bands placed above and below a moving average. Volatility is based on the standard deviation, which changes as volatility increases and decreases. The bands automatically widen when volatility increases and narrow when volatility decreases. This dynamic nature of Bollinger Bands also means they can be used on different securities with the standard settings. For signals, Bollinger Bands can be used to identify Tops and Bottoms or to determine the strength of the trend.

Bollinger Bands reflect direction with the 20-period SMA and volatility with the upper/lower bands. As such, they can be used to determine if prices are relatively high or low. According to Bollinger, the bands should contain 88-89% of price action, which makes a move outside the bands significant. Technically, prices are relatively high when above the upper band and relatively low when below the lower band. However, relatively high should not be regarded as bearish or as a sell signal. Likewise, relatively low should not be considered bullish or as a buy signal. Prices are high or low for a reason. As with other indicators, Bollinger Bands are not meant to be used as a stand alone tool. Chartists should combine Bollinger Bands with basic trend analysis and other indicators for confirmation.

Bollinger Bands are calculated as follows:

Middle Band = 20 day moving average
Upper Band = 20 day moving average + (20 Day standard deviation of price x 2) 
Lower Band = 20 day moving average - (20 Day standard deviation of price x 2)

Bollinger Bands consist of a middle band with two outer bands. The middle band is a simple moving average that is usually set at 20 periods. A simple moving average is used because the standard deviation formula also uses a simple moving average. The look-back period for the standard deviation is the same as for the simple moving average. The outer bands are usually set 2 standard deviations above and below the middle band.

Let’s use Python to compute Bollinger Bands.

1. Start with the 30 Day Moving Average Tutorial code.

import pandas as pd
import pandas.io.data as web
%matplotlib inline
import matplotlib.pyplot as plt

stocks = ['FB']
def get_stock(stock, start, end):
     return web.get_data_yahoo(stock, start, end)['Adj Close']
px = pd.DataFrame({n: get_px(n, '1/1/2016', '12/31/2016') for n in names})
px

2. Compute the 20 Day Moving Average.

px['20 ma'] = pd.stats.moments.rolling_mean(px['FB'],20)

3. Compute 20 Day Standard Deviation. 

px['20 sd'] = pd.stats.moments.rolling_std(px['FB'],20)

4. Create Upper Band.

px['Upper Band'] = px['20 ma'] + (px['20 sd']*2)

5. Create Lower Band.

px['Lower Band'] = px['20 ma'] - (px['20 sd']*2)

6. Plot Bollinger Bands.

px.plot(y=['FB','20 ma', 'Upper Band', 'Lower Band'], title='Bollinger Bands')

There you have it! We created our Bollinger Bands. Here’s the full code:

import pandas as pd
import pandas.io.data as web
%matplotlib inline
import matplotlib.pyplot as plt

stocks = ['FB']
def get_stock(stock, start, end):
     return web.get_data_yahoo(stock, start, end)['Adj Close']
px = pd.DataFrame({n: get_px(n, '1/1/2016', '12/31/2016') for n in names})
px['20 ma'] = pd.stats.moments.rolling_mean(px['FB'],20)
px['20 sd'] = pd.stats.moments.rolling_std(px['FB'],20)
px['Upper Band'] = px['20 ma'] + (px['20 sd']*2)
px['Lower Band'] = px['20 ma'] - (px['20 sd']*2)
px.plot(y=['FB','20 ma', 'Upper Band', 'Lower Band'], title='Bollinger Bands')