Simulation of GARCH in R

和自甴很熟 提交于 2019-11-30 09:55:56

Instead of using numbers in your loop, you can use vectors of size N: that removes the loop hidden in sapply.

randhelp <- function(
  horizon=5, N=1e4, 
  h0 = 2e-4, 
  mu = 0, omega=0,
  alpha1 = 0.027,
  beta1  = 0.963
){
  ret <- zt <- et <- ht <- matrix(NA, nc=horizon, nr=N)
  ht[,1] <- h0
  for(j in 1:horizon){
    zt[,j]   <- rnorm(N,0,1)
    et[,j]   <- zt[,j]*sqrt(ht[,j])
    ret[,j]  <- mu + et[,j]
    if( j < horizon )
      ht[,j+1] <- omega+ alpha1*et[,j]^2 + beta1*ht[,j]
  }
  apply(ret, 1, sum)
}
x <- randhelp(N=1e5)

building on Vincent's response, all I changed was dfining zt all at once and switching apply(ret, 1, sum) to rowSums(ret) and it sped up quite a bit. I tried both compiled, but no major diff:

randhelp2 <- function(horizon = 5, N = 1e4, h0 = 2e-4, 
                       mu = 0, omega = 0, alpha1 = 0.027, 
                       beta1  = 0.963 ){
    ret <- et <- ht <- matrix(NA, nc = horizon, nr = N)
    zt  <- matrix(rnorm(N * horizon, 0, 1), nc = horizon)
    ht[, 1] <- h0
    for(j in 1:horizon){
        et[, j]  <- zt[, j] * sqrt(ht[, j])
        ret[,j]  <- mu + et[, j]
        if( j < horizon )
            ht[, j + 1] <- omega + alpha1 * et[, j] ^ 2 + beta1 * ht[, j]
    }
    rowSums(ret)
}

system.time(replicate(10,randhelp(N=1e5)))
   user  system elapsed 
  7.413   0.044   7.468 

system.time(replicate(10,randhelp2(N=1e5)))   
   user  system elapsed 
  2.096   0.012   2.112 

likely still room for improvement :-)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!