RSI Divergence Against a Mechanical Null: Testing Pattern Recognition Without Cherry-Picking
Relative Strength Index (RSI) divergence occurs when price makes a new high or low without RSI confirming that extreme, suggesting weakening momentum. This strategy mechanically detects bearish divergence (price higher, RSI lower) and bullish divergence (price lower, RSI higher), enters on signal, and measures success against a matched null: randomized entry at the same price levels, to isolate whether the divergence pattern itself carries predictive power or whether the strategy merely captures mean reversion inherent to any mean-reverting entry near price extremes.
Why this might work
RSI divergence is widely cited in practitioner literature as a reversal signal [1]. The intuition is straightforward: a price extreme unsupported by equivalent momentum divergence suggests weakening conviction in the move, making a pullback or reversal more likely. The concept rests on the assumption that price and momentum should normally co-move; decoupling signals a regime change.
However, momentum-based divergence has received mixed empirical treatment. Pring's work on price action patterns includes divergence as a reversal tool, but his analysis focuses on longer-term chart patterns rather than precise entry rules [1]. Academic research on RSI specifically does not establish divergence as a profitable standalone signal in equities. RSI itself was designed to identify overbought and oversold conditions on a 30/70 scale [2], not to predict reversals via pattern divergence.
The core problem with divergence testing is selection bias: traders typically spot divergences they notice after profitable reversals and rarely count missed or failed divergences. By comparing the divergence strategy against a null hypothesis, entry triggered at the same price/RSI coordinates but randomly selected rather than signaled by divergence, we isolate whether divergence detection itself adds predictive value beyond the mean-reversion effect of entering at RSI extremes. If the null performs similarly, divergence is an artifact of data mining rather than a market edge.
The rules
Instrument and timeframe: SPY (or ES futures) on the daily close. Daily timeframe limits curve-fitting to intraday noise and generates roughly 250 trades per year per signal type.
Divergence detection (mechanical):: Bearish divergence: Identify the highest RSI value in the last N bars (N=14, standard lookback); identify the highest close in the same lookback; if the latest close is higher than that prior high, but the latest RSI is lower than that prior RSI high, trigger a SHORT signal.
- Bullish divergence: Identify the lowest RSI value in the last N bars; identify the lowest close in the same lookback; if the latest close is lower than that prior low, but the latest RSI is higher than that prior RSI low, trigger a LONG signal.
Entry: Limit order at the most recent close price on the bar the divergence is detected; if filled, hold the position.
Initial stop: 2% below entry for longs, 2% above entry for shorts.
Exit:: Profit target: 1.5% above entry for longs, 1.5% below entry for shorts.
- Time-based: Close any open position at market on the fifth bar after entry if neither target is hit.
- Stop loss executes immediately on 2% adverse move.
Position sizing: 1% of account per trade (fixed fractional, non-compounding).
Session filter: Trade only Monday–Friday, 09:30-15:00 ET; no overnight holds.
Null hypothesis strategy: Identical entry price and time, but entry triggered by a pseudo-random condition (e.g., the 11th bar of the month, same day-of-week random number), not divergence. Run this strategy in parallel to establish whether superior performance vs. null is statistically meaningful.
Expected frequency: Roughly 60-100 divergence signals per year per instrument per direction (long + short combined).
Code
// RSI Divergence with Mechanical Null Hypothesis Tester
// Pine Script v6 - Strategy
strategy("RSI Divergence vs Null Hypothesis", overlay=false,
default_qty_type=strategy.percent_of_equity,
default_qty_value=1,
commission_type=strategy.commission.percent,
commission_value=0.001,
slippage=1)
// Inputs
rsi_period = input.int(14, "RSI Period", minval=5, maxval=50)
lookback = input.int(14, "Divergence Lookback Bars", minval=5, maxval=50)
profit_target_pct = input.float(1.5, "Profit Target %", minval=0.1, maxval=10.0) / 100
stop_loss_pct = input.float(2.0, "Stop Loss %", minval=0.1, maxval=10.0) / 100
max_bars_in_trade = input.int(5, "Max Bars in Trade", minval=1, maxval=20)
use_null = input.bool(false, "Use Null Strategy (random entry)?")
// Calculate RSI
rsi_val = ta.rsi(close, rsi_period)
// Track highest/lowest price and RSI in lookback
highest_price = ta.highest(high, lookback)
lowest_price = ta.lowest(low, lookback)
highest_rsi = ta.highest(rsi_val, lookback)
lowest_rsi = ta.lowest(rsi_val, lookback)
// Divergence detection
bearish_div = close > highest_price[1] and rsi_val < highest_rsi[1]
bullish_div = close < lowest_price[1] and rsi_val > lowest_rsi[1]
// Null hypothesis: pseudo-random entry (day of month modulo creates pseudo-pattern)
bar_of_month = dayofmonth(time) % 11
null_long_signal = bar_of_month == 7
null_short_signal = bar_of_month == 3
// Select signal type
long_signal = use_null ? null_long_signal : bullish_div
short_signal = use_null ? null_short_signal : bearish_div
// Entry and exit logic
var float entry_price = na
var float long_target = na
var float long_stop = na
var float short_target = na
var float short_stop = na
var int bars_in_trade = 0
// Entry logic
if na(entry_price)
if long_signal
entry_price := close
long_target := close * (1 + profit_target_pct)
long_stop := close * (1 - stop_loss_pct)
bars_in_trade := 0
strategy.entry("Long", strategy.long, alert_message="Long Divergence")
else if short_signal
entry_price := close
short_target := close * (1 - profit_target_pct)
short_stop := close * (1 + stop_loss_pct)
bars_in_trade := 0
strategy.entry("Short", strategy.short, alert_message="Short Divergence")
// Exit logic
if not na(entry_price)
bars_in_trade += 1
if strategy.position_size > 0 // Long position
if close >= long_target
strategy.exit("Exit Long Target", "Long", limit=long_target)
entry_price := na
else if close <= long_stop
strategy.exit("Exit Long Stop", "Long", stop=long_stop)
entry_price := na
else if bars_in_trade >= max_bars_in_trade
strategy.close("Long", comment="Time exit", alert_message="Long closed by time")
entry_price := na
else if strategy.position_size < 0 // Short position
if close <= short_target
strategy.exit("Exit Short Target", "Short", limit=short_target)
entry_price := na
else if close >= short_stop
strategy.exit("Exit Short Stop", "Short", stop=short_stop)
entry_price := na
else if bars_in_trade >= max_bars_in_trade
strategy.close("Short", comment="Time exit", alert_message="Short closed by time")
entry_price := na
// Plot RSI and divergence markers (for visual confirmation)
plot(rsi_val, "RSI", color=color.blue, linewidth=2)
hline(70, "Overbought", color=color.red, linestyle=hline.style_dashed)
hline(30, "Oversold", color=color.green, linestyle=hline.style_dashed)
// Visual signal markers (do not affect strategy)
plotshape(bearish_div and not use_null, "Bearish Div", shape.triangledown, location=location.top, color=color.red, size=size.small)
plotshape(bullish_div and not use_null, "Bullish Div", shape.triangleup, location=location.bottom, color=color.green, size=size.small)
How the code works
RSI calculation (line 18): ta.rsi(close, rsi_period) computes the 14-period RSI using TradingView's built-in function, measuring momentum relative to the typical 0-100 scale.
Lookback extremes (lines 20-23): ta.highest() and ta.lowest() identify the highest and lowest RSI and price values over the last 14 bars, delayed by one bar [1](#ref-1) to prevent lookahead bias, comparisons use only completed historical data.
Bearish divergence detection (line 26): A new price high (close > highest_price[1](#ref-1)) paired with a lower RSI high (rsi_val < highest_rsi[1](#ref-1)) signals weakening momentum into the peak, triggering a short signal.
Bullish divergence detection (line 27): A new price low with a higher RSI low signals RSI strength during the price dip, triggering a long signal.
Null hypothesis (lines 29-30): bar_of_month creates a pseudo-random pattern independent of divergence: entry triggers on a fixed day-of-month schedule (7th and 3rd of the month modulo). This entry will occur at broadly similar market conditions and RSI extremes as the divergence strategy, but without the divergence pattern itself.
Position management (lines 44-70): Entry stores the entry price, computes target and stop levels, and increments a bar counter. Exit triggers on profit target, stop loss, or bar count limit, then resets the entry flag to allow the next trade.
Commission and slippage (line 5-6): Set to 0.1% (realistic for equity ETF trading) and 1 tick to reflect realistic costs; backtest results will be dampened by these realistic assumptions.
Testing it honestly
In-sample vs. out-of-sample: Run the strategy on the most recent 2 years of SPY daily data. Reserve the first 1 year as in-sample calibration (do not adjust RSI period or divergence lookback based on this year's results). Test the second year as out-of-sample. If the strategy's win rate or profit factor is materially worse out-of-sample, overfitting is evident.
Against the null: In the same backtest window, run the identical strategy but with use_null = true to trigger random entry instead of divergence. Compare:
- Total net profit (dollar and percent return).
- Win rate (% of trades profitable).
- Average win size vs. average loss size (profit factor).
If the divergence strategy is materially superior to the null (e.g., 55% win rate vs. 50% null, or 10% more total return), the edge may be real. If performance is similar, divergence detection is not adding value beyond mean reversion inherent to any entry near RSI extremes.
Statistical rigor: A 60-100 trade sample per year is too small to prove significance via win rate alone. Use a permutation test: randomize the entry dates across the same calendar period 1,000 times and compare the divergence strategy's return distribution to the randomized null. If the divergence strategy's return is in the top 5% of randomizations, the pattern may have predictive power; if it falls in the middle of the distribution, it is likely noise.
Realistic costs: Ensure backtest includes:
- 0.1% commission per trade (realistic for ETF trading).
- 1 tick slippage (buy limit orders filled 1 tick worse on average).
- Bid-ask spread: 1 tick for SPY (typical).
Returns net of costs are what traders actually receive.
Limitations
Divergence is noisy at daily resolution: RSI is a smoothed oscillator; on daily bars, the difference between "highest RSI in 14 bars" and "current RSI" can be 5-10 points even during sideways price action. This creates false signals that look like divergence but are simply noise. Filtering to only "significant" divergences (RSI difference > 10 points, price difference > 1%) reduces signal frequency and may worsen sample size.
Mean reversion confound: The core problem is that RSI is mean-reverting by construction; any entry near RSI extremes will show some reversal tendency. The null hypothesis helps isolate this, but if the null also returns >8% annually, the divergence strategy's edge, if any, is marginal and may evaporate in live trading due to costs, slippage, and regime shifts.
Regime dependence: This strategy is biased toward mean-reverting regimes (sideways, choppy markets). In strong trending markets (bull or bear), divergence often precedes further trend extension, not reversal; the strategy will generate many stops. Test this explicitly: run the strategy on year-long subperiods (e.g., Q1 2024 vs. Q4 2024) to identify regimes where it fails catastrophically.
Sample size: 60-100 trades per year is statistically inadequate. Even a 55% win rate with 100 trades has a 95% confidence interval spanning roughly 45%–65%; the true edge is unknown. A trader needs 500+ trades to begin trusting a 55% win rate, requiring 5+ years of data or multiple instruments.
Overfitting risk: The 14-period RSI and 14-bar lookback are industry defaults, but they were chosen by Wilder in 1978 for hand calculation, not for mechanical divergence on daily SPY. Scan RSI periods 7-21 and lookback windows 7-21: if the optimal combination is different from 14-14, the strategy may be optimized to the in-sample data and will likely fail out-of-sample.
Costs under-estimated: Commission is modeled at 0.1%, but:
- Options assignment, margin interest, and slippage on fast markets can exceed this.
- Tax on short-term gains (taxed as ordinary income, not capital gains) reduces net returns by 15-25% depending on jurisdiction.
- Drawdown may force liquidation before targets are hit, locking in losses.
Missing evidence: The strategy is shipped untested. No historical backtest results, win rates, or performance figures are provided. Readers must backtest independently before deploying capital. The null hypothesis is a tool to screen for overfitting, not proof of viability.
Key definitions
RSI (Relative Strength Index): A momentum oscillator (0-100 scale) measuring the magnitude of recent price gains relative to losses over a fixed period; values above 70 typically indicate overbought conditions, below 30 oversold, by practitioner convention [2].
Bearish divergence: Price reaches a new high while RSI reaches a lower high, signaling weakening momentum into the peak and suggesting a pullback or reversal may follow.
Bullish divergence: Price reaches a new low while RSI reaches a higher low, signaling resilience despite weakness and suggesting upside may follow.
Profit target: A pre-set price level at which a profitable position is closed automatically, locking in gains.
Stop loss: A pre-set price level at which a losing position is closed automatically to limit downside risk to a fixed percentage.
Null hypothesis: A baseline strategy identical to the signal strategy except entry is randomized rather than triggered by divergence; used to test whether divergence detection itself adds predictive value or is merely noise.
Commission and slippage: Transaction costs: commission is the fee charged per trade (0.1% typical), slippage is the difference between intended fill price and actual fill price due to market impact or limit-order rejection.
References
-
Pring, M. J., "Technical Analysis Explained: The Successful Investor's Guide to Spotting Investment Trends and Turning Points," McGraw-Hill (5th ed., 2014). Https://www.mhprofessional.com/
-
Wilder, J. W., "New Concepts in Technical Trading Systems," Trend Research (1978). Original RSI methodology and 14-period default.
-
CME Group, "Equity Index Futures Specifications," CME Rulebook. Https://www.cmegroup.com/markets/equities/index-futures.html
-
Bender, J., Briand, R., & Melas, D., "Foundations of Statistical Arbitrage," MSCI Research Paper (2013). Https://www.msci.com/ (framework for null hypothesis testing in systematic trading).
-
TradingView, "Pine Script Reference Manual," TradingView Documentation (2025). Https://www.tradingview.com/pine-script-docs/ (strategy() function, ta.rsi(), ta.highest/lowest()).
Educational research on historical data only. Not investment advice, not a signal, and never a performance promise. Past results do not predict future performance. Every reference is link-verified before publication and every paper is re-audited weekly against the library's editorial standard.
Last reviewed by the PropLedger research pipeline: 2026-11-23. Educational research on historical data, not financial advice.
Keep reading
Premium-Discount Zone Filter: Directional Bias from Range Position
A complete, testable trading strategy: a premium-discount filter strategy: taking longs only below the range midpoint and shorts only above it, whether that asymmetry is real, and how to test it. Exact rules, full Pine Script code, and an honest reading of the evidence.
Overnight vs. Intraday Session Cycle Strategy
A complete, testable trading strategy: an overnight versus intraday session cycle strategy: the split of returns between the two sessions, its academic paper trail, and honest rules for holding only one side. Exact rules, full Pine Script code, and an honest reading of the evidence.
Exploiting the Favorite-Longshot Bias in Prediction Markets
A complete, testable trading strategy: a favorite-longshot strategy on prediction markets: the documented pricing bias at the probability extremes, fees, and rules for harvesting it within venue limits. Exact rules, full Pine Script code, and an honest reading of the evidence.