unitroottools (R): Public API

Software reference for Applied Time Series Econometrics (ATSE)

Miguel A. Arranz, PhD

Overview and purpose

unitroottools provides unit-root and stationarity tests for the Applied Time Series Econometrics (ATSE) course at Universidad Carlos III de Madrid, with one consistent interface and full transparency about how each decision was reached. It is the R companion of the Python package UnitRoot-Tools; both follow a common, language-neutral specification.

This document describes the software/API. The ATSE course material provides the econometric theory; the Labs provide worked examples and exercises. A longer tutorial is the package vignette, rendered here.

Three conventions hold throughout:

What R already provides

unitroottools Closest existing R tool Why the function is kept
adf() urca::ur.df(), tseries::adf.test() MAIC/MBIC lag selection on a common sample, MacKinnon critical values and p-values at the effective sample size, the φ statistics with their tables, full selection table
ur_strategy() — Dolado–Jenkinson–Sosvilla-Rivero / Enders procedure, a conservative variant and Hamilton’s rule, each step recorded
pp() urca::ur.pp() Follows the published formula (urca’s version differs by up to 0.1 in small samples); p-value
dfgls() urca::ur.ers() Same statistic (computed internally); lag selection by Perron and Qu (2007); finite-sample critical values and p-value (urca’s are too liberal: about 8% size at a nominal 5% with T = 100)
kpss() urca::ur.kpss(), tseries::kpss.test() Same statistic; kernels and automatic bandwidths; critical values and p-value from the limiting distribution, computed numerically (the published table is off in the third decimal)
tidy(), glance() — Results of any test as data frames

Installation and loading

# install.packages("remotes")
remotes::install_github("maarranz/UnitRoot-Tools-R", build_vignettes = TRUE)

Dependencies (urca, generics) are installed automatically. Building the vignette needs pandoc, which comes with RStudio; without it, leave out build_vignettes = TRUE and read the vignette here. To install a specific version, add the tag: "maarranz/UnitRoot-Tools-R@v0.3.2".

library(unitroottools)

Example used below

The logarithm of U.S. real GDP, 1947Q1–2012Q4 (264 observations), the example Enders uses for the testing of unit roots when the deterministic terms are unknown. The data come with the package.

gdp  <- read.csv(system.file("fixtures", "enders_rgdp.csv", package = "unitroottools"))
lgdp <- ts(log(gdp$rgdp), start = c(1947, 1), frequency = 4)

The augmented Dickey–Fuller test

The test regression is

Δyt=a+γt+byt−1+∑j=1kβjΔyt−j+εt,H0:b=0(unit root)H1:b<0, \Delta y_t = a + \gamma t + b\, y_{t-1} + \sum_{j=1}^{k} \beta_j \Delta y_{t-j} + \varepsilon_t , \qquad H_0: b = 0 \ \text{(unit root)} \quad H_1: b < 0,

with trend = "n" (no deterministic terms), "c" (constant, γ=0\gamma = 0) or "ct" (constant and trend).

adf(lgdp, trend = "ct")
Augmented Dickey-Fuller test (tau3)

  H0: unit root
  H1: stationary around a linear trend
  Deterministics: constant and linear trend
  Lags: 1 (MAIC, kmax = 15)
  Effective sample: N = 262 (t = 3, ..., 264)

  Statistic:        -1.489
  Critical values:  1%: -3.994   5%: -3.427   10%: -3.137
  Source:           MacKinnon (2010) response surface
  p-value:          0.831

  Decision at 5%: do not reject H0 (unit root)

summary() adds the φ statistics (joint tests of the unit root and the deterministic terms) with their critical values, the lag-selection table and the test regression. Arguments: lags (fixed number of lagged differences), max_lags, criterion ("MAIC", "MBIC", "AIC", "BIC"), final_sample, level (0.01, 0.05 or 0.10) and var (column of a data frame).

Choosing the number of lags

select_lags() compares k=0,…,kmaxk = 0, \dots, k_{\max}, with kmax=⌊12(T/100)1/4⌋k_{\max} = \lfloor 12 (T/100)^{1/4} \rfloor (Schwert 1989), on the same observations, and returns the whole table. The default criterion is the modified AIC of Ng and Perron (2001), computed on the series detrended by OLS. After selection, adf() re-estimates the test regression with all observations available for the chosen order; final_sample = "common" keeps the selection sample.

select_lags(lgdp, trend = "ct")    # MAIC selects k = 1 out of 0, ..., 15

Checking the residuals

The lagged differences must leave white-noise residuals. residual_check() reports the correlogram of the test regression’s residuals (AC, PAC and Ljung–Box QQ, whose p-values use h−kh - k degrees of freedom and are approximate in a regression with lagged dependent variables) and the Breusch–Godfrey test (F form, the main one, and NR2N R^2), valid with lagged dependent variables. The number of lags follows the frequency ss of the data: 3s+33s + 3 (15 quarterly, 39 monthly, 6 annual), capped at N/4N/4, with Breusch–Godfrey at orders ss and 3s+33s + 3; a plain vector is treated as annual unless frequency is given. plot() draws the ACF and PACF with ±1.96/N\pm 1.96/\sqrt N bands. It applies to adf(), dfgls(), ng_perron(), ers_pt() and strategies, not to pp() or kpss(), whose residuals are autocorrelated by design. summary() shows the Breusch–Godfrey p-values, results whose residuals fail carry a warning, and the strategy history has a column bg_p_value. Lags are never raised automatically.

