Load the textbook_example data

library(fGarch)
library(tseries)

setwd("C:/Users/User/Google Drive/P_Project/volatility_garch_sd")
df <- read.fwf("textbook_example.txt", widths = 8, header = T)[,2] #load data
df <- ts(df)

Looking at the data - Closing Price & Returns

plot( df , ylab = "Price", main = "Time Series of Closing Price")

#first differencing on the closing price to get returns
dax <- diff(log(df))

#preview latest 20 days returns
print( tail(dax, 20) )
##  [1]  0.004987542 -0.010000083  0.005012542  0.024692613 -0.012270093
##  [6]  0.031594365  0.000000000  0.000000000 -0.007202912  0.000000000
## [11]  0.011976191  0.004750603 -0.009523882  0.000000000  0.016607736
## [16]  0.007034027  0.000000000 -0.007034027  0.023256862  0.011428696
#plot the returns time series
plot(dax, xlab = "Time", main = "Time Series of Returns")

Fit a GARCH(1,1) model on the returns

log <- capture.output({  #ignore this function (To suppress unnecessary message output ##
      
   fit <- garchFit(~garch(1, 1), data = dax) 
      
}) 

Predict 30-days ahead returns and volatilities

# predict(fit, n.ahead = 10,plot = T)

#1-day ahead volatility forecast
sd1 <- predict(fit, n.ahead = 15,plot = T)[1,3] 

print(sd1)
## [1] 0.01057778

Therefore, the 1-day ahead forecast volatility is 0.0105778.

Calculating volatility using sample standard deviation

sd2 <- sd(dax)
print(sd2)
## [1] 0.01215933

The sample standard deviation of returns is 0.0121593, which is higher than the 1-day ahead forecast volatility, 0.0105778.