LjungBox (ljung_box v0.1.0)
Copy MarkdownThe Ljung-Box test for autocorrelation in time series residuals.
The Ljung-Box Q-statistic tests the null hypothesis that a series of residuals are independently distributed (i.e., exhibit no autocorrelation). It is commonly used to validate ARIMA model residuals.
Formula
The Q-statistic is defined as:
Q = n(n+2) * Σ_{k=1}^{h} ρ̂_k² / (n - k)where n is the number of observations, h is the number of lags tested,
and ρ̂_k is the sample autocorrelation at lag k.
Under the null hypothesis of no autocorrelation, Q follows a chi-squared
distribution with h degrees of freedom (or h - p - q when applied to
ARMA(p, q) residuals).
Interpretation
- p-value < 0.05: Reject the null hypothesis; there is significant autocorrelation at the tested lags.
- p-value ≥ 0.05: Fail to reject the null hypothesis; the series is consistent with white noise at the tested lags.
See test/2 for usage examples.
Summary
Functions
Computes the sample autocorrelation of series at the given lag.
Computes sample autocorrelations of series at lags 1 through max_lag.
Computes the Ljung-Box Q-statistic for series at up to lags lags.
Runs the Ljung-Box test on series up to lags lags.
Functions
@spec autocorrelation([number()], non_neg_integer()) :: float()
Computes the sample autocorrelation of series at the given lag.
Returns 0.0 when the series has zero variance (constant series).
Examples
iex> LjungBox.autocorrelation([1, 2, 3, 4], 1)
0.25
iex> LjungBox.autocorrelation([1, 2, 3, 4], 0)
1.0
iex> LjungBox.autocorrelation([5, 5, 5, 5], 1)
0.0
@spec autocorrelations([number()], pos_integer()) :: [float()]
Computes sample autocorrelations of series at lags 1 through max_lag.
Returns a list of max_lag floats.
Examples
iex> length(LjungBox.autocorrelations([1, 2, 3, 4, 5], 3))
3
@spec statistic([number()], pos_integer()) :: float()
Computes the Ljung-Box Q-statistic for series at up to lags lags.
Examples
iex> q = LjungBox.statistic([1, 2, 3, 4], 2)
iex> Float.round(q, 2)
1.58
@spec test([number()], pos_integer()) :: %{ statistic: float(), p_value: float(), lags: pos_integer(), n: pos_integer() }
Runs the Ljung-Box test on series up to lags lags.
Returns a map with:
:statistic– the Q value:p_value– probability of observing a Q this large under H₀:lags– number of lags tested:n– number of observations
A low p-value (typically < 0.05) indicates significant autocorrelation.
Examples
iex> result = LjungBox.test([1, 2, 1, 2, 1, 2, 1, 2, 1, 2], 2)
iex> result.lags
2
iex> result.n
10