Skip to main content

ndiffs

Function ndiffs 

Source
pub fn ndiffs(x: &[f64], alpha: f64, max_d: usize) -> usize
Expand description

The number of differences that make x level-stationary by KPSS, at most max_d.

Differences while kpss (level) rejects stationarity at alpha, as R’s forecast::ndiffs does. Use it to pick d before fitting.

The KPSS lag is R’s trunc(3 sqrt(n) / 13), recomputed for each difference. pmdarima’s ndiffs uses kpss_short_lags instead, and so can choose another d; this function matches R (checked against forecast 8.23).

The KPSS table only covers [0.01, 0.10], so alpha is clamped to that range, as R does, and a test rejects when its statistic exceeds the critical value at alpha (interpolated in the same table). Comparing clipped p-values instead would make the ends of the range misbehave. Non-finite values are dropped first; a series too short to test counts as needing no more differences.

§Examples

use backshift::ndiffs;

// A random walk: its first difference is white noise.
let mut y = vec![0.0];
let mut state = 2_u32;
for _ in 0..199 {
    state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
    y.push(y.last().unwrap() + f64::from(state >> 8) / f64::from(1_u32 << 24) - 0.5);
}
assert_eq!(ndiffs(&y, 0.05, 2), 1);