Python Tutorial: ROC

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 Tutorial, we outlined steps for calculating Relative Strength Index (RSI).
In this Tutorial, we introduce a new technical indicator, the Rate of Change (ROC).

‘The only thing constant is change’

The Rate of Change (ROC) is a technical indicator of momentum that measures the percentage change in price between the current price and the price n periods in the past.

The Rate of Change (ROC) is calculated as follows:

ROC = ((Most recent closing price - Closing price n periods ago) / Closing price n periods ago) x 100

The Rate of Change (ROC) is classed as a momentum indicator because it measures strength of price momentum. For example, if a stock’s price at the close of trading today is 10, and the closing price five trading days prior was 7, then the Rate of Change (ROC) over that time frame is approximately 43, calculated as (10 – 7 / 7) x 100 = 42.85.

 Positive values indicate upward buying pressure or momentum, while negative values below zero indicate selling pressure or downward momentum. Increasing values in either direction, positive or negative, indicate increasing momentum, and decreasing values indicate waning momentum.

The Rate of Change (ROC) is also sometimes used to indicate overbought or oversold conditions for a security. Positive values that are greater than 30 are generally interpreted as indicating overbought conditions, while negative values lower than negative 30 indicate oversold conditions.

 Let’s use Python to compute the Rate of Change (ROC).

1.) Import modules.

import pandas as pd
import numpy as np
from pandas_datareader import data as web
import matplotlib.pyplot as plt
%matplotlib inline

2.) Define function for querying daily close.

def get_stock(stock,start,end):
     return web.DataReader(stock,'google',start,end)['Close']

3.) Define function for Rate of Change (ROC).

def ROC(df, n):  
    M = df.diff(n - 1)  
    N = df.shift(n - 1)  
    ROC = pd.Series(((M / N) * 100), name = 'ROC_' + str(n))   
    return ROC

How does the ROC function work?

3.a.) Function calculates difference in most recent closing price from closing price n periods ago. Sets the value to variable M.
#M = df.diff(n - 1)

3.b.) Function calculates closing price n periods ago. Sets the value to variable N.

#N = df.shift(n - 1)

3.c.) Function creates series called ROC that is ((M/N) * 100)

#ROC = pd.Series(((M / N) * 100), name = 'ROC_' + str(n))

3.d.) Function returns ROC

#return ROC

4.) Query daily close for ‘FB’ during 2016.

df = pd.DataFrame(get_stock('FB', '1/1/2016', '12/31/2016'))

5.) Run daily close through ROC function. Save series to new column in dataframe.

df['ROC'] = ROC(df['Close'], 12)
df.tail()

6.) Plot daily close and ROC.

df.plot(y=['Close'])
df.plot(y=['ROC'])

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

import pandas as pd
import numpy as np
from pandas_datareader import data as web
import matplotlib.pyplot as plt
%matplotlib inline

def get_stock(stock,start,end):
     return web.DataReader(stock,'google',start,end)['Close']
    
def ROC(df, n):  
    M = df.diff(n - 1)  
    N = df.shift(n - 1)  
    ROC = pd.Series(((M / N) * 100), name = 'ROC_' + str(n))   
    return ROC
    
df = pd.DataFrame(get_stock('FB', '1/1/2016', '12/31/2016'))
df['ROC'] = ROC(df['Close'], 12)
df.tail()

Python Tutorial: 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')