#************************************************************ 
# VAR and Structural VAR Models
#------------------------------------------------------------

#install.packages("vars")
library(quantmod)
library(vars)
getSymbols("UNRATE", src="FRED")
getSymbols("FEDFUNDS", src="FRED")
getSymbols("CPIAUCSL", src="FRED")
getSymbols("M1SL", src="FRED")
getSymbols("GDPDEF", src="FRED")
getSymbols("GDP", src="FRED")
getSymbols("TB3MS", src="FRED")
getSymbols("TWEXBMTH", src="FRED")
getSymbols("^GSPC",src="yahoo")

par(mfrow=c(2,2))
chartSeries(UNRATE,theme = chartTheme("white"))
chartSeries(FEDFUNDS,theme = chartTheme("white"))
ts.plot(UNRATE)
ts.plot(FEDFUNDS)
ts.plot(CPIAUCSL)
ts.plot(M1SL)

u <- diff(UNRATE)
p <- 100*(diff(log(CPIAUCSL)))
i <- diff(FEDFUNDS)

y <- cbind(u,p,i)
head(y)
y <- na.omit(y)
head(y)

VARselect(y,lag.max = 24)
var.2 <- VAR(y,type="const",p=4)
summary(var.2)




# IRF 
plot(irf(var.2, impulse="FEDFUNDS"))
plot(irf(var.2, impulse="CPIAUCSL"))
plot(irf(var.2, impulse="UNRATE"))

# Granger Causality
causality(var.2, cause = "FEDFUNDS")
causality(var.2, cause = "CPIAUCSL")
causality(var.2, cause = "UNRATE")

# Out of Sample Forecasting
var.2f <- predict(var.2, n.ahead = 10, ci = 0.95)
plot(var.2f)
fanchart(var.2f)

# Stability of System
# Eigenvalues of the companion matrix are less than one, the system is stable.
roots(var.2)

# SVAR Model
# Constraint Matrix setting 
amat <- diag(3)
amat[2,1] <- NA
amat[3,1] <- NA
amat[3,2] <- NA
amat

svar.2 <- SVAR(var.2, Amat = amat, Bmat=NULL, estmethod = "direct",hessian=TRUE)
summary(svar.2)

# Impulse Response from SVAR
svar2.irf <- irf(svar.2, impulse="FEDFUNDS", response =c("UNRATE","FEDFUNDS","CPIAUCSL"))
svar2.irf
plot(svar2.irf)

# a Blanchard & Quah [1989]-type SVAR
# Blanchard &  Quah [1989] can be considered as a particular SVAR-model of type B.
# The matrix A is equal to IK and the matrix of the long-run effects is
# lower-triangular 

BQ(var.2)

