setwd("D:/MyGames/RStudio/Works")
cat(rep("\n",50))

#install.packages("vars")

library(quantmod)
library(fBasics)
library(sn)
library(PerformanceAnalytics)
library(car)
library(tseries)
library(forecast)
library(fGarch)
library(Matrix)
library(tinytex)
library(fUnitRoots)
library(MTS)
library(vars)


require(MTS)
require(vars)



da1=read.table("m-unrate-MIILIN.txt",header = T)


#detach("package:vars", unload = TRUE)

head(da1)
dim(da1)
tail(da1)

x=cbind(da1$MI,da1$IL,da1$IN)

head(x)
dim(x)
tail(x)

x_log = log(x)
dim(x_log)
head(x_log)
tail(x_log)

zt1=diffM(x_log)

tail(zt1)
head(zt1)

colnames(x)<-c("MI","IL","IN")
colnames(x_log)<-c("MI","IL","IN")
colnames(zt1)<-c("MI","IL","IN")
MTSplot(zt1)
VARorder(zt1)
head(zt1)
zt1

detach("package:vars", unload = TRUE)
#BIC has the least value, the optimal lag is 2 periods

m1=VAR(zt1,2)
m1
summary(m1)



m1a=refVAR(m1,thres =1.645)

m1a
#apparently, there is an error says argument is of length zero
#oh I didnot know that I have to detach the vars library to work on MTS

sig1=m1a$Sigma
U1=chol(sig1)
MTSdiag(m1a)


library(vars)
require(vars)


varfit1=VAR(zt1,p=2)

summary(varfit1)
impresp1=irf(varfit1)
plot(impresp1)
#cannot compile the plot function

#1.2
#The shock rate from unemployment from each current month of each state has a positively significacnt impact onto the next month.
#However, the shock will drydown after 5 month and change into long run growth.


detach("package:vars", unload = TRUE)
#question2

da2=read.table("m-m1cnwti.txt")


zt2= cbind(da2$V1,da2$V2)
MTSplot(da2)
#2.1






colnames(zt2)<-c("M1","OIL")




VARorder(zt2)
#BIC has the least value, the optimal lag is 3 periods
#2.2
m2=VAR(zt2,3)
m2a<-refVAR(m1,thres=1.645)
sig2=m2a$Sigma
sig2
U2=chol(sig2)
U2
MTSdiag(m2a)



#2.3
require(vars)
library(vars)
varfit2=VAR(zt2,p=3)

summary(varfit2)
impresp2=irf(varfit2)
plot(impresp2)



#2.4


varfit.prd<-predict(varfit2, n.ahead = 6, ci=0.95)
varfit.prd
fanchart(varfit.prd)
fevd(varfit2,n.ahead = 6)


















