[Solved] Heston Simulation Monte Carlo: Slow R code [duplicate]


You will probably speed things up a lot if you get rid of the outer loop and construct an entire column of your matrix at once:

nsim <- 1e5
nt <- 200
U <- matrix(NA, nrow=nsim, ncol=200, byrow=TRUE)
V_last <- V <- rep(0.04, nsim)
U[,1] <- 40

Inv.phi <- function(y,p) ifelse (y <= p, 0, log(1-p))
for(i in 2:nt) {
    m <- V_last * c
    n <- V_last * d
    phi <- n/m ## ??? as currently stated this is just a constant d/c ??
               ## presumably there is a typo somewhere??
    bt <- (phi<=1.5) ## below-threshold
    V[bt] <- rnorm(length(bt)) * e
    V[!bt] <- Inv.phi(runif(length(!bt)), (phi[!bt]-1) / (phi[!bt]+1))
    K <- V_last*ifelse(bt,f,g)
    U[,i] <- U[,i-1] * exp(K * V_last) * exp(V * rnorm(nsim))
    V_last <- V
}

I think this works but can’t test it because you haven’t given a reproducible example …

2

solved Heston Simulation Monte Carlo: Slow R code [duplicate]