OPEN-SOURCE SCRIPT
Actualizado Ljung-Box Serial Dependence Monitor

Ljung-Box Serial Dependence Monitor
Explore serial correlation in returns and in the size of price changes.
This indicator calculates a rolling Ljung-Box Q statistic and its approximate chi-square p-value. It combines the joint test with individual autocorrelations and a compact summary table in a separate pane.
THREE TEST SERIES
• Returns: log returns by default, with simple percentage returns available as an alternative.
• Squared returns: applies the calculation to squared returns.
• Absolute returns: applies the calculation to absolute returns.
The latter two modes explore dependence in return magnitude, including patterns consistent with volatility clustering. They do not establish a particular ARCH/GARCH model.
HOW THE TEST WORKS
For each window, the script subtracts the sample mean and estimates autocorrelations at lags 1 through h. It calculates:
Q = n × (n + 2) × sum[r(k)² / (n − k)], for k = 1…h.
The p-value uses an approximate chi-square distribution with h degrees of freedom. No fitted time-series model or residual degrees-of-freedom adjustment is applied.
A p-value below the selected significance level flags evidence against the joint hypothesis of zero autocorrelation at the tested lags. A larger p-value does not prove independence or unpredictability.
READING THE DISPLAY
• Yellow line: rolling p-value, on a 0–1 scale.
• Dashed level: selected significance threshold; 5% is shown as 0.05.
• Colored background: windows flagged as significant.
• Optional ACF lines: autocorrelation at lags 1, 2 and 3, where included in the lag setting.
• Table: sample size, lag count, Q, p-value, first three ACF values, summed ACF and a descriptive verdict.
The optional ACF band is the simple normal-approximation reference ±z/sqrt(n), labeled “Bartlett” in the script. It is not a simultaneous confidence band across all lags.
WHAT THE REGIME LABELS MEAN
The Ljung-Box statistic squares autocorrelations and does not determine the direction of dependence. This implementation adds a separate heuristic based on the sign of the sum of the tested autocorrelations.
For significant return windows, a positive sum produces the “Momentum / persistence” label; a negative sum produces “Mean reversion.” For transformed-return windows, the corresponding labels describe positive or negative dependence in return magnitude.
These labels summarize the sampled ACF pattern. They are not directional price forecasts or validated trading signals. Positive and negative correlations at different lags can offset one another in the sum.
ILLUSTRATIVE EXAMPLE
With 250 observations, 10 lags and a 5% threshold, a hypothetical p-value of 0.02 is below 0.05 and is highlighted. A p-value of 0.20 is not highlighted.
The first result does not mean a 98% probability that a trade will succeed. The sign-based label requires separate inspection of the ACF pattern. These numbers are illustrative, not backtest results.
SETTINGS AND ALERTS
Defaults are 250 observations, 10 lags, log returns and a 5% significance level. A full window must be available, and the implementation requires h < n/4. Choose a lookback strictly greater than four times the lag count; otherwise the script remains in its warm-up state.
Four alert conditions are included: dependence becomes significant, dependence disappears, positive-sum regime begins and negative-sum regime begins. The last two retain the script's “Momentum regime” and “Mean-reversion regime” alert names even in squared/absolute-return modes; in those modes they concern return magnitude, not price direction.
Values and conditions can change during an open bar. For alerts based on completed candles, select Once Per Bar Close when creating the alert in TradingView.
INTERPRETATION AND LIMITATIONS
Rolling windows overlap, and repeated tests are not independent. There is no multiple-testing correction. The chi-square approximation and the simple ACF reference band rely on statistical assumptions; changing volatility and other departures from these assumptions can affect interpretation.
Missing values are skipped by the sample buffer, so gaps may cause the window to represent the latest valid observations rather than consecutive chart bars. A constant window has no defined autocorrelation; absent Q or p-values must not be read as evidence of independence. Extreme tail probabilities can round to zero numerically. Larger lookbacks and lag counts increase computation substantially.
This is a statistical research display. It does not place trades, estimate expected returns or establish a profitable strategy.
METHOD REFERENCE
NIST: Box-Ljung Test — itl.nist.gov/div898/handbook/pmc/section4/pmc4481.htm
Explore serial correlation in returns and in the size of price changes.
This indicator calculates a rolling Ljung-Box Q statistic and its approximate chi-square p-value. It combines the joint test with individual autocorrelations and a compact summary table in a separate pane.
THREE TEST SERIES
• Returns: log returns by default, with simple percentage returns available as an alternative.
• Squared returns: applies the calculation to squared returns.
• Absolute returns: applies the calculation to absolute returns.
The latter two modes explore dependence in return magnitude, including patterns consistent with volatility clustering. They do not establish a particular ARCH/GARCH model.
HOW THE TEST WORKS
For each window, the script subtracts the sample mean and estimates autocorrelations at lags 1 through h. It calculates:
Q = n × (n + 2) × sum[r(k)² / (n − k)], for k = 1…h.
The p-value uses an approximate chi-square distribution with h degrees of freedom. No fitted time-series model or residual degrees-of-freedom adjustment is applied.
A p-value below the selected significance level flags evidence against the joint hypothesis of zero autocorrelation at the tested lags. A larger p-value does not prove independence or unpredictability.
READING THE DISPLAY
• Yellow line: rolling p-value, on a 0–1 scale.
• Dashed level: selected significance threshold; 5% is shown as 0.05.
• Colored background: windows flagged as significant.
• Optional ACF lines: autocorrelation at lags 1, 2 and 3, where included in the lag setting.
• Table: sample size, lag count, Q, p-value, first three ACF values, summed ACF and a descriptive verdict.
The optional ACF band is the simple normal-approximation reference ±z/sqrt(n), labeled “Bartlett” in the script. It is not a simultaneous confidence band across all lags.
WHAT THE REGIME LABELS MEAN
The Ljung-Box statistic squares autocorrelations and does not determine the direction of dependence. This implementation adds a separate heuristic based on the sign of the sum of the tested autocorrelations.
For significant return windows, a positive sum produces the “Momentum / persistence” label; a negative sum produces “Mean reversion.” For transformed-return windows, the corresponding labels describe positive or negative dependence in return magnitude.
These labels summarize the sampled ACF pattern. They are not directional price forecasts or validated trading signals. Positive and negative correlations at different lags can offset one another in the sum.
ILLUSTRATIVE EXAMPLE
With 250 observations, 10 lags and a 5% threshold, a hypothetical p-value of 0.02 is below 0.05 and is highlighted. A p-value of 0.20 is not highlighted.
The first result does not mean a 98% probability that a trade will succeed. The sign-based label requires separate inspection of the ACF pattern. These numbers are illustrative, not backtest results.
SETTINGS AND ALERTS
Defaults are 250 observations, 10 lags, log returns and a 5% significance level. A full window must be available, and the implementation requires h < n/4. Choose a lookback strictly greater than four times the lag count; otherwise the script remains in its warm-up state.
Four alert conditions are included: dependence becomes significant, dependence disappears, positive-sum regime begins and negative-sum regime begins. The last two retain the script's “Momentum regime” and “Mean-reversion regime” alert names even in squared/absolute-return modes; in those modes they concern return magnitude, not price direction.
Values and conditions can change during an open bar. For alerts based on completed candles, select Once Per Bar Close when creating the alert in TradingView.
INTERPRETATION AND LIMITATIONS
Rolling windows overlap, and repeated tests are not independent. There is no multiple-testing correction. The chi-square approximation and the simple ACF reference band rely on statistical assumptions; changing volatility and other departures from these assumptions can affect interpretation.
Missing values are skipped by the sample buffer, so gaps may cause the window to represent the latest valid observations rather than consecutive chart bars. A constant window has no defined autocorrelation; absent Q or p-values must not be read as evidence of independence. Extreme tail probabilities can round to zero numerically. Larger lookbacks and lag counts increase computation substantially.
This is a statistical research display. It does not place trades, estimate expected returns or establish a profitable strategy.
METHOD REFERENCE
NIST: Box-Ljung Test — itl.nist.gov/div898/handbook/pmc/section4/pmc4481.htm
Notas de prensa
Compact dashboard update• The table now defaults to the top-right corner.
• A compact four-row view replaces the larger six-row table by default, leaving more room for the p-value curve.
• Compact view shows series and n/h, p-value and significance level, Q and summed ACF, and a short descriptive state.
• Disable “Compact table” in Display settings to restore the detailed table with individual ACF values and the reference band. All four table positions remain available.
The calculation, p-value curve, significance highlighting and alert conditions are unchanged. Positive/negative ACF-sum labels are descriptive; they are not directional trading signals.
If an existing chart retains the previous position, select “Top Right” under Table position.
Script de código abierto
Fiel al espíritu de TradingView, el creador de este script lo ha convertido en código abierto, para que los traders puedan revisar y verificar su funcionalidad. ¡Enhorabuena al autor! Aunque puede utilizarlo de forma gratuita, recuerde que cualquier republicación del código está sujeta a nuestras Normas internas.
Exención de responsabilidad
La información y las publicaciones no constituyen, ni deben considerarse como, asesoramiento o recomendaciones financieras, de inversión, de trading u otro tipo, proporcionadas o respaldadas por TradingView. Obtenga más información en Condiciones de uso.
Script de código abierto
Fiel al espíritu de TradingView, el creador de este script lo ha convertido en código abierto, para que los traders puedan revisar y verificar su funcionalidad. ¡Enhorabuena al autor! Aunque puede utilizarlo de forma gratuita, recuerde que cualquier republicación del código está sujeta a nuestras Normas internas.
Exención de responsabilidad
La información y las publicaciones no constituyen, ni deben considerarse como, asesoramiento o recomendaciones financieras, de inversión, de trading u otro tipo, proporcionadas o respaldadas por TradingView. Obtenga más información en Condiciones de uso.