Skip to content

Commit

Permalink
Implement Date.to_date and from_date in C++
Browse files Browse the repository at this point in the history
This makes them about 3x faster.
  • Loading branch information
eltoder committed Jan 25, 2024
1 parent 4049cae commit 7145ad4
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 17 deletions.
18 changes: 13 additions & 5 deletions Python/test/test_date.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,12 @@
FOR A PARTICULAR PURPOSE. See the license for more details.
"""

import datetime
import QuantLib as ql
import unittest


class DateTest(unittest.TestCase):
def setUp(self):
pass

def testArithmetics(self):
"Testing date arithmetics"
today = ql.Date.todaysDate()
Expand Down Expand Up @@ -66,8 +64,18 @@ def testHolidayList(self):
# check if dates both from function and from manual imput are the same
self.assertTrue(all([(a == b) for a, b in zip(holidayLstFunction, holidayLstManual)]))

def tearDown(self):
pass
def testConversion(self):
for m in range(1, 13):
ql_date = ql.Date(m * 2, m, 2020)
py_date = datetime.date(2020, m, m * 2)
self.assertEqual(ql_date.to_date(), py_date)
self.assertEqual(ql.Date.from_date(py_date), ql_date)
# datetime works as well
py_dt = datetime.datetime(2020, m, m * 2)
self.assertEqual(ql.Date.from_date(py_dt), ql_date)

with self.assertRaisesRegex(RuntimeError, "from_date requires a date"):
ql.Date.from_date("2020-01-02")


if __name__ == "__main__":
Expand Down
26 changes: 14 additions & 12 deletions SWIG/date.i
Original file line number Diff line number Diff line change
Expand Up @@ -416,8 +416,11 @@ using QuantLib::DateParser;
%}

#if defined(SWIGPYTHON)
%pythoncode %{
import datetime as _datetime
%{
#include <datetime.h>
%}
%init %{
PyDateTime_IMPORT;
%}
#endif

Expand Down Expand Up @@ -757,18 +760,17 @@ class Date {
bool __ne__(const Date& other) {
return *self != other;
}
PyObject* to_date() {
return PyDate_FromDate(self->year(), self->month(), self->dayOfMonth());
}
static Date from_date(PyObject* date) {
if (!PyDate_Check(date))
throw std::invalid_argument("from_date requires a date");
return Date(PyDateTime_GET_DAY(date), Month(PyDateTime_GET_MONTH(date)),
PyDateTime_GET_YEAR(date));
}
#endif
}
#if defined(SWIGPYTHON)
%pythoncode %{
def to_date(self):
return _datetime.date(self.year(), self.month(), self.dayOfMonth())

@staticmethod
def from_date(date):
return Date(date.day, date.month, date.year)
%}
#endif

#if defined(SWIGJAVA)
%proxycode %{
Expand Down

0 comments on commit 7145ad4

Please sign in to comment.