R中的GARCH模拟 [英] Simulation of GARCH in R
问题描述
我正在模拟 GARCH 模型.模型本身并不太相关,我想问你的是关于优化 R 中的模拟.最重要的是,如果你看到任何矢量化空间,我已经考虑过了,但我看不到它.到目前为止,我所拥有的是:
I am doing a simulation of a GARCH model. The model itself is not too relevant, what I would like to ask you is about optimizing the simulation in R. More than anything if you see any room for vectorization, I have thought about it but I cannot see it. So far what I have is this:
让:
# ht=cond.variance in t
# zt= random number
# et = error term
# ret= return
# Horizon= n periods ahead
所以这是代码:
randhelp= function(horizon=horizon){
ret <- zt <- et <- rep(NA,horizon)#initialize ret and zt et
for( j in 1:horizon){
zt[j]= rnorm(1,0,1)
et[j] = zt[j]*sqrt(ht[j])
ret[j]=mu + et[j]
ht[j+1]= omega+ alpha1*et[j]^2 + beta1*ht[j]
}
return(sum(ret))
}
我想从现在开始模拟 5 个时期的收益,所以我将运行这个假设为 10000.
I want to do a simulation of the returns 5 periods from now, so I will run this let's say 10000.
#initial values of the simulation
ndraws=10000
horizon=5 #5 periods ahead
ht=rep(NA,horizon) #initialize ht
ht[1] = 0.0002
alpha1=0.027
beta1 =0.963
mu=0.001
omega=0
sumret=sapply(1:ndraws,function(x) randhelp(horizon))
我认为这运行得相当快,但我想问你是否有任何方法可以更好地解决这个问题.
I think this is running reasonably fast but I would like to ask you if there is any way of approaching this problem in a better way.
谢谢!
推荐答案
您可以使用大小为 N 的向量,而不是在循环中使用数字:删除隐藏在 sapply
中的循环.
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)
这篇关于R中的GARCH模拟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!