File: monte_carlo_options.py

package info (click to toggle)
python-arrayfire 3.3.20160624-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 764 kB
  • ctags: 826
  • sloc: python: 3,999; makefile: 205
file content (61 lines) | stat: -rw-r--r-- 1,851 bytes parent folder | download
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
#!/usr/bin/python

#######################################################
# Copyright (c) 2015, 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 arrayfire as af
from time import time
import math
import sys

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 i 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)))