由于使用TA库计算的RSI指标总是和Binance以及TradingView有一些差异,无法完全对应上。因此使用了以下代码来计算RSI指标,使用以下代码可以和Binance和TradingView上的RSI指标完全对应。
def calculate_rsi(data, period=12):
"""计算相对强弱指数 (RSI)"""
delta = data.diff(1)
gain = delta.where(delta > 0, 0)
loss = -delta.where(delta < 0, 0)
avg_gain = gain.rolling(window=period, min_periods=period).mean()
avg_loss = loss.rolling(window=period, min_periods=period).mean()
for i in range(period, len(data)):
avg_gain.iloc[i] = (avg_gain.iloc[i - 1] * (period - 1) + gain.iloc[i]) / period
avg_loss.iloc[i] = (avg_loss.iloc[i - 1] * (period - 1) + loss.iloc[i]) / period
rs = avg_gain / avg_loss
rsi = 100 - (100 / (1 + rs))
return rsi