-
Notifications
You must be signed in to change notification settings - Fork 7
/
bs_erf_cython_impl.pyx
109 lines (87 loc) · 2.3 KB
/
bs_erf_cython_impl.pyx
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# Copyright (C) 2019 Intel Corporation
#
# SPDX-License-Identifier: MIT
import numpy as np
cimport numpy as np
from cython cimport boundscheck, wraparound, cdivision, initializedcheck
from cython.parallel cimport prange, parallel
from libc.stdlib cimport srand, rand, RAND_MAX
cdef extern from "mathimf.h":
double erf(double x) nogil
double log(double x) nogil
double exp(double x) nogil
double sqrt(double x) nogil
DTYPE = np.float64
ctypedef np.float64_t DTYPE_t
# the directives below are essential for the best code generation
@boundscheck(False)
@wraparound(False)
@cdivision(True)
@initializedcheck(False)
def black_scholes_par(int nopt,
double[::1] price,
double[::1] strike,
double[::1] t,
double rate,
double vol,
double[::1] call,
double[::1] put):
# using [::1] is essential for autovectorization
cdef int i
cdef double P, S, a, b, z, c, Se, y, T
cdef double d1, d2, w1, w2
cdef double mr = -rate
cdef double sig_sig_two = vol * vol * 2
# In order to release the GIL for a parallel loop, code in the with block cannot
# manipulate Python objects in any way.
with nogil, parallel():
for i in prange(nopt):
P = price [i]
S = strike [i]
T = t [i]
a = log(P / S)
b = T * mr
z = T * sig_sig_two
c = 0.25 * z
y = 1./sqrt(z)
w1 = (a - b + c) * y
w2 = (a - b - c) * y
d1 = 0.5 + 0.5 * erf(w1)
d2 = 0.5 + 0.5 * erf(w2)
Se = exp(b) * S
call [i] = P * d1 - Se * d2
put [i] = call [i] - P + Se
@boundscheck(False)
@wraparound(False)
@cdivision(True)
@initializedcheck(False)
def black_scholes_ser(int nopt,
double[::1] price,
double[::1] strike,
double[::1] t,
double rate,
double vol,
double[::1] call,
double[::1] put):
# using [::1] is essential for vectorization
cdef int i
cdef double P, S, a, b, z, c, Se, y, T
cdef double d1, d2, w1, w2
cdef double mr = -rate
cdef double sig_sig_two = vol * vol * 2
for i in range(nopt):
P = price [i]
S = strike [i]
T = t [i]
a = log(P / S)
b = T * mr
z = T * sig_sig_two
c = 0.25 * z
y = 1./sqrt(z)
w1 = (a - b + c) * y
w2 = (a - b - c) * y
d1 = 0.5 + 0.5 * erf(w1)
d2 = 0.5 + 0.5 * erf(w2)
Se = exp(b) * S
call [i] = P * d1 - Se * d2
put [i] = call [i] - P + Se