It looks like you're new here. If you want to get involved, click one of these buttons!
def RSI(DF):
n = 14
"function to calculate RSI"
delta = DF["close"].diff().dropna()
u = delta * 0
d = u.copy()
u[delta > 0] = delta[delta > 0]
d[delta < 0] = -delta[delta < 0]
u[u.index[n-1]] = np.mean( u[:n]) # first value is average of gains
u = u.drop(u.index[:(n-1)])
d[d.index[n-1]] = np.mean( d[:n]) # first value is average of losses
d = d.drop(d.index[:(n-1)])
rs = u.ewm(com=n,min_periods=n).mean()/d.ewm(com=n,min_periods=n).mean()
rsi = 100 - 100 / (1+rs)
return rsi
You can refer to @arkochhar indicator library in github.
https://github.com/arkochhar/Technical-Indicators/tree/master/indicator
It does not match 100% but very close to the actual which is fine I think. I have been using it. My modified version of the RSI function is below.
You can refer to the function that I use. It calculates the RSI for the data frame and also returns the RSI of the current candle.
def calculate_rsi(df, base="close", period=14, record_location=-1):
delta = df[base].diff()
up, down = delta.copy(), delta.copy()
up[up < 0] = 0
down[down > 0] = 0
rUp = up.ewm(com=period - 1, adjust=False).mean()
rDown = down.ewm(com=period - 1, adjust=False).mean().abs()
df['rsi'] = round(100 - 100 / (1 + rUp / rDown), 2)
df['rsi'].fillna(0, inplace=True)
df ['rsi'] = df['rsi'].astype(int) # Convert RSI column to integer
rsi = df['rsi'].iloc[record_location]
return df, rsi