Learn R Programming

gmvarkit

The goal of gmvarkit is to provide tools to analyse structural and reduced form Gaussian mixture vector autoregressive (GMVAR) model, Student’s t mixtue vector autoregressive (StMVAR) model, and Gaussian and Student’s t mixture vector autoregressive (G-StMVAR) model. gmvarkit provides functions for unconstrained and constrained maximum likelihood estimation of the model parameters, quantile residual based model diagnostics, simulation from the processes, forecasting, estimation of generalized impulse response function, and more.

Installation

You can install the released version of gmvarkit from CRAN with:

install.packages("gmvarkit")

And the development version from GitHub with:

# install.packages("devtools")
devtools::install_github("saviviro/gmvarkit")

Example

Simple example

This is a basic example on how to use gmvarkit in time series analysis. The estimation process is computationally demanding and takes advantage of parallel computing. After estimating the model, it is shown by simple examples how to conduct some further analysis. StMVAR and G-StMVAR model are briefly covered after giving examples related to the reduced form and structural GMVAR model.

# These examples use the data 'gdpdef' which comes with the package, and contains the quarterly percentage growth rate
# of real U.S. GDP and quarterly percentage growth rate of U.S. GDP implicit price deflator, covering the period 
# from 1959Q1 to 2019Q4.
data(gdpdef, package="gmvarkit")

## Reduced form GMVAR model ##

# Estimate a GMVAR(2, 2) model: 20 estimation rounds and seeds for reproducible results
# (note: many empirical applications require more estimation rounds, e.g., hundreds
# or thousands).
fit <- fitGSMVAR(gdpdef, p=2, M=2, ncalls=20, seeds=1:20, ncores=2)
fit

# Estimate a GSMVAR(2, 2) model with autoregressive parameters restricted to be the same for all regimes
C_mat <- rbind(diag(2*2^2), diag(2*2^2))
fitc <- fitGMVAR(gdpdef, p=2, M=2, constraints=C_mat, ncalls=20, seeds=1:20, ncores=2)
fitc

# Estimate a GMVAR(2, 2) model with autoregressive parameters and the unconditional means
# restricted to be the same in both regimes (only the covariance matrix varies)
fitcm <- fitGSMVAR(gdpdef, p=2, M=2, parametrization="mean", constraints=C_mat, same_means=list(1:2),
                  ncalls=20, seeds=1:20, ncores=2)
fitcm 

# Test the above constraints on the AR parameters with likelihood ratio test:
LR_test(fit, fitc)

# Further information on the estimated model:
plot(fit)
summary(fit)
print_std_errors(fit)
get_foc(fit) # The first order condition (gradient of the log-likelihood function)
get_soc(fit) # The second order condition (eigenvalues of approximated Hessian)
profile_logliks(fit) # Profile log-likelihood functions

# Note: models can be built based the results from any estimation round 
# conveniently with the function 'alt_gmvar'.

# Quantile residual diagnostics
diagnostic_plot(fit) # type=c("all", "series", "ac", "ch", "norm")
qrt <- quantile_residual_tests(fit, nsim=10000)

# Simulate a sample path from the estimated process
sim <- simulate(fit, nsim=100)
plot.ts(sim$sample)

# Forecast future values of the process
predict(fit, n_ahead=12)


## Structural GMVAR model ##

# gmvarkit implements two identification methods: recursive identification and
# identification by heteroskedasticity. Reduced form models can be directly used
# as recursively identified structural models. The below examples consider
# identification by heteroskedasticity. 

# Estimate structural GMVAR(2,2) model identified with sign constraints:
W22 <- matrix(c(1, 1, -1, 1), nrow=2, byrow=FALSE)
fit22s <- fitGSMVAR(gdpdef, p=2, M=2, structural_pars=list(W=W22),
                    ncalls=20, seeds=1:20, ncores=2)
fit22s

# Alternatively, if there are two regimes (M=2), a stuctural model can 
# be build based on the reduced form model:
fit22s_2 <- gmvar_to_sgmvar(fit)
fit22s_2

# Columns of the matrix W can be permutated and all signs in any column
# can be swapped without affecting the implied reduced form model, as 
# long as the lambda parameters are also rearranged accordingly: 
fit22s_3 <- reorder_W_columns(fit22s_2, perm=c(2, 1))
fit22s_3

fit22s_4 <- swap_W_signs(fit22s_3, which_to_swap=2)
fit22s_4 # The same model as fit22s

