OPEN-SOURCE SCRIPT
Atualizado Trend Persistence Oscillator

Trend Persistence Oscillator
OVERVIEW
Most oscillators answer "is price stretched?" This one answers the prior question almost everyone skips: "is the market even in a state where a stretch should snap back?" It plots a rolling persistence exponent of price around the 0.5 line. ~0.5 is a random walk; above 0.5 the series is persistent (moves tend to continue → trending); below 0.5 it is anti-persistent (moves tend to reverse → mean-reverting). It is an analytical study of market state — not a directional signal and not a strategy.
WHY THESE COMPONENTS BELONG IN ONE SCRIPT (mashup rationale)
Three parts that chain into one testable idea — is a reversion likely here, and has that held before?
The persistence exponent classifies the regime (trending / random / reverting). Research finds price reverts to its mean significantly faster when the local exponent is anti-persistent, so a low reading is a green light for fades and a high reading is a warning that a reversion will likely fail.
A stretch z-score measures how far price sits from its rolling mean — the "is it extended?" half a regime read alone can't supply.
A fade flag arms only when both agree (anti-persistent regime and stretched), turning the research claim into a concrete, located event.
The calibration harness proves or disproves the claim on your instrument: it logs each fade and checks, a fixed horizon later, whether price actually reverted — reporting Edge versus the unconditional base rate.
A regime read without a stretch is just a state label; a stretch without the regime is a naive fade; either without calibration is an untested assertion. Chained, they answer one question end to end. Remove a part and the chain breaks.
HOW IT WORKS
The exponent is estimated by the structure-function (generalized-Hurst) method: for several lags, the windowed mean of |log-price(t) − log-price(t−lag)| scales like lag^H, so the exponent is the slope of log(mean|Δ|) against log(lag). The first-moment (absolute) form is used deliberately because it is the variant most robust to the heavy tails of financial returns — Monte-Carlo studies find the generalized-Hurst approach gives the lowest bias and variance of the common estimators on heavy-tailed data.
A short optional smoothing tames the noise inherent to short-window local estimates (very short windows are known to produce volatile readings and false alarms).
A stretch z-score and the regime thresholds combine into the fade flag.
The harness logs each fade and, a fixed horizon later, checks a ≥ k × ATR reversion.
HOW TO USE
Read the line for regime: in the green (reverting) zone, mean-reversion / fade setups have the wind behind them; in the gold (trending) zone, expect continuation and treat reversion setups with suspicion; near 0.5 the tape is effectively random. The fade dots mark reverting-and-stretched moments. Then read the Edge row — a regime filter only earns its keep if fades taken inside it beat the unconditional base rate. Context, never a standalone trigger.
Three visual styles are provided (Gradient area + glow / Histogram / Line).
UNIVERSAL ACROSS MARKETS
The price source is an input, so the engine runs on any instrument and timeframe. Defaults target intraday index futures (e.g. NSE NIFTY); change the source for any other market. The reading is self-normalising around 0.5, so the same regime bands work everywhere.
ORIGINALITY
The exponent itself is a standard public statistic, credited below. The original work is the assembly: a structure-function persistence estimator chosen for heavy-tail robustness and smoothed against short-window noise, gated against a stretch z-score into a located fade event, and tied to a forward base-rate calibration so the regime claim is tested on each instrument rather than asserted. It is a regime and validation tool, not a plain exponent plot. No third-party Pine code is reused.
CONCEPT CREDIT
The scaling exponent and rescaled-range analysis — Harold E. Hurst (1951). Fractional / self-similar processes and the generalized exponent — Benoit Mandelbrot. The structure-function (generalized-Hurst) estimator is the variant most robust to heavy-tailed financial data. The anti-persistence-anticipates-reversion application follows recent local-exponent mean-reversion research (2024). Not affiliated with, nor endorsed by, any third party.
HONESTY / LIMITATIONS
The exponent is an estimate from a finite window — it is noisy and lags, and short windows can raise false alarms (which is why a smoothing control is provided, on by default). A low reading is context, not a trigger. The Edge figures are in-sample, close-to-close, with overlapping forward windows and no costs — descriptive context, not a verified backtest. An Edge near zero or negative is the harness honestly reporting that the regime read isn't helping here; do not tune until it turns green — that is curve-fitting. Nothing here predicts direction.
DISCLAIMER
Research and educational tool only. NOT financial advice and NO guarantee of profitability or accuracy. Indicators describe past behaviour; they do not predict the future. Trading carries risk of loss. Test out-of-sample and make your own decisions. The author accepts no liability for any use of this script.
OVERVIEW
Most oscillators answer "is price stretched?" This one answers the prior question almost everyone skips: "is the market even in a state where a stretch should snap back?" It plots a rolling persistence exponent of price around the 0.5 line. ~0.5 is a random walk; above 0.5 the series is persistent (moves tend to continue → trending); below 0.5 it is anti-persistent (moves tend to reverse → mean-reverting). It is an analytical study of market state — not a directional signal and not a strategy.
WHY THESE COMPONENTS BELONG IN ONE SCRIPT (mashup rationale)
Three parts that chain into one testable idea — is a reversion likely here, and has that held before?
The persistence exponent classifies the regime (trending / random / reverting). Research finds price reverts to its mean significantly faster when the local exponent is anti-persistent, so a low reading is a green light for fades and a high reading is a warning that a reversion will likely fail.
A stretch z-score measures how far price sits from its rolling mean — the "is it extended?" half a regime read alone can't supply.
A fade flag arms only when both agree (anti-persistent regime and stretched), turning the research claim into a concrete, located event.
The calibration harness proves or disproves the claim on your instrument: it logs each fade and checks, a fixed horizon later, whether price actually reverted — reporting Edge versus the unconditional base rate.
A regime read without a stretch is just a state label; a stretch without the regime is a naive fade; either without calibration is an untested assertion. Chained, they answer one question end to end. Remove a part and the chain breaks.
HOW IT WORKS
The exponent is estimated by the structure-function (generalized-Hurst) method: for several lags, the windowed mean of |log-price(t) − log-price(t−lag)| scales like lag^H, so the exponent is the slope of log(mean|Δ|) against log(lag). The first-moment (absolute) form is used deliberately because it is the variant most robust to the heavy tails of financial returns — Monte-Carlo studies find the generalized-Hurst approach gives the lowest bias and variance of the common estimators on heavy-tailed data.
A short optional smoothing tames the noise inherent to short-window local estimates (very short windows are known to produce volatile readings and false alarms).
A stretch z-score and the regime thresholds combine into the fade flag.
The harness logs each fade and, a fixed horizon later, checks a ≥ k × ATR reversion.
HOW TO USE
Read the line for regime: in the green (reverting) zone, mean-reversion / fade setups have the wind behind them; in the gold (trending) zone, expect continuation and treat reversion setups with suspicion; near 0.5 the tape is effectively random. The fade dots mark reverting-and-stretched moments. Then read the Edge row — a regime filter only earns its keep if fades taken inside it beat the unconditional base rate. Context, never a standalone trigger.
Three visual styles are provided (Gradient area + glow / Histogram / Line).
UNIVERSAL ACROSS MARKETS
The price source is an input, so the engine runs on any instrument and timeframe. Defaults target intraday index futures (e.g. NSE NIFTY); change the source for any other market. The reading is self-normalising around 0.5, so the same regime bands work everywhere.
ORIGINALITY
The exponent itself is a standard public statistic, credited below. The original work is the assembly: a structure-function persistence estimator chosen for heavy-tail robustness and smoothed against short-window noise, gated against a stretch z-score into a located fade event, and tied to a forward base-rate calibration so the regime claim is tested on each instrument rather than asserted. It is a regime and validation tool, not a plain exponent plot. No third-party Pine code is reused.
CONCEPT CREDIT
The scaling exponent and rescaled-range analysis — Harold E. Hurst (1951). Fractional / self-similar processes and the generalized exponent — Benoit Mandelbrot. The structure-function (generalized-Hurst) estimator is the variant most robust to heavy-tailed financial data. The anti-persistence-anticipates-reversion application follows recent local-exponent mean-reversion research (2024). Not affiliated with, nor endorsed by, any third party.
HONESTY / LIMITATIONS
The exponent is an estimate from a finite window — it is noisy and lags, and short windows can raise false alarms (which is why a smoothing control is provided, on by default). A low reading is context, not a trigger. The Edge figures are in-sample, close-to-close, with overlapping forward windows and no costs — descriptive context, not a verified backtest. An Edge near zero or negative is the harness honestly reporting that the regime read isn't helping here; do not tune until it turns green — that is curve-fitting. Nothing here predicts direction.
DISCLAIMER
Research and educational tool only. NOT financial advice and NO guarantee of profitability or accuracy. Indicators describe past behaviour; they do not predict the future. Trading carries risk of loss. Test out-of-sample and make your own decisions. The author accepts no liability for any use of this script.
Notas de Lançamento
Trend Persistence OscillatorWhat it is. A regime read based on long-memory behaviour: whether the series is currently trending (persistent), mean-reverting (anti-persistent), or behaving like noise.
What's new in this update
Reusable regime gate. A single, clean output now reports one of three states — trend-ok, revert-ok, or stand-aside (the transitional zone) — designed to be consumed by your other scripts as a filter on when to engage a strategy, rather than as an entry signal itself.
Fractal-dimension read (a complexity/roughness companion to the persistence estimate) is added for a fuller picture of market character.
Calibration honesty layer: event-sampling, streak-dependence check and confidence floor.
How the parts work together. The persistence estimate and the fractal-dimension read describe the character of the market; the three-state gate turns that character into a single actionable filter. The design intent is meta-filtering — deciding when a trend or mean-reversion approach is appropriate — not direction-calling.
Reusable outputs. The three-state regime gate, the fractal-dimension read, the persistence value and the calibration edge/floor are published to the Data Window for input.source() use across the suite.
Educational only — the persistence estimate is noisy and is a filter, not a signal. Not financial advice.
Notas de Lançamento
v3.0 — Two-lens regime classifier + honest out-of-sample harness (renamed from Trend Persistence Oscillator)- Added a second, independent lens: the Lo-MacKinlay VARIANCE RATIO with a heteroskedasticity-robust
z (correct under volatility clustering) and a Chow-Denning joint random-walk test across q = 2/4/8.
It sits beside the persistence (Hurst) exponent, and the two are fused into a 5-state regime —
Strong Trend / Trend / Random / Revert / Strong Revert — with a confidence from how far each lens is
from random and whether they agree. Disagreement reads as an honest "Mixed / stand aside."
- Calibration overhaul: the fade track-record now uses a uniqueness-weighted EFFECTIVE sample size
(overlapping windows aren't independent), a multiple-testing DEFLATED significance bar, and an
IN-SAMPLE vs OUT-OF-SAMPLE split — the OOS edge is the one to trust.
- New regime ribbon along the pane bottom, a verdict-led panel, and an expanded EXP_* bus
(EXP_Regime is now a −2…+2 state, plus EXP_VR, EXP_VRz, EXP_RWreject, EXP_EdgeOOS, EXP_Neff …).
- The persistence engine, theme, fades and non-repaint behaviour are unchanged.
Descriptive market-state classifier, in-sample-and-out-of-sample statistics, not investment advice.
Script de código aberto
Em verdadeiro espírito do TradingView, o criador deste script o tornou de código aberto, para que os traders possam revisar e verificar sua funcionalidade. Parabéns ao autor! Embora você possa usá-lo gratuitamente, lembre-se de que a republicação do código está sujeita às nossas Regras da Casa.
Aviso legal
As informações e publicações não se destinam a ser, e não constituem, conselhos ou recomendações financeiras, de investimento, comerciais ou de outro tipo fornecidos ou endossados pela TradingView. Leia mais nos Termos de Uso.
Script de código aberto
Em verdadeiro espírito do TradingView, o criador deste script o tornou de código aberto, para que os traders possam revisar e verificar sua funcionalidade. Parabéns ao autor! Embora você possa usá-lo gratuitamente, lembre-se de que a republicação do código está sujeita às nossas Regras da Casa.
Aviso legal
As informações e publicações não se destinam a ser, e não constituem, conselhos ou recomendações financeiras, de investimento, comerciais ou de outro tipo fornecidos ou endossados pela TradingView. Leia mais nos Termos de Uso.