2

我想根据交易视图图表计算 RSI 14。

根据那里的wiki,这应该是解决方案: https://www.tradingview.com/wiki/Talk:Relative_Strength_Index_(RSI)

我在一个名为 RSI 的对象中实现了这一点:在对象 RSI 内调用:

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

执行代码计算:

    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)

我测试了其他几个解决方案,例如,但没有返回一个好的值:

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

因此,我创建了一个基于以下内容的单元测试: https ://school.stockcharts.com/doku.php?id=technical_indicators:relative_strength_index_rsi

我创建了一个输入文件:(见下面的 excel 图像)和一个输出文件:(见下面的 excel 图像)

运行单元测试(此处未包含单元测试代码)应该会导致但仅检查最后一个值。

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

但是我又一次无法通过测试。我通过excel的帮助检查了所有值。

在此处输入图像描述

所以现在我有点迷路了。

如果我在关注这个问题: Calculate RSI indicator from pandas DataFrame? 但这不会给收益带来任何价值。

  • a)应该如何计算以对齐单元测试?
  • b) 应该如何计算才能与交易观点保持一致?
4

3 回答 3

2

我在计算 RSI 时遇到了同样的问题,结果与 TradingView 不同,我找到了 InvestoPedia 中描述的 RSI 步骤 2 公式,我将代码更改如下:

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 是计算 RSI 的周期数(默认 = 14),代码被放入循环中以计算系列的所有 RSI 值。

于 2020-05-27T13:09:40.807 回答
2

这是 TradingView 中当前 RSI 指标版本的 Python 实现:

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

于 2021-03-15T08:21:26.873 回答
0

对于那些有同样经历的人。

我的原始数据包含交易量为零的刻度。过滤此 OLHCV 行将直接产生良好的结果。

于 2020-06-15T13:01:00.480 回答