0

I'm simulating an asian option (a financial derivative) using R. For this problem, random numbers and some sort of Random Walk have to be simulated. The results have to be extremely precise.

Thus n=2*10^8 paths and 360 intermediate points have to be considered. This totals to 2*10^8*360 random numbers that have to be generated. This clearly exceeds the maximum size of a matrix in R.

So far I have used the following code. Declaring ST as a global variable, I was able to run the function several times and complete the task.

library(fOptions)
set.seed(123)

    MC.C = function(n=2*10^8,
                 d = 360, 
                 Time = 1,
                 r = 0.05,
                 sigma = 0.25,
                 S0 = 100 
                 ){

    delta.t = Time/d
    Payoff = 0
    St = 0
    log.St = log(S0)
    Z = 0
    ST <<- 0

    Z = matrix(rnorm.pseudo(n=n, dimension = d), byrow = TRUE, ncol = d) 
    for(i in 1:d){
      log.St = log.St+(r-0.5*sigma^2)*delta.t + sigma*sqrt(delta.t)*Z[,i] 
      St = St + exp(log.St)
    }
    ST <<- append(0, St/d)
    }

However this is extremely time-consuming.

My aim is to get as quickly as possible to the solution. The two questions I have are:

  1. How to deal with simulations that exceed the memory of a matrix in R?
  2. How to further speed-up the code?

I would be very thankful for any answers or for pointing out mistakes that I've made.

NikB
  • 43
  • 5
  • Are you using any additional packages? Please put the `library(...)`-calls in your code. – jogo Sep 04 '18 at 11:17
  • Damn. Thanks again. I've updated the code. – NikB Sep 04 '18 at 11:20
  • One column of your matrix Z takes 1.5 GB. Eventually you can restructure the calculation to do it column by column. – jogo Sep 04 '18 at 11:31
  • Global assignments are dangerous: `library("fortunes"); fortune(174)` or http://www.burns-stat.com/pages/Tutor/R_inferno.pdf Circle 6 ... or https://stackoverflow.com/questions/9851655/why-is-using-frowned-upon-and-how-can-i-avoid-it – jogo Sep 05 '18 at 06:48

1 Answers1

0

This is my variant of your code:

library("fOptions")
set.seed(123)
MC.C = function(n=2*10^8, d=360, Time=1, r=0.05, sigma=0.25, S0=100) {
  delta.t <- Time/d
  St <- 0
  log.St <- log(S0)

  for(i in 1:d) {
    Zi <- rnorm.pseudo(n=n, dimension=1)
    log.St <- log.St + (r-0.5*sigma^2)*delta.t + sigma*sqrt(delta.t)*Zi 
    St <- St + exp(log.St)
  }
  St/d
}
X <- MC.C(n=2e2, d=7)

You can little speed up by storing the constants (r-0.5*sigma^2)*delta.t and sigma*sqrt(delta.t) in objects.

jogo
  • 12,469
  • 11
  • 37
  • 42