Python with Reticulate

Let’s download some packages.

And calculate European call.

import math
import numpy as np
from timeit import default_timer as timer
start = timer()
S = 100
K = 105 
T = 1 
r = 0.05
sigma = 0.2
I = 100000
z = np.random.standard_normal(I)
ST = S * np.exp((r-0.5*sigma**2)*T + sigma * math.sqrt(T)*z)
hT = np.maximum(ST - K, 0)
C0 = math.exp(-r*T)*np.mean(hT)
print('Value of %5.3f.' % C0)
## Value of 8.008.
end = timer()
print('Elapsed time in seconds %5.3f.' % (end - start))
## Elapsed time in seconds 0.142.

And in R.

start = Sys.time()
S = 100
K = 105 
T = 1 
r = 0.05
sigma = 0.2
I = 100000
z = rnorm(I)
ST = S * exp((r-0.5*sigma**2)*T + sigma * sqrt(T)*z)
hT = pmax(ST - K, 0)
C0 = exp(-r*T)*mean(hT)
C0
## [1] 7.995249
end = Sys.time() - start
print(paste("Elapsed time in seconds:", end))
## [1] "Elapsed time in seconds: 0.0197596549987793"
Avatar
Petri Rautiainen
Fund Analyst

Quantitative analysis with R and Python.