File: monte_carlo_options.cpp

package info (click to toggle)
arrayfire 3.3.2%2Bdfsg1-4
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 109,016 kB
  • sloc: cpp: 127,909; lisp: 6,878; python: 3,923; ansic: 1,051; sh: 347; makefile: 338; xml: 175
file content (84 lines) | stat: -rw-r--r-- 2,285 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*******************************************************
 * Copyright (c) 2014, 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
 ********************************************************/

#include <iostream>
#include <stdio.h>
#include <math.h>
#include <arrayfire.h>
#include <af/util.h>

using namespace af;
template<class ty> dtype get_dtype();

template<> dtype get_dtype<float>() { return f32; }
template<> dtype get_dtype<double>() { return f64; }

template<class ty, bool use_barrier>
static ty monte_carlo_barrier(int N, ty K, ty t, ty vol, ty r, ty strike, int steps, ty B)
{
    dtype pres = get_dtype<ty>();
    array payoff = constant(0, N, 1, pres);

    ty dt = t / (ty)(steps - 1);
    array s = constant(strike, N, 1, pres);

    array randmat = randn(N, steps - 1, pres);
    randmat = exp((r - (vol * vol * 0.5)) * dt + vol * sqrt(dt) * randmat);

    array S = product(join(1, s, randmat), 1);

    if (use_barrier) {
        S = S * allTrue(S < B, 1);
    }

    payoff = max(0.0, S - K);
    ty P = mean<ty>(payoff) * exp(-r * t);
    return P;
}

template<class ty, bool use_barrier>
double monte_carlo_bench(int N)
{
    int steps = 180;
    ty stock_price = 100.0;
    ty maturity = 0.5;
    ty volatility = .30;
    ty rate = .01;
    ty strike = 100;
    ty barrier = 115.0;

    timer::start();
    for (int i = 0; i < 10; i++) {
        monte_carlo_barrier<ty, use_barrier>(N, stock_price, maturity, volatility,
                                             rate, strike, steps, barrier);
    }
    return timer::stop() / 10;
}

int main()
{
    try {

        // Warm up and caching
        monte_carlo_bench<float, false>(1000);
        monte_carlo_bench<float, true>(1000);

        for (int n = 10000; n <= 100000; n += 10000) {
            printf("Time for %7d paths - "
                   "vanilla method: %4.3f ms,  "
                   "barrier method: %4.3f ms\n", n,
                   1000 * monte_carlo_bench<float, false>(n),
                   1000 * monte_carlo_bench<float, true>(n));
        }
    } catch (af::exception &ae) {
        std::cerr << ae.what() << std::endl;
    }

    return 0;
}