diff options
Diffstat (limited to 'python')
| -rw-r--r-- | python/dates.py | 39 |
1 files changed, 39 insertions, 0 deletions
diff --git a/python/dates.py b/python/dates.py new file mode 100644 index 00000000..2a946889 --- /dev/null +++ b/python/dates.py @@ -0,0 +1,39 @@ +import pandas as pd +from pandas.tseries.offsets import CustomBusinessDay, Day +from pandas.tseries.holiday import get_calendar, HolidayCalendarFactory, GoodFriday +import unittest + +fed_cal = get_calendar('USFederalHolidayCalendar') +bond_cal = HolidayCalendarFactory('BondCalendar', fed_cal, GoodFriday) +bus_day = CustomBusinessDay(calendar=bond_cal()) + +def prev_immdate(valdate): + dates = [pd.datetime(valdate.year-1, 12, 20)] + \ + [pd.datetime(valdate.year, m, 20) for m in [3, 6, 9, 12]] + dates = [bus_day.rollforward(d) for d in dates] + for i, d in enumerate(dates[1:], 1): + if d >= valdate: + break + else: + return dates[-1] + return d if d==valdate else dates[i-1] + +def days_accrued(tradedate): + start_protection = pd.Timestamp(tradedate) + Day() + delta = start_protection-prev_immdate(start_protection) + return delta.days + +class TestDaysAccrued(unittest.TestCase): + def test(self): + dates = [('2015-01-07', 17), + ('2015-06-19', 92), + ('2015-03-19', 0), + ('2015-06-20', 93), + ('2015-06-21', 0), + ('2015-12-21', 1), + ('2015-12-28', 8)] + for date, days in dates: + self.assertEqual(days_accrued(date), days) + +if __name__=="__main__": + unittest.main() |
