I developed below code for the RSI, however, the result is not matching with the Zerodha charts. Kindly help me correct the code:
import numpy as np
def rsi(prices, n=14):
diff = np.diff(prices)
gains = np.maximum(diff, 0)
losses = -np.minimum(diff, 0)
avg_gains = np.convolve(gains, np.ones(n), "valid")
avg_loss = np.convolve(losses, np.ones(n), "valid")
rs = avg_gains/avg_loss
rsi = 100 - (100 / (1 + rs))
return rsi
SBIN_CLOSING = np.array([563.05, 563.75, 561.50, 558.95, 559.95, 560.35, 564.45, 568.60, 564.75, 571.75, 594.70, 608.25, 608.45, 611.70, 614.15, 614.25, 612.40, 619.85, 623.65, 648.25])
rsi(SBIN_CLOSING)
I wrote below python code which matches the RSI of the Zerodha charts. Hope this code would help other community members as well. Suggestions are welcomed.
import numpy as np
def rsi(prices, n=14):
"""
Returns a numpy array containing Relative Strength Index from nth Day (by default n=14)
"""
diff = np.diff(prices) # Price change
gains = np.maximum(diff, 0) # If gain, returns the amount of gain, 0 otherwise
losses = -np.minimum(diff, 0) # If loss, returns the absolute amount of loss, 0 otherwise
init_avg_gain = np.sum(gains[:n])/n # Average gain on the nth day
init_avg_loss = np.sum(losses[:n])/n # Average loss on the n4th day
avg_gains = smoothing_avg(init_avg_gain, gains, n) # Numpy array containing average gains from the nth day
avg_losses = smoothing_avg(init_avg_loss, losses, n) # Numpy array containing average losses from the nth day
rs = avg_gains/avg_losses # Relative Strength
rsi = 100 - (100 / (1 + rs)) # Relative Strength Index
return rsi #Returning Relative Strength Index
def smoothing_avg(init_value, value, n):
"""
Returns a numpy array containing smoothing average from nth Day
"""
avg = np.zeros(len(value)-n+1) # Numpy array of one-dimentional null matrix
avg[0] = init_value # Setting nth days average value as the first value of the null matrix
for element in range(1,len(avg)): # Looping over the null entries of the null matrix
avg[element] = ((avg[element-1]*(n-1))+value[n+element-1])/n # Calculating smoothing average
return avg # Returning smoothing average