run_varx: Fit VARX model with diagnostics for I and C

View source: R/tvar-star.R

run_varxR Documentation

Fit VARX model with diagnostics for I and C

Description

Estimates a bivariate VAR model for I and C with exogenous covariates (VARX), and computes a set of standard diagnostics (stability, serial correlation, normality, ARCH). The fitted model and diagnostics are saved to disk and also returned.

Usage

run_varx(DT, p = 2, dir_out = NULL)

Arguments

DT

A data.table (or data.frame) containing at least the following columns:

  • I, C: endogenous variables for the VAR.

  • EconCycle, PopDensity, Epidemics, Climate, War, t_norm: exogenous regressors included in the VARX.

p

Integer; lag order of the VAR part (number of lags for I and C).

dir_out

Character scalar or NULL; directory where the fitted model and diagnostics ("varx_fit.rds") are saved. If NULL (default), nothing is saved to disk.

Details

This function requires the vars package (listed under Suggests); an informative error is raised at call time if it is not installed.

The endogenous vector is y_t = (I_t, C_t)' and the exogenous regressors are: EconCycle, PopDensity, Epidemics, Climate, War, t_norm. The model is fit using vars::VAR() with type = "const" and the exogenous matrix passed via exogen.

After estimation, the following diagnostics from vars are (attempted to be) computed:

  • vars::stability(fit, type = "OLS-CUSUM") for stability.

  • vars::serial.test(fit, lags.pt = 10, type = "PT.asymptotic") for serial correlation.

  • vars::normality.test(fit) for residual normality.

  • vars::arch.test(fit, lags.multi = 5) for ARCH effects.

Each diagnostic call is wrapped in try(), so if a diagnostic fails, the corresponding element in the output will contain a "try-error" instead of stopping the function.

When dir_out is supplied, the result is saved as an RDS file named "varx_fit.rds" in that directory.

Value

A list with components:

  • fit: the estimated VAR model (vars object).

  • stability: result of vars::stability() (or "try-error" on failure).

  • serial: result of vars::serial.test() (or "try-error" on failure).

  • normal: result of vars::normality.test() (or "try-error" on failure).

  • arch: result of vars::arch.test() (or "try-error" on failure).

Examples


# This example runs only when 'vars' is installed.
if (requireNamespace("vars", quietly = TRUE)) {
  DT <- data.table::data.table(
    I = rpois(50, lambda = 10),
    C = rpois(50, lambda = 8),
    EconCycle = rnorm(50),
    PopDensity = rnorm(50),
    Epidemics = rnorm(50),
    Climate = rnorm(50),
    War = rnorm(50),
    t_norm = seq(-1, 1, length.out = 50)
  )

  # p = 1 keeps the example fast and stable.
  res_varx <- run_varx(DT, p = 1)
  if (!inherits(res_varx$fit, "try-error")) {
    print(res_varx$fit)
  }
}



bivarhr documentation built on July 7, 2026, 1:06 a.m.