Loading the packages
library(dplyr)
## Warning: package 'dplyr' was built under R version 4.2.2
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
library(quantmod)
## Loading required package: xts
## Warning: package 'xts' was built under R version 4.2.2
## Loading required package: zoo
##
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
##
## as.Date, as.Date.numeric
##
## Attaching package: 'xts'
## The following objects are masked from 'package:dplyr':
##
## first, last
## Loading required package: TTR
## Registered S3 method overwritten by 'quantmod':
## method from
## as.zoo.data.frame zoo
library(tidyverse)
## Warning: package 'tidyverse' was built under R version 4.2.2
## ── Attaching packages
## ───────────────────────────────────────
## tidyverse 1.3.2 ──
## ✔ ggplot2 3.4.0 ✔ purrr 0.3.5
## ✔ tibble 3.1.8 ✔ stringr 1.5.0
## ✔ tidyr 1.2.1 ✔ forcats 0.5.2
## ✔ readr 2.1.3
## Warning: package 'ggplot2' was built under R version 4.2.2
## Warning: package 'tibble' was built under R version 4.2.2
## Warning: package 'tidyr' was built under R version 4.2.2
## Warning: package 'readr' was built under R version 4.2.2
## Warning: package 'purrr' was built under R version 4.2.2
## Warning: package 'stringr' was built under R version 4.2.2
## Warning: package 'forcats' was built under R version 4.2.2
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ xts::first() masks dplyr::first()
## ✖ dplyr::lag() masks stats::lag()
## ✖ xts::last() masks dplyr::last()
library(ggthemes)
library(forecast)
## Warning: package 'forecast' was built under R version 4.2.2
library(tseries)
## Warning: package 'tseries' was built under R version 4.2.2
library(data.table)
## Warning: package 'data.table' was built under R version 4.2.2
##
## Attaching package: 'data.table'
##
## The following object is masked from 'package:purrr':
##
## transpose
##
## The following objects are masked from 'package:xts':
##
## first, last
##
## The following objects are masked from 'package:dplyr':
##
## between, first, last
library(tidyquant)
## Warning: package 'tidyquant' was built under R version 4.2.2
## Loading required package: lubridate
## Warning: package 'lubridate' was built under R version 4.2.2
## Loading required package: timechange
## Warning: package 'timechange' was built under R version 4.2.2
##
## Attaching package: 'lubridate'
##
## The following objects are masked from 'package:data.table':
##
## hour, isoweek, mday, minute, month, quarter, second, wday, week,
## yday, year
##
## The following objects are masked from 'package:base':
##
## date, intersect, setdiff, union
##
## Loading required package: PerformanceAnalytics
##
## Attaching package: 'PerformanceAnalytics'
##
## The following object is masked from 'package:graphics':
##
## legend
library(gridExtra)
##
## Attaching package: 'gridExtra'
##
## The following object is masked from 'package:dplyr':
##
## combine
library(rugarch)
## Warning: package 'rugarch' was built under R version 4.2.2
## Loading required package: parallel
##
## Attaching package: 'rugarch'
##
## The following object is masked from 'package:purrr':
##
## reduce
##
## The following object is masked from 'package:stats':
##
## sigma
library(kableExtra)
##
## Attaching package: 'kableExtra'
##
## The following object is masked from 'package:dplyr':
##
## group_rows
library(tidyr)
library(goftest)
library(vars)
## Loading required package: MASS
##
## Attaching package: 'MASS'
##
## The following object is masked from 'package:dplyr':
##
## select
##
## Loading required package: strucchange
## Loading required package: sandwich
##
## Attaching package: 'strucchange'
##
## The following object is masked from 'package:stringr':
##
## boundary
##
## Loading required package: urca
## Warning: package 'urca' was built under R version 4.2.2
## Loading required package: lmtest
##
## Attaching package: 'vars'
##
## The following object is masked from 'package:tidyquant':
##
## VAR
library(knitr)
## Warning: package 'knitr' was built under R version 4.2.2
library(FinTS)
##
## Attaching package: 'FinTS'
##
## The following object is masked from 'package:forecast':
##
## Acf
library(aTSA)
##
## Attaching package: 'aTSA'
##
## The following object is masked from 'package:vars':
##
## arch.test
##
## The following objects are masked from 'package:tseries':
##
## adf.test, kpss.test, pp.test
##
## The following object is masked from 'package:forecast':
##
## forecast
##
## The following object is masked from 'package:graphics':
##
## identify
library(timeSeries)
## Warning: package 'timeSeries' was built under R version 4.2.2
## Loading required package: timeDate
##
## Attaching package: 'timeDate'
##
## The following objects are masked from 'package:PerformanceAnalytics':
##
## kurtosis, skewness
##
##
## Attaching package: 'timeSeries'
##
## The following object is masked from 'package:zoo':
##
## time<-
library(fGarch)
## Warning: package 'fGarch' was built under R version 4.2.2
## NOTE: Packages 'fBasics', 'timeDate', and 'timeSeries' are no longer
## attached to the search() path when 'fGarch' is attached.
##
## If needed attach them yourself in your R script by e.g.,
## require("timeSeries")
##
## Attaching package: 'fGarch'
##
## The following object is masked from 'package:TTR':
##
## volatility
library(fBasics)
## Warning: package 'fBasics' was built under R version 4.2.2
##
## Attaching package: 'fBasics'
##
## The following objects are masked from 'package:rugarch':
##
## qgh, qnig
##
## The following objects are masked from 'package:PerformanceAnalytics':
##
## kurtosis, skewness
##
## The following object is masked from 'package:TTR':
##
## volatility
library(caTools)
library(PerformanceAnalytics)
library(zoo)
library(timetk)
## Warning: package 'timetk' was built under R version 4.2.2
##
## Attaching package: 'timetk'
##
## The following object is masked from 'package:data.table':
##
## :=
library(sjPlot)
## Warning: package 'sjPlot' was built under R version 4.2.2
#Setting the working directory
setwd("C:/Users/user/Pictures/BlueStacks/New folder")
#Data import
AEX<- read_csv("AEX.csv")
AEX['Date'] <- as.Date(AEX$Date)
#selecting the 'close' and date columns of data set
AEXprice<-AEX$Close
AEXdate<-AEX$Date
AEX.TS<- xts(AEXprice,order.by=AEXdate)
#log returns of the data
logAEX.rtn<-diff(log(AEXprice), lag=1)
#Normality Tests
#JB Test
jb5 <- jarqueberaTest(logAEX.rtn);jb5
##
## Title:
## Jarque - Bera Normalality Test
##
## Test Results:
## STATISTIC:
## X-squared: 13016.4897
## P VALUE:
## Asymptotic p Value: < 2.2e-16
##
## Description:
## Mon Jan 9 11:52:19 2023 by user: Nick Mutembei
#ADF test
adf.test(logAEX.rtn)
## Augmented Dickey-Fuller Test
## alternative: stationary
##
## Type 1: no drift no trend
## lag ADF p.value
## [1,] 0 -37.7 0.01
## [2,] 1 -26.5 0.01
## [3,] 2 -23.5 0.01
## [4,] 3 -19.7 0.01
## [5,] 4 -17.2 0.01
## [6,] 5 -16.3 0.01
## [7,] 6 -15.0 0.01
## [8,] 7 -14.2 0.01
## Type 2: with drift no trend
## lag ADF p.value
## [1,] 0 -37.7 0.01
## [2,] 1 -26.5 0.01
## [3,] 2 -23.5 0.01
## [4,] 3 -19.7 0.01
## [5,] 4 -17.2 0.01
## [6,] 5 -16.4 0.01
## [7,] 6 -15.0 0.01
## [8,] 7 -14.2 0.01
## Type 3: with drift and trend
## lag ADF p.value
## [1,] 0 -37.7 0.01
## [2,] 1 -26.6 0.01
## [3,] 2 -23.6 0.01
## [4,] 3 -19.8 0.01
## [5,] 4 -17.3 0.01
## [6,] 5 -16.5 0.01
## [7,] 6 -15.1 0.01
## [8,] 7 -14.3 0.01
## ----
## Note: in fact, p.value = 0.01 means p.value <= 0.01
#Normality Test
#histogram
#Is the mean log return significantly different from zero=T test
t.test(logAEX.rtn)
##
## One Sample t-test
##
## data: logAEX.rtn
## t = -0.53679, df = 1380, p-value = 0.5915
## alternative hypothesis: true mean is not equal to 0
## 95 percent confidence interval:
## -0.003412969 0.001946428
## sample estimates:
## mean of x
## -0.0007332706
#Normality Tests
#Plotting the average daily returns ofdataset
p1 <- ggplot(AEX.TS, aes(x=AEXdate,y=AEXprice))+geom_line()+
theme(plot.title=element_text(hjust=0.5))+
labs(x="Date",y="Price",title="Average Daily of the Stock Indices")
p1
#stationarity Test
ggplot(AEX.TS[-1], aes(AEXdate[-1],logAEX.rtn))+geom_line()+
labs(x="Date",y="Log Return",title = " Log Returns plot")
# Test set 500 observations
specgarchaex = ugarchspec(variance.model = list(garchOrder=c(1,1)), distribution.model ="sstd",mean.model =list(armaOrder=c(0,0,2)) )
roll = ugarchroll(specgarchaex, data = logAEX.rtn, n.ahead = 1, forecast.length = 500,refit.every = 25, refit.window = "rolling",
parallel = TRUE,parallel.control = list(pkg = "snowfall", cores = 10), solver = "solnp",
solver.control = list(tol = 1e-05, delta = 1e-06, trace = 0),calculate.VaR = TRUE, VaR.alpha = c(0.01, 0.025, 0.05))
report(roll, type = "VaR", VaR.alpha = 0.01, conf.level = 0.95)
## VaR Backtest Report
## ===========================================
## Model: sGARCH-sstd
## Backtest Length: 500
## Data:
##
## ==========================================
## alpha: 1%
## Expected Exceed: 5
## Actual VaR Exceed: 11
## Actual %: 2.2%
##
## Unconditional Coverage (Kupiec)
## Null-Hypothesis: Correct Exceedances
## LR.uc Statistic: 5.419
## LR.uc Critical: 3.841
## LR.uc p-value: 0.02
## Reject Null: YES
##
## Conditional Coverage (Christoffersen)
## Null-Hypothesis: Correct Exceedances and
## Independence of Failures
## LR.cc Statistic: 6.848
## LR.cc Critical: 5.991
## LR.cc p-value: 0.033
## Reject Null: YES
report(roll,type="VaR",VaR.alpha=0.05,conf.level=0.95)
## VaR Backtest Report
## ===========================================
## Model: sGARCH-sstd
## Backtest Length: 500
## Data:
##
## ==========================================
## alpha: 5%
## Expected Exceed: 25
## Actual VaR Exceed: 31
## Actual %: 6.2%
##
## Unconditional Coverage (Kupiec)
## Null-Hypothesis: Correct Exceedances
## LR.uc Statistic: 1.413
## LR.uc Critical: 3.841
## LR.uc p-value: 0.235
## Reject Null: NO
##
## Conditional Coverage (Christoffersen)
## Null-Hypothesis: Correct Exceedances and
## Independence of Failures
## LR.cc Statistic: 5.501
## LR.cc Critical: 5.991
## LR.cc p-value: 0.064
## Reject Null: NO
fit= ugarchfit(specgarchaex,data=logAEX.rtn[1:965,drop =
FALSE])
Spec=specgarchaex;setfixed(Spec)<-as.list(coef(fit))
filt = ugarchfilter(Spec, logAEX.rtn[965:1381, drop = FALSE]);
actual = logAEX.rtn[965:1381]
VaR = fitted(filt) + sigma(filt)*qdist("sstd", p=0.05, mu=0,
sigma=1,skew=coef(fit)["skew"], shape=coef(fit)["shape"])
f = function(x) qdist("sstd",p=x,mu=0,sigma=1,skew=
coef(fit)["skew"], shape=coef(fit)["shape"])
ES = fitted(filt) + sigma(filt)*integrate(f, 0, 0.01) $value/0.01;print(ESTest(0.01, actual,ES, VaR, boot = T))
## $expected.exceed
## [1] 4
##
## $actual.exceed
## [1] 28
##
## $H1
## [1] "Mean of Excess Violations of VaR is greater than zero"
##
## $boot.p.value
## [1] 1
##
## $p.value
## [1] 1
##
## $Decision
## [1] "Fail to Reject H0"
#back tetsing
p = c()
p[1] = pbinom(q = 0 , size = 500 , prob = 0.05)
for(i in 1:50){
p[i] = (pbinom(q = (i-1) , size = 500 , prob = 0.05) - pbinom(q = (i-2) , size = 500 , prob = 0.05))
}
VaR95_td = mean(logAEX.rtn) + roll@forecast$density[,'Sigma']*qdist(distribution='std', shape=3.7545967917, p=0.05)
qplot(y = VaR95_td , x = 1:500 , geom = 'line') +
geom_point(aes(x = 1:500 , y = logAEX.rtn[759:1258] , color = as.factor(logAEX.rtn[759:1258] < VaR95_td)) , size = 2) + scale_color_manual(values = c('gray' , 'red')) +
labs(y = 'Daily Returns' , x = 'Test set Observation') + theme_light() +
theme(legend.position = 'none')
## Warning: `qplot()` was deprecated in ggplot2 3.4.0.
# VaR and ES at 0.01
#AEX
ys = sort(logAEX.rtn)
op = length(logAEX.rtn)*0.01
VaR = -ys[op]*500
print(VaR)
## [1] 73.14607
ES = -mean(ys[1:op])*500
print(ES)
## [1] 94.29972