diff options
| author | Guillaume Horel <guillaume.horel@gmail.com> | 2017-02-14 17:06:45 -0500 |
|---|---|---|
| committer | Guillaume Horel <guillaume.horel@gmail.com> | 2017-02-14 17:07:29 -0500 |
| commit | c6ea69394eb6a518b5e6a27f08ae77f85cb733e6 (patch) | |
| tree | f4171c73f1a255483797de36aedeeb2e4d17c722 | |
| parent | 1e3db181f9721090440358a5601725ed4d159341 (diff) | |
| download | pyisda-c6ea69394eb6a518b5e6a27f08ae77f85cb733e6.tar.gz | |
Add forward_hazard_rates property
this is also an example of returning a numpy array allocated
with malloc on the C side.
| -rw-r--r-- | pyisda/curve.pyx | 25 | ||||
| -rw-r--r-- | setup.py | 2 |
2 files changed, 26 insertions, 1 deletions
diff --git a/pyisda/curve.pyx b/pyisda/curve.pyx index 489c8e4..0864019 100644 --- a/pyisda/curve.pyx +++ b/pyisda/curve.pyx @@ -1,11 +1,17 @@ from libc.stdlib cimport malloc, free from libc.string cimport memcpy +from libc.math cimport log1p, expm1 from date cimport (JpmcdsStringToDateInterval, pydate_to_TDate, dcc, JpmcdsDateIntervalToFreq, JpmcdsDateFwdThenAdjust, TDate_to_pydate, JpmcdsDateFromBusDaysOffset, JpmcdsStringToDayCountConv) from date import dcc_tostring from cdsone cimport JpmcdsStringToStubMethod, TStubMethod cimport cython +cimport numpy as np +np.import_array() + +cdef extern from "numpy/arrayobject.h": + void PyArray_ENABLEFLAGS(np.ndarray arr, int flags) cdef int SUCCESS = 0 @@ -51,6 +57,25 @@ cdef class Curve(object): 'basis': self._thisptr.fBasis, 'day_count_convention': dcc_tostring(self._thisptr.fDayCountConv), 'data': fArray_to_list(self._thisptr.fArray, self._thisptr.fNumItems)} + + @property + def forward_hazard_rates(self): + cdef double t1, h1, t2, h2 + cdef np.npy_intp shape = self._thisptr.fNumItems + t1 = 0 + h1 = 0 + cdef double* data = <double*>malloc(self._thisptr.fNumItems * sizeof(double)) + for i in range(self._thisptr.fNumItems): + h2 = log1p(self._thisptr.fArray[i].fRate) + t2 = (self._thisptr.fArray[i].fDate - self._thisptr.fBaseDate)/365. + data[i] = (h2 * t2 - h1 * t1) / (t2 - t1) + h1 = h2 + t1 = t2 + cdef np.ndarray[np.float64_t] out = \ + np.PyArray_SimpleNewFromData(1, &shape, np.NPY_DOUBLE, data) + PyArray_ENABLEFLAGS(out, np.NPY_OWNDATA) + return out + @property def base_date(self): return TDate_to_pydate(self._thisptr.fBaseDate) @@ -4,7 +4,7 @@ from Cython.Build import cythonize import numpy all_extensions = Extension("*", ["pyisda/*.pyx"], - include_dirs = ['c_layer'], + include_dirs = ['c_layer', numpy.get_include()], libraries = ["cds"]) c_extension = Extension("pyisda.flat_hazard", |
