diff --git a/README.md b/README.md index 66ce095..bb5cd84 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ PolicyEngine New Zealand is a microsimulation model for New Zealand's tax and be ## Features -- **Tax**: income tax and the ACC Earners' Levy +- **Tax**: income tax on earnings, investment income, NZ Superannuation and Jobseeker Support, and the ACC Earners' Levy - **Working for Families**: Family Tax Credit, In-Work Tax Credit, Best Start - **Benefits**: annualised Jobseeker Support net of tax, from a supplied grant and supplied weekly assessable income, including a linked partner's share of a couple rate; annualised gross NZ Superannuation for a supplied recipient; the annualised Accommodation Supplement before income abatement and rounding; and a separate Accommodation Supplement cash assets test - **Parameters that no formula uses yet**: the GST rate, the KiwiSaver contribution rates and the government contribution's settings @@ -48,7 +48,7 @@ print(f"ACC levy: ${acc_levy[0]:,.2f}") ## System Coverage ### Tax System (Inland Revenue Department) -- **Personal Income Tax**: Progressive rates (10.5%, 17.5%, 30%, 33%, 39%) with current thresholds +- **Personal income tax**: the progressive schedule for each tax year from 2021-22 (period `2022`). To 2023-24, rates of 10.5%, 17.5%, 30%, 33% and 39% start at $0, $14,000, $48,000, $70,000 and $180,000. From 2025-26, the same rates start at $0, $15,600, $53,500, $78,100 and $180,000, and 2024-25 uses the composite schedule that the Taxation (Budget Measures) Act 2024 sets for the year of the change. The tax applies to employment, self-employment and investment income from 2021-22, and from the 2022-23 tax year (period `2023`) also to gross NZ Superannuation and to Jobseeker Support with the income tax that the model assumes MSD pays on it (`jobseeker_support_tax`). The model assumes MSD pays that tax to Inland Revenue on top of the benefit, as section 350(2) of the Social Security Act 2018 allows, so it does not come out of the benefit, and estimates it from the benefit alone. `income_tax` is the year's liability on all the modelled income before credits. `income_tax - jobseeker_support_tax` is the balance after MSD's payment, which is negative when a loss brings the liability below that payment. - **ACC Earners' Levy** on liable employee earnings, capped by tax year: an annual estimate at the GST-inclusive rate Inland Revenue publishes. It does not compute PAYE deductions pay by pay. A bare year uses the rate and cap in force on 1 January of that year, so `2025` uses those of the tax year from April 2024 to March 2025. - **GST**: the model stores the 15% rate as a parameter and does not calculate GST. @@ -72,7 +72,7 @@ sim.calculate("family_tax_credit", "2027") # 7,921 ``` ### Social Security Benefits (Work and Income) -- **Jobseeker Support**: $372.55 a week after tax from 1 April 2026 for a single person aged 25 or over without dependent children (the clause 1(d) rate), before the income test (period `2027` reads the rates for April 2026 to March 2027) +- **Jobseeker Support**: $372.55 a week after tax from 1 April 2026 for a single person aged 25 or over without dependent children who falls outside clause 1(c), which covers some people moved to Jobseeker Support on 15 July 2013 under the Social Security Act 1964's transitional provisions (the clause 1(d) rate), before the income test (period `2027` reads the rates for April 2026 to March 2027) - **New Zealand Superannuation**: the annualised gross standard rate, from age 65, for a person that `receiving_nz_super` marks as a recipient - **Accommodation Supplement**: the annualised amount for the area before income abatement and rounding, and a separate cash assets test diff --git a/changelog.d/benefit-income-tax.fixed.md b/changelog.d/benefit-income-tax.fixed.md new file mode 100644 index 0000000..30e3fdc --- /dev/null +++ b/changelog.d/benefit-income-tax.fixed.md @@ -0,0 +1 @@ +Tax NZ Superannuation and Jobseeker Support from the 2022-23 tax year (period 2023), under sections CF 1(1)(c) and (e) of the Income Tax Act 2007. `taxable_income` now adds the gross `nz_superannuation`, and `jobseeker_support` with the new `jobseeker_support_tax`. That variable is the income tax that the model assumes MSD pays on Jobseeker Support under section 350 of the Social Security Act 2018, and the model finds it by grossing up the year's payment on its own. Section 351 makes it the person's income. A person aged 70 on NZ Superannuation alone, living alone, now owes $4,799.07 of income tax for 2026-27 in place of $0, and a person aged 30 on $19,372.60 of Jobseeker Support has taxable income of $22,158.30, with $2,785.70 of tax that MSD pays. The model still offsets a loss in one modelled source against the others and floors the total at zero, so a self-employment loss now reduces taxable income that includes a benefit, and can leave `income_tax` below `jobseeker_support_tax`. For a period that starts before 1 April 2022, taxable income leaves out both benefits as before, and raises an error for the whole calculation when anyone is marked as a recipient of either. The documentation now states the assumption that MSD pays the tax, and the Jobseeker Support rate metadata now says the rates come before the income test. `family_income` and the Working for Families credits do not yet include either benefit. diff --git a/changelog.d/superannuation-rates.fixed.md b/changelog.d/superannuation-rates.fixed.md index 323d276..e3cfa7f 100644 --- a/changelog.d/superannuation-rates.fixed.md +++ b/changelog.d/superannuation-rates.fixed.md @@ -1 +1 @@ -Annual NZ Superannuation amounts are now 52 times the gross weekly rates in Schedule 1 of the New Zealand Superannuation and Retirement Income Act 2001, as set by the rates orders through 2026–27. Period N is the tax year ending 31 March N. This changes no other output, because no variable reads nz_superannuation yet. +Annual NZ Superannuation amounts are now 52 times the gross weekly rates in Schedule 1 of the New Zealand Superannuation and Retirement Income Act 2001, as set by the rates orders through 2026–27. Period N is the tax year ending 31 March N. diff --git a/docs/index.md b/docs/index.md index bde49bb..6029880 100644 --- a/docs/index.md +++ b/docs/index.md @@ -6,7 +6,7 @@ PolicyEngine New Zealand is a microsimulation model for New Zealand's tax and be ### Calculations -- Personal income tax before credits, using the progressive schedule for the tax year. +- Personal income tax before credits, using the progressive schedule for the tax year, from the 2021-22 tax year on employment, self-employment and investment income, and from the 2022-23 tax year also on gross NZ Superannuation and on Jobseeker Support with the income tax that the model assumes MSD pays on it. - Estimated ACC Earners' Levy on liable employee earnings, using the tax year's rate and cap. - Working for Families tax credits (Family Tax Credit, In-Work Tax Credit, and Best Start). Before abatement, the formulas pay the Family Tax Credit and Best Start for each eligible day and the In-Work Tax Credit for each whole week of eligible days. They leave out, among other rules, the Minimum Family Tax Credit, shared care, the principal caregiver and residence tests, protected months, and changes in caregivers' relationships during the year. They spread a family's annual income evenly through the tax year, and the default family scheme income calculation leaves out main benefits and NZ Superannuation. - Jobseeker Support payment amounts based on a supplied grant status. diff --git a/policyengine_nz/parameters/gov/msd/jobseeker/payment_rates.yaml b/policyengine_nz/parameters/gov/msd/jobseeker/payment_rates.yaml index 74a0111..b1db866 100644 --- a/policyengine_nz/parameters/gov/msd/jobseeker/payment_rates.yaml +++ b/policyengine_nz/parameters/gov/msd/jobseeker/payment_rates.yaml @@ -1,4 +1,4 @@ -description: Jobseeker Support weekly rates (Social Security Act 2018, Schedule 4 Part 1 clause 1) +description: Jobseeker Support weekly rates (Social Security Act 2018, Schedule 4 Part 1 clause 1), before the applicable income test. The model assumes MSD pays the income tax on the payments to Inland Revenue on top of them, as section 350(2) allows. metadata: label: Jobseeker Support payment rates reference: diff --git a/policyengine_nz/tests/policy/baseline/test_benefit_income_tax.yaml b/policyengine_nz/tests/policy/baseline/test_benefit_income_tax.yaml new file mode 100644 index 0000000..b3c8dbc --- /dev/null +++ b/policyengine_nz/tests/policy/baseline/test_benefit_income_tax.yaml @@ -0,0 +1,158 @@ +# NZ Superannuation and Jobseeker Support in taxable income (Income Tax Act +# 2007, sections CF 1(1)(c) and (e)). Period 2027 is the 2026-27 tax year, +# taxed at 10.5% to $15,600, 17.5% to $53,500, 30% to $78,100, 33% to +# $180,000 and 39% above (Schedule 1 Part A clause 1, Table 1). Benefits are +# 52 times the weekly rate from 1 April 2026. + +# 52 x 647.37 (NZS Act Schedule 1 Part 1 clause 1(a)). Tax is 10.5% of +# 15,600 plus 17.5% of 18,063.24. +- name: NZ Superannuation alone is taxed gross + period: 2027 + absolute_error_margin: 0.01 + input: + age: 70 + receiving_nz_super: true + living_alone: true + output: + nz_superannuation: 33_663.24 + taxable_income: 33_663.24 + income_tax: 4_799.07 + +# 1,638 + 17.5% of 37,900 + 30% of 10,163.24. +- name: NZ Superannuation and wages are taxed together + period: 2027 + absolute_error_margin: 0.01 + input: + age: 70 + receiving_nz_super: true + living_alone: true + employment_income: 30_000 + output: + taxable_income: 63_663.24 + income_tax: 11_319.47 + +# 52 x 492.14 (clause 1(c)). Tax is 1,638 plus 17.5% of 9,991.28. The +# partner's $30,000 of wages are taxed on their own: 1,638 plus 17.5% of +# 14,400. Taxing the couple's $55,591.28 together would give 8,897.88. +- name: Each partner of a couple is taxed on their own income + period: 2027 + absolute_error_margin: 0.01 + input: + people: + retiree: + age: 70 + receiving_nz_super: true + has_partner: true + partner: + age: 45 + has_partner: true + employment_income: 30_000 + households: + household: + members: [retiree, partner] + output: + people: + retiree: + nz_superannuation: 25_591.28 + taxable_income: 25_591.28 + income_tax: 3_386.47 + partner: + nz_superannuation: 0 + taxable_income: 30_000 + income_tax: 4_158 + +# 52 x 372.55 (Social Security Act 2018 Schedule 4 Part 1 clause 1(d)). +# Section 350(3) grosses it up: $15,600 leaves 13,962 after tax, and the +# other 5,410.60 needs 5,410.60 / 0.825 = 6,558.30 of gross income, so the +# gross is 22,158.30 and the tax 2,785.70. +- name: Jobseeker Support is grossed up by the tax MSD pays on it + period: 2027 + absolute_error_margin: 0.01 + input: + age: 30 + jobseeker_support: 19_372.60 + output: + jobseeker_support_tax: 2_785.70 + taxable_income: 22_158.30 + income_tax: 2_785.70 + +- name: A Jobseeker Support grant at the clause 1(d) rate gives the same tax + period: 2027 + absolute_error_margin: 0.01 + input: + age: 30 + receiving_jobseeker_support: true + output: + jobseeker_support: 19_372.60 + jobseeker_support_tax: 2_785.70 + taxable_income: 22_158.30 + income_tax: 2_785.70 + +# The gross-up ignores other income. 1,638 + 17.5% of 16,558.30 = 4,535.70, +# of which the earnings bear 1,750. +- name: Wages do not change the tax MSD pays on Jobseeker Support + period: 2027 + absolute_error_margin: 0.01 + input: + age: 30 + jobseeker_support: 19_372.60 + employment_income: 10_000 + output: + jobseeker_support_tax: 2_785.70 + taxable_income: 32_158.30 + income_tax: 4_535.70 + +# 1,638 + 17.5% of 14,400. +- name: Wages alone are taxed as before + period: 2027 + absolute_error_margin: 0.01 + input: + age: 30 + employment_income: 30_000 + output: + jobseeker_support_tax: 0 + taxable_income: 30_000 + income_tax: 4_158 + +# Net income is the sum of all sources, so a loss reduces the benefit too +# (sections BC 4 and BC 5). +- name: A self-employment loss offsets NZ Superannuation + period: 2027 + absolute_error_margin: 0.01 + input: + age: 70 + receiving_nz_super: true + living_alone: true + self_employment_income: -40_000 + output: + taxable_income: 0 + income_tax: 0 + +# The tax MSD pays on Jobseeker Support depends on the benefit alone, so a +# loss that cancels the taxable income leaves it at 2,785.70 while the year's +# liability is 0. +- name: A self-employment loss can leave the liability below the tax MSD pays + period: 2027 + absolute_error_margin: 0.01 + input: + age: 30 + jobseeker_support: 19_372.60 + self_employment_income: -40_000 + output: + jobseeker_support_tax: 2_785.70 + taxable_income: 0 + income_tax: 0 + +# 52 x 538.24 from 1 April 2022, taxed at 10.5% to $14,000 and 17.5% to +# $48,000: 1,470 + 17.5% of 13,988.48. +- name: NZ Superannuation is taxed from the 2022-23 tax year + period: 2023 + absolute_error_margin: 0.01 + input: + age: 70 + receiving_nz_super: true + living_alone: true + output: + nz_superannuation: 27_988.48 + taxable_income: 27_988.48 + income_tax: 3_917.98 diff --git a/policyengine_nz/tests/test_benefit_income_tax.py b/policyengine_nz/tests/test_benefit_income_tax.py new file mode 100644 index 0000000..f41c381 --- /dev/null +++ b/policyengine_nz/tests/test_benefit_income_tax.py @@ -0,0 +1,763 @@ +"""Benefit income tax rules that YAML cases cannot state. + +Section 350(3) of the Social Security Act 2018 grosses Jobseeker Support up so +that what remains after tax equals the payment. These tests check that inverse +against the income tax schedule itself, at every bracket boundary of each tax +year from 2021-22 to 2027-28, and check simulations from 2022-23, when the +benefit rates start, to 2027-28. They also check what taxable income does +with the receipt flags and benefit amounts for a period that starts before +1 April 2022. +""" + +import math +from fractions import Fraction +from types import SimpleNamespace + +import numpy as np +import pytest +from policyengine_core import periods +from policyengine_core.experimental import MemoryConfig +from policyengine_core.parameters import ParameterScale +from policyengine_core.reforms import Reform +from policyengine_core.simulations import Simulation +from policyengine_core.warnings import MemoryConfigWarning + +from policyengine_nz import NewZealandTaxBenefitSystem +from policyengine_nz.variables.gov.msd.jobseeker.jobseeker_support_tax import ( + grossed_up_tax, +) + +SCHEDULE_PERIODS = range(2022, 2029) +PERIODS = range(2023, 2029) +BENEFITS = ["nz_superannuation", "jobseeker_support"] +FLAGS = ["receiving_nz_super", "receiving_jobseeker_support"] +# A simulation stores 32-bit floats, a step of up to 1/64 of a dollar at these +# amounts, so its results match to within 3 cents. +STORED = 0.03 + + +@pytest.fixture(scope="module") +def system(): + return NewZealandTaxBenefitSystem() + + +def _people(system, people, period): + situation = { + "people": { + name: {key: {str(period): value} for key, value in person.items()} + for name, person in people.items() + } + } + return Simulation(tax_benefit_system=system, situation=situation) + + +def _reformed(modify): + """The tax-benefit system with a reform that applies modify to its parameters.""" + + class _Reform(Reform): + def apply(self): + self.modify_parameters(modify) + + return _Reform(NewZealandTaxBenefitSystem()) + + +def _net_amounts(schedule): + """Amounts after tax at each threshold, a cent either side, and between.""" + thresholds = np.asarray(schedule.thresholds, dtype=float) + tax = np.array([schedule.calc(np.array([t]))[0] for t in thresholds]) + edges = thresholds - tax + amounts = [0.0, 0.01, 1.0] + for edge in edges[1:]: + amounts += [edge - 0.01, edge, edge + 0.01] + amounts += list((edges[:-1] + edges[1:]) / 2) + [edges[-1] + 50_000] + return np.array(sorted(amounts)) + + +@pytest.mark.parametrize("period", SCHEDULE_PERIODS) +def test_the_gross_up_leaves_the_payment_after_tax(system, period): + schedule = system.parameters(f"{period}-01-01").gov.ird.income_tax.schedule + net = _net_amounts(schedule) + tax = grossed_up_tax(net, schedule) + assert np.all(tax >= 0) + assert schedule.calc(net + tax) == pytest.approx(tax, abs=1e-6) + + +@pytest.mark.parametrize("period", PERIODS) +def test_a_benefit_only_recipient_owes_nothing_beyond_the_msd_tax(system, period): + schedule = system.parameters(f"{period}-01-01").gov.ird.income_tax.schedule + net = _net_amounts(schedule) + people = {f"p{i}": {"age": 30, "jobseeker_support": b} for i, b in enumerate(net)} + simulation = _people(system, people, period) + msd_tax = simulation.calculate("jobseeker_support_tax", period) + taxable = simulation.calculate("taxable_income", period) + assert taxable - msd_tax == pytest.approx(net, abs=STORED) + income_tax = simulation.calculate("income_tax", period) + assert income_tax - msd_tax == pytest.approx(0, abs=STORED) + + +def test_other_income_leaves_the_msd_tax_unchanged(system): + wages = [0, 10_000, 60_000, 100_000, 250_000] + people = { + f"p{i}": {"age": 30, "jobseeker_support": 19_372.60, "employment_income": w} + for i, w in enumerate(wages) + } + simulation = _people(system, people, 2027) + msd_tax = simulation.calculate("jobseeker_support_tax", 2027) + assert msd_tax == pytest.approx([2_785.70] * len(wages), abs=0.01) + + +def test_each_person_is_grossed_up_on_their_own(system): + # Four payments given directly to four people, whom the simulation puts + # in one benefit unit: each person's tax is the gross-up of their own + # payment, and two equal payments are not pooled. + payments = [13_936.00, 13_936.00, 19_372.60, 0.0] + people = { + f"p{i}": {"age": 40, "jobseeker_support": b} for i, b in enumerate(payments) + } + simulation = _people(system, people, 2027) + schedule = system.parameters("2027-01-01").gov.ird.income_tax.schedule + expected = [grossed_up_tax(np.array([b]), schedule)[0] for b in payments] + msd_tax = simulation.calculate("jobseeker_support_tax", 2027) + assert msd_tax == pytest.approx(expected, abs=STORED) + assert msd_tax[0] < grossed_up_tax(np.array([2 * 13_936.00]), schedule)[0] / 2 + + +def _couple(system, grants): + """Two childless partners in one benefit unit and household, in 2026-27.""" + period = "2027" + situation = { + "people": { + name: { + "age": {period: age}, + "has_partner": {period: True}, + "receiving_jobseeker_support": {period: grant}, + } + for name, age, grant in ( + ("first", 35, grants[0]), + ("second", 42, grants[1]), + ) + }, + "benefit_units": {"unit": {"adults": ["first", "second"], "children": []}}, + "households": {"household": {"members": ["first", "second"]}}, + } + return Simulation(tax_benefit_system=system, situation=situation) + + +def _each_partner(simulation, expected): + for name, amount in expected.items(): + values = simulation.calculate(name, "2027") + assert values == pytest.approx([amount] * 2, abs=STORED), name + + +@pytest.mark.parametrize( + "grants", [(True, False), (True, True)], ids=["one_grant", "both_granted"] +) +def test_each_partner_of_a_linked_couple_is_grossed_up_on_their_own(system, grants): + # With one grant, clause 1(j)(i) pays the childless couple 633.94 a week, + # half to each partner under regulation 191(2). With both granted, clause + # 1(g)(i) pays each partner 316.97 a week. Either way each partner gets + # 52 x 316.97 = 16,482.44. That leaves 2,520.44 above the 13,962 that + # $15,600 leaves after tax, which needs 2,520.44 / 0.825 = 3,055.08 of + # gross income at 17.5%, so each partner's tax is + # 18,655.08 - 16,482.44 = 2,172.64. + expected = { + "jobseeker_support": 16_482.44, + "jobseeker_support_tax": 2_172.64, + "taxable_income": 18_655.08, + "income_tax": 2_172.64, + } + _each_partner(_couple(system, grants), expected) + + +@pytest.fixture(scope="module") +def clause_1g_system(): + """A reform that raises only the clause 1(g)(i) rate, to $401 a week.""" + + def modify(parameters): + rates = parameters.gov.msd.jobseeker.payment_rates.rates + rates.couple_one_eligible.update( + start=periods.instant("2026-04-01"), value=401.0 + ) + return parameters + + return _reformed(modify) + + +@pytest.mark.parametrize( + "grants, expected", + [ + ((True, False), (16_482.44, 2_172.64)), + ((True, True), (20_852.00, 3_099.52)), + ], + ids=["one_grant", "both_granted"], +) +def test_two_grants_take_the_clause_1g_rate(clause_1g_system, grants, expected): + # The couple with one grant keeps clause 1(j)(i). Each partner of the + # couple with two gets 52 x 401 = 20,852, which leaves 6,890 above 13,962 + # and needs 6,890 / 0.825 = 8,351.52 of gross income at 17.5%, so each + # partner's tax is 23,951.52 - 20,852 = 3,099.52. + payment, tax = expected + amounts = { + "jobseeker_support": payment, + "jobseeker_support_tax": tax, + "taxable_income": payment + tax, + "income_tax": tax, + } + _each_partner(_couple(clause_1g_system, grants), amounts) + + +def test_a_small_schedule_gives_exact_gross_ups(): + # 10% to 100 and 50% above: 45 after tax is 50 gross, 90 is 100 gross, + # and 100 is 100 + 10 / 0.5 = 120 gross. + schedule = SimpleNamespace(thresholds=[0, 100], rates=[0.1, 0.5]) + net = np.array([-5.0, 0.0, 45.0, 90.0, 100.0]) + assert grossed_up_tax(net, schedule) == pytest.approx([0, 0, 5, 10, 20]) + + +def test_a_nan_amount_gives_nan(): + schedule = SimpleNamespace(thresholds=[0, 100], rates=[0.1, 0.5]) + tax = grossed_up_tax(np.array([np.nan, 45.0]), schedule) + assert np.isnan(tax[0]) + assert tax[1] == pytest.approx(5) + + +def test_a_tiny_rate_keeps_its_tax_and_a_large_tax_stays_finite(): + # 1,000 at a rate of 1e-20 owes 1e-17. A net amount of 1e308 at 50% owes + # 1e308, which a 64-bit float holds although the gross amount does not. + tiny = SimpleNamespace(thresholds=[0], rates=[1e-20]) + assert grossed_up_tax(np.array([1_000.0]), tiny)[0] == pytest.approx( + 1e-17, rel=1e-9 + ) + half = SimpleNamespace(thresholds=[0], rates=[0.5]) + assert grossed_up_tax(np.array([1e308]), half)[0] == 1e308 + + +def test_rates_just_below_one_leave_nothing_untaxed_and_nothing_taxed(system): + # The 2025-26 schedule with its top three rates just below 1. Nothing + # after tax owes nothing, and an amount in the first bracket owes + # 10.5 / 89.5 of itself. + schedule = system.parameters("2026-01-01").gov.ird.income_tax.schedule + rates = np.array(schedule.rates, dtype=float) + rates[-3:] = np.nextafter(1.0, 0.0) + steep = SimpleNamespace(thresholds=schedule.thresholds, rates=rates) + tax = grossed_up_tax(np.array([0.0, 1.0, 10_000.0]), steep) + assert tax[0] == 0 + assert tax[1:] == pytest.approx([0.105 / 0.895, 10_000 * 0.105 / 0.895]) + + +def _exact_bounds(thresholds, rates): + """The exact net amounts at the thresholds.""" + bounds = [Fraction(0)] + for k in range(len(thresholds) - 1): + width = Fraction(thresholds[k + 1]) - Fraction(thresholds[k]) + bounds.append(bounds[-1] + (1 - Fraction(rates[k])) * width) + return bounds + + +def _exact_fraction(net, thresholds, rates): + """The gross-up's tax in exact rational arithmetic, for a reference.""" + net = Fraction(net) + if net <= 0: + return Fraction(0) + bounds = _exact_bounds(thresholds, rates) + k = max(i for i, bound in enumerate(bounds) if bound <= net) + gross = Fraction(thresholds[k]) + (net - bounds[k]) / (1 - Fraction(rates[k])) + return gross - net + + +def _exact_tax(net, thresholds, rates): + """The gross-up in exact rational arithmetic, as a float.""" + return float(_exact_fraction(net, thresholds, rates)) + + +def test_a_large_bracket_keeps_its_small_net_width(): + # The middle bracket, at a rate just below 1, leaves 2**-53 of each of its + # 1e17 - 100 dollars, about 11.10 in all, so 61.10 after tax marks the top + # bracket. Subtracting a tax near 1e17 from the threshold would lose those + # 11.10 to rounding. + thresholds = [0.0, 100.0, 1e17] + rates = [0.5, float(np.nextafter(1.0, 0.0)), 0.1] + schedule = SimpleNamespace(thresholds=thresholds, rates=rates) + net = [55.0, 62.0, 100.0] + expected = [_exact_tax(n, thresholds, rates) for n in net] + assert grossed_up_tax(np.array(net), schedule) == pytest.approx(expected, rel=1e-12) + + +Q = float(np.nextafter(1.0, 0.0)) +TOP = float(np.finfo(float).max) +# One unit in the last place of the largest float. +TOP_ULP = Fraction(2) ** 971 +SIGNALLING = np.array([0x7F800001], dtype=np.uint32).view(np.float32) + + +def _around(values, steps=2): + """Each value and the floats up to steps away on either side.""" + out = set() + for value in values: + low = high = float(value) + out.add(low) + for _ in range(steps): + low = float(np.nextafter(low, -np.inf)) + high = float(np.nextafter(high, np.inf)) + out.update([low, high]) + return sorted(out) + + +def test_a_rounded_net_boundary_takes_the_exact_bracket(): + # 100 after tax is the exact net amount at the threshold of 100, so it + # owes nothing. The next bracket's 25 dollars leave 25 * 2**-53 after + # tax, which rounds away, so the next float above 100 owes about 25. + tied = SimpleNamespace(thresholds=[0.0, 100.0, 125.0], rates=[0.0, Q, 0.0]) + tax = grossed_up_tax(np.array([100.0, float(np.nextafter(100.0, 200.0))]), tied) + assert tax[0] == 0 + assert tax[1] == pytest.approx(25) + # 10% of 100 leaves an exact net amount 10 * 2**-54 below 90, which + # rounds to 90. So 90 lies above it and owes 10 plus that excess times + # Q / (1 - Q), about 5 more. + close = SimpleNamespace(thresholds=[0.0, 100.0], rates=[0.1, Q]) + assert grossed_up_tax(np.array([90.0]), close)[0] == pytest.approx(15) + + +@pytest.mark.parametrize( + "thresholds, rates", + [ + ([0.0, 100.0, 125.0], [0.0, Q, 0.0]), + ([0.0, 100.0], [0.1, Q]), + # The third review's six-bracket reform, with three rates just below 1. + ( + [0.0, 12314.1, 12573.35, 66449.16, 78100.0, 180000.0], + [Q, Q, Q, 0.30, 0.33, 0.39], + ), + ], +) +def test_amounts_around_each_net_boundary_owe_the_exact_tax(thresholds, rates): + bounds = [float(bound) for bound in _exact_bounds(thresholds, rates)] + nets = [net for net in _around([0.0, *bounds]) if net >= 0] + tax = grossed_up_tax( + np.array(nets), SimpleNamespace(thresholds=thresholds, rates=rates) + ) + for net, value in zip(nets, tax): + exact = _exact_fraction(net, thresholds, rates) + error = abs(Fraction(float(value)) - exact) + assert error <= 4 * Fraction(math.ulp(float(exact))), (net, value) + + +def test_widths_that_add_past_the_largest_float_give_no_overflow(): + # In 64-bit arithmetic the two widths add up past the largest float. The + # sums run in exact arithmetic, so no amount overflows. + schedule = SimpleNamespace( + thresholds=[0.0, 3 * 2.0**970, TOP], rates=[0.0, 0.0, 0.0] + ) + with np.errstate(all="raise"): + tax = grossed_up_tax(np.array([0.0, 1.0, TOP]), schedule) + assert tax.tolist() == [0, 0, 0] + + +def test_a_first_bracket_one_subnormal_wide_owes_nothing_on_nothing(): + # Half the smallest subnormal float rounds to 0, so the exact net amount + # at the second threshold rounds to the first's. + schedule = SimpleNamespace(thresholds=[0.0, 5e-324, 1.0], rates=[0.5, 0.2, 0.3]) + tax = grossed_up_tax(np.array([-1.0, -0.0, 0.0]), schedule) + assert tax.tolist() == [0, 0, 0] + + +@pytest.mark.parametrize( + "thresholds, rates, net", + [ + ([0.0, 1.0], [0.75, 0.5], TOP), + ([0.0], [0.8125], 4.1485226189130364e307), + ([0.0], [0.54], 1.5313682259938243e308), + ([0.0], [0.53125], 1.586199824878514e308), + ([0.0], [0.9999999999999997], 5.987520928604161e292), + ([0.0, 3.4927205416857597e292, 4.49064069645312e292], [0.5, 0.75, 0.5], TOP), + ([0.0], [0.5625], 1.3982057715595789e308), + ([0.0], [0.999999999999987], 2.3351331621556522e294), + ([0.0, 3.7422005803775996e291], [0.0, 0.75], 5.992310449541053e307), + ([0.0, 5.987520928604159e292], [0.5, 0.5], TOP), + ], +) +def test_a_tax_near_the_largest_float_is_close_or_raises(thresholds, rates, net): + exact = _exact_fraction(net, thresholds, rates) + schedule = SimpleNamespace(thresholds=thresholds, rates=rates) + try: + tax = grossed_up_tax(np.array([net]), schedule)[0] + except ValueError: + assert exact >= Fraction(TOP) - 4 * TOP_ULP + else: + assert abs(Fraction(float(tax)) - exact) <= 4 * TOP_ULP + + +@pytest.mark.parametrize( + "thresholds, rates", + [ + ([0.0, -TOP, TOP], [0.0, 0.0, 0.0]), + ([0.0, TOP, -TOP], [0.0, 0.0, 0.0]), + ([0.0], SIGNALLING), + (SIGNALLING, [0.5]), + ], +) +def test_a_bad_schedule_raises_its_own_error_under_strict_numpy(thresholds, rates): + schedule = SimpleNamespace(thresholds=thresholds, rates=rates) + with np.errstate(all="raise"): + with pytest.raises(ValueError, match="gross-up needs a schedule"): + grossed_up_tax(np.array([1.0]), schedule) + + +def test_a_signalling_nan_amount_gives_nan_under_strict_numpy(): + schedule = SimpleNamespace(thresholds=[0.0], rates=[0.5]) + with np.errstate(all="raise"): + assert np.isnan(grossed_up_tax(SIGNALLING, schedule)).all() + assert np.isnan(grossed_up_tax(SIGNALLING[0], schedule)) + + +def test_a_tax_too_large_for_a_float_raises(): + steep = SimpleNamespace(thresholds=[0], rates=[np.nextafter(1.0, 0.0)]) + with pytest.raises(ValueError, match="too large for a 64-bit float"): + grossed_up_tax(np.array([1e300]), steep) + + +@pytest.mark.parametrize( + "thresholds, rates", + [ + ([], []), + ([10, 100], [0.1, 0.2]), + ([0, 100, 100], [0.1, 0.2, 0.3]), + ([0, 100, 50], [0.1, 0.2, 0.3]), + ([0, 100], [-0.1, 0.2]), + ([0, 100], [0.1, 1.0]), + ([0, 100], [0.1, 1.5]), + ([0, 100], [0.1, np.nan]), + ([0, 100], [np.nan, 0.2]), + ([0, np.nan], [0.1, 0.2]), + ([0, 100, np.nan], [0.1, 0.2, 0.3]), + ([0, np.inf], [0.1, 0.2]), + ([0, 100], [0.1, 0.2, 0.3]), + ([0, 100, 200], [0.1, 0.2]), + ([[0, 100]], [[0.1, 0.2]]), + (0, 0.1), + ], +) +def test_a_schedule_the_gross_up_cannot_invert_raises(thresholds, rates): + schedule = SimpleNamespace(thresholds=thresholds, rates=rates) + with pytest.raises(ValueError, match="gross-up needs a schedule"): + grossed_up_tax(np.array([1_000.0]), schedule) + + +def test_a_nan_rate_in_a_real_schedule_raises(system): + # The 2024-25 schedule, with its 12.82% bracket made NaN as a reform could. + schedule = system.parameters("2025-01-01").gov.ird.income_tax.schedule + rates = np.array(schedule.rates, dtype=float) + assert np.sum(rates == 0.1282) == 1 + rates[rates == 0.1282] = np.nan + broken = SimpleNamespace(thresholds=schedule.thresholds, rates=rates) + with pytest.raises(ValueError, match="gross-up needs a schedule"): + grossed_up_tax(np.array([13_000.0, 19_000.0]), broken) + + +def test_a_nan_rate_set_by_a_reform_raises(): + # The same rate made NaN through Core's Parameter.update. + def modify(parameters): + rate = parameters.gov.ird.income_tax.schedule.brackets[1].rate + rate.update( + start=periods.instant("2024-04-01"), + stop=periods.instant("2025-03-31"), + value=float("nan"), + ) + return parameters + + simulation = _people( + _reformed(modify), {"p": {"age": 30, "jobseeker_support": 13_000}}, 2025 + ) + with pytest.raises(ValueError, match="gross-up needs a schedule"): + simulation.calculate("jobseeker_support_tax", 2025) + + +def test_an_average_rate_schedule_raises(): + # A reform can give the schedule average rates, which Core builds into a + # linear average-rate scale. The gross-up inverts only a marginal-rate one. + def modify(parameters): + node = parameters.gov.ird.income_tax + brackets = [ + {"threshold": {"2000-01-01": t}, "average_rate": {"2000-01-01": r}} + for t, r in ((0, 0.1), (100, 0.3)) + ] + scale = ParameterScale( + "gov.ird.income_tax.schedule", {"brackets": brackets}, None + ) + node.children["schedule"] = scale + node.schedule = scale + return parameters + + simulation = _people( + _reformed(modify), {"p": {"age": 30, "jobseeker_support": 45}}, 2027 + ) + with pytest.raises(TypeError, match="marginal-rate"): + simulation.calculate("jobseeker_support_tax", 2027) + + +@pytest.mark.parametrize("flag", FLAGS) +def test_a_recipient_before_april_2022_stops_the_calculation(system, flag): + # One recipient stops the calculation for everyone in it. + people = { + "earner": {"age": 40, "employment_income": 50_000}, + "recipient": {"age": 70, flag: True}, + } + simulation = _people(system, people, 2022) + with pytest.raises(ValueError, match=r"from 1 April 2022"): + simulation.calculate("taxable_income", 2022) + + +@pytest.mark.parametrize("benefit", BENEFITS) +def test_before_april_2022_an_amount_without_a_flag_is_left_out(system, benefit): + # Taxable income for such a period leaves out a benefit amount given + # without a receipt flag, as it did before. + people = { + "earner": {"age": 40, "employment_income": 50_000}, + "benefit": {"age": 30, benefit: 10_000}, + } + simulation = _people(system, people, 2022) + assert simulation.calculate("taxable_income", 2022) == pytest.approx([50_000, 0]) + assert simulation.calculate("income_tax", 2022) == pytest.approx([8_020, 0]) + + +def test_before_april_2022_an_earner_is_taxed_as_before(system): + # No benefit input is given, so nothing may run the benefit formulas, + # which raise for a period before their rates start. + simulation = _people( + system, {"earner": {"age": 40, "employment_income": 50_000}}, 2022 + ) + assert simulation.calculate("jobseeker_support_tax", 2022) == pytest.approx([0]) + assert simulation.calculate("taxable_income", 2022) == pytest.approx([50_000]) + assert simulation.calculate("income_tax", 2022) == pytest.approx([8_020]) + + +def test_before_april_2022_false_flags_and_zero_amounts_are_accepted(system): + people = { + "earner": {"age": 40, "employment_income": 50_000}, + "zero_benefits": { + "age": 30, + "nz_superannuation": 0, + "jobseeker_support": 0, + "receiving_nz_super": False, + "receiving_jobseeker_support": False, + }, + } + simulation = _people(system, people, 2022) + assert simulation.calculate("jobseeker_support_tax", 2022) == pytest.approx([0, 0]) + assert simulation.calculate("taxable_income", 2022) == pytest.approx([50_000, 0]) + assert simulation.calculate("income_tax", 2022) == pytest.approx([8_020, 0]) + + +@pytest.mark.parametrize("flag", FLAGS) +@pytest.mark.parametrize( + "default, branch, default_raises, branch_raises", + [ + (None, True, False, True), + (True, None, True, True), + (False, True, False, True), + (True, False, True, False), + ], + ids=["branch_only", "default_only", "false_on_default", "false_on_branch"], +) +def test_before_april_2022_each_branch_reads_its_own_flag( + system, flag, default, branch, default_raises, branch_raises +): + # A branch inherits the flags stored when it was made, and its own input + # replaces them. Each read uses a fresh simulation, so neither read sees + # the other's results. + for read_branch, raises in ((False, default_raises), (True, branch_raises)): + earner = {"age": 40, "employment_income": 50_000} + if default is not None: + earner[flag] = default + simulation = _people(system, {"earner": earner}, 2022) + fork = simulation.get_branch("fork") + if branch is not None: + fork.set_input(flag, "2022", np.array([branch])) + target = fork if read_branch else simulation + if raises: + with pytest.raises(ValueError, match=r"from 1 April 2022"): + target.calculate("taxable_income", 2022) + else: + assert target.calculate("taxable_income", 2022) == pytest.approx([50_000]) + assert target.calculate("income_tax", 2022) == pytest.approx([8_020]) + + +@pytest.mark.parametrize("flag", FLAGS) +def test_a_flag_for_a_year_from_july_2021_raises(system, flag): + # A year that starts on 1 July 2021 also starts before the benefit rates. + simulation = _people(system, {"person": {"age": 40}}, 2022) + simulation.set_input(flag, "year:2021-07", np.array([True])) + with pytest.raises(ValueError, match=r"from 1 April 2022"): + simulation.calculate("taxable_income", "year:2021-07") + + +# Core 3.38.0 reads a year that starts in April, keeps a value on disk under a +# memory limit, and drops a branch's results calculated from an input that +# the branch replaces. Taxable income reads both benefits and both receipt +# flags through each. + +# On $60,000 in 2025-26, tax is 1,638 + 6,632.50 + 1,950 = $10,220.50. The +# Jobseeker Support gross-up adds 10,000 * 0.105 / 0.895 = $1,173.18, taxed +# at 30%. +WITH_BENEFIT = { + "nz_superannuation": (60_000, 10_220.5), + "jobseeker_support": (61_173.18, 10_572.45), +} + + +def _earner(system, inputs): + """One earner aged 40 with inputs as {variable: {period: value}}.""" + person = {"age": {"2022": 40}, **inputs} + situation = { + "people": {"earner": person}, + "households": {"household": {"members": ["earner"]}}, + } + return Simulation(tax_benefit_system=system, situation=situation) + + +def _on_disk(simulation): + """Keep every input but age on disk from now on.""" + with pytest.warns(MemoryConfigWarning): + simulation.memory_config = MemoryConfig(0.0, priority_variables=["age"]) + + +@pytest.mark.parametrize("benefit", BENEFITS) +def test_a_benefit_for_a_year_from_april_leaves_other_years_working(system, benefit): + wages = {"2023": 50_000, "2027": 50_000} + simulation = _earner(system, {"employment_income": wages}) + simulation.set_input(benefit, "year:2025-04", np.array([10_000])) + assert simulation.calculate("taxable_income", "2023") == pytest.approx([50_000]) + assert simulation.calculate("income_tax", "2023") == pytest.approx([8_020]) + assert simulation.calculate("income_tax", "2027") == pytest.approx([7_658]) + + +@pytest.mark.parametrize("benefit", BENEFITS) +def test_a_benefit_for_a_year_from_april_counts_in_that_year(system, benefit): + year = "year:2025-04" + inputs = {"employment_income": {year: 50_000}, benefit: {year: 10_000}} + simulation = _earner(system, inputs) + taxable, tax = WITH_BENEFIT[benefit] + assert simulation.calculate("taxable_income", year) == pytest.approx( + [taxable], abs=STORED + ) + assert simulation.calculate("income_tax", year) == pytest.approx([tax], abs=STORED) + + +@pytest.mark.parametrize("value", [True, False]) +@pytest.mark.parametrize("flag", FLAGS) +def test_a_flag_for_a_year_from_april_leaves_2022_working(system, flag, value): + simulation = _earner(system, {"employment_income": {"2022": 50_000}}) + simulation.set_input(flag, "year:2025-04", np.array([value])) + assert simulation.calculate("taxable_income", "2022") == pytest.approx([50_000]) + assert simulation.calculate("income_tax", "2022") == pytest.approx([8_020]) + + +@pytest.mark.parametrize("flag", FLAGS) +def test_a_flag_for_a_year_from_april_2021_counts_in_that_year(system, flag): + year = "year:2021-04" + for value in (False, True): + inputs = {"employment_income": {year: 50_000}, flag: {year: value}} + simulation = _earner(system, inputs) + if value: + with pytest.raises(ValueError, match=r"from 1 April 2022"): + simulation.calculate("taxable_income", year) + else: + assert simulation.calculate("income_tax", year) == pytest.approx([8_020]) + + +@pytest.mark.parametrize("flag", FLAGS) +def test_a_flag_kept_on_disk_is_read(system, flag): + for value in (False, True): + simulation = _earner(system, {}) + _on_disk(simulation) + simulation.set_input("employment_income", "2022", np.array([50_000])) + simulation.set_input(flag, "2022", np.array([value])) + holder, year = simulation.get_holder(flag), periods.period("2022") + assert holder._memory_storage.get(year) is None + assert holder._disk_storage.get(year).tolist() == [value] + if value: + with pytest.raises(ValueError, match=r"from 1 April 2022"): + simulation.calculate("taxable_income", "2022") + else: + assert simulation.calculate("income_tax", "2022") == pytest.approx([8_020]) + + +@pytest.mark.parametrize("benefit", BENEFITS) +def test_a_benefit_kept_on_disk_is_taxed(system, benefit): + simulation = _earner(system, {}) + _on_disk(simulation) + simulation.set_input("employment_income", "2026", np.array([50_000])) + simulation.set_input(benefit, "2026", np.array([10_000])) + holder, year = simulation.get_holder(benefit), periods.period("2026") + assert holder._memory_storage.get(year) is None + assert holder._disk_storage.get(year).tolist() == [10_000] + taxable, tax = WITH_BENEFIT[benefit] + assert simulation.calculate("taxable_income", "2026") == pytest.approx( + [taxable], abs=STORED + ) + assert simulation.calculate("income_tax", "2026") == pytest.approx( + [tax], abs=STORED + ) + + +@pytest.mark.parametrize("benefit", BENEFITS) +def test_a_branch_made_after_a_calculation_taxes_its_own_benefit(system, benefit): + parent = _earner(system, {"employment_income": {"2026": 50_000}}) + assert parent.calculate("income_tax", "2026") == pytest.approx([7_658]) + branch = parent.get_branch("benefit") + branch.set_input(benefit, "2026", np.array([10_000])) + taxable, tax = WITH_BENEFIT[benefit] + assert branch.calculate("taxable_income", "2026") == pytest.approx( + [taxable], abs=STORED + ) + assert branch.calculate("income_tax", "2026") == pytest.approx([tax], abs=STORED) + assert parent.calculate("income_tax", "2026") == pytest.approx([7_658]) + + +_HAS_WIDER_LONGDOUBLE = np.finfo(np.longdouble).max > np.finfo(float).max + + +@pytest.mark.skipif( + not _HAS_WIDER_LONGDOUBLE, + reason="requires a longdouble wider than 64-bit float", +) +def test_wider_floating_inputs_match_quiet_mode_under_strict_numpy(): + basic = SimpleNamespace(thresholds=[0.0], rates=[0.5]) + underflow_rate = SimpleNamespace( + thresholds=[0.0], rates=np.array([np.longdouble("1e-400")]) + ) + with np.errstate(all="raise"): + assert grossed_up_tax(np.array([100.0]), underflow_rate).tolist() == [0.0] + assert grossed_up_tax(np.array([np.longdouble("1e-400")]), basic).tolist() == [ + 0.0 + ] + assert grossed_up_tax(np.array([np.longdouble("-1e-400")]), basic).tolist() == [ + 0.0 + ] + assert grossed_up_tax(np.array([np.longdouble("-1e400")]), basic).tolist() == [ + 0.0 + ] + overflow_net = grossed_up_tax(np.array([np.longdouble("1e400")]), basic) + with np.errstate(all="ignore"): + quiet_overflow_net = grossed_up_tax(np.array([np.longdouble("1e400")]), basic) + assert np.array_equal(overflow_net, quiet_overflow_net) + + for bad_schedule in ( + SimpleNamespace(thresholds=[0.0], rates=np.array([np.longdouble("1e400")])), + SimpleNamespace( + thresholds=np.array([np.longdouble("0"), np.longdouble("1e400")]), + rates=[0.5, 0.5], + ), + SimpleNamespace( + thresholds=np.array([np.longdouble("0"), np.longdouble("1e-400")]), + rates=[0.5, 0.2], + ), + ): + with np.errstate(all="raise"): + with pytest.raises(ValueError, match="gross-up needs a schedule"): + grossed_up_tax(np.array([100.0]), bad_schedule) + + +def test_a_subnormal_tied_boundary_with_strict_rounding_owes_nothing_on_zero(): + schedule = SimpleNamespace(thresholds=[0.0, 5e-324], rates=[0.75, Q]) + assert grossed_up_tax(np.array([0.0]), schedule).tolist() == [0.0] diff --git a/policyengine_nz/variables/gov/ird/income_tax/income_tax.py b/policyengine_nz/variables/gov/ird/income_tax/income_tax.py index 3f4f78e..0481c39 100644 --- a/policyengine_nz/variables/gov/ird/income_tax/income_tax.py +++ b/policyengine_nz/variables/gov/ird/income_tax/income_tax.py @@ -9,10 +9,18 @@ class income_tax(Variable): definition_period = YEAR label = "Income tax" documentation = ( - "Annual personal income tax at basic rates before credits. Bare year " - "labels refer to the tax year ending on 31 March of that year. " - "Provide the income totals for that tax year. The schedule starts " - "with the 2021-22 tax year (period 2022); earlier periods raise an " + "Annual personal income tax at basic rates before credits, the year's " + "liability on taxable_income. Bare year labels refer to the tax year " + "ending on 31 March of that year. Provide the income totals for that " + "tax year. For a Jobseeker Support recipient, jobseeker_support_tax is " + "a separate estimate of the tax that the model assumes MSD pays to " + "Inland Revenue on the benefit, as section 350(2) of the Social " + "Security Act 2018 allows. income_tax less jobseeker_support_tax is the " + "balance after that payment, and it is negative when a loss brings the " + "liability below the payment. In 2026-27, $19,372.60 of Jobseeker " + "Support beside a $40,000 self-employment loss gives $2,785.70 of " + "jobseeker_support_tax and no income tax. The schedule starts with the " + "2021-22 tax year (period 2022), and an earlier period raises an " "error." ) reference = [ diff --git a/policyengine_nz/variables/gov/ird/income_tax/taxable_income.py b/policyengine_nz/variables/gov/ird/income_tax/taxable_income.py index 603aa44..f04b28a 100644 --- a/policyengine_nz/variables/gov/ird/income_tax/taxable_income.py +++ b/policyengine_nz/variables/gov/ird/income_tax/taxable_income.py @@ -2,6 +2,29 @@ from policyengine_nz.model_api import * +ACT = "https://www.legislation.govt.nz/act/public/2007/0097/latest/" + + +def _other_income(person, period): + return ( + person("employment_income", period) + + person("self_employment_income", period) + + person("investment_income", period) + ) + + +def benefit_recipients(person, period): + """Who receives NZ Superannuation or Jobseeker Support, by flag. + + A person counts when receiving_nz_super or receiving_jobseeker_support + marks them as a recipient. The function reads only the flags, so neither + benefit's formula runs. Both formulas raise for a period that starts + before their rates do on 1 April 2022. + """ + return person("receiving_nz_super", period) | person( + "receiving_jobseeker_support", period + ) + class taxable_income(Variable): value_type = float @@ -9,18 +32,43 @@ class taxable_income(Variable): definition_period = YEAR label = "Taxable income" documentation = ( - "Approximate annual taxable income from the modeled income sources, " - "assuming no additional deductions or available tax losses." + "Net income from the modelled sources, floored at zero (sections BC 4 " + "and BC 5). The sources are employment, self-employment and " + "investment income, NZ Superannuation (section CF 1(1)(e)), and " + "Jobseeker Support (section CF 1(1)(c)) together with " + "jobseeker_support_tax, the income tax that the model assumes MSD " + "pays on it, which section 351(b)(iv) of the Social Security Act 2018 " + "makes the person's income. The model offsets a loss " + "in one modelled source against the others, and assumes no other " + "income, no further deductions and no available tax losses. The " + "benefit rates start on 1 April 2022, and for a period that starts " + "earlier taxable income leaves out both benefits. It raises an error, " + "for every person in the calculation, when receiving_nz_super or " + "receiving_jobseeker_support marks anyone as a recipient, and leaves " + "out an amount of either benefit given without one of those flags." ) reference = ( - "https://www.legislation.govt.nz/act/public/2007/97/en/latest/parts/DLM1512313/" + ACT + "DLM1512339.html", + ACT + "DLM1512344.html", + ACT + "DLM1512819.html", + "https://www.legislation.govt.nz/act/public/2018/0032/latest/DLM6783844.html", ) unit = NZD def formula(person, period, parameters): + if np.any(benefit_recipients(person, period)): + raise ValueError( + "NZ Superannuation and Jobseeker Support are modelled from 1 April " + f"2022, so taxable income for period {period} cannot include them. " + "Use a period that starts on or after 1 April 2022, such as 2023." + ) + return max_(_other_income(person, period), 0) + + def formula_2022_04_01(person, period, parameters): income = ( - person("employment_income", period) - + person("self_employment_income", period) - + person("investment_income", period) + _other_income(person, period) + + person("nz_superannuation", period) + + person("jobseeker_support", period) + + person("jobseeker_support_tax", period) ) return max_(income, 0) diff --git a/policyengine_nz/variables/gov/msd/jobseeker/jobseeker_support.py b/policyengine_nz/variables/gov/msd/jobseeker/jobseeker_support.py index 8d4627b..e0b4acc 100644 --- a/policyengine_nz/variables/gov/msd/jobseeker/jobseeker_support.py +++ b/policyengine_nz/variables/gov/msd/jobseeker/jobseeker_support.py @@ -230,9 +230,11 @@ class jobseeker_support(Variable): "52 times the weekly Jobseeker Support MSD pays the person, at the rates in " "force on the period's start date. A bare year N starts on 1 January N and " "stands for the tax year ending on 31 March N, so it reads the rates from 1 " - "April N - 1. The amount is net cash: MSD pays the income tax on an " - "instalment to Inland Revenue on top of it (section 350), and that tax " - "counts as the person's income (section 351). Under regulation 191(2) of " + "April N - 1. The amount is net cash. The model assumes MSD pays the " + "income tax on each instalment to Inland Revenue on top of it, as " + "section 350(2) allows, and that tax counts as the person's income " + "(section 351). jobseeker_support_tax models that tax. Under " + "regulation 191(2) of " "the Social Security Regulations 2018, MSD pays a " "clause 1(j) couple rate half to the beneficiary and half to the partner: " "in a benefit unit of two partners in one household each gets half, and a " diff --git a/policyengine_nz/variables/gov/msd/jobseeker/jobseeker_support_tax.py b/policyengine_nz/variables/gov/msd/jobseeker/jobseeker_support_tax.py new file mode 100644 index 0000000..18ddedf --- /dev/null +++ b/policyengine_nz/variables/gov/msd/jobseeker/jobseeker_support_tax.py @@ -0,0 +1,133 @@ +"""Income tax that the model assumes MSD pays on Jobseeker Support.""" + +from fractions import Fraction + +from policyengine_core.taxscales import MarginalRateTaxScale +from policyengine_nz.model_api import * + +SSA = "https://www.legislation.govt.nz/act/public/2018/0032/latest/" + + +def _exact_parts(values): + """Each Fraction as its nearest float, the rest as a float and its sign.""" + near = np.array([float(value) for value in values]) + rests = [value - Fraction(x) for value, x in zip(values, near)] + rest = np.array([float(r) for r in rests]) + sign = np.array([(r > 0) - (r < 0) for r in rests]) + return near, rest, sign + + +def grossed_up_tax(net, schedule): + """Tax on the gross amount that the schedule's tax reduces to net. + + The schedule's tax rises by each bracket's rate, below 1, so the amount left + after tax rises with the gross amount, and each net amount has one gross + amount. The function adds up, in exact rational arithmetic, the tax on each + full bracket and the amount it leaves after tax. It finds the bracket whose + net amounts hold the net amount, comparing exactly, and adds the tax at the + bracket's threshold to the net amount's excess over the bracket's lowest net + amount, times the bracket's rate over one minus that rate. A net amount at + or below zero gives no tax, and a NaN gives NaN. + + The function reads the schedule's thresholds and rates as arrays of 64-bit + floats, as NumPy converts them, and checks the converted arrays. For a + schedule built from a Core parameter scale, these are the brackets that + Core builds for the instant. For a finite net amount, the result lies + within four units in the last place of the exact tax on those converted + values, or within 1e-300 of it, where a subnormal float loses precision. + The function raises a ValueError when the exact tax exceeds the largest + 64-bit float by more than four units in the last place, and it may raise + one when the exact tax lies within four such units of the largest float. + It raises no FloatingPointError under any NumPy error setting. + """ + # Converting a signalling NaN or wide floating dtype (e.g., longdouble) + # can raise invalid, overflow, or underflow before the checks below run. + with np.errstate(over="ignore", under="ignore", invalid="ignore"): + thresholds = np.asarray(schedule.thresholds, dtype=float) + rates = np.asarray(schedule.rates, dtype=float) + net = np.asarray(net, dtype=float) + valid = ( + thresholds.ndim == 1 + and rates.shape == thresholds.shape + and len(thresholds) > 0 + and np.all(np.isfinite(thresholds)) + and thresholds[0] == 0 + and np.all(thresholds[1:] > thresholds[:-1]) + and np.all((rates >= 0) & (rates < 1)) + ) + if not valid: + raise ValueError( + "The gross-up needs a schedule of finite thresholds, with one rate " + "for each, whose first threshold is 0, whose thresholds rise and " + "whose rates lie in [0, 1)." + ) + net_at, tax_at = [Fraction(0)], [Fraction(0)] + for low, high, rate in zip(thresholds[:-1], thresholds[1:], rates[:-1]): + width = Fraction(high) - Fraction(low) + net_at.append(net_at[-1] + (1 - Fraction(rate)) * width) + tax_at.append(tax_at[-1] + Fraction(rate) * width) + net_near, net_rest, net_sign = _exact_parts(net_at) + tax_near = np.array([float(value) for value in tax_at]) + # A net amount at or below zero, or a NaN, becomes 0, which takes the + # first bracket with no excess and so gives no tax. + amount = np.where(net > 0, net, 0.0) + # The exact net amounts at the thresholds rise, so their nearest floats + # never fall, and among those that round to one float, the signs of their + # rests never fall. The bracket starts at the last threshold whose exact + # net amount is at most the amount. + below = np.searchsorted(net_near, amount, side="left") + tied = np.searchsorted(net_near, amount, side="right") + at_most = np.concatenate([[0], np.cumsum(net_sign <= 0)]) + bracket = below + at_most[tied] - at_most[below] - 1 + rate = rates[bracket] + with np.errstate(over="ignore", invalid="ignore", under="ignore"): + excess = (amount - net_near[bracket]) - net_rest[bracket] + above = np.where(rate == 0, 0, excess * (rate / (1 - rate))) + tax = tax_near[bracket] + above + tax = np.where(np.isnan(net), np.nan, tax) + if np.any(np.isfinite(net) & ~np.isfinite(tax)): + raise ValueError("The tax on a net amount is too large for a 64-bit float.") + return tax + + +class jobseeker_support_tax(Variable): + value_type = float + entity = Person + definition_period = YEAR + label = "Income tax the model assumes MSD pays on Jobseeker Support" + documentation = ( + "The income tax that the model assumes MSD pays to Inland Revenue on " + "the person's jobseeker_support instead of deducting it from the " + "payments, as section 350(2) of the Social Security Act 2018 allows. " + "Section 350(3) grosses each payment up so that what remains after tax " + "equals the payment, and section 351(b)(iv) makes the tax the person's " + "income under the Income Tax Act 2007. The model grosses up the " + "year's jobseeker_support, apart from the person's other income, on the " + "personal income tax schedule for the tax year. Section 350(3) uses the " + "rate that the Commissioner determines for each payment, in consultation " + "with MSD's chief executive, under section RD 11(3) of the Income Tax Act " + "2007, so the tax on each payment can differ from this annual figure. " + "The model grosses up each partner's share of a couple rate " + "separately. The benefit rates start on 1 April 2022, and a " + "period that starts earlier gives 0. A reform that makes the income " + "tax schedule anything other than a marginal-rate scale raises an " + "error." + ) + reference = ( + SSA + "DLM6783836.html", + SSA + "DLM6783843.html", + SSA + "DLM6783844.html", + "https://www.legislation.govt.nz/act/public/2007/0097/latest/DLM1519963.html", + ) + unit = NZD + + def formula_2022_04_01(person, period, parameters): + benefit = person("jobseeker_support", period) + schedule = parameters(period).gov.ird.income_tax.schedule + if not isinstance(schedule, MarginalRateTaxScale): + raise TypeError( + "The gross-up inverts a marginal-rate income tax schedule, and " + f"the schedule for period {period} is a " + f"{type(schedule).__name__}." + ) + return grossed_up_tax(benefit, schedule)