|
| 1 | +# |
| 2 | +# Copyright (c) 2017 Intel Corporation |
| 3 | +# SPDX-License-Identifier: BSD-2-Clause |
| 4 | +# |
| 5 | + |
| 6 | +import numba |
| 7 | +import numpy as np |
| 8 | +import math |
| 9 | +import argparse |
| 10 | +import time |
| 11 | + |
| 12 | +@numba.vectorize(nopython=True) |
| 13 | +def cndf2(inp): |
| 14 | + #out = 0.5 + 0.5 * math.erf((math.sqrt(2.0)/2.0) * inp) |
| 15 | + out = 0.5 + 0.5 * ((math.sqrt(2.0)/2.0) * inp) |
| 16 | + return out |
| 17 | + |
| 18 | +def blackscholes_slow(sptprice, strike, rate, volatility, timev): |
| 19 | + logterm = np.log(sptprice / strike) |
| 20 | + powterm = 0.5 * volatility * volatility |
| 21 | + den = volatility * np.sqrt(timev) |
| 22 | + d1 = (((rate + powterm) * timev) + logterm) / den |
| 23 | + d2 = d1 - den |
| 24 | + NofXd1 = cndf2(d1) |
| 25 | + NofXd2 = cndf2(d2) |
| 26 | + futureValue = strike * np.exp(- rate * timev) |
| 27 | + c1 = futureValue * NofXd2 |
| 28 | + call = sptprice * NofXd1 - c1 |
| 29 | + put = call - futureValue + sptprice |
| 30 | + return put |
| 31 | + |
| 32 | +@numba.njit(parallel={'csa':True}) |
| 33 | +def blackscholes(sptprice, strike, rate, volatility, timev): |
| 34 | + logterm = np.log(sptprice / strike) |
| 35 | + powterm = 0.5 * volatility * volatility |
| 36 | + den = volatility * np.sqrt(timev) |
| 37 | + d1 = (((rate + powterm) * timev) + logterm) / den |
| 38 | + d2 = d1 - den |
| 39 | + NofXd1 = cndf2(d1) |
| 40 | + NofXd2 = cndf2(d2) |
| 41 | + futureValue = strike * np.exp(- rate * timev) |
| 42 | + c1 = futureValue * NofXd2 |
| 43 | + call = sptprice * NofXd1 - c1 |
| 44 | + put = call - futureValue + sptprice |
| 45 | + return put |
| 46 | + |
| 47 | + |
| 48 | +def run(OPT_N, iterations): |
| 49 | + sptprice = np.full((OPT_N,), 42.0) |
| 50 | + initStrike = 40 + (np.arange(OPT_N) + 1.0) / OPT_N |
| 51 | + rate = np.full((OPT_N,), 0.5) |
| 52 | + volatility = np.full((OPT_N,), 0.2) |
| 53 | + timev = np.full((OPT_N,), 0.5) |
| 54 | + |
| 55 | + spt1 = sptprice.__array_interface__['data'] |
| 56 | + print("spt1", spt1) |
| 57 | + put = blackscholes(sptprice, initStrike, rate, volatility, timev) |
| 58 | + print("compare", np.sum(put), np.sum(blackscholes_slow(sptprice, initStrike, rate, volatility, timev))) |
| 59 | + |
| 60 | +# t1 = time.time() |
| 61 | +# for i in range(iterations): |
| 62 | +# put = blackscholes(sptprice, initStrike, rate, volatility, timev) |
| 63 | +# t = time.time()-t1 |
| 64 | +# return 1000 * (t / iterations) |
| 65 | + |
| 66 | +def main(*args): |
| 67 | +# OPT_N = 4000000 |
| 68 | +# iterations = 10 |
| 69 | + OPT_N = 4000 |
| 70 | + iterations = 1 |
| 71 | + if len(args) >= 2: |
| 72 | + iterations = int(args[0]) |
| 73 | + |
| 74 | +# run(1, 1) |
| 75 | + run(OPT_N, iterations) |
| 76 | +# t = run(OPT_N, iterations) |
| 77 | +# print("SELFTIMED ", t) |
| 78 | + |
| 79 | +if __name__ == '__main__': |
| 80 | + main() |
0 commit comments