Concept 27 / 52·Statistics·Return to the mean
‹ Market StructureMoney Flow Index (MFI) ›

Mean Reversion in Pine Script

reversion to the mean · fading · counter-trend trading · z-score reversion

The tendency of price to return towards an average after a stretch away from it, the regimes in which that holds, and the rules that trade the return without being run over when it fails.

Reads best on: Liquid equity indices and large-cap stocks on daily bars, and any liquid market inside a defined range on 15-minute to 4-hour charts. It is switched off in trends and around scheduled news.
On this page: the Pine v6 script, checked, drawn on real NVDA bars. Backtest it free, costs charged, every trade on the chart.
Backtest results: Mean reversion strategy: SPY, QQQ and more since 2016, costs charged, every trade listed.
01

Definition

Mean reversion is the tendency of a series to move back towards its average after it has strayed. In trading it is the claim that a price stretched far from a moving average, a band or a value area will, more often than not, come part of the way back. It is a statistical property of ranges, of the short-term behaviour of liquid equity indices, and of spreads between related instruments. It is not a law of price. The concept sits in the Statistics category because the whole question is whether the returns in this market, on this horizon, actually have a mean to revert to.

It works where there is a mechanism pulling price back: dealers hedging, arbitrage between related markets, or simply a crowd that overreacts to news and then reconsiders. On liquid stock indices, short-term reversion has been one of the more persistent effects: a few days of sharp declines are more often followed by a bounce than by further declines. It fails where the mechanism is absent or overwhelmed. A stock repricing on earnings, a currency after a policy change or a commodity in a supply shock does not have a mean to revert to; the old average is simply wrong.

The measures are all versions of the same idea: how far is price from an average, in units of the market's own variability. A z-score divides the distance from a moving average by the standard deviation over the same window. Bollinger %B expresses the same thing as a position between two bands. A short RSI, 2 to 5 bars, turns a run of closes into a bounded number. The library's two strategies use the last two. One goes long on RSI crossing back above 30 and exits at 50; the other goes long on a close back inside the lower Bollinger band and exits at the basis.

Mechanically, a reversion rule aims at frequent small exits and has a poor worst case. Most stretched readings come partway back, so most trades are small winners. The ones that do not are the trend days, where the stretch becomes a breakout and keeps going. Without a stop those losses swamp the winners, and with a stop too tight the trade is stopped before the reversion arrives. The library's strategies handle this with an ATR stop on every entry and an exit at the mean rather than at the opposite extreme, taking the reliable part of the move and leaving the rest.

02

Reading the chart

Reversion starts with the regime, then the stretch, then the exit before the entry.

  1. Decide whether the market is in a regime where reversion has been working. Look at the last few months: do stretches beyond the bands or below RSI 30 come back within days, or do they extend into trends?
  2. Define the mean and the stretch in the market's own units. A 20-bar average with 2 standard deviation bands, a 14-period RSI at 30 and 70, or a z-score of 2 each name a mean and a distance.
  3. Wait for the turn back towards the mean rather than going long at the extreme. A close back inside the lower band, or RSI crossing back above 30, is what the library's strategies use, because the first close back inside says the decline has paused.
  4. Set the exit at the mean. The basis line of the bands or RSI 50 is where the core of the move ends; targeting the opposite band is asking reversion to do a trend's job.
  5. Place the stop in volatility units, not at a round number. An ATR multiple gives the trade room for the noise that created the stretch; the library's defaults use 2 ATR.
  6. Check the calendar and the higher timeframe. A stretch into scheduled news or against a strong higher-timeframe trend is the setup that turns into the trend day; a filter skips it or sizes it down.
03

The maths

Every reversion measure is a distance from a mean scaled by the market's recent variability.

μt=1n∑i=t−n+1tCi\mu_t = \frac{1}{n} \sum_{i=t-n+1}^{t} C_i
σt=1n∑i=t−n+1t(Ci−μt)2\sigma_t = \sqrt{\frac{1}{n} \sum_{i=t-n+1}^{t} (C_i - \mu_t)^{2}}
zt=Ct−μtσtz_t = \frac{C_t - \mu_t}{\sigma_t}
%Bt=Ct−(μt−k σt)2 k σt\%B_t = \frac{C_t - (\mu_t - k \, \sigma_t)}{2 \, k \, \sigma_t}
CiC_iclose of bar i
CtC_tclose of the current bar
nnthe window, 20 bars by default
μt\mu_tthe mean of the closes over the window
σt\sigma_tthe standard deviation of the closes over the window
ztz_tthe z-score, the distance from the mean in standard deviations
kkthe band multiplier, 2 by default
%Bt\%B_tthe position between the bands: 0 at the lower band, 1 at the upper, 0.5 at the basis

A z-score of 2 and a close at a 2 standard deviation Bollinger band are the same statement; %B of 0 is the lower band, 1 the upper, 0.5 the basis.

Standard deviation of price is not stable: it grows in a trend, so the bands widen and the same distance in price becomes a smaller z-score. That is a feature: the stretch is measured against the current regime.

Short RSI, 2 to 5 bars, is a common reversion input on equity indices because it saturates on a few one-way closes; the library's RSI strategy uses 14 by default and takes any length.

04

Inputs that matter

