#EE435 Wasin Siwasarit  #Assignment5
#Step1: You need to set your current directory
setwd("/Users/wasin_siwasarit/Desktop/EE435")
library(fBasics)
library(timeDate)
library(timeSeries)
library(fGarch)
library(quantmod)
# Step2: You need to clear the previous work
cat(rep("\n",50))  #clear R Console

getSymbols("CAT",from="2006-01-03",to="2017-04-14")
head(CAT)
tail(CAT)
rtn =diff(log(as.numeric(CAT[,6])))
ts.plot(rtn)

Box.test(rtn,lag=10,type="Ljung")

t.test(rtn)

Box.test(rtn^2,lag=10,type="Ljung")
m1 = garchFit(~garch(1,1),data=rtn,trace=F)
summary(m1)

#plot(m1)

m2 = garchFit(~garch(1,1),data=rtn,cond.dist="std",trace=F)
summary(m2)
pm2 = predict(m2,5)
pm2
qstd(0.975,nu=5.1)
lcl = pm2$meanForecast-1.99*pm2$standardDeviation
ucl = pm2$meanForecast+1.99*pm2$standardDeviation
CI = cbind(lcl,ucl)
CI


#Question2
da = read.table("m-kovw-5116.txt",header=T)
dim(da)
ko =log(da$ko+1)
t.test(ko)
Box.test(ko,lag=12,type="Ljung")
acf(ko,lag.max = 20)
at = ko-mean(ko)
Box.test(at^2,lag=12,type="Ljung")
m1 = garchFit(~arma(1,0)+garch(1,1),data=ko,trace=F)
summary(m1)

m2 = garchFit(~arma(1,0)+garch(1,1),data=ko,cond.dist="std",trace=F)
summary(m2)

m3 = garchFit(~garch(1,1),data=ko,trace=F)
summary(m3)

m4 = garchFit(~garch(1,1),data=ko,cond.dist="std",trace=F)
summary(m4)

#Question4
# You can download the data set from the folder "EE435" if your current folder is named "EE435" 
da=read.table("m-deciles.txt",header =T )
#Select the column you would like to estimate, in this example, it is the column with the name "CAP9RET"
simple_return = da$CAP9RET
# Transform the simple return to be log return
rt =log(1+simple_return)
acf(rt,lag.max = 20)
t.test(rt)
Box.test(rt,lag=12,type="Ljung")
at = rt-mean(rt)
Box.test(at^2,lag=10,type="Ljung")

m1 = garchFit(~arma(1,0)+garch(1,0),data=rt,trace=F)
summary(m1)

m2 = garchFit(~arma(1,0)+garch(1,0),data=rt,cond.dist="std",trace=F)
summary(m2)

m3 = garchFit(~garch(1,0),data=rt,trace=F)
summary(m3)

m4 = garchFit(~garch(1,1),data=rt,cond.dist="std",trace=F)
summary(m4)



source("Igarch.R")
da=read.table("m-mcd3dx6614.txt",header=T)
head(da)
mcd=log(da$mcd+1)
t.test(mcd)
Box.test(mcd,lag=12,type='Ljung')
at=mcd-mean(mcd)
Box.test(at^2,lag=12,type='Ljung')
n1=garchFit(~garch(1,1),data=mcd,trace=F)
summary(n1)
n2=Igarch(mcd,include.mean=T)
n3=garchFit(~garch(1,1),data=mcd,trace=F,cond.dist="sstd")
summary(n3)
#plot(n3)
tt=(.8333-1)/.0507
tt
source("garchM.R")
n4=garchM(mcd)
n5=garchFit(~garch(1,1),data=mcd,trace=F,leverage=T)
summary(n5)
n7=garchFit(~garch(1,1),data=mcd,trace=F,leverage=T,cond.dist="sstd")
summary(n7)

vw=log(da$vwretd+1)
t.test(vw)
Box.test(vw,lag=12,type='Ljung')
g1=garchFit(~garch(1,1),data=vw,trace=F,cond.dist="std")
summary(g1)
#plot(g1)
g2=garchFit(~garch(1,1),data=vw,trace=F,cond.dist="sstd")
summary(g2)
predict(g2,5)
g3=garchFit(~aparch(1,1),data=vw,trace=F,cond.dist="sstd",delta=2,include.delta=F)
summary(g3)
