Skip to content

Instantly share code, notes, and snippets.

@jmoz
Created September 27, 2019 07:41
Show Gist options
  • Save jmoz/1f93b264650376131ed65875782df386 to your computer and use it in GitHub Desktop.
Save jmoz/1f93b264650376131ed65875782df386 to your computer and use it in GitHub Desktop.
RSI calculation to match Tradingview
import pandas as pd
def rsi(ohlc: pd.DataFrame, period: int = 14) -> pd.Series:
"""See source https://github.com/peerchemist/finta
and fix https://www.tradingview.com/wiki/Talk:Relative_Strength_Index_(RSI)
Relative Strength Index (RSI) is a momentum oscillator that measures the speed and change of price movements.
RSI oscillates between zero and 100. Traditionally, and according to Wilder, RSI is considered overbought when above 70 and oversold when below 30.
Signals can also be generated by looking for divergences, failure swings and centerline crossovers.
RSI can also be used to identify the general trend."""
delta = ohlc["close"].diff()
up, down = delta.copy(), delta.copy()
up[up < 0] = 0
down[down > 0] = 0
_gain = up.ewm(com=(period - 1), min_periods=period).mean()
_loss = down.abs().ewm(com=(period - 1), min_periods=period).mean()
RS = _gain / _loss
return pd.Series(100 - (100 / (1 + RS)), name="RSI")
@lukaszbinden
Copy link

here is an implementation in Python that is equivalent to the current one in TradingView. Happy trading.

https://github.com/lukaszbinden/rsi_tradingview

@Mablung
Copy link

Mablung commented Apr 30, 2021

here is an implementation in Python that is equivalent to the current one in TradingView. Happy trading.

https://github.com/lukaszbinden/rsi_tradingview

Hello. I just want to know value of rsi. Can i do this by using this?

@johanekb
Copy link

here is an implementation in Python that is equivalent to the current one in TradingView. Happy trading.

https://github.com/lukaszbinden/rsi_tradingview

I implemented your implemenation with data from yahoo finance. The vast majority of them work, But I found that they differ on AAPL, MSFT and WMT. Do you know why this is?

@olliebakhtiari
Copy link

@lukaszbinden many thanks chief

@brandonros
Copy link

brandonros commented Aug 7, 2022

pine_sma(x, y) =>
    sum = 0.0
    for i = 0 to y - 1
        sum := sum + x[i] / y
    sum
pine_rma(src, length) =>
  alpha = 1/length
  sum = 0.0
  sum := na(sum[1]) ? 
    pine_sma(src, length) : 
    alpha * src + (1 - alpha) * nz(sum[1])
  sum
pine_rsi(x, y) =>
    u = math.max(x - x[1], 0) // upward ta.change
    d = math.max(x[1] - x, 0) // downward ta.change
    rs = pine_rma(u, y) / pine_rma(d, y)
    res = 100 - 100 / (1 + rs)
    res

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment