Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/uprate-cadence-rounding.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Find the latest leap day for annual uprating and use the configured month-end dates. Use exact decimal arithmetic to apply index growth and round cadence amounts to fractional intervals. Show valid rounding formats when an interval is written as a bare integer.
100 changes: 62 additions & 38 deletions policyengine_core/parameters/operations/uprate_parameters.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import sys
from fractions import Fraction

from numpy import ceil, floor
from numpy import ceil, float64, floor

# rrule is purposely imported this way to allow for programmatic
# calling of rrule.YEARLY, rrule.MONTHLY, and rrule.DAILY
Expand Down Expand Up @@ -822,7 +822,12 @@ def project_from_base(
return float(base + whole_intervals * step)


def round_uprated_value(meta: dict, uprated_value: float) -> float:
def round_uprated_value(
meta: dict,
amount: float,
*,
index_values: Optional[tuple[float, float]] = None,
) -> float:
rounding_config = meta["rounding"]
if isinstance(rounding_config, float):
interval = rounding_config
Expand All @@ -834,8 +839,37 @@ def round_uprated_value(meta: dict, uprated_value: float) -> float:
upwards=ceil,
downwards=floor,
)[rounding_config["type"]]
uprated_value = rounding_fn(uprated_value / interval) * interval
return uprated_value
else:
# Keep the exception text for callers that inspect it.
error = UnboundLocalError(
"cannot access local variable 'rounding_fn' where it is not associated with a value"
)
error.add_note("Write the rounding interval as a float or a mapping.")
raise error

if index_values is not None:
index_start, index_end = index_values
if (
isinstance(interval, float)
and interval != 0
and math.isfinite(interval)
and all(
isinstance(value, numbers.Integral) or math.isfinite(value)
for value in (amount, index_start, index_end)
)
):
step = exact_decimal(interval)
ratio = exact_decimal(index_end) / exact_decimal(index_start)
intervals = exact_decimal(amount) * ratio / step
round_intervals = {ceil: math.ceil, floor: math.floor}.get(
rounding_fn, round
)
whole_intervals = round_intervals(intervals)
result_type = type(interval) if rounding_fn is round else float64
return result_type(whole_intervals * step)
amount = (index_end / index_start) * amount

return rounding_fn(amount / interval) * interval


def find_cadence_first(parameter: Parameter, cadence_options: dict) -> datetime:
Expand Down Expand Up @@ -934,22 +968,18 @@ def find_cadence_last(uprater: Parameter, cadence_options: dict) -> datetime:
# Pull of the first (newest) value and parse into datetime object
last_param: datetime = parse(uprater_values[0].instant_str)

# Create an offset to allow us to search for one year, from one year
# minus 1 day before the last uprater param, to the last uprater param;
# this must be 1 year, minus 1 day, because rrule is inclusive of its
# start date. This must also be done as 1 year, then 1 day, because
# leap years are not handled differently when specifying a day-based offset,
# resulting in 25% of offsets being one day short if calculated
# using days only; further, this must be done with relativedelta and not
# datetime's timedelta, which doesn't handle year-based offsets
start_date: datetime = last_param - relativedelta(years=1) + relativedelta(days=1)

# Conditionally determine settings to utilize
# Set the month only if the interval is "year"
month_option = cadence_options["end"].month if interval == "year" else None
# Set the day if interval is "year" or "month", just not "day"
day_option = cadence_options["end"].day if interval != "day" else None

if (month_option, day_option) == (2, 29):
# Leap days can be eight years apart at a century boundary.
start_date = datetime(max(1, last_param.year - 8), 1, 1)
else:
start_date = last_param - relativedelta(years=1) + relativedelta(days=1)

rrule_obj = rrule.rrule(
freq=rrule.YEARLY,
dtstart=start_date,
Expand All @@ -958,18 +988,13 @@ def find_cadence_last(uprater: Parameter, cadence_options: dict) -> datetime:
bymonthday=day_option,
)

# rrule can't look backward, so we generated an entire array of options
# for a year; for monthly and daily intervals, we'll need the last item
# in this array
last_end: datetime = rrule_obj[-1]
last_end = rrule_obj.before(last_param, inc=True)

