I need to simulate the stock price, that follows stochastic volatility process (Heston Model). I already asked, how to speed up my loops, but for this case I´m not able to use some tips due to the V[i-1] dependence.
Basically the code is: V is the volatility of the stock and S is the stock price. And: a,b,c... constants.
Here is the code:
V[1] <- 0.04
S[1] <- 40
U <- matrix(NA, nrow=100000, ncol=200, byrow=TRUE)
### Function ###
Inv.Phi <- function(y){
if (y <= p) {0} else {log(1-p)}
}
### Simulation ####
for(j in 1:100000){
for(i in 2:200){
m <- V[i-1] * c
n <- V[i-1] * d
phi <- n/m
if(phi <= 1.5){
Z <- rnorm(1)
V[i] <- rnorm(1) * e
K <- V[i-1] * f
}else{
p <- (phi-1) / (phi+1)
u <- runif(1)
V[i] <- Inv.Phi(u)
K <- V[i-1] * g
}
S[i] <- S[i-1] * exp(K * V[i-1]) * exp(V[i] * rnorm(1))
}
U[j,] = S
}
Any suggestion to speed up this process! I known, I´m using a lot of bad things for R, but I couldn´t figure out a better solution.