Skip to content

Instantly share code, notes, and snippets.

@bkamins
Created October 19, 2017 20:50
Show Gist options
  • Save bkamins/141b46c26dc94efe10e71e9130f8c4df to your computer and use it in GitHub Desktop.
Save bkamins/141b46c26dc94efe10e71e9130f8c4df to your computer and use it in GitHub Desktop.
Asian option pricing in Python
import math
import random
import statistics
import numpy
from timeit import default_timer as timer
from numba import jit
def v_asian_sample(T, r, K, s, X0, m):
xhat = 0.0
X = X0
D = T / m
for i in range(m):
X *= math.exp(random.normalvariate((r-s**2/2)*D, s*D**0.5))
xhat += X
return math.exp(-r*T)*max(xhat/m - K, 0)
@jit
def v_asian_sample_jit(T, r, K, s, X0, m):
xhat = 0.0
X = X0
D = T / m
for i in range(m):
X *= math.exp(random.normalvariate((r-s**2/2)*D, s*D**0.5))
xhat += X
return math.exp(-r*T)*max(xhat/m - K, 0)
def v_asian_sample_vec(T, r, K, s, X0, m):
D = T / m
X = numpy.random.normal((r-s**2/2)*D, s*D**0.5, m)
return math.exp(-r*T)*max(numpy.mean(numpy.exp(numpy.cumsum(X)))*X0 - K, 0)
def v_asian(T, r, K, s, Xo, m, n, fun):
return statistics.mean([fun(T, r, K, s, Xo, m) for i in range(n)])
for f in [v_asian_sample, v_asian_sample_jit, v_asian_sample_vec]:
for i in range(2):
start = timer()
v_asian(1.0, 0.05, 55.0, 0.3, 50, 1000, 100000, f)
duration = timer() - start
print(f, "\n ", duration, " seconds")
# Output:
#
# <function v_asian_sample at 0x000001BAC05B8F28>
# 218.74880357997608 seconds
# <function v_asian_sample at 0x000001BAC05B8F28>
# 218.45428551167777 seconds
# CPUDispatcher(<function v_asian_sample_jit at 0x000002722635BEA0>)
# 5.729526031990998 seconds
# CPUDispatcher(<function v_asian_sample_jit at 0x000002722635BEA0>)
# 5.397216579782951 seconds
# <function v_asian_sample_vec at 0x000002722636A1E0>
# 7.5086485608902915 seconds
# <function v_asian_sample_vec at 0x000002722636A1E0>
# 7.4985504866390045 seconds
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment