#require(quantmod)
#library(quantmod)
#install.packages("fGarch")
#library(fGarch)
#install.packages('forecast')
#library(forecast)
getSymbols("CAT",from="2006-01-03",to="2017-04-13")

#1.a
a = as.numeric(CAT[,6])
rt = diff(log(a))
acf(rt)
pacf(rt)
Box.test(rt,lag=10,type='Ljung')
#According to the Ljung-Box Test, with null hypothesis p0=p1=p2=...=pt=0
#The calculated p-value is greater than 0.05, we can reject null hypothesis at 95% confidence interval
#The log return series of rt contain serial correlations problem.

#1.b
par(mfrow=c(2,1))
acf(rt^2)
pacf(rt^2)
Box.test(rt^2,lag=10,type='Ljung')
#The calculated p-value by performing Ljung-box Test is lower than 0.05
#Therefore, we cannot reject H0: There is no ARCH effect in the series at 95% confidence interval

#1.c
m2 <- garchFit(~arma(1,0)+garch(1,1), data=rt,trace=F)
summary(m2)
plot(m2, which = 13)

#1.d
m3 <- garchFit(~garch(1,1), data=rt,trace=F, cond.dist="std")
summary(m3)
plot(m3, which = 13)

#1.e

#1.f
predict(m3,5)

#1.g


#2.a
read.table(file.choose(), header = T)
O=read.table("m-kovw-5116.txt", header=T)
KOrt<-(log(as.numeric(O[,3]+1)))
t.test(KOrt)
par(mfrow=c(2,1))
acf(KOrt)
pacf(KOrt)
Box.test(KOrt,lag=10,type='Ljung')
Box.test(KOrt^2,lag=10,type='Ljung')

#2.b
m4<-garchFit(~arma(1,0)+garch(1,1), data=KOrt,trace=F)
summary(m4)
par(mfrow=c(1,1))
plot(m4, which=13)

#2.c
m5<-garchFit(~arma(1,0)+garch(1,1), data=KOrt,trace=F, cond.dist="std")
summary(m5)
plot(m5, which=13)

#2.d
m6<-garchFit(~garch(1,1),data=KOrt,trace=F)
summary(m6)
plot(m6,which=13)

#2.e
m7<-garchFit(~garch(1,1),data=KOrt,trace=F,cond.dist="std")
summary(m7)
plot(m7,which=13)

#3.a
getSymbols("GOOG",from="2005-01-02",to="2021-03-31")
Grt=diff(log(as.numeric(GOOG[,6])))
Grt
t.test(Grt)
par(mfrow=c(2,1))
acf(Grt)
pacf(Grt)
Box.test(Grt,lag=10,type='Ljung')

#3.b
m8 <- auto.arima(Grt)
m8
par(mfrow=c(1,1))
pacf(m8$residuals^2)
Box.test(m8$residuals^2,lag=10,type='Ljung')

m9 <- garchFit(~arma(1,0)+garch(1,1), data=Grt,trace=F)
summary(m9)
plot(m9,which=13)

#3.c
m10 <- garchFit(~arma(1,0)+garch(1,1),data=Grt,trace=F,cond.dist='std')
summary(m10)

#3.d
predict(m10)

#4.a
read.table(file.choose(), header = T)
A=read.table("m-deciles.txt", header=T)
Drt = log(A[,10]+1)
t.test(Drt)
Box.test(Drt,lag=10,type='Ljung')
m11 = auto.arima(Drt)
summary(m11)

#4.b
Box.test(Drt^2,lag=10,type='Ljung')

#4.c
m12 <- garchFit(~arma(1,0)+garch(1,0),data=Drt,trace=F)
summary(m12)
plot(m12,which=13)

#4.d
m13 <- garchFit(~arma(1,0)+garch(1,0),data=Drt,trace=F,cond.dist="std")
summary(m13)
plot(m13,which=13)

#4.e
m14 <- garchFit(~garch(1,0),data=Drt,trace=F)
summary(m14)
plot(m14,which=13)

#4.f
m15 <- garchFit(~garch(1,0),data=Drt,trace=F,cond.dist='std')
summary(m15)
plot(m15,which=13)
