⬡ INDICATOR · WITH CODE · 12 MIN READ

RSI: how to use and code the Relative Strength Index.

The most popular momentum oscillator in the world — explained for real, from the formula to divergences, with ready-to-use Pine Script and Python code for you to automate.

By the RoboTraderIA Team· updated May 2026· beginner to intermediate level

The RSI is probably the first indicator every trader learns — and also one of the most misused. Most people memorize "70 sell, 30 buy" and stop there, which loses money in strong trends. This guide goes further: it explains what the RSI actually measures, where it shines, where it fails, and hands you the code to plug into a bot.

01What the RSI actually measures

RSI stands for Relative Strength Index, created by J. Welles Wilder in 1978. It's a momentum oscillator: it ranges from 0 to 100 and measures the speed and magnitude of recent price moves. In plain terms: it compares the size of recent gains with the size of recent losses.

  • RSI above 70: overbought — price rose quickly, it may be "stretched."
  • RSI below 30: oversold — price fell quickly, it may be "stretched" to the downside.
  • RSI at 50: balance between buying and selling pressure.
70 — overbought 30 — oversold 50
The RSI oscillating between the zones. Touches above 70 (red) and below 30 (green) mark extremes.

02The formula (to understand, not memorize)

You don't need to calculate it by hand — every platform does it — but understanding the formula keeps you from using it wrong:

RSI = 100 − [ 100 / (1 + RS) ]

where RS = average gain / average loss (over the period)

The default period is 14. The practical consequence of the formula: when there are only gains in the period, RS tends to infinity and the RSI goes to 100; when there are only losses, the RSI goes to 0. That's why it "saturates" — and that's exactly where the trap we'll see later lives.

03The 3 real uses (beyond the obvious)

1. Overbought / oversold

The classic use. But careful: it works well in a ranging market; in a strong trend, the RSI gets "glued" to the extreme (above 70 for days in a strong rally) and the "sell" signal makes you trade against the trend — an expensive mistake.

2. Divergences (the most valuable use)

This is the gold of the RSI. Divergence happens when price and RSI disagree:

  • Bearish divergence: price makes a higher high, but RSI makes a lower high → the uptrend is losing strength, possible reversal down.
  • Bullish divergence: price makes a lower low, but RSI makes a higher low → the decline is weakening, possible reversal up.
Bearish divergence price HIGHER high ↑ RSI LOWER high ↓ Price rises, RSI doesn't follow = buying strength weakening = possible reversal signal
In a bearish divergence, price makes a higher high but the RSI makes a lower high — a reversal warning.

3. The 50 line as a trend filter

An underrated use: RSI consistently above 50 confirms an uptrend; below 50, a downtrend. Great as a filter for other strategies — only buy with RSI above 50, for example.

The #1 RSI mistake: selling just because it crossed 70. In a strong uptrend, the RSI can stay above 70 for weeks while price keeps rising. RSI alone isn't an entry signal — it's context. Always combine it with trend and structure.

04Coding the RSI

Here's ready-to-use code for the two most-used platforms. Note that both Pine and Python have the RSI in their library — you rarely compute it by hand, but I show the manual calculation in Python so you understand what's happening under the hood.

Pine Script (TradingView)
//@version=5
indicator("RSI with Zones")

period = input.int(14, "Period")
rsi = ta.rsi(close, period)

plot(rsi, "RSI", color=color.blue)
hline(70, "Overbought", color=color.red)
hline(30, "Oversold", color=color.green)
hline(50, "Midline", color=color.gray)

// crossover alert
if ta.crossunder(rsi, 30)
    alert("RSI entered oversold")
Python (manual calculation, to understand)
import pandas as pd

def compute_rsi(prices: pd.Series, period=14) -> pd.Series:
    delta = prices.diff()
    gain = delta.clip(lower=0)
    loss = -delta.clip(upper=0)
    # Wilder's exponential moving average
    avg_gain = gain.ewm(alpha=1/period, adjust=False).mean()
    avg_loss = loss.ewm(alpha=1/period, adjust=False).mean()
    rs = avg_gain / avg_loss
    return 100 - (100 / (1 + rs))

# usage
df["rsi"] = compute_rsi(df["close"])
if df["rsi"].iloc[-1] < 30:
    print("Oversold — consider a buy with confirmation")

Python shortcut: libraries like ta or pandas-ta already have RSI built in: ta.momentum.rsi(df["close"], window=14). Use the manual calculation above only to understand what's happening inside.

Want to build a strategy with RSI?

See our collection of ready-to-automate strategies, several using RSI as a filter.

See strategies →

05Which period to use

The default 14 is a good balance, but you can adjust it to your style:

  • Short periods (7-9): a more sensitive RSI, more signals, more noise. For scalping and fast day trading.
  • Period 14 (default): balanced. Works in most cases.
  • Long periods (21+): a smoother RSI, fewer signals, more reliable. For swing trading.

Automation tip: when optimizing the period in a backtest, avoid picking the single number that gave the best isolated result (overfitting). Prefer a range that performs similarly — robustness is worth more than a peak of past performance.

06Frequently asked questions

What is the RSI?

It's a momentum oscillator ranging from 0 to 100 that measures the speed and magnitude of price changes. Above 70 indicates overbought; below 30, oversold. Created by Wilder in 1978.

What's the best period for the RSI?

The default is 14. Smaller periods (7-9) make it more sensitive and signal-generating (day trading); larger ones (21+) make it smoother and more reliable (swing). There's no universal "best" — it depends on your style and the asset.

What is RSI divergence?

It's when price and RSI disagree: price makes a new high but the RSI doesn't follow (bearish divergence), or price makes a new low but the RSI rises (bullish divergence). It signals weakening and a possible reversal. It's one of the most valuable uses.

Can I trade with RSI alone?

Not recommended. RSI alone generates many false signals, especially in a trend. Use it as context/filter combined with market structure, trend and risk management. RSI shines in combination, not in isolation.

Does RSI work in crypto and futures?

Yes, it's market-agnostic — it works on any asset with price data (stocks, index futures, Forex, crypto). The interpretation is the same; what changes is calibrating the period to the asset's behavior.