4

I would like to calculate RSI 14 in line with the tradingview chart.

According to there wiki this should be the solution: https://www.tradingview.com/wiki/Talk:Relative_Strength_Index_(RSI)

I implemented this is in a object called RSI: Calling within object RSI:

    self.df['rsi1'] = self.calculate_RSI_method_1(self.df, period=self.period)

Implementation of the code the calculation:

    def calculate_RSI_method_1(self, ohlc: pd.DataFrame, period: int = 14) -> pd.Series:

        delta = ohlc["close"].diff()

        ohlc['up'] = delta.copy()
        ohlc['down'] = delta.copy()

        ohlc['up'] = pd.to_numeric(ohlc['up'])
        ohlc['down'] = pd.to_numeric(ohlc['down'])

        ohlc['up'][ohlc['up'] < 0] = 0
        ohlc['down'][ohlc['down'] > 0] = 0

        # This one below is not correct, but why?
        ohlc['_gain'] = ohlc['up'].ewm(com=(period - 1), min_periods=period).mean()
        ohlc['_loss'] = ohlc['down'].abs().ewm(com=(period - 1), min_periods=period).mean()

        ohlc['RS`'] = ohlc['_gain']/ohlc['_loss']

        ohlc['rsi'] = pd.Series(100 - (100 / (1 + ohlc['RS`'])))

        self.currentvalue = round(self.df['rsi'].iloc[-1], 8)
        print (self.currentvalue)

        self.exportspreadsheetfordebugging(ohlc, 'calculate_RSI_method_1', self.symbol)

I tested several other solution like e.g but non return a good value:

https://github.com/peerchemist/finta https://gist.github.com/jmoz/1f93b264650376131ed65875782df386

Therefore I created a unittest based on : https://school.stockcharts.com/doku.php?id=technical_indicators:relative_strength_index_rsi

I created an input file: (See excel image below) and a output file: (See excel image below)

Running the unittest (unittest code not included here) should result in but is only checking the last value.

if result == 37.77295211:
    log.info("Unit test 001 - PASSED")
    return True
else:
    log.error("Unit test 001 - NOT PASSED")
    return False 

But again I cannot pass the test. I checked all values by help with excel.

enter image description here

So now i'm a little bit lost.

If I'm following this question: Calculate RSI indicator from pandas DataFrame? But this will not give any value in the gain.

  • a) How should the calculation be in order to align the unittest?
  • b) How should the calculation be in order to align with tradingview?
Justme
  • 211
  • 2
  • 9

3 Answers3

5

Here is a Python implementation of the current RSI indicator version in TradingView:

https://github.com/lukaszbinden/rsi_tradingview/blob/main/rsi.py

Asclepius
  • 57,944
  • 17
  • 167
  • 143
Lukas Z.
  • 335
  • 4
  • 5
  • 1
    Yes, this works very nicely provided you run the script on a sufficiently large dataset. (You will need to provide at least 100 data points before the calculated RSI and the TradingView RSI will correlate.) Thank you for posting. – Lucas Schwartz Jun 10 '22 at 11:46
4

I had same issue in calculating RSI and the result was different from TradingView, I have found RSI Step 2 formula described in InvestoPedia and I changed the code as below:

N = 14
close_price0 = float(klines[0][4])
gain_avg0 = loss_avg0 = close_price0
for kline in klines[1:]:
    close_price = float(kline[4])
    if close_price > close_price0:
        gain = close_price - close_price0
        loss = 0
    else:
        gain = 0
        loss = close_price0 - close_price
    close_price0 = close_price
    gain_avg = (gain_avg0 * (N - 1) + gain) / N
    loss_avg = (loss_avg0 * (N - 1) + loss) / N
    rsi = 100 - 100 / (1 + gain_avg / loss_avg)
    gain_avg0 = gain_avg
    loss_avg0 = loss_avg

N is the number of period for calculating RSI (by default = 14) the code is put in a loop to calculate all RSI values for a series.

Asclepius
  • 57,944
  • 17
  • 167
  • 143
Hamed
  • 61
  • 4
  • This is classic Wilder’s Smoothing Method and it is not the same that trading view is using. – Hamboy75 Sep 08 '21 at 16:57
  • https://goodcalculators.com/rsi-calculator/ here you can find wilder's method and you will see that it doesnt match with trading view rsi – Hamboy75 Sep 08 '21 at 17:01
  • I had the same problem - I was trying to validate Trading Views standard RSI against a C# charting tool I am creating. Using your code above, I was able to exactly reconstruct Trading Views RSI with 100% accuracy. You sir are a steely eyed missile man. – Code Warrior Nov 15 '21 at 10:43
2

For those who are experience the same.

My raw data contained ticks where the volume is zero. Filtering this OLHCV rows will directly give the good results.

Justme
  • 211
  • 2
  • 9