From 452c5548bcfd6196bc00b8d7d76eb24c32ad416a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Tue, 1 Dec 2026 18:36:23 +0000 Subject: [PATCH 1/2] Add a UK budgetary impact from the government's accounts pe.uk.calculate_budgetary_impact and pe.uk.BudgetaryImpact give the change in gov_tax, which counts employer National Insurance, less the change in gov_spending. configure_budgetary_impact_variables adds both accounts to the simulations' outputs before they run. The UK economic_impact_analysis calls neither, because it also runs on stored outputs without those columns. Co-Authored-By: Claude Opus 5.5 --- changelog.d/779.added.md | 1 + docs/impact-analysis.md | 13 ++ .../tax_benefit_models/uk/__init__.py | 8 +- .../tax_benefit_models/uk/analysis.py | 111 +++++++++++- tests/test_uk_budgetary_impact.py | 168 ++++++++++++++++++ 5 files changed, 299 insertions(+), 2 deletions(-) create mode 100644 changelog.d/779.added.md create mode 100644 tests/test_uk_budgetary_impact.py diff --git a/changelog.d/779.added.md b/changelog.d/779.added.md new file mode 100644 index 000000000..37f18e83c --- /dev/null +++ b/changelog.d/779.added.md @@ -0,0 +1 @@ +`pe.uk.calculate_budgetary_impact` and `pe.uk.BudgetaryImpact` give a UK reform's budgetary impact from the government's accounts: the change in `gov_tax`, which counts employer National Insurance, less the change in `gov_spending`. `configure_budgetary_impact_variables` in `policyengine.tax_benefit_models.uk.analysis` adds both accounts to the simulations' outputs before they run, as the US function does. The UK `economic_impact_analysis` is unchanged. diff --git a/docs/impact-analysis.md b/docs/impact-analysis.md index 9db77ac42..00ee9143e 100644 --- a/docs/impact-analysis.md +++ b/docs/impact-analysis.md @@ -35,6 +35,7 @@ A `PolicyReformAnalysis` with: | `wealth_decile_impacts` | `OutputCollection[DecileImpact]` | UK only: household net income impacts grouped by `household_wealth_decile` | | `intra_wealth_decile_impacts` | `OutputCollection[IntraDecileImpact]` | UK only: within-wealth-decile distribution of household net income changes | | `program_statistics` | `OutputCollection[ProgramStatistics]` | Totals, counts, winners/losers per program | +| `budgetary_impact` | `BudgetaryImpact` | US only: the reform's budgetary impact as `federal`, `state`, `unattributed` and their `total`, positive when the government is better off | | `baseline_poverty` | `OutputCollection[Poverty]` | Baseline rates by measure and demographic group | | `reform_poverty` | `OutputCollection[Poverty]` | Reform rates, same schema as baseline | | `baseline_inequality` | `Inequality` | Gini plus top / bottom income shares (baseline) | @@ -56,6 +57,18 @@ if hasattr(analysis, "wealth_decile_impacts"): analysis.reform_inequality.gini - analysis.baseline_inequality.gini ``` +For a UK reform's budgetary impact, call `pe.uk.calculate_budgetary_impact`. It returns the changes in the government's tax revenue (`gov_tax`, employer National Insurance included) and spending (`gov_spending`), and their difference, `total`, positive when the government is better off. Neither account is a default UK output, so add both to the simulations before they run: + +```python +from policyengine.tax_benefit_models.uk.analysis import ( + configure_budgetary_impact_variables, +) + +configure_budgetary_impact_variables(baseline, reformed) +budget = pe.uk.calculate_budgetary_impact(baseline, reformed) +budget.total +``` + ## When to call it - Producing a reform brief covering multiple metrics diff --git a/src/policyengine/tax_benefit_models/uk/__init__.py b/src/policyengine/tax_benefit_models/uk/__init__.py index 338d1805f..5405509c5 100644 --- a/src/policyengine/tax_benefit_models/uk/__init__.py +++ b/src/policyengine/tax_benefit_models/uk/__init__.py @@ -17,7 +17,11 @@ from policyengine.core import Dataset from policyengine.outputs import LaborSupplyResponse, ProgramStatistics - from .analysis import economic_impact_analysis + from .analysis import ( + BudgetaryImpact, + calculate_budgetary_impact, + economic_impact_analysis, + ) from .datasets import ( PolicyEngineUKDataset, UKYearData, @@ -56,6 +60,8 @@ "uk_latest", "calculate_household", "economic_impact_analysis", + "calculate_budgetary_impact", + "BudgetaryImpact", "ProgramStatistics", "LaborSupplyResponse", ] diff --git a/src/policyengine/tax_benefit_models/uk/analysis.py b/src/policyengine/tax_benefit_models/uk/analysis.py index 7460565b0..19df1abec 100644 --- a/src/policyengine/tax_benefit_models/uk/analysis.py +++ b/src/policyengine/tax_benefit_models/uk/analysis.py @@ -6,7 +6,7 @@ from __future__ import annotations -from pydantic import BaseModel +from pydantic import BaseModel, Field, computed_field from policyengine.core import OutputCollection, Simulation from policyengine.outputs import ( @@ -20,10 +20,15 @@ configure_labor_supply_response_variables, validate_program_statistics_config, ) +from policyengine.outputs.change_aggregate import ( + ChangeAggregate, + ChangeAggregateType, +) from policyengine.outputs.decile_impact import ( DecileImpact, calculate_decile_impacts, ) +from policyengine.outputs.extra_variables import add_extra_variables from policyengine.outputs.inequality import ( Inequality, calculate_uk_inequality, @@ -61,6 +66,110 @@ "state_pension": {"is_tax": False}, } +# The UK model's government accounts, which the budgetary impact totals: +# ``gov_tax`` (every tax the government raises in respect of a household, +# employer National Insurance included) and ``gov_spending`` (every benefit +# and other programme it pays for). Their difference is ``gov_balance``. +BUDGETARY_IMPACT_VARIABLES: tuple[str, str] = ("gov_tax", "gov_spending") + +# Neither account is in the default UK output, so both are materialized +# before the reform simulations run. +_BUDGETARY_IMPACT_EXTRA_VARIABLES: dict[str, list[str]] = { + "household": list(BUDGETARY_IMPACT_VARIABLES), +} + + +class BudgetaryImpact(BaseModel): + """A UK reform's budgetary impact: the change in the government's balance. + + Sign convention: ``total`` is positive when the government is better off + (more tax revenue or less spending) and negative when the reform costs it + money. ``tax_revenue`` and ``spending`` are the reform-minus-baseline + changes in the government's tax revenue and spending, so more spending is + a positive ``spending``. See :func:`calculate_budgetary_impact`. + """ + + tax_revenue: float = Field( + ..., + description=( + "Change in government tax revenue (gov_tax), GBP, employer " + "National Insurance included." + ), + ) + spending: float = Field( + ..., + description=( + "Change in government spending (gov_spending), GBP; positive " + "means more spending." + ), + ) + + @computed_field # type: ignore[prop-decorator] + @property + def total(self) -> float: + """Budgetary impact, GBP: tax revenue change minus spending change.""" + return self.tax_revenue - self.spending + + +def _sum_change( + baseline_simulation: Simulation, + reform_simulation: Simulation, + variable: str, +) -> float: + """Reform minus baseline total for a variable.""" + agg = ChangeAggregate( + baseline_simulation=baseline_simulation, + reform_simulation=reform_simulation, + variable=variable, + aggregate_type=ChangeAggregateType.SUM, + ) + agg.run() + return float(agg.result) + + +def configure_budgetary_impact_variables( + baseline_simulation: Simulation, + reform_simulation: Simulation, +) -> None: + """Materialize ``gov_tax`` and ``gov_spending`` in the reform outputs. + + Neither is in the default UK output, so both are added as extra output + variables before the simulations run. Call this before + :meth:`Simulation.ensure` so they are present when + :func:`calculate_budgetary_impact` reads them. + """ + add_extra_variables(baseline_simulation, _BUDGETARY_IMPACT_EXTRA_VARIABLES) + add_extra_variables(reform_simulation, _BUDGETARY_IMPACT_EXTRA_VARIABLES) + + +def calculate_budgetary_impact( + baseline_simulation: Simulation, + reform_simulation: Simulation, +) -> BudgetaryImpact: + """Return a UK reform's budgetary impact from the government's accounts. + + ``tax_revenue`` is the reform-minus-baseline weighted total of + ``gov_tax`` and ``spending`` that of ``gov_spending``; ``total`` is their + difference, the change in ``gov_balance``. + + The totals are the government's, not the household totals + ``household_tax`` and ``household_benefits``: ``household_tax`` leaves out + employer National Insurance, which employers pay. Under policyengine-uk's + default incidence an employer NI change moves employees' pay, so a total + of household taxes would count the income tax and NI on that pay change + but not the employer NI receipts behind it. + + ``gov_tax`` and ``gov_spending`` are not in the default UK output: call + :func:`configure_budgetary_impact_variables` before the simulations run. + :func:`economic_impact_analysis` calls neither, because it also runs on + stored outputs that hold neither column. + """ + tax_variable, spending_variable = BUDGETARY_IMPACT_VARIABLES + return BudgetaryImpact( + tax_revenue=_sum_change(baseline_simulation, reform_simulation, tax_variable), + spending=_sum_change(baseline_simulation, reform_simulation, spending_variable), + ) + class PolicyReformAnalysis(BaseModel): """Complete policy reform analysis result.""" diff --git a/tests/test_uk_budgetary_impact.py b/tests/test_uk_budgetary_impact.py new file mode 100644 index 000000000..f3014af43 --- /dev/null +++ b/tests/test_uk_budgetary_impact.py @@ -0,0 +1,168 @@ +"""Tests for the UK budgetary impact, totalled from the government's accounts. + +The unit tests patch ``_sum_change`` and feed reform-minus-baseline changes, +so they check the arithmetic alone. The others run against tiny output +simulations on the installed policyengine-uk model, so a rename of +``gov_tax`` or ``gov_spending`` fails here instead of in a report. +""" + +from unittest.mock import patch + +import pandas as pd +from microdf import MicroDataFrame + +from policyengine.core import Simulation +from policyengine.tax_benefit_models.uk.analysis import ( + BUDGETARY_IMPACT_VARIABLES, + BudgetaryImpact, + calculate_budgetary_impact, + configure_budgetary_impact_variables, +) +from policyengine.tax_benefit_models.uk.datasets import ( + PolicyEngineUKDataset, + UKYearData, +) +from policyengine.tax_benefit_models.uk.model import uk_latest + + +def _budgetary_impact_from_changes(changes: dict[str, float]) -> BudgetaryImpact: + def fake_sum_change(baseline_simulation, reform_simulation, variable): + return changes.get(variable, 0.0) + + with patch( + "policyengine.tax_benefit_models.uk.analysis._sum_change", + side_effect=fake_sum_change, + ): + return calculate_budgetary_impact(None, None) + + +def test_total_is_the_tax_revenue_change_less_the_spending_change(): + """An employer NI cut passed on as pay: tax revenue falls and benefit + spending falls a little, so the total is the revenue lost less the + spending saved.""" + result = _budgetary_impact_from_changes({"gov_tax": -6.0e9, "gov_spending": -0.1e9}) + + assert isinstance(result, BudgetaryImpact) + assert result.tax_revenue == -6.0e9 + assert result.spending == -0.1e9 + assert result.total == -5.9e9 + + +def test_more_spending_costs_the_budget(): + result = _budgetary_impact_from_changes({"gov_spending": 2.0e9}) + + assert result.tax_revenue == 0 + assert result.total == -2.0e9 + + +def test_budgetary_impact_round_trips_through_json(): + result = BudgetaryImpact(tax_revenue=-6.0e9, spending=-0.1e9) + + dumped = result.model_dump() + + assert dumped["total"] == -5.9e9 + assert BudgetaryImpact.model_validate_json(result.model_dump_json()) == result + + +def test_budgetary_impact_variables_are_household_variables_of_the_model(): + """Both accounts must exist in the installed policyengine-uk model, as + household variables, so a rename fails loudly here.""" + for variable in BUDGETARY_IMPACT_VARIABLES: + assert variable in uk_latest.variables_by_name, ( + f"{variable} is not defined in the installed policyengine-uk model" + ) + assert uk_latest.get_variable(variable).entity == "household" + + +def _microdf(data: dict, weights: str) -> MicroDataFrame: + return MicroDataFrame(pd.DataFrame(data), weights=weights) + + +def _make_uk_output_simulation( + tmp_path, + simulation_id: str, + *, + gov_tax: tuple[float, float] = (0.0, 0.0), + gov_spending: tuple[float, float] = (0.0, 0.0), +) -> Simulation: + """Return an output simulation of two households, weighted 1 and 2.""" + ids = [1, 2] + weights = [1.0, 2.0] + data = UKYearData( + person=_microdf( + { + "person_id": ids, + "benunit_id": ids, + "household_id": ids, + "person_weight": weights, + }, + "person_weight", + ), + benunit=_microdf( + {"benunit_id": ids, "benunit_weight": weights}, + "benunit_weight", + ), + household=_microdf( + { + "household_id": ids, + "household_weight": weights, + "gov_tax": list(gov_tax), + "gov_spending": list(gov_spending), + }, + "household_weight", + ), + ) + dataset = PolicyEngineUKDataset( + id=simulation_id, + name=f"{simulation_id} output", + description="Mocked UK output dataset for the budgetary impact", + filepath=str(tmp_path / f"{simulation_id}.h5"), + year=2026, + is_output_dataset=True, + data=data, + ) + return Simulation( + id=simulation_id, + dataset=dataset, + tax_benefit_model_version=uk_latest, + output_dataset=dataset, + ) + + +def test_configure_budgetary_impact_variables_materializes_the_accounts(tmp_path): + """Neither account is in the default UK output, so a caller adds both + before the simulations run. Without them calculate_budgetary_impact would + raise on real data.""" + baseline = _make_uk_output_simulation(tmp_path, "baseline") + reform = _make_uk_output_simulation(tmp_path, "reform") + + configure_budgetary_impact_variables(baseline, reform) + + for simulation in (baseline, reform): + household_extras = simulation.extra_variables["household"] + for variable in BUDGETARY_IMPACT_VARIABLES: + assert variable in household_extras + + +def test_calculate_budgetary_impact_runs_against_real_output_simulation(tmp_path): + baseline = _make_uk_output_simulation( + tmp_path, + "baseline", + gov_tax=(1_000.0, 400.0), + gov_spending=(300.0, 100.0), + ) + reform = _make_uk_output_simulation( + tmp_path, + "reform", + gov_tax=(900.0, 380.0), + gov_spending=(310.0, 90.0), + ) + + result = calculate_budgetary_impact(baseline, reform) + + # tax revenue = 1 x (900 - 1,000) + 2 x (380 - 400) = -140 + assert result.tax_revenue == -140.0 + # spending = 1 x (310 - 300) + 2 x (90 - 100) = -10 + assert result.spending == -10.0 + # total = -140 - (-10) = -130 + assert result.total == -130.0 From ef2fb987e0b690fbc748daa33a91859140555ac1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Wed, 2 Dec 2026 13:26:42 +0000 Subject: [PATCH 2/2] Count benefit uprating in the UK spending, and take the review's code points Spending is totalled from household_benefits and the two terms policyengine-uk's gov_spending adds to it, instead of read from gov_spending, which leaves out what the benefit uprating reforms pay. The docstring lists how the accounts differ from the household totals. configure_budgetary_impact_variables takes any number of simulations and is exported from pe.uk. sum_change is one helper for the US and UK functions. Co-Authored-By: Claude Opus 5.5 --- changelog.d/779.added.md | 2 +- docs/impact-analysis.md | 8 +- src/policyengine/outputs/change_aggregate.py | 16 + .../tax_benefit_models/uk/__init__.py | 2 + .../tax_benefit_models/uk/analysis.py | 116 ++++--- .../tax_benefit_models/us/analysis.py | 35 +- tests/test_budgetary_impact.py | 6 +- tests/test_uk_budgetary_impact.py | 320 ++++++++++++++---- 8 files changed, 353 insertions(+), 152 deletions(-) diff --git a/changelog.d/779.added.md b/changelog.d/779.added.md index 37f18e83c..6d0b4ba2a 100644 --- a/changelog.d/779.added.md +++ b/changelog.d/779.added.md @@ -1 +1 @@ -`pe.uk.calculate_budgetary_impact` and `pe.uk.BudgetaryImpact` give a UK reform's budgetary impact from the government's accounts: the change in `gov_tax`, which counts employer National Insurance, less the change in `gov_spending`. `configure_budgetary_impact_variables` in `policyengine.tax_benefit_models.uk.analysis` adds both accounts to the simulations' outputs before they run, as the US function does. The UK `economic_impact_analysis` is unchanged. +`pe.uk.calculate_budgetary_impact` and `pe.uk.BudgetaryImpact` give a UK reform's budgetary impact from the government's accounts: the change in `gov_tax`, which counts employer National Insurance, less the change in the government's spending. Spending is `household_benefits` plus the two terms policyengine-uk's `gov_spending` adds to it, because `gov_spending` leaves out what the benefit uprating reforms pay. `pe.uk.configure_budgetary_impact_variables` adds what isn't a default UK output to any number of simulations before they run. The UK `economic_impact_analysis` is unchanged. diff --git a/docs/impact-analysis.md b/docs/impact-analysis.md index 00ee9143e..1f511924b 100644 --- a/docs/impact-analysis.md +++ b/docs/impact-analysis.md @@ -57,14 +57,10 @@ if hasattr(analysis, "wealth_decile_impacts"): analysis.reform_inequality.gini - analysis.baseline_inequality.gini ``` -For a UK reform's budgetary impact, call `pe.uk.calculate_budgetary_impact`. It returns the changes in the government's tax revenue (`gov_tax`, employer National Insurance included) and spending (`gov_spending`), and their difference, `total`, positive when the government is better off. Neither account is a default UK output, so add both to the simulations before they run: +For a UK reform's budgetary impact, call `pe.uk.calculate_budgetary_impact`. It returns the changes in the government's tax revenue (`gov_tax`, employer National Insurance included) and spending (the household benefits, the Lifetime ISA bonus and any public spending a reform sets), and their difference, `total`, positive when the government is better off. Not all of that is in the default UK output, so configure the simulations before they run: ```python -from policyengine.tax_benefit_models.uk.analysis import ( - configure_budgetary_impact_variables, -) - -configure_budgetary_impact_variables(baseline, reformed) +pe.uk.configure_budgetary_impact_variables(baseline, reformed) budget = pe.uk.calculate_budgetary_impact(baseline, reformed) budget.total ``` diff --git a/src/policyengine/outputs/change_aggregate.py b/src/policyengine/outputs/change_aggregate.py index f9ea65024..8572cc8de 100644 --- a/src/policyengine/outputs/change_aggregate.py +++ b/src/policyengine/outputs/change_aggregate.py @@ -235,3 +235,19 @@ def run(self): self.result = filtered_change.sum() elif self.aggregate_type == ChangeAggregateType.MEAN: self.result = filtered_change.mean() + + +def sum_change( + baseline_simulation: Simulation, + reform_simulation: Simulation, + variable: str, +) -> float: + """Return the reform-minus-baseline weighted total of a variable.""" + aggregate = ChangeAggregate( + baseline_simulation=baseline_simulation, + reform_simulation=reform_simulation, + variable=variable, + aggregate_type=ChangeAggregateType.SUM, + ) + aggregate.run() + return float(aggregate.result) diff --git a/src/policyengine/tax_benefit_models/uk/__init__.py b/src/policyengine/tax_benefit_models/uk/__init__.py index 5405509c5..6016cb956 100644 --- a/src/policyengine/tax_benefit_models/uk/__init__.py +++ b/src/policyengine/tax_benefit_models/uk/__init__.py @@ -20,6 +20,7 @@ from .analysis import ( BudgetaryImpact, calculate_budgetary_impact, + configure_budgetary_impact_variables, economic_impact_analysis, ) from .datasets import ( @@ -61,6 +62,7 @@ "calculate_household", "economic_impact_analysis", "calculate_budgetary_impact", + "configure_budgetary_impact_variables", "BudgetaryImpact", "ProgramStatistics", "LaborSupplyResponse", diff --git a/src/policyengine/tax_benefit_models/uk/analysis.py b/src/policyengine/tax_benefit_models/uk/analysis.py index 19df1abec..43d0da72f 100644 --- a/src/policyengine/tax_benefit_models/uk/analysis.py +++ b/src/policyengine/tax_benefit_models/uk/analysis.py @@ -20,10 +20,7 @@ configure_labor_supply_response_variables, validate_program_statistics_config, ) -from policyengine.outputs.change_aggregate import ( - ChangeAggregate, - ChangeAggregateType, -) +from policyengine.outputs.change_aggregate import sum_change from policyengine.outputs.decile_impact import ( DecileImpact, calculate_decile_impacts, @@ -66,16 +63,28 @@ "state_pension": {"is_tax": False}, } -# The UK model's government accounts, which the budgetary impact totals: -# ``gov_tax`` (every tax the government raises in respect of a household, -# employer National Insurance included) and ``gov_spending`` (every benefit -# and other programme it pays for). Their difference is ``gov_balance``. +# The UK model's government accounts, which name the two sides of the budgetary +# impact: ``gov_tax`` (every tax the government raises in respect of a +# household, employer National Insurance included) and ``gov_spending`` (every +# benefit and other programme it pays for). Their difference is ``gov_balance``. BUDGETARY_IMPACT_VARIABLES: tuple[str, str] = ("gov_tax", "gov_spending") -# Neither account is in the default UK output, so both are materialized -# before the reform simulations run. +# What the spending side totals. policyengine-uk's ``gov_spending`` leaves out +# what the benefit uprating reforms pay (``gov.contrib.benefit_uprating``), +# which ``household_benefits`` counts, so a benefit uprating reform would cost +# nothing. Until it counts them, this totals the same spending itself: the +# household benefits, plus the two terms ``gov_spending`` adds to them. +SPENDING_TERMS: tuple[str, ...] = ( + "household_benefits", + "lifetime_isa_bonus", + "other_public_spending_budget_change", +) + +# ``household_benefits`` is in the default UK output. The rest is not, so it is +# materialized before the simulations run. _BUDGETARY_IMPACT_EXTRA_VARIABLES: dict[str, list[str]] = { - "household": list(BUDGETARY_IMPACT_VARIABLES), + "household": ["gov_tax", "other_public_spending_budget_change"], + "person": ["lifetime_isa_bonus"], } @@ -99,8 +108,8 @@ class BudgetaryImpact(BaseModel): spending: float = Field( ..., description=( - "Change in government spending (gov_spending), GBP; positive " - "means more spending." + "Change in government spending (gov_spending, and what the benefit " + "uprating reforms pay), GBP; positive means more spending." ), ) @@ -111,35 +120,17 @@ def total(self) -> float: return self.tax_revenue - self.spending -def _sum_change( - baseline_simulation: Simulation, - reform_simulation: Simulation, - variable: str, -) -> float: - """Reform minus baseline total for a variable.""" - agg = ChangeAggregate( - baseline_simulation=baseline_simulation, - reform_simulation=reform_simulation, - variable=variable, - aggregate_type=ChangeAggregateType.SUM, - ) - agg.run() - return float(agg.result) +def configure_budgetary_impact_variables(*simulations: Simulation) -> None: + """Materialize what the budgetary impact totals in the simulations' outputs. - -def configure_budgetary_impact_variables( - baseline_simulation: Simulation, - reform_simulation: Simulation, -) -> None: - """Materialize ``gov_tax`` and ``gov_spending`` in the reform outputs. - - Neither is in the default UK output, so both are added as extra output - variables before the simulations run. Call this before - :meth:`Simulation.ensure` so they are present when - :func:`calculate_budgetary_impact` reads them. + ``gov_tax`` and two of ``SPENDING_TERMS`` are not in the default UK output, + so they are added as extra output variables before the simulations run. Call + this before :meth:`Simulation.ensure`, so that they are present when + :func:`calculate_budgetary_impact` reads them. It takes any number of + simulations: a precomputed baseline has no reform to go with it. """ - add_extra_variables(baseline_simulation, _BUDGETARY_IMPACT_EXTRA_VARIABLES) - add_extra_variables(reform_simulation, _BUDGETARY_IMPACT_EXTRA_VARIABLES) + for simulation in simulations: + add_extra_variables(simulation, _BUDGETARY_IMPACT_EXTRA_VARIABLES) def calculate_budgetary_impact( @@ -148,26 +139,43 @@ def calculate_budgetary_impact( ) -> BudgetaryImpact: """Return a UK reform's budgetary impact from the government's accounts. - ``tax_revenue`` is the reform-minus-baseline weighted total of - ``gov_tax`` and ``spending`` that of ``gov_spending``; ``total`` is their - difference, the change in ``gov_balance``. + ``tax_revenue`` is the reform-minus-baseline weighted total of ``gov_tax``, + and ``spending`` that of the government's spending; ``total`` is their + difference, the change in the government's balance. The totals are the government's, not the household totals - ``household_tax`` and ``household_benefits``: ``household_tax`` leaves out - employer National Insurance, which employers pay. Under policyengine-uk's - default incidence an employer NI change moves employees' pay, so a total - of household taxes would count the income tax and NI on that pay change - but not the employer NI receipts behind it. - - ``gov_tax`` and ``gov_spending`` are not in the default UK output: call + ``household_tax`` and ``household_benefits``. They differ in these terms: + + - ``gov_tax`` counts employer National Insurance, which employers pay and + ``household_tax`` leaves out. Under policyengine-uk's default incidence an + employer NI change moves employees' pay, so a total of household taxes + would count the income tax and NI on that pay change but not the employer + NI receipts behind it. ``household_tax`` holds shares of the change + instead, which are not revenue of their own. + - ``gov_tax`` counts the Lifetime ISA withdrawal charge, and spending the + Lifetime ISA bonus. + - Spending counts ``other_public_spending_budget_change``, which only a + reform sets. + + ``gov_tax`` holds VAT and private school VAT as levels where + ``household_tax`` holds their changes from baseline, which are the same + change. + + Spending is totalled from ``SPENDING_TERMS`` rather than read from + ``gov_spending``, which leaves out what the benefit uprating reforms pay. + + ``gov_tax`` and the terms are not all in the default UK output: call :func:`configure_budgetary_impact_variables` before the simulations run. :func:`economic_impact_analysis` calls neither, because it also runs on - stored outputs that hold neither column. + stored outputs that hold none of them. """ - tax_variable, spending_variable = BUDGETARY_IMPACT_VARIABLES + tax_variable, _ = BUDGETARY_IMPACT_VARIABLES return BudgetaryImpact( - tax_revenue=_sum_change(baseline_simulation, reform_simulation, tax_variable), - spending=_sum_change(baseline_simulation, reform_simulation, spending_variable), + tax_revenue=sum_change(baseline_simulation, reform_simulation, tax_variable), + spending=sum( + sum_change(baseline_simulation, reform_simulation, variable) + for variable in SPENDING_TERMS + ), ) diff --git a/src/policyengine/tax_benefit_models/us/analysis.py b/src/policyengine/tax_benefit_models/us/analysis.py index 0465e97ea..dcd5c24da 100644 --- a/src/policyengine/tax_benefit_models/us/analysis.py +++ b/src/policyengine/tax_benefit_models/us/analysis.py @@ -22,10 +22,7 @@ configure_labor_supply_response_variables, validate_program_statistics_config, ) -from policyengine.outputs.change_aggregate import ( - ChangeAggregate, - ChangeAggregateType, -) +from policyengine.outputs.change_aggregate import sum_change from policyengine.outputs.decile_impact import ( DecileImpact, calculate_decile_impacts, @@ -103,22 +100,6 @@ def total(self) -> float: return self.federal + self.state + self.unattributed -def _sum_change( - baseline_simulation: Simulation, - reform_simulation: Simulation, - variable: str, -) -> float: - """Reform minus baseline total for a variable.""" - agg = ChangeAggregate( - baseline_simulation=baseline_simulation, - reform_simulation=reform_simulation, - variable=variable, - aggregate_type=ChangeAggregateType.SUM, - ) - agg.run() - return float(agg.result) - - # Budgetary-impact variables that are not in the default US output # (household_tax, household_benefits, and the three tax variables are). They # must be materialized before the reform simulations run. @@ -212,16 +193,16 @@ def calculate_budgetary_impact( :func:`configure_budgetary_impact_variables` to materialize them before the simulations run. Callers using this helper directly must do the same. """ - household_tax_change = _sum_change( + household_tax_change = sum_change( baseline_simulation, reform_simulation, "household_tax" ) - household_benefits_change = _sum_change( + household_benefits_change = sum_change( baseline_simulation, reform_simulation, "household_benefits" ) - federal_benefit_cost_change = _sum_change( + federal_benefit_cost_change = sum_change( baseline_simulation, reform_simulation, "federal_benefit_cost" ) - state_benefit_cost_change = _sum_change( + state_benefit_cost_change = sum_change( baseline_simulation, reform_simulation, "state_benefit_cost" ) @@ -233,12 +214,12 @@ def calculate_budgetary_impact( total -= federal_benefit_cost_change + state_benefit_cost_change federal = ( - _sum_change(baseline_simulation, reform_simulation, "income_tax") - + _sum_change(baseline_simulation, reform_simulation, "employee_payroll_tax") + sum_change(baseline_simulation, reform_simulation, "income_tax") + + sum_change(baseline_simulation, reform_simulation, "employee_payroll_tax") - federal_benefit_cost_change ) state = ( - _sum_change(baseline_simulation, reform_simulation, "state_income_tax") + sum_change(baseline_simulation, reform_simulation, "state_income_tax") - state_benefit_cost_change ) diff --git a/tests/test_budgetary_impact.py b/tests/test_budgetary_impact.py index eefcb9277..32dc64454 100644 --- a/tests/test_budgetary_impact.py +++ b/tests/test_budgetary_impact.py @@ -1,6 +1,6 @@ """Tests for federal/state/unattributed budgetary impact partitioning. -The unit tests patch ``_sum_change`` and feed mocked reform-minus-baseline +The unit tests patch ``sum_change`` and feed mocked reform-minus-baseline deltas, so they exercise the partition arithmetic in isolation. The integration test at the bottom runs ``calculate_budgetary_impact`` against a tiny hand-built US output simulation so that every variable name it references @@ -41,7 +41,7 @@ def _fake_sum_change_factory(variable_to_delta: dict[str, float]): - """Return a fake _sum_change that looks up deltas by variable name.""" + """Return a fake sum_change that looks up deltas by variable name.""" def fake_sum_change(baseline_sim, reform_sim, variable): return variable_to_delta.get(variable, 0.0) @@ -54,7 +54,7 @@ def _budgetary_impact_from_deltas( ) -> BudgetaryImpact: with ( patch( - "policyengine.tax_benefit_models.us.analysis._sum_change", + "policyengine.tax_benefit_models.us.analysis.sum_change", side_effect=_fake_sum_change_factory(deltas), ), patch( diff --git a/tests/test_uk_budgetary_impact.py b/tests/test_uk_budgetary_impact.py index f3014af43..c5622ab7b 100644 --- a/tests/test_uk_budgetary_impact.py +++ b/tests/test_uk_budgetary_impact.py @@ -1,19 +1,29 @@ """Tests for the UK budgetary impact, totalled from the government's accounts. -The unit tests patch ``_sum_change`` and feed reform-minus-baseline changes, -so they check the arithmetic alone. The others run against tiny output -simulations on the installed policyengine-uk model, so a rename of -``gov_tax`` or ``gov_spending`` fails here instead of in a report. +The unit tests patch ``sum_change`` and feed reform-minus-baseline changes, so +they check the arithmetic alone. The others run against tiny output simulations +on the installed policyengine-uk model, so a rename of a variable the budgetary +impact reads fails here instead of in a report. The last ones fill those +simulations with the model's own results for made-up households. """ from unittest.mock import patch import pandas as pd +import policyengine_uk +import pytest from microdf import MicroDataFrame +from policyengine_uk.variables.gov.gov_spending import GOV_SPENDING_VARIABLES +from policyengine_uk.variables.household.income.household_benefits import ( + HOUSEHOLD_BENEFIT_VARIABLES, +) +import policyengine as pe from policyengine.core import Simulation +from policyengine.tax_benefit_models.uk import analysis as uk_analysis from policyengine.tax_benefit_models.uk.analysis import ( BUDGETARY_IMPACT_VARIABLES, + SPENDING_TERMS, BudgetaryImpact, calculate_budgetary_impact, configure_budgetary_impact_variables, @@ -24,13 +34,15 @@ ) from policyengine.tax_benefit_models.uk.model import uk_latest +YEAR = 2026 + def _budgetary_impact_from_changes(changes: dict[str, float]) -> BudgetaryImpact: def fake_sum_change(baseline_simulation, reform_simulation, variable): return changes.get(variable, 0.0) with patch( - "policyengine.tax_benefit_models.uk.analysis._sum_change", + "policyengine.tax_benefit_models.uk.analysis.sum_change", side_effect=fake_sum_change, ): return calculate_budgetary_impact(None, None) @@ -40,7 +52,9 @@ def test_total_is_the_tax_revenue_change_less_the_spending_change(): """An employer NI cut passed on as pay: tax revenue falls and benefit spending falls a little, so the total is the revenue lost less the spending saved.""" - result = _budgetary_impact_from_changes({"gov_tax": -6.0e9, "gov_spending": -0.1e9}) + result = _budgetary_impact_from_changes( + {"gov_tax": -6.0e9, "household_benefits": -0.1e9} + ) assert isinstance(result, BudgetaryImpact) assert result.tax_revenue == -6.0e9 @@ -48,11 +62,25 @@ def test_total_is_the_tax_revenue_change_less_the_spending_change(): assert result.total == -5.9e9 -def test_more_spending_costs_the_budget(): - result = _budgetary_impact_from_changes({"gov_spending": 2.0e9}) +def test_spending_is_the_sum_of_its_terms(): + result = _budgetary_impact_from_changes( + { + "household_benefits": 1.0e9, + "lifetime_isa_bonus": 2.0e9, + "other_public_spending_budget_change": 4.0e9, + } + ) + assert result.spending == 7.0e9 assert result.tax_revenue == 0 - assert result.total == -2.0e9 + assert result.total == -7.0e9 + + +def test_the_models_own_gov_spending_is_not_read(): + """``gov_spending`` leaves out what the benefit uprating reforms pay.""" + result = _budgetary_impact_from_changes({"gov_spending": 2.0e9}) + + assert result.spending == 0 def test_budgetary_impact_round_trips_through_json(): @@ -64,6 +92,15 @@ def test_budgetary_impact_round_trips_through_json(): assert BudgetaryImpact.model_validate_json(result.model_dump_json()) == result +def test_the_functions_are_exported_together(): + assert pe.uk.calculate_budgetary_impact is calculate_budgetary_impact + assert ( + pe.uk.configure_budgetary_impact_variables + is configure_budgetary_impact_variables + ) + assert pe.uk.BudgetaryImpact is BudgetaryImpact + + def test_budgetary_impact_variables_are_household_variables_of_the_model(): """Both accounts must exist in the installed policyengine-uk model, as household variables, so a rename fails loudly here.""" @@ -74,52 +111,55 @@ def test_budgetary_impact_variables_are_household_variables_of_the_model(): assert uk_latest.get_variable(variable).entity == "household" +def test_what_is_read_is_a_default_output_or_is_configured(): + configured = uk_analysis._BUDGETARY_IMPACT_EXTRA_VARIABLES + for entity, variables in configured.items(): + for variable in variables: + assert uk_latest.get_variable(variable).entity == entity + read = {BUDGETARY_IMPACT_VARIABLES[0], *SPENDING_TERMS} + defaults = {name for names in uk_latest.entity_variables.values() for name in names} + extras = {name for names in configured.values() for name in names} + assert read <= defaults | extras + # A variable in both would be asked for twice. + assert not defaults & extras + + +def test_spending_terms_are_what_gov_spending_adds_to_household_benefits(): + # The spending total rests on these being the only terms ``gov_spending`` + # adds to the household benefits. If policyengine-uk's lists change, this + # fails, so that the total is updated with them. + assert set(HOUSEHOLD_BENEFIT_VARIABLES) <= set(GOV_SPENDING_VARIABLES) + beyond = set(GOV_SPENDING_VARIABLES) - set(HOUSEHOLD_BENEFIT_VARIABLES) + assert beyond == set(SPENDING_TERMS) - {"household_benefits"} + + def _microdf(data: dict, weights: str) -> MicroDataFrame: return MicroDataFrame(pd.DataFrame(data), weights=weights) -def _make_uk_output_simulation( +def _output_simulation( tmp_path, simulation_id: str, - *, - gov_tax: tuple[float, float] = (0.0, 0.0), - gov_spending: tuple[float, float] = (0.0, 0.0), + person: dict, + household: dict, ) -> Simulation: - """Return an output simulation of two households, weighted 1 and 2.""" - ids = [1, 2] - weights = [1.0, 2.0] - data = UKYearData( - person=_microdf( - { - "person_id": ids, - "benunit_id": ids, - "household_id": ids, - "person_weight": weights, - }, - "person_weight", - ), - benunit=_microdf( - {"benunit_id": ids, "benunit_weight": weights}, - "benunit_weight", - ), - household=_microdf( - { - "household_id": ids, - "household_weight": weights, - "gov_tax": list(gov_tax), - "gov_spending": list(gov_spending), - }, - "household_weight", - ), - ) + """Return an output simulation of people and the households they are in.""" + benunit = { + "benunit_id": household["household_id"], + "benunit_weight": household["household_weight"], + } dataset = PolicyEngineUKDataset( id=simulation_id, name=f"{simulation_id} output", description="Mocked UK output dataset for the budgetary impact", filepath=str(tmp_path / f"{simulation_id}.h5"), - year=2026, + year=YEAR, is_output_dataset=True, - data=data, + data=UKYearData( + person=_microdf(person, "person_weight"), + benunit=_microdf(benunit, "benunit_weight"), + household=_microdf(household, "household_weight"), + ), ) return Simulation( id=simulation_id, @@ -129,40 +169,198 @@ def _make_uk_output_simulation( ) -def test_configure_budgetary_impact_variables_materializes_the_accounts(tmp_path): - """Neither account is in the default UK output, so a caller adds both - before the simulations run. Without them calculate_budgetary_impact would - raise on real data.""" - baseline = _make_uk_output_simulation(tmp_path, "baseline") - reform = _make_uk_output_simulation(tmp_path, "reform") +def _two_households( + tmp_path, + simulation_id: str, + *, + gov_tax: tuple[float, float] = (0.0, 0.0), + household_benefits: tuple[float, float] = (0.0, 0.0), + other_public_spending: tuple[float, float] = (0.0, 0.0), + lifetime_isa_bonus: tuple[float, float] = (0.0, 0.0), +) -> Simulation: + """Return an output simulation of two one-person households, weighted 1 and 2.""" + ids, weights = [1, 2], [1.0, 2.0] + return _output_simulation( + tmp_path, + simulation_id, + person={ + "person_id": ids, + "benunit_id": ids, + "household_id": ids, + "person_weight": weights, + "lifetime_isa_bonus": list(lifetime_isa_bonus), + }, + household={ + "household_id": ids, + "household_weight": weights, + "gov_tax": list(gov_tax), + "household_benefits": list(household_benefits), + "other_public_spending_budget_change": list(other_public_spending), + }, + ) + + +@pytest.mark.parametrize("count", [1, 2, 3]) +def test_configure_budgetary_impact_variables_takes_any_number_of_simulations( + tmp_path, count +): + """A caller adds what isn't a default output before the simulations run. + Without it calculate_budgetary_impact would raise on real data. A + precomputed baseline has no reform to go with it.""" + simulations = [_two_households(tmp_path, f"s{index}") for index in range(count)] - configure_budgetary_impact_variables(baseline, reform) + configure_budgetary_impact_variables(*simulations) + configure_budgetary_impact_variables(*simulations) - for simulation in (baseline, reform): - household_extras = simulation.extra_variables["household"] - for variable in BUDGETARY_IMPACT_VARIABLES: - assert variable in household_extras + for simulation in simulations: + assert simulation.extra_variables == { + "household": ["gov_tax", "other_public_spending_budget_change"], + "person": ["lifetime_isa_bonus"], + } def test_calculate_budgetary_impact_runs_against_real_output_simulation(tmp_path): - baseline = _make_uk_output_simulation( + baseline = _two_households( tmp_path, "baseline", gov_tax=(1_000.0, 400.0), - gov_spending=(300.0, 100.0), + household_benefits=(300.0, 100.0), + other_public_spending=(0.0, 0.0), + lifetime_isa_bonus=(0.0, 50.0), ) - reform = _make_uk_output_simulation( + reform = _two_households( tmp_path, "reform", gov_tax=(900.0, 380.0), - gov_spending=(310.0, 90.0), + household_benefits=(310.0, 90.0), + other_public_spending=(5.0, 7.0), + lifetime_isa_bonus=(20.0, 80.0), ) result = calculate_budgetary_impact(baseline, reform) # tax revenue = 1 x (900 - 1,000) + 2 x (380 - 400) = -140 assert result.tax_revenue == -140.0 - # spending = 1 x (310 - 300) + 2 x (90 - 100) = -10 - assert result.spending == -10.0 - # total = -140 - (-10) = -130 - assert result.total == -130.0 + # household benefits = 1 x 10 + 2 x (-10) = -10; public spending = 1 x 5 + + # 2 x 7 = 19; Lifetime ISA bonus = 1 x 20 + 2 x 30 = 80 + assert result.spending == 89.0 + # total = -140 - 89 = -229 + assert result.total == -229.0 + + +def test_calculate_budgetary_impact_says_which_column_is_missing(tmp_path): + """Stored outputs without the columns fail with the variable's name.""" + simulation = _two_households(tmp_path, "baseline") + simulation.output_dataset.data.household.drop(columns=["gov_tax"], inplace=True) + + with pytest.raises(ValueError, match="gov_tax"): + calculate_budgetary_impact(simulation, simulation) + + +def _model_simulation( + tmp_path, simulation_id: str, reform: dict[str, float] | None +) -> Simulation: + """Return the installed model's outputs for two made-up households. + + A worker with a child, who gets Child Benefit and has a Lifetime ISA, and a + pensioner, weighted 1 and 2. People are weighted as their household is. + """ + model = policyengine_uk.Simulation( + situation={ + "people": { + "worker": { + "age": {YEAR: 40}, + "employment_income": {YEAR: 30_000.0}, + "lifetime_isa_payments": {YEAR: 4_000.0}, + }, + "child": {"age": {YEAR: 6}}, + "pensioner": { + "age": {YEAR: 75}, + "state_pension_reported": {YEAR: 11_500.0}, + }, + }, + "benunits": { + "family": {"members": ["worker", "child"]}, + "older": {"members": ["pensioner"]}, + }, + "households": { + "family": {"members": ["worker", "child"]}, + "older": {"members": ["pensioner"]}, + }, + }, + reform=reform, + ) + + def values(variable: str) -> list[float]: + return [float(value) for value in model.calculate(variable, YEAR)] + + return _output_simulation( + tmp_path, + simulation_id, + person={ + "person_id": [1, 2, 3], + "benunit_id": [1, 1, 2], + "household_id": [1, 1, 2], + "person_weight": [1.0, 1.0, 2.0], + "lifetime_isa_bonus": values("lifetime_isa_bonus"), + }, + household={ + "household_id": [1, 2], + "household_weight": [1.0, 2.0], + **{ + variable: values(variable) + for variable in ( + "gov_tax", + "household_benefits", + "other_public_spending_budget_change", + # Not read: the tests compare the total with it. + "gov_spending", + ) + }, + }, + ) + + +def _weighted_change(baseline: Simulation, reform: Simulation, variable: str) -> float: + before, after = ( + simulation.output_dataset.data.household[variable] + for simulation in (baseline, reform) + ) + return float((after - before).sum()) + + +@pytest.mark.parametrize("rate", ["all", "non_sp"]) +def test_spending_counts_what_a_benefit_uprating_reform_pays(tmp_path, rate): + baseline = _model_simulation(tmp_path, "baseline", None) + reform = _model_simulation( + tmp_path, "reform", {f"gov.contrib.benefit_uprating.{rate}": 0.05} + ) + paid = _weighted_change(baseline, reform, "household_benefits") + assert paid > 0 + + result = calculate_budgetary_impact(baseline, reform) + + assert result.spending == pytest.approx(paid, abs=0.01) + + +@pytest.mark.parametrize( + "reform", + [ + {"gov.hmrc.child_benefit.amount.eldest": 40.0}, + {"gov.hmrc.isa.lifetime.bonus_rate": 0.5}, + ], + ids=["child_benefit", "lifetime_isa_bonus"], +) +def test_spending_is_the_models_gov_spending_without_an_uprating_reform( + tmp_path, reform +): + # The lists can agree while a formula adds something beyond them, as + # ``household_benefits`` does, so compare the totals themselves. + before = _model_simulation(tmp_path, "baseline", None) + after = _model_simulation(tmp_path, "reform", reform) + spent = _weighted_change(before, after, "gov_spending") + assert spent > 0 + + result = calculate_budgetary_impact(before, after) + + assert result.spending == pytest.approx(spent, abs=0.01)