Skip to content

Instantly share code, notes, and snippets.

@ultragtx
Forked from so1tsuda/RSI_and_StochRSI.py
Created November 17, 2018 18:30
Show Gist options
  • Star 31 You must be signed in to star a gist
  • Fork 14 You must be signed in to fork a gist
  • Save ultragtx/6831eb04dfe9e6ff50d0f334bdcb847d to your computer and use it in GitHub Desktop.
Save ultragtx/6831eb04dfe9e6ff50d0f334bdcb847d to your computer and use it in GitHub Desktop.
Functions that calculate RSI and StochRSI which give the same value as Trading View. I wrote these functions as RSI and StochRSI functions from TA-Lib give different values as TV.
# calculating RSI (gives the same values as TradingView)
# https://stackoverflow.com/questions/20526414/relative-strength-index-in-python-pandas
def RSI(series, period=14):
delta = series.diff().dropna()
ups = delta * 0
downs = ups.copy()
ups[delta > 0] = delta[delta > 0]
downs[delta < 0] = -delta[delta < 0]
ups[ups.index[period-1]] = np.mean( ups[:period] ) #first value is sum of avg gains
ups = ups.drop(ups.index[:(period-1)])
downs[downs.index[period-1]] = np.mean( downs[:period] ) #first value is sum of avg losses
downs = downs.drop(downs.index[:(period-1)])
rs = ups.ewm(com=period-1,min_periods=0,adjust=False,ignore_na=False).mean() / \
downs.ewm(com=period-1,min_periods=0,adjust=False,ignore_na=False).mean()
return 100 - 100 / (1 + rs)
# calculating Stoch RSI (gives the same values as TradingView)
# https://www.tradingview.com/wiki/Stochastic_RSI_(STOCH_RSI)
def StochRSI(series, period=14, smoothK=3, smoothD=3):
# Calculate RSI
delta = series.diff().dropna()
ups = delta * 0
downs = ups.copy()
ups[delta > 0] = delta[delta > 0]
downs[delta < 0] = -delta[delta < 0]
ups[ups.index[period-1]] = np.mean( ups[:period] ) #first value is sum of avg gains
ups = ups.drop(ups.index[:(period-1)])
downs[downs.index[period-1]] = np.mean( downs[:period] ) #first value is sum of avg losses
downs = downs.drop(downs.index[:(period-1)])
rs = ups.ewm(com=period-1,min_periods=0,adjust=False,ignore_na=False).mean() / \
downs.ewm(com=period-1,min_periods=0,adjust=False,ignore_na=False).mean()
rsi = 100 - 100 / (1 + rs)
# Calculate StochRSI
stochrsi = (rsi - rsi.rolling(period).min()) / (rsi.rolling(period).max() - rsi.rolling(period).min())
stochrsi_K = stochrsi.rolling(smoothK).mean()
stochrsi_D = stochrsi_K.rolling(smoothD).mean()
return stochrsi, stochrsi_K, stochrsi_D
# calculating Stoch RSI
# -- Same as the above function but uses EMA, not SMA
def StochRSI_EMA(series, period=14, smoothK=3, smoothD=3):
# Calculate RSI
delta = series.diff().dropna()
ups = delta * 0
downs = ups.copy()
ups[delta > 0] = delta[delta > 0]
downs[delta < 0] = -delta[delta < 0]
ups[ups.index[period-1]] = np.mean( ups[:period] ) #first value is sum of avg gains
ups = ups.drop(ups.index[:(period-1)])
downs[downs.index[period-1]] = np.mean( downs[:period] ) #first value is sum of avg losses
downs = downs.drop(downs.index[:(period-1)])
rs = ups.ewm(com=period-1,min_periods=0,adjust=False,ignore_na=False).mean() / \
downs.ewm(com=period-1,min_periods=0,adjust=False,ignore_na=False).mean()
rsi = 100 - 100 / (1 + rs)
# Calculate StochRSI
stochrsi = (rsi - rsi.rolling(period).min()) / (rsi.rolling(period).max() - rsi.rolling(period).min())
stochrsi_K = stochrsi.ewm(span=smoothK).mean()
stochrsi_D = stochrsi_K.ewm(span=smoothD).mean()
return stochrsi, stochrsi_K, stochrsi_D
@justmeonthegit
Copy link

