# [R-SIG-Finance] Monte Carlo Option Pricing formula R code vs Matlab

rex rex at nosyntax.net
Fri Feb 3 23:38:29 CET 2012

```Roupell, Darko <Darko.Roupell at cba.com.au> [2012-02-02 15:37]:

>What I find the most puzzling is that even if I re-code using sample from matlab the results obtained in R are very different to those obtained by matlab, despite using the same parameters apart of Rnorm(). As I am at loss I am hoping that you or someone else in R-SIG may spot the difference that explains it.

As Enrico pointed out, you want pmax, not max, and the final price is
all that matters, not the path, so you don't need the inner loop. And,
you don't need the outer loop, either. Here, your code runs in 38.9
seconds with itr = 10000.

large nested loops in R are an abomination; using the language
effectively requires learning to avoid them whenever possible. In this
case, your code takes 18702(!) times as long to run as a vectorized
Monte Carlo version.

For possible pedagogical value, here's a vectorized MC approach:

start = Sys.time()
E    = 100                            #exercise price
S    = 100                            #initial stock price
t    = 5                              #time to expiration (years)
sd   = 0.2                            #annual volatility
d    = 0.0                            #annual dividend rate
r    = 0.06                           #riskless interest rate
N    = 1000000                        #number of random walks
mu   = (r - d - 0.5*sd^2)*t           #total drift
SD   = sd*sqrt(t)                     #total volatility
z    = as.vector(rlnorm(N, mu, SD))   #generate all lognormal randoms
endS = S*z                            #ending stock prices
fv   = pmax(0, endS-E)                #future option values
opt  = fv*exp(-r*t)                   #present option values
mean(opt)
#31.6
Sys.time() - start
Time difference of 0.2075577 secs

Note that N is 100 times as large in the above, so the nested loop
version takes 100*38.9/0.208 = 18702 times as long as the vectorized
version does.

HTH,

-rex
--
"In the real world, this would be a problem.  But in mathematics, we
can just define a place where this problem doesn't exist.  So we'll go