all.equal(fit22s$loglik, fit$loglik)
all.equal(fit22s$loglik, fit22s_2$loglik)
all.equal(fit22s$loglik, fit22s_3$loglik)
all.equal(fit22s$loglik, fit22s_4$loglik)

# Check out also the function: estimate_sgsmvar
# for estimating overidentified structural models.

# Estimate generalized impulse response function (GIRF) with starting values
# generated from the stationary distribution of the process:
girf1 <- GIRF(fit22s, N=20, ci=c(0.95, 0.8), R1=200, R2=200, ncores=2)

# Estimate GIRF with starting values generated from the stationary distribution
# of the first regime:
girf2 <- GIRF(fit22s, N=20, ci=c(0.95, 0.8), init_regimes=1, R1=200, R2=200, ncores=2)

# Estimate GIRF with starting values given by the last p observations of the
# data:
girf3 <- GIRF(fit22s, N=20, init_values=fit22s$data, R1=1000, ncores=2)

# Estimate generalized forecast error variance decmposition (GFEVD) with the
# initial values being all possible lenght p the histories in the data:
gfevd1 <- GFEVD(fit22s, N=20, R1=100, initval_type="data", ncores=2)
plot(gfevd1)

# Estimate GFEVD with the initial values generated from the stationary
# distribution of the second regime:
gfevd2 <- GFEVD(fit22s, N=20, R1=100, R2=100, initval_type="random",
                init_regimes=2, ncores=2)
plot(gfevd2)

# Estimate GFEVD with fixed starting values that are the unconditional mean
# of the process: 
myvals <- rbind(fit22s$uncond_moments$uncond_mean,
                fit22s$uncond_moments$uncond_mean)
gfevd3 <- GFEVD(fit22s, N=48, R1=250, initval_type="fixed",
                init_values=myvals, ncores=2)
plot(gfevd3)

# Check also the function linear_IRF for estimating linear impulse response 
# functions based on a specific regime.

# Test with Wald test whether the diagonal elements of the first AR coefficient
# matrix of the second regime are identical:
# fit22s has parameter vector of length 27 with the diagonal elements  of the
# first A-matrix of the second regime are in elements 13 and 16.
A <- matrix(c(rep(0, times=12), 1, 0, 0, -1, rep(0, times=27-16)), nrow=1, ncol=27)
c <- 0
Wald_test(fit22s, A, c)

# The same functions used in the demonstration of the reduced form model also
# work with structural models.


## StMVAR and G-StMVAR models ##

# Fit a StMVAR(2, 2) model
fit22t <- fitGSMVAR(gdpdef, p=2, M=2, model="StMVAR", ncalls=1, seeds=1)

# Printout shows that there is an overly large degrees of freedom estimate
# in the 2nd regime!
fit22t

# So we change it to GMVAR type by switching to the appropariate G-StMVAR model
fit22gs <- stmvar_to_gstmvar(fit22t) 

# Printout of the appropriate G-StMVAR model that is based on the above StMVAR model.
fit22gs 

# Switch to the stastitically identified structural model
fit22gss <- gsmvar_to_sgsmvar(fit22gs)

# Printout of the structural model that is implied by the reduced form model
fit22gss

References

  • Kalliovirta L., Meitz M. and Saikkonen P. (2016) Gaussian mixture vector autoregression. Journal of Econometrics, 192, 485-498.
  • Kalliovirta L. and Saikkonen P. (2010) Reliable Residuals for Multivariate Nonlinear Time Series Models. Unpublished Revision of HECER Discussion Paper No. 247.
  • Virolainen S. (forthcoming). A statistically identified structural vector autoregression with endogenously switching volatility regime. Journal of Business & Economic Statistics, doi:10.1080/07350015.2024.2322090.
  • Virolainen S. (2022). Gaussian and Student’s t mixture vector autoregressive model with application to the assymetric effects of monetary policy shocks in the Euro area. Unpublished working paper, available as arXiv:2109.13648.

Copy Link

Version

Install

install.packages('gmvarkit')

Monthly Downloads

477

Version

2.1.4

License

GPL-3

Maintainer

Savi Virolainen

Last Published

January 8th, 2025

Functions in gmvarkit (2.1.4)

GIRF

Estimate generalized impulse response function for structural (and reduced form) GMVAR, StMVAR, and G-StMVAR models.
GMVAR

DEPRECATED! USE THE FUNCTION GSMVAR INSTEAD! Create a class 'gsmvar' object defining a reduced form or structural GMVAR model
Wald_test

Perform Wald test for a GMVAR, StMVAR, or G-StMVAR model
VAR_pcovmat

