I am attempting to use an oscillator (relative strength index) to know when to buy and sell a stock. I created a dataframe for RSI and closing price. I am able to plot both but I want to also add to my plot when the RSI hits a buy and sell signal. So in order to do this I need to create a comparison of my RSI column when the RSI drops below 25, which will trigger my buy signal and a sell signal for my RSI if it goes over 85. My issue is that I cannot figure out pull my closing price column on the date when my RSI column drops below 25 until the date when my RSI column rises above 85. All I get is Nan in my new dataframe column.
#rsi
import pandas
import warnings
import pandas_datareader.data as web
import datetime
import matplotlib.pyplot as plt
warnings.filterwarnings('ignore')
# Window length for moving average
window_length = 14
# Dates
start = datetime.datetime(2016, 1, 5)
end = datetime.datetime(2016, 12, 31)
# Get data
data = web.DataReader('FB', 'morningstar', start, end)
df= pd.DataFrame(data)
# Get just the close
close = data['Close']
# Get the difference in price from previous step
delta = close.diff()
# Get rid of the first row, which is NaN since it did not have a previous
# row to calculate the differences
delta = delta[1:]
# Make the positive gains (up) and negative gains (down) Series
up, down = delta.copy(), delta.copy()
up[up < 0] = 0
down[down > 0] = 0
# Calculate the EWMA
roll_up1 = pandas.stats.moments.ewma(up, window_length)
roll_down1 = pandas.stats.moments.ewma(down.abs(), window_length)
# Calculate the RSI based on EWMA
RS1 = roll_up1 / roll_down1
RSI1 = 100.0 - (100.0 / (1.0 + RS1))
# Calculate the SMA
roll_up2 = pandas.rolling_mean(up, window_length)
roll_down2 = pandas.rolling_mean(down.abs(), window_length)
# Calculate the RSI based on SMA
RS2 = roll_up2 / roll_down2
RSI2 = 100.0 - (100.0 / (1.0 + RS2))
df['RSI2']=RSI2
df=df.dropna(axis=0)
df['RSI2']=df['RSI2'].astype(float)
df['BUY']=df['Close'][df['RSI2'] < 25]
print (df['BUY'])
# Compare graphically
plt.figure()
df['BUY'].plot(title='FB',figsize = (20, 5))
plt.show()
RSI1.plot(title='Relative Strength Index',figsize = (20, 5))
RSI2.plot(figsize = (20, 5))
plt.legend(['RSI via EWMA', 'RSI via SMA'])
plt.show()