#EE435 Wasin Siwasarit  #Assignment5
# Spring/2020
#Step1: You need to set your current directory
setwd("/Users/wasinsiwasarit/Dropbox/My Mac (Wasins-MacBook-Pro.local)/Desktop/Solution_assignment")
library(fBasics)
library(timeDate)
library(timeSeries)
library(fGarch)
library(quantmod)
library(forecast)
# 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)

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


#(b)
Box.test(rtn^2,lag=10,type="Ljung")


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

plot(m1,which = 13)

#(d)+(e)
m2 = garchFit(~garch(1,1),data=rtn,cond.dist="std",trace=F)
summary(m2)
#(f)
pm2 = predict(m2,5)
pm2
#(g)
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)
#(a)
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")

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

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

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

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


#(f) Compare the model


#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)
pacf(rt,lag.max = 20)
t.test(rt)
auto.arima(rt)

Box.test(rt,lag=12,type="Ljung")
m1 <- arima(rt,order=c(0,0,2))
Box.test(m1$residuals^2,lag=10,type="Ljung")


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

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

#(d)
m2 = garchFit(~arma(1,0)+garch(1,0),data=rt,cond.dist="std",trace=F)
summary(m2)
#(e)
m3 = garchFit(~garch(1,0),data=rt,trace=F)
summary(m3)
#(f)
m4 = garchFit(~garch(1,0),data=rt,cond.dist="std",trace=F)
summary(m4)