InputTypicalWhat changing it does
Mean window20 bars (bands), 14 (RSI)Shorter windows follow price closely and call small wobbles stretches; longer windows set a slower mean and reserve signals for larger departures.
Stretch threshold2 standard deviations, RSI 30 and 70Wider thresholds trade less often and wait for larger stretches; tighter ones trade more and take smaller reversions.
Stop (ATR multiples)2Wider stops survive the noise around an extreme and keep the win rate; tighter stops cut the worst trades but stop many good ones before they turn.
Exitthe mean (basis or RSI 50)Exiting at the mean takes the core of the move; extending to the opposite extreme raises the average win and lowers the win rate.
05

In practice

  • As an RSI reversion system: the rule goes long on RSI crossing back above 30, short on it crossing back below 70, and exits when RSI returns to 50, with a 2 ATR stop. That is the library's RSI Mean-Reversion Strategy exactly.
  • As a band reversion system: the rule goes long on the close back above the lower Bollinger band, short on the close back below the upper, and exits at the basis, 2 ATR stop. That is the library's Bollinger Mean-Reversion Strategy.
  • As a pullback method in a trend: the filter keeps only the reversion entries that point with the higher-timeframe trend, so an uptrend takes longs at the lower band and no shorts at the upper.
  • As an index-specific short-term system: on liquid equity indices, a short RSI of 2 to 4 below 10 after a few down days is a widely studied long setup. The same rule on a single stock into earnings is not.
  • As a pairs or spread tool: the z-score of the ratio between two related instruments is the classic reversion input, because the spread has an economic reason to return that a single price does not.
  • As a sizing discipline: because the losers are the trend days, the sizing rule keeps each trade's risk at a fixed fraction of equity in ATR units and never adds to a stretched position that keeps stretching.
06

Where it goes wrong

  • Fading a breakout. The same reading that is a stretch in a range is the start of a trend on a news day; check the regime and the calendar before fading.
  • Going long at the extreme instead of the turn. Price can close outside the band for days; wait for the close back inside or the RSI cross, which is what the library's strategies do.
  • Targeting the opposite band. Reversion reaches the mean far more often than the other side; the exit rule takes the middle and lets a separate trade handle the rest.
  • Trading without a stop because the win rate is high. The rare trend day erases many small wins; an ATR stop bounds that day.
07

Compared with

Overbought & Oversold. Overbought and oversold are oscillator readings that suggest a stretch; mean reversion is the statistical claim that the stretch will close, plus the rules that trade it. A reading is an input; the strategy is the regime check, the entry on the turn, the exit at the mean and the stop.

Breakout. A breakout rule goes long on the move out of a range expecting continuation; a reversion rule goes short on the same move expecting a return. The two fit different regimes: breakouts fit trends and squeezes, reversion fits ranges. The regime read decides which one you are.

Bollinger Bands. Bollinger Bands are the most common reversion measure but they are only a measure: a close outside the band is two standard deviations from the average. Mean reversion is the trade built on that measure, with the entry on the close back inside, the exit at the basis and the stop that the bands do not provide.

Trailing Stop. A trailing stop is a trend-following exit that follows price as it runs, giving a trade room to become large. Reversion trades do the opposite: they exit at a fixed mean and hold a fixed stop. Putting a trailing stop on a reversion trade turns a high win rate system into a lower one with fatter tails.

08

Build it in Quant

Type one of these in the Quant desk, or click it. A request that fits a checked template is assembled on the spot without a credit; anything beyond the blanks goes to the copilot, which edits on top of the checked script.

Backtest Mean Reversion as a strategy
Costs and slippage included; every version stays selectable.
09

Questions

  • When does mean reversion fail?

    When the mean itself is moving. A repricing on news, a regime change in a currency, a commodity in a supply shock or an index in a crash all produce stretches that keep stretching. The old average is no longer the right one. The tell is a stretch on a break of structure with high relative volume; the fix is a regime check, a stop, and refusing to add.

  • Should I use RSI or Bollinger Bands for mean reversion?

    They measure different things. RSI counts one-sided closes and saturates fast on short lengths, which suits index reversion after a few down days. Bands measure distance from a 20-bar average in standard deviations, which suits price-level stretches on any market. The library ships both as strategies with the same stop and exit logic; test both on your market and keep the one whose losers are smaller.

  • Where should the exit go?

    At the mean. Most of the move is from the extreme back to the average, which is the basis line of the bands or RSI 50. Extending the target to the opposite band raises the average winner but turns many winners into break-evens when price stalls at the mean and reverses. The library's strategies exit at the basis and at RSI 50 for that reason.

  • What is a z-score in trading?

    The distance of price from a moving average, divided by the standard deviation of price over the same window. A z-score of 2 means price is two standard deviations from the mean, which is the same as a close at a 2 standard deviation Bollinger band. Z-scores are used for single prices, for the spread between two related instruments, and for ranking a watchlist by stretch.

  • How do the library's reversion strategies manage risk?

    Both put a stop 2 ATR from the entry on every trade, using a 14-period ATR, and exit at the mean: RSI 50 in one, the Bollinger basis in the other. Longs and shorts can be switched off separately. Orders fill on the next bar and the backtest charges commission and slippage, so the results already include the cost of the frequent trading that reversion systems generate.

  • Does mean reversion work on crypto?

    On the largest pairs and in ranging regimes it behaves like any liquid market. In trending regimes crypto stretches much further than a 2 standard deviation band and stays there, and the losers on a reversion system are correspondingly large. Use a wider threshold, a wider ATR stop and a higher-timeframe trend filter, and expect the system to be switched off for months at a time.