date_parser decorator now only needs positions

Implemented using inspector.signature
This commit is contained in:
Gourav Kumar 2022-02-27 19:26:03 +05:30
parent eeda4064b2
commit 347634f536
2 changed files with 13 additions and 8 deletions

View File

@ -1,4 +1,5 @@
import datetime import datetime
import inspect
from collections import UserDict, UserList from collections import UserDict, UserList
from dataclasses import dataclass from dataclasses import dataclass
from numbers import Number from numbers import Number
@ -16,23 +17,27 @@ class Frequency:
symbol: str symbol: str
def date_parser(pos, params): def date_parser(pos):
def parse_dates(func): def parse_dates(func):
def wrapper_func(*args, **kwargs): def wrapper_func(*args, **kwargs):
date_format = kwargs.get("date_format", None) date_format = kwargs.get("date_format", None)
args = list(args) args = list(args)
for i, j in enumerate(params): sig = inspect.signature(func)
date = kwargs.get(j, None) params = [i[0] for i in sig.parameters.items()]
# print(params)
for j in pos:
kwarg = params[j]
date = kwargs.get(kwarg, None)
in_args = False in_args = False
if date is None: if date is None:
date = args[pos[i]] date = args[j]
in_args = True in_args = True
parsed_date = _parse_date(date, date_format) parsed_date = _parse_date(date, date_format)
if not in_args: if not in_args:
kwargs[j] = parsed_date kwargs[kwarg] = parsed_date
else: else:
args[pos[i]] = parsed_date args[j] = parsed_date
return func(*args, **kwargs) return func(*args, **kwargs)
return wrapper_func return wrapper_func

View File

@ -184,7 +184,7 @@ class TimeSeries(TimeSeriesCore):
return self.__class__(new_ts, frequency=self.frequency.symbol) return self.__class__(new_ts, frequency=self.frequency.symbol)
@date_parser(pos=[1], params=['as_on']) @date_parser(pos=[1])
def calculate_returns( def calculate_returns(
self, self,
as_on: Union[str, datetime.datetime], as_on: Union[str, datetime.datetime],
@ -277,7 +277,7 @@ class TimeSeries(TimeSeriesCore):
returns = returns ** (1 / years) returns = returns ** (1 / years)
return (current[0] if return_actual_date else as_on), returns - 1 return (current[0] if return_actual_date else as_on), returns - 1
@date_parser(pos=[1, 2], params=['from_date', 'to_date']) @date_parser(pos=[1, 2])
def calculate_rolling_returns( def calculate_rolling_returns(
self, self,
from_date: Union[datetime.date, str], from_date: Union[datetime.date, str],