Python for Finance: Analyze Big Financial Data

(Elle) #1

Example 3-2. Monte Carlo valuation of European call option with pure Python



Monte Carlo valuation of European call options with pure Python


mcs_pure_python.py



from time import time
from math import exp, sqrt, log
from random import gauss, seed


seed( 20000 )
t0 = time()


Parameters


S0 = 100. # initial value
K = 105. # strike price
T = 1.0 # maturity
r = 0.05 # riskless short rate
sigma = 0.2 # volatility
M = 50 # number of time steps
dt = T / M # length of time interval
I = 250000 # number of paths


Simulating I paths with M time steps


S = []
for i in range(I):
path = []
for t in range(M + 1 ):
if t == 0 :
path.append(S0)
else:
z = gauss(0.0, 1.0)
St = path[t - 1 ] exp((r - 0.5 sigma * 2 ) dt



  • sigma sqrt(dt) z)
    path.append(St)
    S.append(path)


Calculating the Monte Carlo estimator


C0 = exp(-r T) sum([max(path[- 1 ] - K, 0 ) for path in S]) / I


Results output


tpy = time() - t0
print “European Option Value %7.3f” % C0
print “Duration in Seconds %7.3f” % tpy


Running the script yields the following output:


In  [ 20 ]: %run mcs_pure_python.py

Out[ 20 ]:  European Option Value 7.999
Duration in Seconds 34.258

Note that the estimated option value itself depends on the pseudorandom numbers


generated while the time needed is influenced by the hardware the script is executed on.


The major part of the code in Example 3-2 consists of a nested loop that generates step-


by-step single values of an index level path in the inner loop and adds completed paths to


a list object with the outer loop. The Monte Carlo estimator is calculated using Python’s


list comprehension syntax. The estimator could also be calculated by a for loop:


In  [ 21 ]: sum_val =   0.0
for path in S:
# C-like iteration for comparison
sum_val += max(path[- 1 ] - K, 0 )
C0 = exp(-r * T) * sum_val / I
round(C0, 3 )
Out[21]: 7.999

Although this loop yields the same result, the list comprehension syntax is more compact


and closer to the mathematical notation of the Monte Carlo estimator.

Free download pdf