From c99ffe02d0e97163240ae62df54c6a9bd6c6fe73 Mon Sep 17 00:00:00 2001 From: gouravkr Date: Sun, 24 Apr 2022 18:43:06 +0530 Subject: [PATCH] changes to getitem to fetch closest date --- fincal/core.py | 31 +++++++++++++++++++------------ fincal/utils.py | 2 +- tests/test_core.py | 2 +- 3 files changed, 21 insertions(+), 14 deletions(-) diff --git a/fincal/core.py b/fincal/core.py index 8ba6d66..85884e9 100644 --- a/fincal/core.py +++ b/fincal/core.py @@ -393,7 +393,7 @@ class TimeSeriesCore: def _get_item_from_date(self, date: str | datetime.datetime): """Helper function to retrieve item using a date""" - return date, self.data[date] + return self.get(date, raise_error=True) def _get_item_from_key(self, key: str | datetime.datetime): """Helper function to implement special keys""" @@ -447,9 +447,9 @@ class TimeSeriesCore: raise TypeError("Only numerical values can be stored in TimeSeries") if key in self.data: - self.data[key] = value + self.data[key] = float(value) else: - self.data.update({key: value}) + self.data.update({key: float(value)}) self.data = dict(sorted(self.data.items())) @date_parser(1) @@ -765,19 +765,22 @@ class TimeSeriesCore: raise NotImplementedError("This operation is not supported.") @date_parser(1) - def get(self, date: str | datetime.datetime, default=None, closest=None): + def get(self, date: str | datetime.datetime, default=None, closest=None, raise_error: bool = False): if closest is None: closest = FincalOptions.get_closest if closest == "exact": - try: - item = self._get_item_from_date(date) - return item - except KeyError: - return default + # try: + # item = self.data[date] + # return date, item + # except KeyError: + # if raise_error: + # raise KeyError(date) - if closest == "previous": + # return default + delta = 0 + elif closest == "previous": delta = datetime.timedelta(-1) elif closest == "next": delta = datetime.timedelta(1) @@ -786,9 +789,13 @@ class TimeSeriesCore: while True: try: - item = self._get_item_from_date(date) - return item + item = self.data[date] + return date, item except KeyError: + if delta == 0: + if raise_error: + raise KeyError(date) + return default date += delta @property diff --git a/fincal/utils.py b/fincal/utils.py index 0de1dcd..8c1fcbf 100644 --- a/fincal/utils.py +++ b/fincal/utils.py @@ -8,7 +8,7 @@ from .exceptions import DateNotFoundError, DateOutOfRangeError @dataclass class FincalOptions: date_format: str = "%Y-%m-%d" - closest: str = "before" # after + closest: str = "previous" # next traded_days: int = 365 get_closest: str = "exact" diff --git a/tests/test_core.py b/tests/test_core.py index 01bfcec..3b8d0bb 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -386,7 +386,7 @@ class TestTimeSeriesArithmatic: def test_truediv(self): ts = TimeSeriesCore(self.data, "M") - ser = Series([21, 21, 23, 24], "number") + ser = Series([22, 23, 24, 25], "number") num_div_ts = ts / 10 assert num_div_ts["2021-01-01"][1] == 22