Calculate the dp-dimensional covariance matrix of p consecutive observations of a VAR process
GFEVD

Estimate generalized forecast error variance decomposition for structural (and reduced form) GMVAR, StMVAR, and G-StMVAR models.
Pearson_residuals

Calculate multivariate Pearson residuals of a GMVAR, StMVAR, or G-StMVAR model
Rao_test

Perform Rao's score test for a GSMVAR model
GAfit

Genetic algorithm for preliminary estimation of a GMVAR, StMVAR, or G-StMVAR model
GSMVAR

Create a class 'gsmvar' object defining a reduced form or structural GMVAR, StMVAR, or G-StMVAR model
LR_test

Perform likelihood ratio test for a GMVAR, StMVAR, or G-StMVAR model
change_parametrization

Change parametrization of a parameter vector
add_data

Add data to an object of class 'gsmvar' defining a GMVAR, StMVAR, or G-StMVAR model
alt_gsmvar

Construct a GMVAR, StMVAR, or G-StMVAR model based on results from an arbitrary estimation round of fitGSMVAR
calc_gradient

Calculate gradient or Hessian matrix
alt_gmvar

DEPRECATED! USE THE FUNCTION alt_gsmvar INSTEAD! Construct a GMVAR model based on results from an arbitrary estimation round of fitGSMVAR
check_constraints

Check the constraint matrix has the correct form
all_pos_ints

Check whether all arguments are positive integers
Wvec

Vectorization operator that removes zeros
change_regime

Change regime parameters \(\upsilon_{m}\)\( = (\phi_{m,0},\)\(\phi_{m}\)\(,\sigma_{m})\) of the given parameter vector
check_data

Check the data is in the correct form
cond_moment_plot

Conditional mean or variance plot for a GMVAR, StMVAR, or G-StMVAR model
cond_moments

Compute conditional moments of a GMVAR, StMVAR, or G-StMVAR model
diag_Omegas

Simultaneously diagonalize two covariance matrices
check_gsmvar

Checks whether the given object has class attribute 'gsmvar'
create_J_matrix

Create a special matrix J
check_parameters

Check that the given parameter vector satisfies the model assumptions
diagnostic_plot

Quantile residual diagnostic plot for a GMVAR, StMVAR, or G-StMVAR model
check_null_data

Checks whether the given object contains data
check_same_means

Check whether the parametrization is correct for usage of same means restrictions
check_pMd

Check that p, M, and d are correctly set
fitGMVAR

DEPRECATED! USE THE FUNCTION fitGSMVAR INSTEAD! Two-phase maximum likelihood estimation of a GMVAR model
estimate_sgsmvar

Maximum likelihood estimation of a structural GMVAR, StMVAR, or G-StMVAR model with preliminary estimates
fitGSMVAR

Two-phase maximum likelihood estimation of a GMVAR, StMVAR, or G-StMVAR model
dlogmultistudent

Calculate logarithms of multiple multivariate Student's t densities with varying mean and covariance matrix of specific structure, but constant degrees of freedom.
euromone

A monthly Euro area data covering the period from January 1999 to December 2021 (276 observations) and consisting four variables: cyclical component of log industrial production index, the log-difference of harmonized consumer price index, the log-difference of Brent crude oil prices (Europe), and an interest rate variable. The interest rate variable is the Euro overnight index average rate (EONIA) from January 1999 to October 2008, and after that the Wu and Xia (2016) shadow rate, which is not constrained by the zero lower bound and also quantifies unconventional monetary policy measures. The log-difference of the harmonized consumer price index is multiplied by hundred and the log-difference of oil price by ten. This data is the one that was used in Virolainen (2022).
format_valuef

Function factory for value formatting
gdpdef

U.S. real GDP percent change and GDP implicit price deflator percent change.
form_boldA

Form the \(((dp)x(dp))\) "bold A" matrices related to the VAR processes
get_IC

Calculate AIC, HQIC, and BIC
dlogmultinorm

Calculate logarithms of multiple multivariate normal densities with varying mean and constant covariance matrix
get_regime_means_int

Calculate regime means \(\mu_{m}\)
get_boldA_eigens

Calculate absolute values of the eigenvalues of the "bold A" matrices containing the AR coefficients
get_omega_eigens

Calculate the eigenvalues of the "Omega" error term covariance matrices
get_alpha_mt

Get mixing weights alpha_mt (this function is for internal use)
get_symmetric_sqrt

Calculate symmetric square root matrix of a positive definite covariance matrix
get_minval

