the outer loop in Example 3-2 are now delegated to NumPy, avoiding the outer loop
completely on the Python level.
VECTORIZATION
Using vectorization with NumPy generally results in code that is more compact, easier to read (and maintain), and
faster to execute. All these aspects are in general important for financial applications.
Full Vectorization with Log Euler Scheme
Using a different discretization scheme for the SDE in Equation 3-5 can yield an even
more compact implementation of the Monte Carlo algorithm. To this end, consider the log
version of the discretization in Equation 3-6, which takes on the form in Equation 3-8.
Equation 3-8. Euler discretization of SDE (log version)
This version is completely additive, allowing for an implementation of the Monte Carlo
algorithm without any loop on the Python level. Example 3-4 shows the resulting code.
Example 3-4. Monte Carlo valuation of European call option with NumPy (second
version)
Monte Carlo valuation of European call options with NumPy (log version)
mcs_full_vector_numpy.py
import math
from numpy import *
from time import time
star import for shorter code
random.seed( 20000 )
t0 = time()
Parameters
S0 = 100.; K = 105.; T = 1.0; r = 0.05; sigma = 0.2
M = 50 ; dt = T / M; I = 250000
Simulating I paths with M time steps
S = S0 exp(cumsum((r - 0.5 sigma * 2 ) dt
- sigma * math.sqrt(dt)
- random.standard_normal((M + 1 , I)), axis= 0 ))
sum instead of cumsum would also do
if only the final values are of interest
S[ 0 ] = S0
- random.standard_normal((M + 1 , I)), axis= 0 ))
Calculating the Monte Carlo estimator
C0 = math.exp(-r T) sum(maximum(S[- 1 ] - K, 0 )) / I
Results output
tnp2 = time() - t0
print “European Option Value %7.3f” % C0
print “Duration in Seconds %7.3f” % tnp2
Let us run this third simulation script.
In [ 28 ]: %run mcs_full_vector_numpy.py
Out[28]: European Option Value 8.166
Duration in Seconds 1.439