rc <- residual_check(adf(lgdp, trend = "ct"))   # no autocorrelation with k = 1
plot(rc)
adf(lgdp, trend = "ct", lags = 0)$warnings       # with k = 0: autocorrelated

Recursive and rolling tests

recursive_adf() computes the ADF statistic on samples with a fixed start and a moving end (window = "recursive", first sample max(5s,30)\max(5s, 30) observations) or on rolling windows (window = "rolling", width max(10s,40)\max(10s, 40)), with the lags selected once on the full sample and kept fixed, which uses later observations to set the lag order of early windows (reselect = TRUE selects them in each window, capped by max_lags if given). Each statistic is compared with the critical value for its own sample size; these are nominal pointwise references (one date chosen in advance, fixed lag order), not valid for the minimum over windows (Banerjee, Lumsdaine and Stock 1992). It returns a data frame (start, end, NN, kk, statistic, critical value, p-value, decision) with print() and plot().

plot(recursive_adf(lgdp, trend = "ct"))
plot(recursive_adf(lgdp, trend = "ct", window = "rolling"))

Which deterministic terms? Specification strategies

ur_strategy() decides the deterministic terms and tests for a unit root in one call, recording every step:

ur_strategy(lgdp, "original", lags = 1)
Specification strategy: Original (Dolado-Jenkinson-Sosvilla-Rivero / Enders)

  Lags: 1 (fixed)
  Sample (all regressions): N = 262 (t = 3, ..., 264)   Level: 5%

  Step Regr.  Test       Statistic Crit.val.  p-value  Decision    Next
  1    ct     tau3          -1.489    -3.427    0.831  not reject  test phi3
  2    ct     phi3           2.966     6.337    0.471  not reject  go to stage C
  3    c      tau2          -2.049    -2.873    0.266  not reject  test phi1
  4    c      phi1          25.485     4.631  < 0.001  reject      test constant, b = 0 imposed
  5    aux_c  t(const)       6.797     1.969  < 0.001  reject      conditional t test of b
  6    c      t(b) cond.    -2.049    -1.651    0.021  reject      stop

  Specification: constant
  Conclusion:    no unit root: stationary around a non-zero mean

  Note: p-values are for each step on its own;
  no p-value or size is reported for the sequence as a whole.

The original procedure removes the trend and then rejects the unit root through a conventional t test justified by the constant, a conclusion Enders himself rejects for GDP. The conservative variant keeps the constant and does not reject (unit root (constant retained)); Hamilton’s rule with trending = TRUE uses τ3\tau_3 only (unit root (with drift)). The history ($history, or tidy()) separates rejections of the unit root from rejections that only decide the path of the procedure.

Other tests

pp(lgdp, trend = "ct")       # Phillips-Perron Z_tau
dfgls(lgdp, trend = "ct")    # Elliott-Rothenberg-Stock DF-GLS
kpss(lgdp, trend = "ct")     # KPSS: H0 is stationarity
ng_perron(lgdp, trend = "ct")  # Ng-Perron M tests (MZ_t reported; MZ_a, MSB, MP_T alongside)
ers_pt(lgdp, trend = "ct")     # ERS point-optimal P_T
boot_ur(lgdp, trend = "ct", B = 999, seed = 1)   # bootstrap ADF (needs bootUR)

Results as data frames

glance() gives one row per test, tidy() one row per statistic (on a strategy: one row per outcome, and the history):

tests <- list(adf(lgdp, trend = "ct"), pp(lgdp, trend = "ct"),
              dfgls(lgdp, trend = "ct"), ng_perron(lgdp, trend = "ct"),
              kpss(lgdp, trend = "ct"))
res <- do.call(rbind, lapply(tests, glance))
res[, c("test", "statistic_name", "statistic", "p_value", "reject", "lags", "nobs")]
       test statistic_name statistic p_value reject lags nobs
1       ADF           tau3   -1.4891  0.8312  FALSE    1  262
2        PP          Z_tau   -1.1105  0.9243  FALSE    5  263
3    DF-GLS        tau_GLS   -1.0193  0.8625  FALSE    1  262
4 Ng-Perron            MZt   -1.0664  0.8445  FALSE    1  262
5      KPSS        eta_tau    0.7008  0.0000   TRUE    5  264

All five point the same way for log GDP: the unit root is not rejected, and stationarity around a trend is rejected.

Critical values and p-values

