# R 3.3.1 # example for the multivariate Ljung Box test and # cross correlations library("zoo") ## Required source("mq_R.txt") # multivariate Ljung-Box Test / Call: mq(xx,16) # xx <- as.matrix(data) #e.g. ## Generated data n <- 200; #AR(1) x <- c(1:n)*0; aa <- 0.5; x[1]=0.1; for (i in (2:n)) { x[i]=aa*x[i-1] + rnorm(1) }; x2 <- as.ts(x); x1 <- 2*lag(x2,-3) + as.ts(rnorm(n),0,0.5); # note lag(x,k=-1) ... one lag x3 <- as.ts(rnorm(n)); x4 <- as.ts(rnorm(n)); xx <- merge.zoo(x1,x2,x3,x4, all=FALSE) # NAs excluded # data.class(xx) is "zooreg" ## Plots plot(xx) #plot the single series plot(xx[,1],xx[,2]); plot(xx[,1],xx[,3]); plot(xx[,1],xx[,4]); # plot 2-dim scatters plot(xx[,2],xx[,3]); plot(xx[,2],xx[,4]); plot(xx[,3],xx[,4]); plot( lag(xx[,2],-3), xx[,1] ) # this scatter makes the data structure visible ## Univariate tests of white noise acf(xx[,1]); acf(xx[,2]); # compare with acf(xx[,1]) acf(xx[,3]); acf(xx[,4]); Box.test(xx[,1], lag = 10, type = "Ljung-Box", fitdf = 0) Box.test(xx[,2], lag = 10, type = "Ljung-Box", fitdf = 0) Box.test(xx[,3], lag = 10, type = "Ljung-Box", fitdf = 0) Box.test(xx[,4], lag = 10, type = "Ljung-Box", fitdf = 0) ## Cross-correlations: ## ccf(x1,x2) := { corr(x_{1,t},x_{2,t-ll}), ll= ...,-1,0,1,... } ## if ll=5: corr(x_{1,t},x_{2,t-5}) # try: ccf(xx[,1], xx[,2], lag.max = 10, type = "correlation", plot = FALSE) ccf(xx[,1], xx[,2], lag.max = 10, type = "correlation", plot = TRUE) ccf(xx[,1], xx[,3], lag.max = 10, type = "correlation", plot = TRUE) ccf(xx[,1], xx[,4], lag.max = 10, type = "correlation", plot = TRUE) ccf(xx[,2], xx[,3], lag.max = 10, type = "correlation", plot = TRUE) ccf(xx[,2], xx[,4], lag.max = 10, type = "correlation", plot = TRUE) ccf(xx[,3], xx[,4], lag.max = 10, type = "correlation", plot = TRUE) ## Multivariate Ljung-Box test (up to lag 15) mq(xx,15) ## EXERCISE: # (1) Look at the data set. Verify that x1 is essentially x2 lagged by 3 periods. # (2) Plot the univariate data, test for univariate white noise. # (3) Plot the data in bivariate scattergrams. # (4) Calculate and interprete the ccf's. # (4.a) Which series leads the other? # (4.b) What is rho_{1,2}(3), rho_{1,2}(-3)? # (4.c) What is rho_{2,1}(3), rho_{2,1}(-3)? # (4.d) Build the CCM matrix Rho(3). # (5) Perform the mv Ljung-Box test. What is H0, what is the alternative? # Do the analysis for # (A) x2 is an AR(1) as above # (B) x2 is white noise. # Check with library(vars) mod <- VAR(xx,p=3) summary(mod)