From 4f3d4de3796744ee1d6d0e91e8bec76e0487de90 Mon Sep 17 00:00:00 2001 From: xengineering Date: Tue, 3 Sep 2024 21:34:08 +0200 Subject: finance: Use datetime for Income.integrate() Time-based Integration in general is done between two time stamps. For the financial context it makes sense to use Python's datetime.datetime class for this purpose. This commit implements integrating an income between two datetime.datetime time stamps. --- finance/income.py | 26 ++++++++++++++++++++++++-- finance/test_income.py | 13 ++++++++++++- 2 files changed, 36 insertions(+), 3 deletions(-) diff --git a/finance/income.py b/finance/income.py index 12d5d4e..94759ff 100644 --- a/finance/income.py +++ b/finance/income.py @@ -1,10 +1,32 @@ import dataclasses +from datetime import datetime @dataclasses.dataclass(kw_only=True, frozen=True) class Income: + """Income models financial income paid on the first day of a month""" amount: float - def integrate(self, delta_t: int) -> float: - return delta_t * self.amount + def integrate(self, start: datetime, end: datetime) -> float: + """Integrate the income from a start to an end date""" + + retval = 0.0 + + current = datetime(start.year, start.month, 1) + + if start == current: + retval += self.amount + + while True: + if current.month == 12: + current = datetime(current.year + 1, 1, 1) + else: + current = datetime(current.year, current.month + 1, 1) + + if current <= end: + retval += self.amount + else: + break + + return retval diff --git a/finance/test_income.py b/finance/test_income.py index 21d42f7..0ce3507 100644 --- a/finance/test_income.py +++ b/finance/test_income.py @@ -1,6 +1,17 @@ +from datetime import datetime + from finance import income def test_income_integration() -> None: inc = income.Income(amount=3000.0) - assert inc.integrate(5) == 15000.0 + + tests = ( + (datetime(2024, 3, 12), datetime(2024, 4, 2), 3000.0), + (datetime(2024, 3, 1), datetime(2024, 3, 15), 3000.0), + (datetime(2024, 2, 25), datetime(2024, 3, 1), 3000.0), + (datetime(2024, 2, 25), datetime(2024, 6, 12), 12000.0), + ) + + for test in tests: + assert inc.integrate(start=test[0], end=test[1]) == test[2] -- cgit v1.2.3-70-g09d2