Returns the default smallest allowed log-likelihood for given data.
get_Sigmas

Calculate the dp-dimensional covariance matrices \(\Sigma_{m,p}\) in the mixing weights of the GMVAR, StMVAR, or G-StMVAR model.
get_regime_autocovs

Calculate regimewise autocovariance matrices
get_regime_means

Calculate regime means \(\mu_{m}\)
get_regime_autocovs_int

Calculate regimewise autocovariance matrices
gsmvar_to_sgsmvar

Switch from two-regime reduced form GMVAR, StMVAR, or G-StMVAR model to a structural model.
gmvar_to_sgmvar

DEPRECATED! USE THE FUNCTION fitGSMVAR INSTEAD! Switch from two-regime reduced form GMVAR model to a structural model.
gmvarkit-package

gmvarkit: Estimate Gaussian and Student's t Mixture Vector Autoregressive Models
in_paramspace_int

Determine whether the parameter vector lies in the parameter space
get_test_Omega

Compute covariance matrix Omega used in quantile residual tests
in_paramspace

Determine whether the parameter vector lies in the parameter space
gmvar_to_gsmvar

Makes class 'gmvar' objects compatible with the functions using class 'gsmvar' objects
get_unconstrained_structural_pars

Get structural parameters that indicate there are no constraints
get_varying_h

Get differences 'h' which are adjusted for overly large degrees of freedom parameters
is_stationary

Check the stationary condition of a given GMVAR, StMVAR, or G-StMVAR model
linear_IRF

Estimate linear impulse response function based on a single regime of a structural GMVAR, StMVAR, or G-StMVAR model.
iterate_more

Maximum likelihood estimation of a GMVAR, StMVAR, or G-StMVAR model with preliminary estimates
loglikelihood_int

Compute log-likelihood of a GMVAR, StMVAR, and G-StMVAR models
loglikelihood

Compute log-likelihood of a GMVAR, StMVAR, or G-StMVAR model using parameter vector
mat_power

Compute the j:th power of a square matrix A
pick_Omegas

Pick covariance matrices
n_params

Calculate the number of parameters in a GMVAR, StMVAR, or G-StMVAR model's parameter vector
pick_W

Pick the structural parameter matrix W
pick_Ami

Pick coefficient matrix
pick_Am

Pick coefficient matrices
plot.gsmvarpred

plot method for class 'gsmvarpred' objects
pick_df

Pick the degrees of freedom parameters \(\nu\)\(=(\nu_{M1+1},...,\nu_{M})\)
pick_all_phi0_A

Pick all \(\phi_{m,0}\) or \(\mu_{m}\) and \(A_{m,1},...,A_{m,p}\) parameter values
plot.gmvarpred

plot method for class 'gmvarpred' objects
predict.gmvar

DEPRECATED! USE THE FUNCTION predict.gsmvar INSTEAD! Predict method for class 'gmvar' objects
pick_regime

Pick regime parameters \(\upsilon_{m}\)\( = (\phi_{m,0},\)\(\phi_{m}\)\(,\sigma_{m},\nu_{m})\)
pick_alphas

Pick mixing weight parameters \(\alpha_{m}, m=1,...,M\)
pick_allA

Pick coefficient all matrices
pick_phi0

Pick \(\phi_{m,0}\) or \(\mu_{m}\), m=1,..,M vectors
pick_lambdas

Pick the structural parameters eigenvalue 'lambdas'
print.gmvarsum

Summary print method from objects of class 'gmvarsum'
print.gsmvarpred

Print method for class 'gsmvarpred' objects
predict.gsmvar

Predict method for class 'gsmvar' objects
print.gmvar

Deprecated S3 methods for the deprecated class 'gmvar'
print.gsmvarsum

Summary print method from objects of class 'gsmvarsum'
profile_logliks

Plot profile log-likehoods around the estimates
plot.qrtest

Quantile residual tests
print.hypotest

Print method for the class hypotest
quantile_residuals

Calculate multivariate quantile residuals of a GMVAR, StMVAR, or G-StMVAR model
print_std_errors

Print standard errors of a GMVAR, StMVAR, or G-StMVAR model in the same form as the model estimates are printed
random_coefmats2

Create random stationary VAR model \((dxd)\) coefficient matrices \(A\).
random_ind2

Create somewhat random parameter vector of a GMVAR, StMVAR, or G-StMVAR model that is always stationary
random_df

Create random degrees of freedom parameter values
quantile_residuals_int

Calculate multivariate quantile residuals of GMVAR, StMVAR, or G-StMVAR model
random_covmat

