Needed Help with RSI and StochRSI Code

kaushalmalkan
Hello everyone,

Here's my code of calculating RSI but it's not accurate to Zerodha Kite. Can anyone suggest changes to make it more accurate?

Also, I would be really thankful if someone can even help me making it to StochRSI as per investing.com

Code:
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
  • ganeshv02
    ganeshv02 edited July 2020
    Hi @kaushalmalkan,

    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
Sign In or Register to comment.