The Relative Strength Index (RSI), is treated as a predictive momentum indicator. It generates values between 0 and 100 based on whether the previous days closed up or down. According to http://www.investopedia.com/terms/r/rsi.asp, an RSI over 70 or below 30 means a stock is “overbought” or “oversold,” respectively.

The same article says that large surges or drops in price may create “false” buy or sell signals. It claims that RSI is best used as a “complement.”

The RSI has one parameter measuring the lookback period. It is usually set to 14 trading days.

This notebook defines formulas which add an RSI column. Some strategies will use these formulas to define bull and bear signals.

Contents

# Import Packages¶

```
import numpy as np
import pandas as pd
import cPickle as pickle
shortUniverse = True
```

# Load Pickle Data¶

First, we’ll load the pickle we developed in the previous section. The new prices dataframe is given a new name to reflect edits made during this notebook.

```
if shortUniverse:
with open('intermediaries/prices.p', 'rb') as handle:
prices = pickle.load(handle)
else:
with open('intermediaries/prices-full.p', 'rb') as handle:
prices = pickle.load(handle)
```

# Development of RSI¶

The following formula adds an RSI column to a price dataframe. The calculation steps are as follows.

- Add column ‘
`U`

‘, giving the upwards daily dollar change in the stock. Is zero for downward days. - Add column ‘
`D`

‘, giving the downwards daily dollar change in the stock. Is zero for upward days. - Add columns ‘
`U_EMA`

‘ and ‘`D_EMA`

‘, which provide exponential smoothing of ‘`U`

‘ and ‘`D`

‘, respectively, with parameter 1/14 as the alpha value. - If ‘
`D_EMA`

‘ == 0, then set ‘`D_EMA`

‘ to an aribtrarily low value (i.e. .01). - Add column ‘RS’ which is equal to ‘
`U_EMA`

‘ divided by ‘`D_EMA`

‘. - Add column ‘RSI’ which is equal to
`100 - (100/(1 + RS))`

. - Remove all new columns except for ‘RSI’.

```
def add_RSI(df, lag=14):
df['U'] = df['close'] - df.groupby('symbol')['close'].shift(1)
df['D'] = -1 * df['U']
df.loc[df['U'] < 0, 'U'] = 0
df.loc[df['D'] < 0, 'D'] = 0
df['U_EMA'] = pd.ewma(df['U'], span=14, min_periods=14, adjust=True)
df['D_EMA'] = pd.ewma(df['D'], span=14, min_periods=14, adjust=True)
df.loc[df['D_EMA'] == 0, 'D_EMA'] = .01
df['RS'] = df['U_EMA'] / df['D_EMA']
df['RSI'] = 100 - (100 / (1 + df['RS']))
df = df.drop(['U', 'D', 'U_EMA', 'D_EMA', 'RS'], axis=1)
return df
```

```
prices = add_RSI(prices)
```

# Output Example¶

The first 11th through 20th observations are displayed below.

```
prices.head(20).tail(10)
```

# Save Formulas¶

No new price file is created. However, `add_RSI`

have been added to the separate document “`helper_functions.py`

” which can be imported into future tests.

# Potential Extensions¶

This space is reserved.