From fb479fcd7a477959157bdeb9543f11c8b9e8870c Mon Sep 17 00:00:00 2001 From: xengineering Date: Sun, 8 Sep 2024 10:02:58 +0200 Subject: Implement finance.flow.simulate() --- finance/flow.py | 22 ++++++++++++++++++++++ finance/test_flow.py | 28 ++++++++++++++++++++++++++-- 2 files changed, 48 insertions(+), 2 deletions(-) diff --git a/finance/flow.py b/finance/flow.py index 9ea72c8..836c137 100644 --- a/finance/flow.py +++ b/finance/flow.py @@ -42,3 +42,25 @@ def monthly_candidates(start: datetime) -> Generator[datetime, None, None]: current = datetime(current.year + 1, 1, 1) else: current = datetime(current.year, current.month + 1, 1) + + +def simulate( + start: datetime, end: datetime, flows: tuple[Flow] +) -> tuple[list[datetime], list[Decimal]]: + dates: list[datetime] = [] + values: list[Decimal] = [] + + for candidate in monthly_candidates(start): + if start <= candidate <= end: + dates.append(candidate) + + if candidate > end: + break + + for date in dates: + value = Decimal(0.0) + for flow in flows: + value += flow.integrate(start, date) + values.append(value) + + return (dates, values) diff --git a/finance/test_flow.py b/finance/test_flow.py index 497c8d7..db1b695 100644 --- a/finance/test_flow.py +++ b/finance/test_flow.py @@ -1,11 +1,11 @@ from datetime import datetime from decimal import Decimal -from finance import flow +from finance.flow import Flow, simulate def test_flow_integration() -> None: - fl = flow.Flow( + fl = Flow( amount=Decimal(3000.0), since=datetime(2023, 1, 1), until=datetime(2026, 1, 5), @@ -26,3 +26,27 @@ def test_flow_integration() -> None: for test in tests: assert fl.integrate(start=test[0], end=test[1]) == test[2] + + +def test_simulate() -> None: + flows = (Flow(amount=Decimal(100.0), since=None, until=None),) + + dates, values = simulate( + start=datetime(2024, 1, 1), + end=datetime(2024, 4, 1), + flows=flows, + ) + + assert dates == [ + datetime(2024, 1, 1), + datetime(2024, 2, 1), + datetime(2024, 3, 1), + datetime(2024, 4, 1), + ] + + assert values == [ + Decimal(100.0), + Decimal(200.0), + Decimal(300.0), + Decimal(400.0), + ] -- cgit v1.2.3-70-g09d2