Skip to content

Instantly share code, notes, and snippets.

@26dhruv
Forked from jmoz/rsi.py
Created June 4, 2022 19:34
Show Gist options
  • Save 26dhruv/b2fe9652dd0412d2fe4b96e29e1455e7 to your computer and use it in GitHub Desktop.
Save 26dhruv/b2fe9652dd0412d2fe4b96e29e1455e7 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")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment