"""Business-day arithmetic with a holiday list.""" from __future__ import annotations import datetime as dt from typing import FrozenSet, Iterable, Set def fixed_holidays(year: int) -> Set[dt.date]: """Fixed-date public holidays: New Year, Labour Day, Christmas and Boxing Day.""" return {dt.date(year, 1, 1), dt.date(year, 5, 1), dt.date(year, 12, 25), dt.date(year, 12, 26)} class BusinessCalendar: """Knows which days are business days: not a weekend day and not a holiday.""" def __init__(self, holidays: Iterable[dt.date] = (), weekend: Iterable[int] = (5, 6)) -> None: self.holidays: FrozenSet[dt.date] = frozenset(holidays) self.weekend: FrozenSet[int] = frozenset(weekend) @classmethod def for_years(cls, years: Iterable[int]) -> "BusinessCalendar": holidays: Set[dt.date] = set() for year in years: holidays |= fixed_holidays(year) return cls(holidays) def is_business_day(self, d: dt.date) -> bool: return d.weekday() not in self.weekend and d not in self.holidays def next_business_day(self, d: dt.date) -> dt.date: """``d`` itself if it is a business day, otherwise the next one.""" while not self.is_business_day(d): d += dt.timedelta(days=1) return d def previous_business_day(self, d: dt.date) -> dt.date: """``d`` itself if it is a business day, otherwise the previous one.""" while not self.is_business_day(d): d -= dt.timedelta(days=1) return d def add_business_days(self, d: dt.date, n: int) -> dt.date: """Move ``n`` business days forward (backward for negative ``n``). Each step goes to the next business day strictly after (before) the current date, so starting on a weekend or holiday is fine: Saturday plus one business day is Monday. ``n == 0`` returns ``d`` unchanged. """ step = dt.timedelta(days=1 if n >= 0 else -1) current = d remaining = abs(n) while remaining: current += step if self.is_business_day(current): remaining -= 1 return current def business_days_between(self, start: dt.date, end: dt.date) -> int: """Number of business days after ``start`` up to and including ``end`` (negative if ``end`` is earlier).""" if end < start: return -self.business_days_between(end, start) count = 0 current = start while current < end: current += dt.timedelta(days=1) if self.is_business_day(current): count += 1 return count def business_days_in_month(self, year: int, month: int) -> int: count = 0 current = dt.date(year, month, 1) while current.month == month: if self.is_business_day(current): count += 1 current += dt.timedelta(days=1) return count