wilsonfreitas / python-bizdays

Business days calculations and utilities
http://wilsonfreitas.github.io/python-bizdays/
MIT License
80 stars 34 forks source link

Unusual results using offset method #22

Closed etrajano closed 4 years ago

etrajano commented 7 years ago

I was testing biz days and found a strange. Here follows a little code fragment:

from bizdays import * cal = Calendar.load('files/cal/ANBIMA.cal') # path in my file system - should be changed cal.offset('2016-11-03', -1) cal.offset('2016-11-02', -1)

The first call to offset gives me the expected result: Out[25]: datetime.date(2016, 11, 1)

The second one, however, does not: Out[26]: datetime.date(2016, 10, 31)

I was expecting to get the exact same result (i.e. '2016-11-1').

wilsonfreitas commented 7 years ago

Hi @etrajano, Thanks for reporting your question.

This happens because the date you pass is adjusted if it's not a business day. Business days calculations count jumps between business days, so you have to start on a business day.

The offset function

    def offset(self, dt, n, iso=False):
        dt = self.__adjust_next(dt) if n >= 0 else self.__adjust_previous(dt)
        isoornot = lambda dt: dt if not iso else dt.isoformat()
        return isoornot(self._index.offset(dt, n))

If n is positive then dt is adjusted to its next business day, once you are passing -1, the given date is adjusted to its previous business day, which is '2016-11-01'.

This can be solved if you adjust the date before you call offset.

In [9]: cal.offset(cal.adjust_next("2016-11-02"), -1)
Out[9]: datetime.date(2016, 11, 1)

This can also be set when you call the constructor Calendar, but not on load method. I think that it might be a good thing to have the adjustment options on the load method also.