Skip to content

Commit

Permalink
Merge pull request #35 from EchoRLiu/23-data-with-dates-issue
Browse files Browse the repository at this point in the history
resolve importing, data dates, and other issues
  • Loading branch information
dan9401 authored Oct 19, 2024
2 parents 0267042 + bcb5d06 commit 86ba27d
Show file tree
Hide file tree
Showing 8 changed files with 56 additions and 32 deletions.
11 changes: 8 additions & 3 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,12 @@
S3method(plot,robustGARCH)
S3method(print,robustGARCH)
S3method(summary,robustGARCH)
export(.aValue)
export(.expFisherI)
export(aef)
export(robGarch)
importFrom(graphics,legend)
importFrom(graphics,par)
importFrom(stats,density)
importFrom(stats,integrate)
importFrom(stats,median)
importFrom(stats,nlminb)
importFrom(stats,pnorm)
importFrom(xts,xts)
1 change: 1 addition & 0 deletions R/data.R
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,5 @@
#'
#' @keywords datasets
#' @source \url{https://finance.yahoo.com/quote/\%5EGSPC/history?period1=949363200&period2=1025222400&interval=1d&filter=history&frequency=1d}
#' @importFrom xts xts
"gspc"
24 changes: 17 additions & 7 deletions R/robGarch.R
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#' @importFrom stats median pnorm density nlminb
#' @importFrom graphics par
#' @title Robust Estimates for GARCH(1,1) Model
#'
#' @name robGarch
Expand Down Expand Up @@ -59,9 +61,13 @@
robGarch <- function(data, methods = c("BM", "M", "QML", "MLE"), fixed_pars = c(0.8, 3.0),
optimizer = c("Rsolnp", "nloptr", "nlminb"), optimizer_x0 = FALSE,
optimizer_control = list(trace=0), stdErr_method = c("numDeriv", "optim", "sandwich")){
# TODO: xts data takes a long time
if(!is.numeric(data) || length(data)==0)
stop("Data must be a numeric vector of non-zero length")

# if(!is.numeric(data) || length(data)==0)
# stop("Data must be a numeric vector of non-zero length")

# the calculation will use data_, which only has the return data and without dates
# but we will keep data to retain the original dates
data_ = zoo::coredata(data)

methods = match.arg(methods)
optimizer = match.arg(optimizer)
Expand Down Expand Up @@ -99,7 +105,7 @@ robGarch <- function(data, methods = c("BM", "M", "QML", "MLE"), fixed_pars = c(
stop("use Rsolnp optimizer for now")
}

std_errors <- sqrt(diag(abs(solve(H)/length(data))))
std_errors <- sqrt(diag(abs(solve(H)/length(data_))))
if(methods == "MLE"){
standard_error <- c(std_errors[2:4], std_errors[6])
fit$observed_I <- -H[c(2,3,4,6), c(2,3,4,6)]
Expand Down Expand Up @@ -189,7 +195,7 @@ robGarchDistribution <- function(param = c(8.76e-04, 0.135, 0.686), methods = c(
fixed <- param
names(fixed) <- c("gamma", "alpha", "beta", "shape")
fspec <- spec
setfixed(fspec) <- fixed
rugarch::setfixed(fspec) <- fixed
y <- rugarch::ugarchpath(fspec, n.sim = n, m.sim = m, rseed = 42)
y. <- y@path$seriesSim

Expand Down Expand Up @@ -221,7 +227,7 @@ robGarchDistribution <- function(param = c(8.76e-04, 0.135, 0.686), methods = c(
fixed <- param
names(fixed) <- c("gamma", "alpha", "beta")
fspec <- spec
setfixed(fspec) <- fixed
rugarch::setfixed(fspec) <- fixed
y <- rugarch::ugarchpath(fspec, n.sim = n, m.sim = m, rseed = 42)
y. <- y@path$seriesSim

Expand Down Expand Up @@ -251,6 +257,10 @@ rgFit_local <- function(data, optimizer, optimizer_x0, optimizer_control, shared
# unpack shared_vars
methods <- shared_vars$methods

# for minimum code change, data_ and data naming are exchanged here
data_ = data # retain the dates and structure
data = zoo::coredata(data) # for calculation

start_time <- Sys.time()
# optimizer/optimizer_control

Expand Down Expand Up @@ -315,7 +325,7 @@ rgFit_local <- function(data, optimizer, optimizer_x0, optimizer_control, shared

time_elapsed <- Sys.time() - start_time

list(data=data,
list(data=data_,
methods = methods,
optimizer=optimizer,
optimizer_x0=res$x0,
Expand Down
15 changes: 9 additions & 6 deletions R/robustGARCH-infomat.R
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#' @export
# import methods from other packages
#' @importFrom stats integrate
.aValue <- function(fit, top = FALSE, v=5){
if(top){
# Calculate a(Psi_0, g), the top value of AEF, where Psi_0 = rho_0'.
Expand Down Expand Up @@ -158,11 +159,13 @@

g
}
#' @export
.expFisherI <- function(fit, true_pars){

# Big difference between expected and observed Fisher Information matrix.
T <- length(fit$data)

data_ = zoo::coredata(fit$data)

T <- length(data_)

if(fit$methods == 'MLE'){
# to be added.
Expand All @@ -175,17 +178,17 @@
# it seems like k is used here as an index
# could any k was supposed to be the global one implemented before?
for(k in 1:(T-1)){
FS[2,1] <- FS[2,1] + true_pars[3]^(k-1) * (fit$data[T-k])^2
FS[2,1] <- FS[2,1] + true_pars[3]^(k-1) * (data_[T-k])^2
}

FS[3,1] <- true_pars[1]/(1-true_pars[3])^2
for(k in 1:(T-2)){
FS[3,1] <- FS[3,1] + true_pars[2]*k*true_pars[3]^(k-1)*(fit$data[T-k-1])^2
FS[3,1] <- FS[3,1] + true_pars[2]*k*true_pars[3]^(k-1)*(data_[T-k-1])^2
}

ht <- true_pars[1]/(1-true_pars[3])
for(k in 1:(T-1)){
ht <- ht + true_pars[2] * true_pars[3]^(k-1) * (fit$data[T-k])^2
ht <- ht + true_pars[2] * true_pars[3]^(k-1) * (data_[T-k])^2
}
}

Expand Down
23 changes: 14 additions & 9 deletions R/robustGARCH-plots.R
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
#' @importFrom graphics legend par
#' @importFrom stats density integrate median nlminb pnorm
.plot.garchsim <- function(fit, digits = 3, estimation_pos = "topleft", line_name_pos = "topright",
par_ = par(no.readonly = TRUE), pctReturn_ = TRUE, abs_ = TRUE, original_ = FALSE, main_name = "Conditional Volatility (vs |pctReturns(%)|)")
{

n <- length(fit$data) + 100
n <- length(zoo::coredata(fit$data)) + 100
a0 <- fit$fitted_pars["gamma"]
a1 <- fit$fitted_pars["alpha"]
b1 <- fit$fitted_pars["beta"]
Expand All @@ -21,11 +23,11 @@
#}
#sigma2 <- sigma2[101:n]

returns <- xts::xts(fit$data)
sigma2 <- xts::xts(sqrt(fit$sigma), order.by = zoo::index(returns))
returns <- zoo::coredata(fit$data)
sigma2 <- xts::xts(sqrt(fit$sigma), order.by = zoo::index(fit$data))

if(original_){
zoo::plot.zoo(returns, type = "l", xlab = "", ylab = "Return", main = "Returns")
zoo::plot.zoo(fit$data, type = "l", xlab = "", ylab = "Return", main = "Returns")
}

if(pctReturn_){
Expand All @@ -34,14 +36,17 @@
}

if(abs_){
retAndVol <- cbind(abs(returns),sigma2)
} else{
retAndVol <- cbind(returns,sigma2)
retAndVol <- cbind(abs(returns), sigma2)
} else {
retAndVol <- cbind(returns, sigma2)
}

# Ensure retAndVol retains the dates from fit$data
retAndVol <- xts::xts(retAndVol, order.by = zoo::index(fit$data))

par_
zoo::plot.zoo(retAndVol, screens = "single", type = "l", xlab = "",ylab = "",main = main_name,
lty = c("dotted","solid"),col = c("blue","black"), lwd = c(.8,1.5))
zoo::plot.zoo(retAndVol, screens = "single", type = "l", xlab = "", ylab = "", main = main_name,
lty = c("dotted", "solid"), col = c("blue", "black"), lwd = c(.8, 1.5))
exprss <- c(bquote(alpha[0]~'='~.(signif(a0, digits))),
bquote(alpha[1]~'='~.(signif(a1, digits))),
bquote(beta[1]~'='~.(signif(b1, digits))))
Expand Down
10 changes: 6 additions & 4 deletions R/robustGARCH-summary.R
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,7 @@
#' @param pctReturn_ a logical argument. IF TRUE, the plot function will plot the returns in percentage instead of original. Default is TRUE.
#' @param abs_ a logical argument, when TRUE, the plot function will plot abs(returns) with conditional standard deviation instead of returns, default to TRUE.
#' @param ... # to be written
#' @param nu # to be written
#' @param v degrees of freedom in a Student's t-distribution.
#' @param nu degrees of freedom in a Student's t-distribution.
#'
#' @name robustGARCH-summary
#' @aliases summary.robustGARCH
Expand All @@ -31,7 +30,6 @@
#' summary(fit)
#' print(fit)
#' plot(fit)
#' aef(fit)
#'
#' @export
summary.robustGARCH <- function(object, digits = 3, ...){
Expand All @@ -45,6 +43,8 @@ summary.robustGARCH <- function(object, digits = 3, ...){
# The \usage entries must correspond to syntactically valid R code.
# See chapter ‘Writing R documentation files’ in the ‘Writing R
# Extensions’ manual.
fit <- object

res <- rbind(round(fit$fitted_pars, digits), round(fit$standard_error, digits), round(fit$t_value, digits), round(fit$p_value, digits))
colnames(res) <- names(fit$fitted_pars)
rownames(res) <- c("Estimates", "Std. Errors", "t-statistic", "p-value")
Expand Down Expand Up @@ -75,6 +75,8 @@ summary.robustGARCH <- function(object, digits = 3, ...){
#' @export
print.robustGARCH <- function(x, digits = 3, ...){

fit <- x

res <- rbind(round(fit$fitted_pars, digits))
colnames(res) <- names(fit$fitted_pars)
rownames(res) <- c("Estimates (Std. Errors)")
Expand All @@ -96,12 +98,12 @@ print.robustGARCH <- function(x, digits = 3, ...){
#' @export
plot.robustGARCH <- function(x, digits = 3, estimation_pos = "topleft", line_name_pos = "topright", par_ = par(no.readonly = TRUE), pctReturn_ = TRUE, abs_ = TRUE, original_ = FALSE, main_name = "Conditional Volatility (vs |pctReturns(%)|)", ...){

fit <- x
.plot.garchsim(fit, digits, estimation_pos, line_name_pos, par_, pctReturn_, abs_, original_, main_name)

}

#' @rdname robustGARCH-summary
#' @export
aef <- function(fit, nu=5){

aTop <- .aValue(fit, TRUE, nu)
Expand Down
Binary file modified data/gspc.rda
Binary file not shown.
4 changes: 1 addition & 3 deletions man/robustGARCH-summary.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 86ba27d

Please sign in to comment.