Pandas RSI Different From TradingView: Causes and Fixes
Pandas RSI is different from TradingView because most code uses rolling().mean() or ewm(span=n) instead of Wilder smoothing, which is ewm(alpha=1/n, adjust=False), and because seeds differ. After about 10n bars, correct versions agree.
- Wilder smoothing (RMA) is an EMA with alpha=1/n, while a standard EMA uses alpha=2/(n+1); rolling(n).mean() and ewm(span=n) never converge to RSI or ATR from TA-Lib or TradingView.
- ewm(alpha=1/n, adjust=False) matches TA-Lib and TradingView after warm-up, but only a manual SMA-seeded loop matches TA-Lib from the first output bar.
- Seed differences decay as (1-alpha)^k, so compare only after roughly 10n bars (about 150 to 200 bars for n=14), and a gap that never shrinks points to a formula or data bug.
- ATR needs the true range max(high-low, |high-prev_close|, |low-prev_close|); using high-low alone gives permanently lower values.
- A repeatable test compares your function with talib on the same float64 CSV using np.allclose after warm-up, then repeats against a TradingView chart export.
Why does my pandas RSI differ from TradingView?
Almost always for one of two reasons: the smoothing is wrong, or the seed and history length differ. A wrong smoothing type produces a gap that never closes. A seed difference produces a gap that shrinks exponentially and is negligible after the warm-up.
That split is the most useful diagnostic you have. Plot the absolute difference against bar index on a log axis. A straight downward line is a seed effect, and a flat or noisy line is a formula or data problem.
The common formula mistakes are rolling(n).mean() on gains and losses, which is Cutler's RSI, and ewm(span=n), which uses alpha=2/(n+1) instead of Wilder's 1/n. Wilder's smoothing of length n equals an EMA with span 2n-1, so ewm(span=27) is the equivalent of Wilder 14.
What smoothing and seed does each platform use?
The table lists what the reference implementations do and the pandas equivalent. The seed column explains the early-bar differences.
TradingView's ta.rsi and ta.atr use ta.rma internally. The legacy atr() function used an SMA of true range, so very old scripts and some broker charts can still show SMA-based ATR.
| Indicator | TA-Lib / TradingView method | pandas equivalent | Seed |
|---|---|---|---|
| EMA | alpha=2/(n+1); TA-Lib and ta.ema | ewm(span=n, adjust=False).mean() | TA-Lib: SMA of first n values (first output at index n-1). pandas: first value |
| RMA (Wilder) | alpha=1/n; ta.rma | ewm(alpha=1/n, adjust=False).mean() | SMA of first n values; pandas: first value |
| RSI | RMA of gains and losses; 100*avg_gain/(avg_gain+avg_loss) | gain/loss clipped diffs, then ewm(alpha=1/n, adjust=False) | First n price changes averaged; first output at index n |
| ATR | RMA of true range; ta.atr | true range, then ewm(alpha=1/n, adjust=False) | Average of first n true ranges (TA-Lib first output at index n) |
| Cutler's RSI | SMA of gains and losses | rolling(n).mean() on gains and losses | None, window only |
| ATR (legacy atr()) | SMA of true range | tr.rolling(n).mean() | None, window only |
How do I write pandas RSI, ATR and EMA that match TA-Lib?
The module below has a seeded loop that reproduces TA-Lib from the first valid bar, plus the short ewm version that matches after warm-up. The loop skips leading NaN, seeds at the SMA of the first n valid values, then applies out[i] = out[i-1] + alpha*(x[i]-out[i-1]).
True range needs the previous close, so the first bar is NaN. That is why ATR and RSI start at index n, not n-1. Using high-low alone ignores overnight gaps and lowers ATR permanently.
RSI is computed as 100*avg_gain/(avg_loss+avg_gain), which equals 100-100/(1+RS) and avoids dividing by zero. When avg loss is 0 and avg gain is positive it returns 100. When both are 0 (a flat series) TA-Lib returns 0, while Pine's formula branches on down == 0 and returns 100, so expect a mismatch on constant prices.
import numpy as np
import pandas as pd
def smooth_seeded(x, alpha, n):
"""Recursive smoothing seeded with the SMA of the first n valid values."""
v = np.asarray(x, dtype=np.float64)
out = np.full(v.shape, np.nan)
ok = np.flatnonzero(~np.isnan(v))
if ok.size < n:
return out
i0 = ok[0] + n - 1
out[i0] = v[ok[0]:i0 + 1].mean()
for i in range(i0 + 1, len(v)):
out[i] = out[i - 1] + alpha * (v[i] - out[i - 1])
return out
def rma(x, n): return smooth_seeded(x, 1.0 / n, n)
def ema(x, n): return smooth_seeded(x, 2.0 / (n + 1), n)
def rsi(close, n=14):
c = np.asarray(close, dtype=np.float64)
d = np.diff(c, prepend=np.nan)
gain = np.where(np.isnan(d), np.nan, np.maximum(d, 0.0))
loss = np.where(np.isnan(d), np.nan, np.maximum(-d, 0.0))
ag, al = rma(gain, n), rma(loss, n)
den = ag + al
return np.where(den == 0, 0.0, 100.0 * ag / den)
def true_range(high, low, close):
h, l, c = (np.asarray(a, dtype=np.float64) for a in (high, low, close))
pc = np.concatenate([[np.nan], c[:-1]])
return np.maximum.reduce([h - l, np.abs(h - pc), np.abs(l - pc)])
def atr(high, low, close, n=14):
return rma(true_range(high, low, close), n)
# Short pandas version: matches after warm-up, not at the start
def rsi_pd(close: pd.Series, n=14):
d = close.diff()
ag = d.clip(lower=0).ewm(alpha=1/n, adjust=False).mean()
al = (-d.clip(upper=0)).ewm(alpha=1/n, adjust=False).mean()
return 100 * ag / (ag + al) Why do the first values differ, and when do they converge?
The seed is a one-time error. In a recursive filter that error is multiplied by (1-alpha) every bar, so after k bars it is (1-alpha)^k of its starting size. For Wilder n=14, alpha=1/14 and 0.9286^100 is about 6e-4, while 0.9286^200 is about 4e-7.
A rule of thumb: after 10n bars the leftover is about e^-10, roughly 5e-5 of the initial gap. After about 14n bars it is around 1e-6. For n=14 that means 150 to 200 bars before six decimals agree. EMA with alpha=2/(n+1) converges faster, in roughly 7n bars.
TA-Lib also has an unstable period. Calling talib.set_unstable_period('RSI', 100) (also 'ATR' or 'EMA') makes it drop the first 100 extra outputs, so you get NaN for n+100 bars. The values themselves are unchanged, since TA-Lib still seeds with the SMA, so this just forces you to skip the unstable region.
TradingView adds another effect. Its chart loads a limited number of bars, so its RSI seed sits at the left edge of the loaded history, not at your CSV's first bar. If your series is shorter than about 15n bars from that point, nothing will match to many decimals, and that is expected.
How do I verify an indicator against TA-Lib and TradingView?
Use the same bars for every implementation and compare numerically instead of by eye. The test below uses synthetic random-walk data, which is enough to catch smoothing and true-range bugs.
TA-Lib needs float64 arrays and raises an error on integer or object dtype. Pass np.ascontiguousarray(x, dtype=np.float64) when slicing DataFrame columns with steps or strides.
- Load one OHLC CSV and keep float64 columns. Drop or fix NaN rows first, because TA-Lib recursive indicators stay NaN after one NaN input.
- Run talib.RSI, talib.ATR and talib.EMA, and your own functions, on those arrays.
- Compare with np.allclose(a[w:], b[w:], rtol=0, atol=1e-8), with w = 10*n at least. The seeded loop should also match from the first valid bar.
- Plot np.abs(a - b) on a log y-axis. A straight decaying line indicates seed difference, and a flat line indicates a formula bug.
- Export the TradingView chart data CSV for the same symbol, timeframe and bars. Compare using atol of about 0.01 if the export is rounded to displayed precision, and only on bars after the TradingView warm-up.
import numpy as np, talib
from indicators import rsi, atr, ema, rsi_pd # the module above
def make_ohlc(n=1000, seed=0):
rng = np.random.default_rng(seed)
c = 100 + np.cumsum(rng.normal(0, 1, n))
h = c + rng.uniform(0.1, 1, n)
l = c - rng.uniform(0.1, 1, n)
return h, l, c
def test_against_talib():
h, l, c = make_ohlc()
n = 14
assert np.allclose(rsi(c, n)[n:], talib.RSI(c, n)[n:], atol=1e-9)
assert np.allclose(atr(h, l, c, n)[n:], talib.ATR(h, l, c, n)[n:], atol=1e-9)
assert np.allclose(ema(c, n)[n-1:], talib.EMA(c, n)[n-1:], atol=1e-9)
def test_ewm_shortcut_after_warmup():
import pandas as pd
_, _, c = make_ohlc()
ref = talib.RSI(c, 14)
out = rsi_pd(pd.Series(c)).to_numpy()
assert np.allclose(out[200:], ref[200:], atol=1e-6) Which data differences make the values differ even when the formula is right?
If the formula passes the TA-Lib test but still differs from a chart, the input series is not the same. These are the usual causes, and each shifts values by far more than any seed effect.
| Data issue | Effect | What to check |
|---|---|---|
| Adjusted vs unadjusted closes | Splits and dividends change every price before the event, so RSI and ATR differ in history | Use the same adjustment setting on both sides |
| Session and extended hours | Extra pre/post-market bars change diff and true range | Match regular-hours-only vs extended settings |
| Time zone and bar boundaries | Daily bars cut at different hours group ticks differently, mainly in crypto and FX | Compare timestamps in UTC and check the daily open hour |
| Volume source | Consolidated vs single-exchange volume affects volume-based indicators only | Confirm the feed on both sides |
| Forming last bar | The live bar's value repaints until it closes | Drop the last row or compare closed bars only |
| Crypto exchange | Each exchange has its own prices and bar highs and lows | Use the same exchange and pair |
What is the debug checklist, ordered by likelihood?
Work down this list in order. Each item is cheaper to check and more likely than the next.
Rounding comes last because a chart shows two decimals, so a difference below 0.005 is display precision and not a bug.
| Order | Suspect | Test |
|---|---|---|
| 1 | Data: adjustment, session, time zone, forming bar, symbol or exchange | Compare raw closes for a few bars first; if they differ, stop here |
| 2 | Smoothing type: rolling mean, span instead of alpha, adjust=True | Check that your code gives ewm(alpha=1/n, adjust=False) results after warm-up |
| 3 | Seed and warm-up: too few bars | Difference should shrink as (1-alpha)^k; skip 10n bars |
| 4 | Parameters: length, source (close vs hl2), true range definition | Confirm n and the price source on the chart settings |
| 5 | NaN handling and dtype | Look for NaN in input, check float64 and contiguous arrays |
| 6 | Rounding of exported or displayed values | Use atol of about 0.01 for chart exports |
Common questions
Why does talib.ATR differ from pandas rolling mean?
TA-Lib ATR is Wilder's RMA of true range, which gives every past bar a decaying weight, while rolling(n).mean() is a flat window of the last n bars. The gap does not shrink with more data. Use true range with ewm(alpha=1/n, adjust=False) instead.
Is pandas ewm(span=14) the same as Wilder smoothing of 14?
No. span=14 gives alpha=2/15, about 0.133, while Wilder 14 has alpha=1/14, about 0.071. To mimic Wilder n with span, use span=2n-1, or simply pass alpha=1/n.
Why does pandas ema differ from TradingView ema?
Typically the cause is the seed or history length. pandas ewm with adjust=False starts at the first value, while TA-Lib starts from an SMA of the first n values. Different start bars and adjust=True weighting also change early values. They agree to many decimals after roughly 7n bars.
How many bars do I need before RSI matches TradingView?
About 150 to 200 bars of history before the compared bar for n=14, since the seed error falls as 0.9286^k. TradingView's own first bar depends on how much history the chart has loaded, so scroll or load more bars before comparing.
Does the RSI formula change when average loss is zero?
With RSI = 100 - 100/(1+RS), zero average loss with positive average gain gives RSI of 100. Compute it as 100*avg_gain/(avg_gain+avg_loss) so you never divide by zero. A completely flat series is an edge case where TA-Lib returns 0 and Pine returns 100.