Create random VAR model error term covariance matrix
reform_data

Reform data
random_coefmats

Create random VAR-model \((dxd)\) coefficient matrices \(A\).
reform_constrained_pars

Reform constrained parameter vector into the "standard" form
random_ind

Create random mean-parametrized parameter vector of a GMVAR, StMVAR, or G-StMVAR model that may not be stationary
redecompose_Omegas

In the decomposition of the covariance matrices (Muirhead, 1982, Theorem A9.9), change the order of the covariance matrices.
simulate.gsmvar

Simulate method for class 'gsmvar' objects
reorder_W_columns

Reorder columns of the W-matrix and lambda parameters of a structural GMVAR, StMVAR, or G-StMVAR model.
simulateGMVAR

DEPRECATED! USE THE FUNCTION simulate.gsmvar INSTEAD! Simulate from GMVAR process
smart_covmat

Create random VAR-model \((dxd)\) error term covariance matrix \(\Omega\) fairly close to a given positive definite covariance matrix using (scaled) Wishart distribution
sort_W_and_lambdas

Sort the columns of W matrix by sorting the lambda parameters of the second regime to increasing order
regime_distance

Calculate "distance" between two (scaled) regimes \(\upsilon_{m}\)\( = (\phi_{m,0},\)\(\phi_{m}\)\(,\sigma_{m})\)
sort_and_standardize_alphas

Sort mixing weight parameters in a decreasing order and standardize them to sum to one. For G-StMVAR models, the mixing weight parameters are sorted to a decreasing order for GMVAR and StMVAR type regimes separately.
smart_df

Create random degrees of freedom parameter values close to given values
reform_structural_pars

Reform structural parameter vector into the "standard" form
smart_ind

Create random parameter vector of a GMVAR, StMVAR, or G-StMVAR model fairly close to a given parameter vector
swap_parametrization

Swap the parametrization of a GMVAR, StMVAR, or G-StMVAR model
stmvar_to_gstmvar

Estimate a G-StMVAR model based on a StMVAR model that has large degrees of freedom parameters
unvec

Reverse vectorization operator
uncond_moments

Calculate the unconditional mean, variance, the first p autocovariances, and the first p autocorrelations of a GMVAR, StMVAR, or G-StMVAR process
swap_W_signs

Swap all signs in pointed columns a the \(W\) matrix of a structural GMVAR, StMVAR, or G-StMVAR model.
uncond_moments_int

Calculate the unconditional mean, variance, the first p autocovariances, and the first p autocorrelations of a GMVAR, StMVAR, or G-StMVAR process
stmvarpars_to_gstmvar

Transform a StMVAR (or G-StMVAR) model parameter vector to the corresponding G-StMVAR model parameter vector with the large df parameters removed.
sort_components

Sort components in parameter vector according to mixing weights into a decreasing order
unWvec

Reverse vectorization operator that restores zeros
standard_errors

Calculate standard errors for estimates of a GMVAR, StMVAR, or G-StMVAR model
vec

Vectorization operator
warn_df

Warn about large degrees of freedom parameter values
unvech

Reverse operator of the parsimonious vectorization operator vech
vech

Parsimonious vectorization operator for symmetric matrices
update_numtols

Update the stationarity and positive definiteness numerical tolerances of an existing class 'gsmvar' model.
warn_eigens

Warn about near-unit-roots in some regimes
usamon

A quarterly U.S. data covering the period from 1954Q3 to 2021Q4 (270 observations) and consisting four variables: the log-difference of real GDP, the log-difference of GDP implicit price deflator, the log-difference of producer price index (all commodities), and an interest rate variable. The interest rate variable is the effective federal funds rate from 1954Q3 to 2008Q2 and after that the Wu and Xia (2016) shadow rate, which is not constrained by the zero lower bound and also quantifies unconventional monetary policy measures. The log-differences of the GDP, GDP deflator, and producer price index are multiplied by hundred. This data is used in Virolainen (forthcoming).
usamone

A quarterly U.S. data covering the period from 1954Q3 to 2021Q4 (270 observations) and consisting four variables: cyclical component of the log of real GDP, the log-difference of GDP implicit price deflator, the log-difference of producer price index (all commodities), and an interest rate variable. The interest rate variable is the effective federal funds rate from 1954Q3 to 2008Q2 and after that the Wu and Xia (2016) shadow rate, which is not constrained by the zero lower bound and also quantifies unconventional monetary policy measures. The log-differences of the GDP deflator and producer price index are multiplied by hundred.