-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathmonte_carlo_options.py
More file actions
64 lines (46 loc) · 1.76 KB
/
monte_carlo_options.py
File metadata and controls
64 lines (46 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#!/usr/bin/env python
#######################################################
# Copyright (c) 2019, ArrayFire
# All rights reserved.
#
# This file is distributed under 3-clause BSD license.
# The complete license agreement can be obtained at:
# http://arrayfire.com/licenses/BSD-3-Clause
########################################################
import math
import sys
from time import time
import arrayfire as af
def monte_carlo_options(N, K, t, vol, r, strike, steps, use_barrier=True, B=None, ty=af.Dtype.f32):
payoff = af.constant(0, N, 1, dtype=ty)
dt = t / float(steps - 1)
s = af.constant(strike, N, 1, dtype=ty)
randmat = af.randn(N, steps - 1, dtype=ty)
randmat = af.exp((r - (vol * vol * 0.5)) * dt + vol * math.sqrt(dt) * randmat)
S = af.product(af.join(1, s, randmat), 1)
if use_barrier:
S = S * af.all_true(S < B, 1)
payoff = af.maxof(0, S - K)
return af.mean(payoff) * math.exp(-r * t)
def monte_carlo_simulate(N, use_barrier, num_iter=10):
steps = 180
stock_price = 100.0
maturity = 0.5
volatility = 0.3
rate = 0.01
strike = 100
barrier = 115.0
start = time()
for _ in range(num_iter):
monte_carlo_options(N, stock_price, maturity, volatility, rate, strike, steps, use_barrier, barrier)
return (time() - start) / num_iter
if __name__ == "__main__":
if len(sys.argv) > 1:
af.set_device(int(sys.argv[1]))
af.info()
monte_carlo_simulate(1000, use_barrier=False)
monte_carlo_simulate(1000, use_barrier=True)
af.sync()
for n in range(10000, 100001, 10000):
print("Time for %7d paths - vanilla method: %4.3f ms, barrier method: % 4.3f ms\n" %
(n, 1000 * monte_carlo_simulate(n, False, 100), 1000 * monte_carlo_simulate(n, True, 100)))