I struggle to manually calculate RSI indicator via python.
The formula is explained here and here.
I tried many answers here. This and this give me the same result but different from the value displayed on TradingView. Below is my implementation of these answers.
#price change from Sep 17 to 15 days ago
delta = pd.Series([1.5, -0.9, 1.6, -1.8, -1.9, -0.3, 0.3, -1.1, 0.7, 0.7, 0.3, -0.9, 2.0, 1.2, -1.9, ])
delta = delta[::-1] #reverse result Sep 3 -> Sep17 list
period = 14 #calculate RSI 14
gain = delta.clip(lower=0)
loss = delta.clip(upper=0).abs()
gain_avg = gain.ewm(alpha=1 / period).mean()
loss_avg = loss.ewm(alpha=1 / period).mean()
rsi = np.where(gain_avg == 0, 0, np.where(loss_avg == 0, 100, 100 - (100 / (1 + gain_avg / loss_avg))))
Result
array([ 0. , 40.48192897, 65.52871773, 54.42860064, 57.04085224,
62.44962094, 66.93315247, 55.68193396, 57.76701673, 54.98126804,
41.37316127, 33.03207836, 43.86550257, 39.95053047, 48.2417529 ])
The RSI on Sep 17 calculated is 48.2
while the one show on TradingView is 51.51
(source)
I also tried some manual calculations which results 69.13
:
def Avg_EMA_cal(alpha_, t, gain_or_loss):
if t == 0:
return gain_or_loss[t]
return alpha_ * gain_or_loss[t] + (1 - alpha_) * Avg_EMA_cal(alpha_, t - 1, gain_or_loss)
alpha = 1 / period
avg_up_ema = Avg_EMA_cal(alpha, N, gain)
avg_down_ema = Avg_EMA_cal(alpha, N, loss)
rs_ema = avg_up_ema / avg_down_ema
rsi_ema = 100 - 100 / (1 + rs_ema)
These are really making me dizzy, both the formula and numerical precision.