Wauw, finnaly somebody who is actually giving the correct result. Thxs !

@ChessNomad
Copy link

Thanks a lot! :D

@rushiai
Copy link

rushiai commented Dec 17, 2020

Not showing correct result !!!

@justmeonthegit
Copy link

@rushiai, can you give a unittest for this ?

@iVyperion
Copy link

Are there any packages needed for this?
and is there any specific way the prices need to be passed?, can you give an example.
thanks for making this.

@JustinLindsayChapman
Copy link

I have tried to implement this and experience multiple problems, I have imported pandas and numpy are there any other dependencies that I am missing?

@justmeonthegit
Copy link

Which error do you get ?

@justmeonthegit
Copy link

I looked into my code. Only numpy is needed. (import numpy as np) You have to pass a series and not a pd.DataFrame. A series is only 1 column from a df.

@JustinLindsayChapman
Copy link

JustinLindsayChapman commented Jun 10, 2021

@justmeonthegit, you say only numpy but as I understand it dropna() is a pandas function. I can only get it to work by doing this
delta = pd.Series(numpy.diff(series)).dropna() otherwise the line of code you originally had does not work. delta = series.diff().dropna()
image
check the screenshot of how vastly different the numbers are on the binance 1m chart and the values coming from this function with 1m closes plugged in. Not only that the numbers jump wildly from 80 to 50 to 10 back to 100 within a couple of closes. Maybe I am using it incorrectly, any insight would be appreciated.

@justmeonthegit
Copy link

If you have trouble to the first line of code ( delta = series.diff().dropna()) you are passing a wrong type of parameter to the function as it describes here.
The difference in calculation can be from a lot of things. Just check if all settings on tradingview are the same, and align with your code.

@JustinLindsayChapman
Copy link

This is how I am calling the function
'r, t_1, t_2 = StochRSI(numpy.array(chistory[sym]))'
Where chistory contains the closing prices from the 1m chart for whatever ticker symbol is being iterated.
the I will put the .diff().dropna() line back in and run a breakpoint to see if I can get some more info.

@JustinLindsayChapman
Copy link

JustinLindsayChapman commented Jun 10, 2021

Further everything I have read about dropna() says it is a pandas function, pandas is built on numpy but the functions are specific to pandas

@JustinLindsayChapman
Copy link

This works for that line of code

'r, t_1, t_2 = StochRSI(pd.DataFrame(numpy.array(chistory[sym])))' also works as a pd.Series()

@JustinLindsayChapman
Copy link

The numbers jump all over the shop. Check this out.
image

@JustinLindsayChapman
Copy link

Here are the settings for the chart I am comparing it to.
image

@justmeonthegit
Copy link

Did you remove from input: all rows with timestamps who do not have any olhvc value ?

@JustinLindsayChapman
Copy link

Yes, I am giving only the closing values for the last 120 periods (minutes in this case) I then append the current value every time the function is called.
This is a screenshot of the data that is being fed to the stochastic rsi function.
image

@jhaanuj2108
Copy link

What should we pass in the series? The OHLC data or just open data?

@abdrakhmanovi
Copy link

What should we pass in the series? The OHLC data or just open data?

You need to pass closing series (OHLC 'Close')

@iarri
Copy link

iarri commented Feb 23, 2022

I was getting "NaN" as the output when passing in a list of numbers into the StochRSI function until I added the 'min_periods=0' argument to the 'rolling' functions at the bottom. Did anyone else have this problem?

@cryptoliciousdev
Copy link

after careful review of ku and binance api candle data i noticed trading view close values , for btc, are 100 to 200 off from both exchange API candle closes vs what TV charts say for the same UTC candles close price....manipulation to give edge against us and make the indicators relying on close values wrong or make the charts give basic traders the wrong idea? ...

@aldefrawy
Copy link

You are awesome , this the only code that i had found similar to Trading view.
Thanks

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