Reputation: 37
I have been trying to build my own GARCH(1,1) model. However the solvers I have used so far have either failed to return the optimized parameters or taking way too long to optimize (maybe not converging?). So far I have tried optim() (with Nelder-Mead & BFGS), nlm() with no success. I have included my code with the "solnp" optimizer which is actually used in the "rugarch" package as well.Thought that might solve the issue, however it didn't. Would really appreciate if someone can point out where I am making mistakes. Thanks!
library(tseries)
library(zoo)
AAPL <-get.hist.quote(instrument = "AAPL",
start = "2015-09-15",
end = "2016-09-14",
quote = "AdjClose",
retclass = "zoo",
quiet = TRUE)
garch_likelihood <- function(asset,fixed=c(FALSE,FALSE,FALSE)) {
pars <- fixed
function(p) {
pars[!fixed] <- p
omega <- pars[1]
alpha <- pars[2]
beta <- pars[3]
#constructor function
# object must be a time series class
if (class(asset) !="zoo")
stop("asset must be a time series object!!")
# Calculating log returns
r <- log(asset)-log(lag(asset,-1))
#calculating squared returns & variance
r2 <- r^2
variance.r <- var(r,na.rm = TRUE)
# Setting up the initial model
mod.pregarch <- cbind(r2,variance.r)
mod.pregarch[2:nrow(mod.pregarch),2] <- 0
# Using a loop to calculate the conditional variances
for (i in 2:nrow(mod.pregarch)) {
# pregarch model: var(t+1) = omega+alpha*r(t)^2+beta*var(t)
mod.pregarch[i,2] <- omega +alpha*mod.pregarch[i-1,1]+beta*mod.pregarch[i-1,2]}
pregarch <-mod.pregarch[,2]
sum(pregarch)
pregarch <- cbind(pregarch,rep(0,length(pregarch)))
#calculating log likelihoods
for (i in 1:nrow(pregarch)){
pregarch[i,2] <- dnorm(r[i,1],mean = 0,sd = sqrt(pregarch[i,1]),log = TRUE)
}
## Loglike.alternative <- -.5*log(2*pi)-.5*log(pregarch[i,1])-.5*(r2[i]/pregarch[[i,1]])
sum_log.like <- sum(pregarch[,2])
sum_log.like
}
}
pars <- c(0.000005,0.10,0.85) #initial values
garch11.ML <- garch_likelihood(AAPL)
library(Rsolnp)
optim_garch <- solnp(pars =pars,fun = garch11.ML) #Rsolnp solver package
Upvotes: 1
Views: 473
Reputation: 711
I would suggest re visiting your model, when I ask the function to print the parameters e.g.
garch_likelihood <- function(asset,fixed=c(FALSE,FALSE,FALSE)) {
pars <- fixed
function(p) {
print(p)
...}
Parameters look like in the right range as follows.
[1] 0.0000781018 0.0672768675 0.6338644923
[1] 5.796055e-05 6.020388e-02 7.161618e-01
I used optim also with the following call,
optim_garch <- optim(par =pars ,fn = garch11.ML, control =list(fnscale = -1))
I also get the following warnings()
warnings()
1: In sqrt(pregarch[i, 1]) : NaNs produced
I am unfamiliar with this model, but if you have an idea on the bounds of your parameters you can penalise for when parameters getting close to to avoid getting NaN results. I know this doesn't answer your question but in order to get help optimising your code, it should be able to reach a solution first.
Upvotes: 1