[R] Please help with volatility calculation in R (For my thesis)

Mehmet Dogan m.dogan at mail.com
Fri Jan 8 01:23:47 CET 2016


Dear Sir or Madam,

Since long time I am trying to complete my thesis, but was not able to 
complete due to the problem with R program. I do have R_codes 
(attached), but I just can calculate the parameters with the attached 
code. (EUR/USD currency pair, weekends are excluded thanks to code 
attached). I could not calculate the average volatility for 10 minutes 
intervals.

I need to calculate average volatility for 10 minutes time intervals of 
my data set and plot them the results in one plot as in the sample 
attached(plot_example.png based on the GARCH(1,1), EGARCH(1,1) and 
TGARCH(1,1) models.  My codes are not enough to do it.

I am wondering if you could help me with my thesis.

Many many thanks in advance,

Yours sincerely,

Mehmet Dogan
+48 732 926 877
mehmetdogan_07 at windowslive.com

-- 
Mehmet Dogan
m.dogan at mail.com
+48 732 926 877



---
This email has been checked for viruses by Avast antivirus software.
https://www.avast.com/antivirus
-------------- next part --------------

setwd("D:\\NewThesis")

# installation of needed packages
install.packages("fBasics")
install.packages("tseries")
install.packages("car")
install.packages("FinTS")
install.packages("fGarch")
install.packages("rugarch")


# Library Installations
library(xts)
library(fBasics) # e.g. basicStats()
library(tseries)# e.g. jarque.bera.test()
library(car) # e.g. durbinWatsonTest()
library(FinTS) # e.g. ArchTest()
library(fGarch) # e.g. garchFit()
library(rugarch) # e.g. ugarchfit()

source("functions/TSA_lab06_functions.R")

# Data import
EUR <- read.csv("Data_Forecast/EURUSD.csv",
                stringsAsFactors = FALSE)  #o import data

# First and last 6 data
head(EUR)
tail(EUR)

# formatting the date and time - without the need for a lubridate package
EUR$Date <- strptime(EUR$Date, format = "%d.%m.%Y %H:%M:%S")

str(EUR)

# The code was not working as you should not use the as.Date() function 
# which only works on dates (not times)

EUR <- EUR[EUR$Date >= strptime("2015-01-01 23:00:00", format = "%Y-%m-%d %H:%M:%S"),]

# now it works


# we need just weekdays
wday_ <- as.POSIXlt(EUR$Date)$wday
EUR <- EUR[!wday_ %in% c(0,6) ,]

# lets create vector of hours and minutes based on the existing data
hour_ <- as.POSIXlt(EUR$Date)$hour
minute_ <- as.POSIXlt(EUR$Date)$min

###########################################################################
# Exclude first and last 5 minutes
exclude_ <- ((hour_ == 23 & minute_ < 6) | (hour_ == 22 & minute_ > 55) )*1

EUR <- EUR[exclude_ == 0,]

head(EUR)
tail(EUR)


# xts object creation
EUR.xts<-xts(EUR$Close,EUR$Date)

# plot of original close pricess
plot(EUR$Date,EUR$Close,type="l", col="blue",
     main="EUR/USD")

# log-returns calculation
EUR$r<-diff.xts(log(EUR$Close))

# log returns plot
plot(EUR$Date,EUR$r,type="l", col="red",
     main="Log-returns of USD/JPY")
abline(h=0,col="gray",lty=2) #abline functions adds line to the plot


#############################################################################
#GARCH MODEL
# remove missing values and zeroes
data_ <- EUR[!is.na(EUR$r) & EUR$r!=0,]

k.garch11<-garchFit(~garch(1,1),
                    data = 100*data_$r,
                    include.mean=F,
                    cond.dist= "norm", # conditional distribution of errors
                    trace=FALSE) # if we don't want to see history of iterations


summary(k.garch11)
# lets see if the model converges on a shorter sample
k.garch11<-garchFit(~garch(1,1),
                    data = 100*data_$r[1:15000],
                    include.mean=F,
                    cond.dist= "norm", # conditional distribution of errors
                    trace=FALSE) # if we don't want to see history of iterations

k.garch11<-garchFit(~garch(1,1),
                    data = 100*data_$r[-c(1:15000)],
                    include.mean=F,
                    cond.dist= "norm", # conditional distribution of errors
                    trace=FALSE) # if we don't want to see history of iterations

plot(100*data_$r[30000:32000], type="l")

which(100*data_$r > 0.9)

k.garch11<-garchFit(~garch(1,1),
                    data = 100*data_$r[-15000],
                    include.mean=F,
                    cond.dist= "norm", # conditional distribution of errors
                    trace=FALSE) # if we don't want to see history of iterations

summary(k.garch11)


# Does the best model have all parameters significant? 

# Let's assume that the final model is GARCH(1,1) 
str(k.garch11)

# 7.
# Plot of conditional variance estimates
par(mfrow=c(2,1))
plot(k.garch11 at data, # @data = original data values
     type="l",col="red",ylab="r",main="Log-returns of EUR/USD")
plot(k.garch11 at h.t, # @h.t = conditional variance
     type="l",col="blue",
     ylab="cvar",main="Estimated Volatility of EUR/USD")
par(mfrow=c(1,1))


# Do standardized residuals come from normal distribution?
stdres<-k.garch11 at residuals/sqrt(k.garch11 at h.t)

hist(stdres,breaks=20,prob=T,
     main="Histogram of standardized residuals \n from GARCH(1,1) for EUR/USD")
# lets add a normal density curve for 
# sample mean and variance 
curve(dnorm(x, mean=mean(stdres,na.rm=T), 
            sd=sd(stdres,na.rm=T)), 
      col="darkblue", lwd=2, add=TRUE)

# Jarque-Bera test
jarque.bera.test(stdres)

# normalit yrejected

# Durbin Watson test
durbinWatsonTest(lm(stdres~1),
                 max.lag=5) # lets check first 5 orders

# ARCH effects among standardized residuals
ArchTest(stdres,lags=5)

# How should we interpret these statistics?

###########################################################################################################       
# The EGARCH model     
#########################################################################

# Let's examine whether conditional variance reacts asymmetrically 
# to the news arriving to the market.
# Below estimation of the EGARCH(1,1) model.

# ugarchfit() from rugarch package

# lets first define a model specification
spec = ugarchspec(# variance equation
  variance.model=list(model="eGARCH",garchOrder=c(1,1)),
  # sGARCH would stand for standard GARCH model
  # mean equation
  mean.model=list(armaOrder=c(0,0),include.mean=F), 
  # assumed distribution of errors
  distribution.model="norm")

# function doesn't accept missing values
k.egarch11 = ugarchfit( spec=spec, data=na.omit(EUR$r))

k.egarch11


# coefficient alpha captures the sign effect and gamma the size effect
# alpha is negative and significant, so the asymmetry is found

# Plot of conditional standard deviation estimates (3)
# and News-Impact curve (12).
# ESC to exit

plot(k.egarch11)



##########################################################################                                   
# The TGARCH model
###################################################################

# lets first define a model specification
spec = ugarchspec(# variance equation
  variance.model=list(model="fGARCH",garchOrder=c(1,1),
                      submodel="TGARCH"),
  # model="fGARCH" (family GARCH) together with submodel="TGARCH"
  # mean equation
  mean.model=list(armaOrder=c(0,0),include.mean=F), 
  # assumed distribution of errors
  distribution.model="norm")

# function doesn't accept missing values
k.tgarch11 = ugarchfit( spec=spec, data=na.omit(EUR$r))

k.tgarch11


# Plot of News-Impact curve (12).
# ESC to exit
plot(k.tgarch11)

# What is our conclusion? 
# Do we see asymmetry in the conditional variance function?


# CAUTION !!!
### all above options can be combined !!!   HOW????


-------------- next part --------------
A non-text attachment was scrubbed...
Name: plot_example.png
Type: image/png
Size: 112997 bytes
Desc: not available
URL: <https://stat.ethz.ch/pipermail/r-help/attachments/20160108/cbf646db/attachment.png>


More information about the R-help mailing list