⬡ INDICATOR · WITH CODE · 12 MIN READ

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

The world's most popular momentum oscillator — truly explained, from formula to divergences, with ready-to-use code in Pine Script and Python for automation.

By 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 memorize "70 sell, 30 buy" and stop there, which leads to losing money in strong trends. This guide goes further: explains what the RSI actually measures, where it shines, where it fails, and delivers the code for you 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: ranges from 0 to 100 and measures the speed and magnitude of recent price changes. In simple terms: it compares the size of recent gains against the size of recent losses.

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

02The formula (to understand, not memorize)

You don't need to calculate by hand — every platform does —, but understanding the formula prevents misuse:

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

where RS = average gains / average losses (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 RSI goes to 100; when there are only losses, RSI goes to 0. That's why it "saturates" — and that's exactly where the trap we'll see ahead lies.

03The 3 real uses (beyond the obvious)

1. Overbought / oversold

The classic use. But attention: in ranging markets it works well; in strong trends, the RSI stays "stuck" at the extreme (above 70 for days in a strong rally) and the "sell" signal makes you trade against the trend — expensive mistake.

2. Divergences (the most valuable use)

Here's the RSI gold. Divergence happens when price and RSI disagree:

  • Bearish divergence: price makes a higher high, but RSI makes a lower high → the upward movement is losing strength, possible downward reversal.
  • Bullish divergence: price makes a lower low, but RSI makes a higher low → the decline is weakening, possible upward reversal.
Bearish divergence price HIGHER high ↑ RSI LOWER high ↓ Price rises, RSI doesn't follow = buying force weakening = possible reversal signal
Na divergência de baixa, o price faz topo mais alto but o RSI faz topo mais baixo — alerta de reversal.

3. The 50 line as trend filter

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

O erro nº1 com RSI: vender só because passou de 70. Numa trend de alta forte, o RSI can ficar above de 70 por semanas while o price continua subindo. RSI sozinho isn't sinal de entrada — é contexto. Combine always com trend e estrutura.

04Coding the RSI

Here's the ready-to-use code for the two most popular platforms. Note that both Pine and Python have RSI in their libraries — you rarely calculate by hand, but I show the manual calculation in Python so you understand the internals.

Pine Script (TradingView)
//@version=5
indicator("RSI com Zonas")

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

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

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

def calcular_rsi(precos: pd.Series, periodo=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/periodo, adjust=False).mean()
    avg_loss = loss.ewm(alpha=1/periodo, adjust=False).mean()
    rs = avg_gain / avg_loss
    return 100 - (100 / (1 + rs))

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

Python shortcut: libraries like ta or pandas-ta already have RSI ready: ta.momentum.rsi(df["close"], window=14). Use the manual calculation above only to understand what happens 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 based on style:

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

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

06Preguntas frecuentes

What is RSI?

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

What's the best RSI period?

Default is 14. Shorter periods (7-9) make it more sensitive and signal-generating (day trading); longer (21+) make it smoother and more reliable (swing). There's no universal "best" — depends on style and asset.

What is RSI divergence?

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

Can I trade with RSI alone?

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

Does RSI work in crypto and stocks?

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