我一直在尝试建立自己的 GARCH(1,1) 模型。然而,到目前为止我使用的求解器要么无法返回优化的参数,要么优化的时间太长(可能没有收敛?)。到目前为止,我已经尝试了 optim() (使用 Nelder-Mead 和 BFGS), nlm() 没有成功。我已将我的代码包含在“rugarch”包中实际使用的“solnp”优化器中。我认为这可能会解决问题,但事实并非如此。如果有人能指出我在哪里犯错误,我将不胜感激。谢谢!
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