The RSI (Relative Strength Index) is a momentum oscillator used in technical analysis, first introduced by J. Welles Wilder in 1978. RSI measures the speed and magnitude of price movements by comparing the average gains and losses over a specific period. It is commonly used to determine whether an asset is overbought or oversold, helping traders make buy or sell decisions.

Core Principle of RSI

The core idea of RSI lies in the concept of relative strength, referring to the ratio of recent price changes over a set time frame. The RSI value ranges from 0 to 100. Typically:

  • An RSI above 70 suggests an overbought condition.
  • An RSI below 30 suggests an oversold condition.

The underlying logic is that strong short-term price movements often lose momentum and may reverse.

RSI uses smoothed averages of price gains and losses to filter out random market noise and better reflect the overall trend.

How RSI Is Calculated

The RSI is calculated through a series of steps, starting with daily price changes and ending with the final RSI value:

1. Choose a Time Window
The default is 14 days, but other periods may be used depending on the strategy.

2. Calculate Daily Price Changes
For each day in the window, subtract the previous day’s close from the current day’s close. This yields positive (gains) or negative (losses) values.

3. Calculate Average Gains and Losses

Average Gain: Sum of all positive changes ÷ number of days

Average Loss: Sum of absolute values of negative changes ÷ number of days

4. Calculate Relative Strength (RS):
RS = Average Gain / Average Loss

5. Calculate RSI: RSI = 100 − [100 / (1 + RS)]

Example:

  • Over 14 days: 8 gain days totaling 120 points, 6 loss days totaling 40 points.
  • Average gain = 120 ÷ 14 = 8.57
  • Average loss = 40 ÷ 14 = 2.86
  • RS = 8.57 ÷ 2.86 ≈ 3
  • RSI = 100 − (100 / (1 + 3)) = 75

This RSI of 75 suggests the asset is potentially overbought.

RSI Parameter Settings

The RSI period can vary:

  • 14-day RSI: Balanced, good for short to medium-term trading (Wilder’s default).
  • 7-day RSI: More sensitive, suited for short-term trading but prone to false signals.
  • 21-day RSI: Smoother, more suitable for long-term investors, but lags more.

Different markets may require different settings. For instance, while 14 is ideal for U.S. stocks (Wilder’s original focus), many Chinese traders find that 9-day RSI better suits the A-share market. Backtesting is essential to choose the best setting.

The asset type and market also matter:

  • Stocks with high volatility may benefit from shorter RSIs.
  • Forex markets, being fast-moving, often use 7- or 9-day RSIs.
  • Commodities like oil or gold require custom tuning.
  • Crypto markets may use even shorter RSIs like 5 or 7 days due to extreme volatility.

RSI Trading Strategies

Traders primarily use RSI to identify potential market reversal points based on overbought and oversold levels.

Oversold Strategy

When RSI < 30, the asset is potentially oversold—a buy signal. Traders often wait for RSI to rebound above 30 to confirm a reversal. This is ideal for bottom-fishing strategies but should be combined with other signals to avoid false entries.

Overbought Strategy

When RSI > 70, the asset is potentially overbought—a sell signal. Traders may wait for RSI to fall back below 70 to confirm a reversal. This works well for taking profits or initiating shorts near market tops.

Divergence Strategy

Divergence occurs when price and RSI move in opposite directions:

  • Bearish divergence: Price makes a new high, RSI does not → possible downtrend.
  • Bullish divergence: Price makes a new low, RSI does not → possible uptrend.

These can signal trend reversals and are useful for timing entries/exits.

Like any technical indicator, RSI can produce false signals. It’s best used alongside other tools like the MACD (discussed in another article) to improve reliability.

Code Example

import pandas as pd
import requests
import ta
import time

def get_realtime_data(stock_code):
    url = f"https://api.alltick.io/v1/quotes/{stock_code}"
    response = requests.get(url)
    data = response.json()
    return data

def rsi_strategy(data, rsi_period=14, rsi_oversold=30, rsi_overbought=70):
    data['RSI'] = ta.momentum.rsi(data['close'], window=rsi_period)
    data['Signal'] = 0
    data['Signal'][data['RSI'] < rsi_oversold] = 1
    data['Signal'][data['RSI'] > rsi_overbought] = -1
    return data

def simulate_trading(stock_code, interval=60):
    while True:
        data = get_realtime_data(stock_code)

        df = pd.DataFrame(data)

        df = rsi_strategy(df)

        latest_signal = df['Signal'].iloc[-1]

        if latest_signal == 1:
            print("Buy")
        elif latest_signal == -1:
            print("Sell")
        else:
            print("No Signal")
        
        time.sleep(interval)

if __name__ == "__main__":
    stock_code = "00941.HK"
    simulate_trading(stock_code)