# Ensure that data exists for the "start" parameter for this "end,"
# otherwise raise error
end_start_diff: relativedelta = relativedelta(
cadence_options["end"], cadence_options["start"]
)
last_start = last_end - end_start_diff
if (uprater(instant(last_start.date()))) is None:
# Check the index at the corresponding start. A forward offset can clip
# the day at month-end, so compute the offset in the lookup direction.
end_to_start = relativedelta(cadence_options["start"], cadence_options["end"])
last_start = last_end + end_to_start if last_end is not None else None
if last_start is None or uprater(instant(last_start.date())) is None:
raise ValueError(
f"Error while uprating using {uprater.name}: no valid start, end pair found; did "
+ "you forget to add earlier values, or is there a long gap between start and end year?"
Expand Down Expand Up @@ -1005,14 +1030,13 @@ def uprate_by_cadence(
# Generate a list of iterations
iterations = rrule.rrule(freq=rrule_interval, dtstart=first_date, until=last_date)

# Determine the offset between the first enactment
# date and the first start and end date
# Use offsets from enactment to the index dates to account for month ends.
uprated_data: list[ParameterAtInstant] = []
enactment_start_offset: relativedelta = relativedelta(
cadence_options["enactment"], cadence_options["start"]
enactment_to_start = relativedelta(
cadence_options["start"], cadence_options["enactment"]
)
enactment_end_offset: relativedelta = relativedelta(
cadence_options["enactment"], cadence_options["end"]
enactment_to_end = relativedelta(
cadence_options["end"], cadence_options["enactment"]
)

# Set a starting reference value to calculate against
Expand All @@ -1021,8 +1045,8 @@ def uprate_by_cadence(
# For each entry (corresponding to an enactment date) in the iteration list...
for enactment_date in iterations:
# Calculate the start and end calculation dates
start_calc_date: datetime = enactment_date - enactment_start_offset
end_calc_date: datetime = enactment_date - enactment_end_offset
start_calc_date: datetime = enactment_date + enactment_to_start
end_calc_date: datetime = enactment_date + enactment_to_end

# Find uprater value at cadence start
start_val = uprating_parameter.get_at_instant(instant(start_calc_date.date()))
Expand All @@ -1036,13 +1060,13 @@ def uprate_by_cadence(
f"Failed to uprate {parameter.name} using {uprating_parameter.name}: uprater missing values at date {start_calc_date.date()}"
)

# Find difference of these values
difference = end_val / start_val

# Uprate value
uprated_value = difference * reference_value
if "rounding" in meta:
uprated_value = round_uprated_value(meta, uprated_value)
uprated_value = round_uprated_value(
meta, reference_value, index_values=(start_val, end_val)
)
else:
uprated_value = (end_val / start_val) * reference_value

# Add uprated value to data list
uprated_data.append(
Expand Down
185 changes: 185 additions & 0 deletions tests/core/parameters/operations/test_uprating.py
Original file line number Diff line number Diff line change
Expand Up @@ -1020,3 +1020,188 @@ def test_parameter_uprating_cadence_minimal_data():
uprated = uprate_parameters(root)

assert round(uprated.to_be_uprated("2023-04-01"), 3) == 1.101


@pytest.mark.parametrize(
"year, later_observation",
[("2004", None), ("2004", "2005-03-01"), ("2096", "2104-02-28")],
)
def test_cadence_uses_latest_leap_day(year, later_observation):
from policyengine_core.parameters import ParameterNode, uprate_parameters

index = {f"{year}-01-01": 100, f"{year}-02-29": 102}
if later_observation:
index[later_observation] = 103
root = ParameterNode(
data={
"amount": {
"values": {f"{year}-02-29": 1},
"metadata": {
"uprating": {
"parameter": "index",
"at_defined_interval": {
"start": f"{year}-01-01",
"end": f"{year}-02-29",
"enactment": f"{year}-03-01",
},
},
},
},
"index": {"values": index},
}
)

amount = uprate_parameters(root).amount

assert [(entry.instant_str, entry.value) for entry in amount.values_list] == [
(f"{year}-03-01", 1.02),
(f"{year}-02-29", 1),
]


@pytest.mark.parametrize(
"start, enactment, earlier_index",
[
pytest.param(
"2004-01-31", "2004-03-01", {"2004-01-31": 100}, id="january-31-start"
),
pytest.param(
"2004-01-01",
"2004-03-31",
{"2004-01-01": 100, "2004-02-27": 101},
id="march-31-enactment",
),
],
)
def test_leap_day_cadence_uses_month_end_dates(start, enactment, earlier_index):
from policyengine_core.parameters import ParameterNode, uprate_parameters

root = ParameterNode(
data={
"amount": {
"values": {"2004-02-29": 1},
"metadata": {
"uprating": {
"parameter": "index",
"at_defined_interval": {
"start": start,
"end": "2004-02-29",
"enactment": enactment,
},
},
},
},
"index": {
"values": {**earlier_index, "2004-02-29": 102, "2005-03-01": 103}
},
}
)

assert uprate_parameters(root).amount(enactment) == 1.02


@pytest.mark.parametrize(
"amount, rounding_type, expected",
[
pytest.param(0.29, "downwards", 0.29, id="aligned-downwards"),
pytest.param(0.7, "downwards", 0.7, id="downwards-bound"),
pytest.param(0.030000000000000002, "upwards", 0.04, id="upwards-bound"),
pytest.param(0.695, "nearest", 0.7, id="nearest-product"),
pytest.param(0.125, "nearest", 0.12, id="half-to-even"),
],
)
def test_flat_index_cadence_rounds_to_exact_cents(amount, rounding_type, expected):
from numpy import float64

from policyengine_core.parameters import ParameterNode, uprate_parameters

root = ParameterNode(
data={
"amount": {
"values": {"2026-07-01": amount},
"metadata": {
"uprating": {
"parameter": "index",
"rounding": {"interval": 0.01, "type": rounding_type},
"at_defined_interval": {
"start": "2026-05-01",
"end": "2027-05-01",
"enactment": "2027-07-01",
},
},
},
},
"index": {"values": {"2026-05-01": 100, "2027-05-01": 100}},
}
)

projected = uprate_parameters(root).amount("2027-07-01")
assert projected == expected
assert type(projected) is (float if rounding_type == "nearest" else float64)


@pytest.mark.parametrize(
"amount, index_end, rounding_type, expected",
[
pytest.param(0.07, 300, "upwards", 0.21, id="upwards-exact-cent"),
pytest.param(0.07, 150, "nearest", 0.10, id="nearest-half-to-even"),
pytest.param(-0.07, 300, "downwards", -0.21, id="downwards-negative-cent"),
pytest.param(0.29, 300, "downwards", 0.87, id="downwards-exact-cent"),
],
)
def test_cadence_rounds_exact_index_projection(
amount, index_end, rounding_type, expected
):
from policyengine_core.parameters import ParameterNode, uprate_parameters

root = ParameterNode(
data={
"amount": {
"values": {"2026-07-01": amount},
"metadata": {
"uprating": {
"parameter": "index",
"rounding": {"interval": 0.01, "type": rounding_type},
"at_defined_interval": {
"start": "2026-05-01",
"end": "2027-05-01",
"enactment": "2027-07-01",
},
},
},
},
"index": {"values": {"2026-05-01": 100, "2027-05-01": index_end}},
}
)

assert uprate_parameters(root).amount("2027-07-01") == expected


@pytest.mark.parametrize(
"rounding",
[
pytest.param(50, id="bare-int"),
pytest.param(50.0, id="bare-float"),
pytest.param({"interval": 50, "type": "nearest"}, id="mapped-int"),
],
)
def test_chained_rounding_interval_forms(rounding):
from policyengine_core.parameters import ParameterNode, uprate_parameters

root = ParameterNode(
data={
"amount": {
"values": {"2026-01-01": 50},
"metadata": {
"uprating": {"parameter": "index", "rounding": rounding},
},
},
"index": {"values": {"2026-01-01": 2, "2027-01-01": 5}},
}
)

if isinstance(rounding, int):
with pytest.raises(UnboundLocalError, match="rounding.*float or a mapping"):
uprate_parameters(root)
else:
assert uprate_parameters(root).amount("2027-01-01") == 100