2022-02-19 17:33:41 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2022-02-16 17:47:50 +00:00
|
|
|
import datetime
|
2022-02-24 05:58:37 +00:00
|
|
|
from typing import List, Literal, Union
|
2022-02-17 10:50:48 +00:00
|
|
|
|
|
|
|
from dateutil.relativedelta import relativedelta
|
2022-02-16 17:47:50 +00:00
|
|
|
|
2022-02-26 07:16:42 +00:00
|
|
|
from .core import AllFrequencies, TimeSeriesCore
|
|
|
|
from .utils import (
|
2022-02-25 19:14:45 +00:00
|
|
|
_find_closest_date,
|
2022-02-24 05:58:37 +00:00
|
|
|
_interval_to_years,
|
|
|
|
_parse_date,
|
|
|
|
_preprocess_match_options,
|
|
|
|
)
|
2022-02-17 16:57:22 +00:00
|
|
|
|
|
|
|
|
|
|
|
def create_date_series(
|
2022-02-20 10:37:50 +00:00
|
|
|
start_date: datetime.datetime, end_date: datetime.datetime, frequency: str, eomonth: bool = False
|
2022-02-17 16:57:22 +00:00
|
|
|
) -> List[datetime.datetime]:
|
|
|
|
"""Creates a date series using a frequency"""
|
|
|
|
|
2022-02-20 10:37:50 +00:00
|
|
|
frequency = getattr(AllFrequencies, frequency)
|
2022-02-19 17:33:41 +00:00
|
|
|
if eomonth and frequency.days < AllFrequencies.M.days:
|
|
|
|
raise ValueError(f"eomonth cannot be set to True if frequency is higher than {AllFrequencies.M.name}")
|
|
|
|
|
2022-02-22 07:34:44 +00:00
|
|
|
start_date = _parse_date(start_date)
|
|
|
|
end_date = _parse_date(end_date)
|
2022-02-19 17:33:41 +00:00
|
|
|
datediff = (end_date - start_date).days / frequency.days + 1
|
2022-02-17 16:57:22 +00:00
|
|
|
dates = []
|
|
|
|
|
|
|
|
for i in range(0, int(datediff)):
|
2022-02-19 17:33:41 +00:00
|
|
|
diff = {frequency.freq_type: frequency.value * i}
|
|
|
|
date = start_date + relativedelta(**diff)
|
|
|
|
if eomonth:
|
|
|
|
if date.month == 12:
|
|
|
|
date = date.replace(day=31)
|
2022-02-18 15:47:04 +00:00
|
|
|
else:
|
2022-02-19 17:33:41 +00:00
|
|
|
date = date.replace(day=1).replace(month=date.month+1) - relativedelta(days=1)
|
2022-02-20 10:37:50 +00:00
|
|
|
if date <= end_date:
|
|
|
|
dates.append(date)
|
2022-02-19 07:53:15 +00:00
|
|
|
|
2022-02-19 17:33:41 +00:00
|
|
|
return dates
|
2022-02-19 07:53:15 +00:00
|
|
|
|
|
|
|
|
|
|
|
class TimeSeries(TimeSeriesCore):
|
|
|
|
"""Container for TimeSeries objects"""
|
|
|
|
|
2022-02-17 10:50:48 +00:00
|
|
|
def info(self):
|
|
|
|
"""Summary info about the TimeSeries object"""
|
|
|
|
|
2022-02-21 16:57:48 +00:00
|
|
|
total_dates = len(self.data.keys())
|
2022-02-17 10:50:48 +00:00
|
|
|
res_string = "First date: {}\nLast date: {}\nNumber of rows: {}"
|
|
|
|
return res_string.format(self.start_date, self.end_date, total_dates)
|
|
|
|
|
2022-02-19 17:33:41 +00:00
|
|
|
def ffill(self, inplace: bool = False, limit: int = None) -> Union[TimeSeries, None]:
|
|
|
|
"""Forward fill missing dates in the time series
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
|
|
|
inplace : bool
|
|
|
|
Modify the time-series data in place and return None.
|
|
|
|
|
|
|
|
limit : int, optional
|
|
|
|
Maximum number of periods to forward fill
|
|
|
|
|
|
|
|
Returns
|
|
|
|
-------
|
|
|
|
Returns a TimeSeries object if inplace is False, otherwise None
|
|
|
|
"""
|
|
|
|
|
|
|
|
eomonth = True if self.frequency.days >= AllFrequencies.M.days else False
|
2022-02-20 10:37:50 +00:00
|
|
|
dates_to_fill = create_date_series(self.start_date, self.end_date, self.frequency.symbol, eomonth)
|
2022-02-17 10:50:48 +00:00
|
|
|
|
|
|
|
new_ts = dict()
|
2022-02-19 17:33:41 +00:00
|
|
|
for cur_date in dates_to_fill:
|
2022-02-17 10:50:48 +00:00
|
|
|
try:
|
2022-02-21 16:57:48 +00:00
|
|
|
cur_val = self.data[cur_date]
|
2022-02-17 10:50:48 +00:00
|
|
|
except KeyError:
|
|
|
|
pass
|
2022-02-18 15:47:04 +00:00
|
|
|
new_ts.update({cur_date: cur_val})
|
2022-02-17 10:50:48 +00:00
|
|
|
|
|
|
|
if inplace:
|
2022-02-21 16:57:48 +00:00
|
|
|
self.data = new_ts
|
2022-02-17 10:50:48 +00:00
|
|
|
return None
|
|
|
|
|
2022-02-21 17:18:24 +00:00
|
|
|
return self.__class__(new_ts, frequency=self.frequency.symbol)
|
2022-02-17 10:50:48 +00:00
|
|
|
|
2022-02-20 12:49:34 +00:00
|
|
|
def bfill(self, inplace: bool = False, limit: int = None) -> Union[TimeSeries, None]:
|
|
|
|
"""Backward fill missing dates in the time series
|
2022-02-17 10:50:48 +00:00
|
|
|
|
2022-02-20 12:49:34 +00:00
|
|
|
Parameters
|
|
|
|
----------
|
|
|
|
inplace : bool
|
|
|
|
Modify the time-series data in place and return None.
|
|
|
|
|
|
|
|
limit : int, optional
|
|
|
|
Maximum number of periods to back fill
|
|
|
|
|
|
|
|
Returns
|
|
|
|
-------
|
|
|
|
Returns a TimeSeries object if inplace is False, otherwise None
|
|
|
|
"""
|
|
|
|
|
|
|
|
eomonth = True if self.frequency.days >= AllFrequencies.M.days else False
|
|
|
|
dates_to_fill = create_date_series(self.start_date, self.end_date, self.frequency.symbol, eomonth)
|
|
|
|
dates_to_fill.append(self.end_date)
|
|
|
|
|
|
|
|
bfill_ts = dict()
|
|
|
|
for cur_date in reversed(dates_to_fill):
|
2022-02-17 10:50:48 +00:00
|
|
|
try:
|
2022-02-21 16:57:48 +00:00
|
|
|
cur_val = self.data[cur_date]
|
2022-02-17 10:50:48 +00:00
|
|
|
except KeyError:
|
|
|
|
pass
|
2022-02-20 12:49:34 +00:00
|
|
|
bfill_ts.update({cur_date: cur_val})
|
|
|
|
new_ts = {k: bfill_ts[k] for k in reversed(bfill_ts)}
|
2022-02-17 10:50:48 +00:00
|
|
|
if inplace:
|
2022-02-21 16:57:48 +00:00
|
|
|
self.data = new_ts
|
2022-02-17 10:50:48 +00:00
|
|
|
return None
|
|
|
|
|
2022-02-21 17:18:24 +00:00
|
|
|
return self.__class__(new_ts, frequency=self.frequency.symbol)
|
2022-02-16 17:47:50 +00:00
|
|
|
|
|
|
|
def calculate_returns(
|
2022-02-19 07:53:15 +00:00
|
|
|
self,
|
2022-02-21 07:41:19 +00:00
|
|
|
as_on: Union[str, datetime.datetime],
|
2022-02-25 05:08:20 +00:00
|
|
|
return_actual_date: bool = True,
|
2022-02-19 17:33:41 +00:00
|
|
|
as_on_match: str = "closest",
|
|
|
|
prior_match: str = "closest",
|
2022-02-26 15:12:27 +00:00
|
|
|
closest: Literal["previous", "next", "exact"] = 'previous',
|
2022-02-25 05:08:20 +00:00
|
|
|
if_not_found: Literal['fail', 'nan'] = 'fail',
|
2022-02-19 07:53:15 +00:00
|
|
|
compounding: bool = True,
|
2022-02-24 05:58:37 +00:00
|
|
|
interval_type: Literal['years', 'months', 'days'] = 'years',
|
|
|
|
interval_value: int = 1,
|
2022-02-21 07:41:19 +00:00
|
|
|
date_format: str = None
|
2022-02-18 15:47:04 +00:00
|
|
|
) -> float:
|
2022-02-16 17:47:50 +00:00
|
|
|
"""Method to calculate returns for a certain time-period as on a particular date
|
2022-02-19 07:53:15 +00:00
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
|
|
|
as_on : datetime.datetime
|
|
|
|
The date as on which the return is to be calculated.
|
|
|
|
|
2022-02-25 05:08:20 +00:00
|
|
|
return_actual_date : bool, default True
|
|
|
|
If true, the output will contain the actual date based on which the return was calculated.
|
|
|
|
Set to False to return the date passed in the as_on argument.
|
|
|
|
|
2022-02-19 07:53:15 +00:00
|
|
|
as_on_match : str, optional
|
|
|
|
The mode of matching the as_on_date. Refer closest.
|
|
|
|
|
|
|
|
prior_match : str, optional
|
|
|
|
The mode of matching the prior_date. Refer closest.
|
|
|
|
|
|
|
|
closest : str, optional
|
|
|
|
The mode of matching the closest date.
|
|
|
|
Valid values are 'exact', 'previous', 'next' and next.
|
|
|
|
|
2022-02-25 05:08:20 +00:00
|
|
|
if_not_found : 'fail' | 'nan'
|
|
|
|
What to do when required date is not found:
|
|
|
|
* fail: Raise a ValueError
|
|
|
|
* nan: Return nan as the value
|
|
|
|
|
2022-02-19 07:53:15 +00:00
|
|
|
compounding : bool, optional
|
|
|
|
Whether the return should be compounded annually.
|
|
|
|
|
2022-02-25 05:08:20 +00:00
|
|
|
interval_type : 'years', 'months', 'days'
|
|
|
|
The type of time period to use for return calculation.
|
|
|
|
|
|
|
|
interval_value : int
|
|
|
|
The value of the specified interval type over which returns needs to be calculated.
|
|
|
|
|
|
|
|
date_format: str
|
|
|
|
The date format to use for this operation.
|
|
|
|
Should be passed as a datetime library compatible string.
|
|
|
|
Sets the date format only for this operation. To set it globally, use FincalOptions.date_format
|
2022-02-19 07:53:15 +00:00
|
|
|
|
|
|
|
Returns
|
|
|
|
-------
|
2022-02-25 05:08:20 +00:00
|
|
|
A tuple containing the date and float value of the returns.
|
2022-02-19 07:53:15 +00:00
|
|
|
|
|
|
|
Raises
|
|
|
|
------
|
|
|
|
ValueError
|
|
|
|
* If match mode for any of the dates is exact and the exact match is not found
|
|
|
|
* If the arguments passsed for closest, as_on_match, and prior_match are invalid
|
|
|
|
|
|
|
|
Example
|
|
|
|
--------
|
2022-02-17 10:50:48 +00:00
|
|
|
>>> calculate_returns(datetime.date(2020, 1, 1), years=1)
|
2022-02-16 17:47:50 +00:00
|
|
|
"""
|
|
|
|
|
2022-02-21 07:41:19 +00:00
|
|
|
as_on = _parse_date(as_on, date_format)
|
2022-02-19 07:53:15 +00:00
|
|
|
as_on_delta, prior_delta = _preprocess_match_options(as_on_match, prior_match, closest)
|
2022-02-17 10:50:48 +00:00
|
|
|
|
2022-02-24 05:58:37 +00:00
|
|
|
prev_date = as_on - relativedelta(**{interval_type: interval_value})
|
2022-02-25 19:14:45 +00:00
|
|
|
current = _find_closest_date(self.data, as_on, as_on_delta, if_not_found)
|
|
|
|
previous = _find_closest_date(self.data, prev_date, prior_delta, if_not_found)
|
|
|
|
|
|
|
|
if current[1] == str('nan') or previous[1] == str('nan'):
|
|
|
|
return as_on, float('NaN')
|
|
|
|
|
|
|
|
returns = current[1] / previous[1]
|
2022-02-16 17:47:50 +00:00
|
|
|
if compounding:
|
2022-02-24 05:58:37 +00:00
|
|
|
years = _interval_to_years(interval_type, interval_value)
|
2022-02-17 10:50:48 +00:00
|
|
|
returns = returns ** (1 / years)
|
2022-02-25 19:14:45 +00:00
|
|
|
return (current[0] if return_actual_date else as_on), returns - 1
|
2022-02-16 17:47:50 +00:00
|
|
|
|
|
|
|
def calculate_rolling_returns(
|
|
|
|
self,
|
2022-02-21 07:41:19 +00:00
|
|
|
from_date: Union[datetime.date, str],
|
|
|
|
to_date: Union[datetime.date, str],
|
|
|
|
frequency: str = None,
|
2022-02-19 17:33:41 +00:00
|
|
|
as_on_match: str = "closest",
|
|
|
|
prior_match: str = "closest",
|
2022-02-17 10:50:48 +00:00
|
|
|
closest: str = "previous",
|
2022-02-25 05:08:20 +00:00
|
|
|
if_not_found: Literal['fail', 'nan'] = 'fail',
|
2022-02-16 17:47:50 +00:00
|
|
|
compounding: bool = True,
|
2022-02-24 17:08:53 +00:00
|
|
|
interval_type: Literal['years', 'months', 'days'] = 'years',
|
|
|
|
interval_value: int = 1,
|
2022-02-21 07:41:19 +00:00
|
|
|
date_format: str = None
|
2022-02-16 17:47:50 +00:00
|
|
|
) -> List[tuple]:
|
|
|
|
"""Calculates the rolling return"""
|
|
|
|
|
2022-02-21 07:41:19 +00:00
|
|
|
from_date = _parse_date(from_date, date_format)
|
|
|
|
to_date = _parse_date(to_date, date_format)
|
|
|
|
|
|
|
|
if frequency is None:
|
|
|
|
frequency = self.frequency
|
|
|
|
else:
|
|
|
|
try:
|
|
|
|
frequency = getattr(AllFrequencies, frequency)
|
|
|
|
except AttributeError:
|
|
|
|
raise ValueError(f"Invalid argument for frequency {frequency}")
|
2022-02-20 03:49:43 +00:00
|
|
|
|
2022-02-21 02:57:01 +00:00
|
|
|
dates = create_date_series(from_date, to_date, frequency.symbol)
|
2022-02-19 07:53:15 +00:00
|
|
|
if frequency == AllFrequencies.D:
|
2022-02-21 16:57:48 +00:00
|
|
|
dates = [i for i in dates if i in self.data]
|
2022-02-16 17:47:50 +00:00
|
|
|
|
|
|
|
rolling_returns = []
|
|
|
|
for i in dates:
|
2022-02-19 17:33:41 +00:00
|
|
|
returns = self.calculate_returns(
|
|
|
|
as_on=i,
|
|
|
|
compounding=compounding,
|
2022-02-24 17:08:53 +00:00
|
|
|
interval_type=interval_type,
|
|
|
|
interval_value=interval_value,
|
2022-02-19 17:33:41 +00:00
|
|
|
as_on_match=as_on_match,
|
|
|
|
prior_match=prior_match,
|
|
|
|
closest=closest,
|
2022-02-25 05:08:20 +00:00
|
|
|
if_not_found=if_not_found
|
2022-02-19 17:33:41 +00:00
|
|
|
)
|
2022-02-25 05:08:20 +00:00
|
|
|
rolling_returns.append(returns)
|
2022-02-20 03:49:43 +00:00
|
|
|
rolling_returns.sort()
|
2022-02-21 17:38:13 +00:00
|
|
|
return self.__class__(rolling_returns, self.frequency.symbol)
|
2022-02-17 16:57:22 +00:00
|
|
|
|
|
|
|
|
2022-02-19 17:33:41 +00:00
|
|
|
if __name__ == "__main__":
|
2022-02-17 16:57:22 +00:00
|
|
|
date_series = [
|
2022-02-25 19:14:45 +00:00
|
|
|
datetime.datetime(2020, 1, 11),
|
2022-02-17 16:57:22 +00:00
|
|
|
datetime.datetime(2020, 1, 12),
|
2022-02-25 19:14:45 +00:00
|
|
|
datetime.datetime(2020, 1, 13),
|
|
|
|
datetime.datetime(2020, 1, 14),
|
|
|
|
datetime.datetime(2020, 1, 17),
|
|
|
|
datetime.datetime(2020, 1, 18),
|
|
|
|
datetime.datetime(2020, 1, 19),
|
|
|
|
datetime.datetime(2020, 1, 20),
|
|
|
|
datetime.datetime(2020, 1, 22),
|
2022-02-17 16:57:22 +00:00
|
|
|
]
|