Statistic Critical values p-value
τ\tau (ADF), ZτZ_\tau (PP) MacKinnon (2010) response surfaces at the effective NN; MacKinnon (1996) without deterministic terms MacKinnon (1996), finite-sample, same NN
ϕ1,ϕ2,ϕ3\phi_1, \phi_2, \phi_3 Own response surfaces in (T,k)(T, k) from a Monte Carlo simulation (code in data-raw/); they reproduce Dickey and Fuller’s (1981) tables without lags Interpolated between the simulated quantiles; reported as < 0.001 or > 0.999 beyond them
ZαZ_\alpha (PP) Own response surface for the Dickey–Fuller normalized bias, which has the same limit same surface
DF-GLS Own response surfaces in (T,k)(T, k) from a Monte Carlo simulation Interpolated between the simulated quantiles; reported as < 0.001 or > 0.999 beyond them
Ng–Perron M tests, ERS PTP_T Own simulation, tabulated in (T,k)(T, k) and interpolated in 1/T1/T Interpolated between the simulated quantiles; reported as < 0.001 or > 0.999 beyond them
Bootstrap (boot_ur()) none bootUR’s bootstrap p-value
KPSS Limiting distribution, computed numerically (kernel eigenvalues, Imhof inversion) same distribution; < 0.001 or > 0.999 beyond its 0.001/0.999 quantiles
Conditional and auxiliary t tests in strategies Student t Student t

Every result records its source in $calibration, and warns when the sample is below 25 observations or outside the simulated range.

Compact API summary

Function Purpose Returns
adf(y, trend, lags, max_lags, criterion, final_sample, level, var) Augmented Dickey–Fuller test ur_test
select_lags(y, trend, max_lags, criterion, var) Lag order by MAIC, MBIC, AIC or BIC, with the full table ur_lags
ur_strategy(y, strategy, trending, allow_no_constant, lags, max_lags, criterion, final_sample, level, var) Deterministic terms and unit-root decision, step by step ur_strategy
pp(y, trend, kernel, bandwidth, level, var) Phillips–Perron ZτZ_\tau (and ZαZ_\alpha) ur_test
dfgls(y, trend, lags, max_lags, criterion, level, var) DF-GLS test ur_test
kpss(y, trend, kernel, bandwidth, level, var) KPSS test of stationarity ur_test
ng_perron(y, trend, lags, max_lags, criterion, statistic, level, var) Ng–Perron M tests ur_test
ers_pt(y, trend, lags, max_lags, criterion, level, var) ERS point-optimal test ur_test
boot_ur(y, trend, bootstrap, B, union, detrend, lags, max_lags, criterion, criterion_scale, seed, level, var) Bootstrap ADF or union test through bootUR ur_test
residual_check(x, lags, bg_orders, frequency) Correlogram and Breusch–Godfrey test of the test regression’s residuals, with plot() ur_residual_check
recursive_adf(y, trend, lags, max_lags, criterion, window, min_size, width, reselect, frequency, level, var) Recursive or rolling ADF statistics, with plot() ur_recursive (data frame)
simulate_df(T, R, trend, seed) Simulated Dickey–Fuller distribution, with plot() df_simulation
tidy(x), glance(x) Results as data frames data frame
match_trend(trend) Canonical deterministic code from an alias string
new_ur_test(), validate_ur_test() Build and check a result object (for developers) ur_test

A ur_test is a list: statistic, statistic_name, critical_values, p_value, reject, level, tail, trend, lags, lag_selection, nobs, sample, calibration, other_statistics (e.g. the φ statistics), engine, warnings, regression (including the residuals and regressors of the test regression), series (name, frequency, time points), call. Accepted inputs: numeric vectors, ts, zoo, xts, data frames, tibbles and tsibbles (choose a column with var).

Agreement with the Python version

Both implementations follow the same specification, which records every convention as a numbered decision. The ADF regressions, φ statistics and auxiliary tests are checked against 120-digit reference calculations shared with the Python package (agreement better than 3×10−153 \times 10^{-15}), and the τ\tau critical values agree to 10−1510^{-15}. Known differences of the Python version are listed in notes-for-python.md.

Course, resources, and author

ATSE course material and Labs — Universidad Carlos III de Madrid: public link to be added when available. The course material supplies theory; the Labs supply fuller examples and exercises. This API reference is not a substitute for either.

Miguel A. Arranz, PhD
Department of Economics
Universidad Carlos III de Madrid (UC3M)
Email: maarranz@eco.uc3m.es
ORCID: 0000-0002-5951-2284

Rebuilding the HTML

The examples are ordinary R code blocks, validated in a fresh session rather than executed during rendering. Equations are rendered as MathML, which needs no external script or fonts. With Quarto (or pandoc) installed, from the repository root:

quarto pandoc docs/unitroottools_Documentation.qmd \
  --from markdown --to html5 --standalone --toc --toc-depth=2 \
  --mathml --embed-resources -o docs/index.html
Rscript -e 'rmarkdown::render("vignettes/unitroottools.Rmd",
  output_format = rmarkdown::html_vignette(math_method = "mathml"),
  output_dir = "docs", output_file = "vignette.html")'