RSI definition (calculation in Python)

Greetings all,

I’m trying to understand how RSI is calculated in P123. What I do myself is:

returns = ticker.returns[‘close’].iloc[::-1]
close_delta = returns.diff()

Make two series: one for lower closes and one for higher closes

up = close_delta.clip(lower=0)
down = -1 * close_delta.clip(upper=0)

Use simple moving average

ma_up = up.rolling(window=periods, min_periods=200).mean()
ma_down = down.rolling(window=periods, min_periods=200).mean()

rs = ma_up / ma_down
rsi = 100 - (100 / (1 + rs))
rsi = rsi.iloc[::-1]
rsi = rsi[0]

The data I use is adjusted for dividends. For AMGN my rsi(200) is equal to 47.6. However, in P123 I get 53.39. That’s quite a difference. Where could this difference be coming from?

See the dividend adjusted prices attached.

AMPG prices.xlsx (91.2 KB)

Smoothing needs to be applied for both the average gain and the average loss series.

The average gain and average loss series are initialized using an average of the first period samples. Then 100 bars of gain and loss are used for smoothing. So for RSI(200), you would use 301 bars most of the time and as few as 201 bars. (Only fewer than 100 are used if a stock doesn’t have enough price history yet.)

Check the spreadsheet linked on this page to see how this smoothing would be done iteratively: Relative Strength Index Spreadsheet

Hi Aschiff,

When I look at the definition that P123 uses, I see no smoothing is mentioned. See https://www.portfolio123.com/doc/doc_detail.jsp?factor=RSI

RSI = 100 - ( 100 / (1 + RS))
RS = (average of N up closes) / (average of N down closes)
N = period in bars (typically 14)

The documentation is wrong and will be updated. Thank you for pointing it out.