From 4400b67e111cdd1aa442037545d95cd8041f9f10 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Sun, 25 Oct 2026 08:01:56 +0000 Subject: [PATCH 1/6] Track unused Income Tax trading losses without repeating supplied losses --- changelog.d/2087.fixed.md | 1 + docs/engineering/income-tax-trading-losses.md | 55 ++++ .../hmrc/income_tax/reliefs/loss_relief.yaml | 12 +- .../reliefs/trade_loss_carry_forward.yaml | 246 ++++++++++++++++++ .../trade_loss_net_pay_carry_forward.yaml | 58 +++++ .../test_income_tax_loss_carry_forward.py | 170 ++++++++++++ policyengine_uk/utils/pensions.py | 8 +- policyengine_uk/utils/supplied_inputs.py | 1 + .../hmrc/income_tax/reliefs/loss_relief.py | 62 ++++- ...rade_loss_relief_against_general_income.py | 20 +- .../variables/input/trading_loss.py | 11 +- 11 files changed, 617 insertions(+), 27 deletions(-) create mode 100644 changelog.d/2087.fixed.md create mode 100644 docs/engineering/income-tax-trading-losses.md create mode 100644 policyengine_uk/tests/policy/baseline/gov/hmrc/income_tax/reliefs/trade_loss_carry_forward.yaml create mode 100644 policyengine_uk/tests/policy/baseline/gov/hmrc/income_tax/reliefs/trade_loss_net_pay_carry_forward.yaml create mode 100644 policyengine_uk/tests/test_income_tax_loss_carry_forward.py diff --git a/changelog.d/2087.fixed.md b/changelog.d/2087.fixed.md new file mode 100644 index 0000000000..e06bc35810 --- /dev/null +++ b/changelog.d/2087.fixed.md @@ -0,0 +1 @@ +Recognise Income Tax trading losses only in their supplied year and carry forward unused losses after relief already given, retaining explicit opening-stock overrides and the separate Class 4 balance. diff --git a/docs/engineering/income-tax-trading-losses.md b/docs/engineering/income-tax-trading-losses.md new file mode 100644 index 0000000000..caf815faea --- /dev/null +++ b/docs/engineering/income-tax-trading-losses.md @@ -0,0 +1,55 @@ +# Income Tax trading losses + +Supply `trading_loss` as the positive loss made in each tax year. Income Tax +recognises only a value explicitly supplied for that year as a current loss; +an earlier value inherited or uprated by the engine is not a new loss. + +The existing general-income formula assumes a commercial trade and a claim +against the loss-making year's income under ITA 2007 section 64. It retains +the trading-allowance election, available-income limit and section 24A cap. +It does not choose a previous-year claim or optimise claim ordering. +The available-income limit subtracts the existing ordinary net-pay pension +relief, which is already deducted at Step 1 and cannot also consume a loss +at Step 2. This does not establish the ordering of claimed excess employee +contributions or other pension reliefs. + +`loss_relief` is the opening unrelieved Income Tax loss stock. The model assumes +an eligible carry-forward claim under sections 83 and 84 for the same +continuing trade, or a trade pool whose eligibility the caller has assessed. +It does not reconstruct unrelated trades or establish their eligibility from +the person's aggregate profit and loss inputs. + +The opening stock for a year follows the actual supplied loss history. Each +earlier year consumes only the stock absorbed by that year's trading profits, +after capital allowances and the trading allowance. Only the year's eligible +new loss left after actual general-income relief enters the next balance. +Relief consumption is the amount deducted from income, rather than the tax +saving. An allowance year can leave an older loss unused. A stock may appear +in several zero-profit years without being deducted in any of them. + +An explicit `loss_relief` input, including zero, overrides that year's opening +stock and starts a new accounting segment. Use it to reconcile earlier +history or relief obtained outside the model, including other Income Tax or +capital-gains claims. Do not enter a loss again merely because it remains +unused. The stock can exceed the current deduction: taxable trading profits +remain floored at zero, and brought-forward losses do not reduce other income. + +The annual formula resolves past opening balances in ascending order before +requesting each year's allowance and general-income relief. It uses ordinary +engine calculation caching and the existing supplied-input API, without +writing inputs or private caches. The pension annual-allowance net-pay +recomputation also recognises only the exact supplied current loss; its other +pension rules are unchanged. + +Class 4 National Insurance keeps its independent balance. A loss used against +pay for Income Tax can still remain available against later Class 4 profits. +Other programmes retain their own loss rules; callers should still supply +later zeros where those programmes read an inherited `trading_loss` value. + +These conventions do not implement every historical, early-year, terminal, +foreign-trade, partnership or external-relief election. They do not establish +national impacts, input coverage or population accuracy. + +References: [ITA 2007 sections 63–65](https://www.legislation.gov.uk/ukpga/2007/3/part/4/chapter/2), +[sections 83–84](https://www.legislation.gov.uk/ukpga/2007/3/part/4/chapter/2/crossheading/carryforward-trade-loss-relief), +and [section 24A](https://www.legislation.gov.uk/ukpga/2007/3/section/24A). diff --git a/policyengine_uk/tests/policy/baseline/gov/hmrc/income_tax/reliefs/loss_relief.yaml b/policyengine_uk/tests/policy/baseline/gov/hmrc/income_tax/reliefs/loss_relief.yaml index 31a1e52134..aab04b46fd 100644 --- a/policyengine_uk/tests/policy/baseline/gov/hmrc/income_tax/reliefs/loss_relief.yaml +++ b/policyengine_uk/tests/policy/baseline/gov/hmrc/income_tax/reliefs/loss_relief.yaml @@ -1,6 +1,6 @@ -# loss_relief holds trade losses brought forward from earlier years (ITA 2007 -# s.83). A loss made in the year itself is trading_loss, relieved against -# general income instead (see trade_loss_relief_against_general_income.yaml). +# loss_relief is opening unrelieved trade-loss stock (ITA 2007 s.83). +# Explicit entries override the automatically computed opening balance. +# A new loss is trading_loss, relieved against general income first. - name: Losses brought forward come off the trade's profits period: 2024 @@ -25,7 +25,7 @@ taxable_employment_income: 20_000 adjusted_net_income: 20_000 -- name: Last year's trading loss is not brought forward automatically +- name: Last year's unused trading loss is brought forward automatically period: 2024 absolute_error_margin: 0 input: @@ -35,5 +35,5 @@ 2023: 5_000 2024: 0 output: - loss_relief: 0 - taxable_self_employment_income: 10_000 + loss_relief: 5_000 + taxable_self_employment_income: 5_000 diff --git a/policyengine_uk/tests/policy/baseline/gov/hmrc/income_tax/reliefs/trade_loss_carry_forward.yaml b/policyengine_uk/tests/policy/baseline/gov/hmrc/income_tax/reliefs/trade_loss_carry_forward.yaml new file mode 100644 index 0000000000..b045ca7c1e --- /dev/null +++ b/policyengine_uk/tests/policy/baseline/gov/hmrc/income_tax/reliefs/trade_loss_carry_forward.yaml @@ -0,0 +1,246 @@ +- name: A loss already relieved against pay is not a new loss next year + period: 2026 + absolute_error_margin: 0.01 + input: + employment_income: + 2025: 40_000 + 2026: 40_000 + trading_loss: + 2025: 10_000 + output: + trade_loss_relief_against_general_income: 0 + loss_relief: 0 + net_income: 40_000 + +- name: Only the loss not used against pay survives later trade profits + period: 2026 + absolute_error_margin: 0.01 + input: + age: 40 + taxable_social_security_income: 0 + employment_income: + 2023: 2_000 + 2024: 0 + 2025: 0 + 2026: 0 + self_employment_income: + 2023: 0 + 2024: 3_000 + 2025: 1_000 + 2026: 4_000 + trading_loss: + 2023: 7_000 + trading_allowance_deduction: + 2023: 0 + 2024: 0 + 2025: 0 + 2026: 0 + output: + # 7,000 - 2,000 general relief - 3,000 profits - 1,000 profits. + loss_relief: 1_000 + trade_loss_relief_against_general_income: 0 + taxable_self_employment_income: 3_000 + net_income: 3_000 + +- name: Cap-limited Income Tax loss and Class 4 loss have distinct balances + period: 2025 + absolute_error_margin: 0.01 + input: + age: 40 + taxable_social_security_income: 0 + employment_income: + 2024: 150_000 + 2025: 0 + self_employment_income: + 2024: 0 + 2025: 40_000 + trading_loss: + 2024: 80_000 + trading_allowance_deduction: + 2024: 0 + 2025: 0 + output: + # The 50,000 s64 deduction against pay does not consume Class 4 stock. + loss_relief: 30_000 + trade_loss_relief_against_general_income: 0 + taxable_self_employment_income: 10_000 + ni_class_4_losses_brought_forward: 80_000 + ni_class_4_profits: 0 + +- name: A supplied opening balance is consumed rather than repeated + period: 2026 + absolute_error_margin: 0.01 + input: + age: 40 + taxable_social_security_income: 0 + loss_relief: + 2024: 7_000 + self_employment_income: + 2024: 3_000 + 2025: 3_000 + 2026: 3_000 + trading_allowance_deduction: + 2024: 0 + 2025: 0 + 2026: 0 + output: + loss_relief: 1_000 + taxable_self_employment_income: 2_000 + +- name: A supplied zero opening balance reconciles external loss use + period: 2026 + absolute_error_margin: 0.01 + input: + age: 40 + taxable_social_security_income: 0 + trading_loss: + 2023: 10_000 + loss_relief: + 2025: 0 + self_employment_income: + 2023: 0 + 2024: 0 + 2025: 0 + 2026: 5_000 + trading_allowance_deduction: + 2026: 0 + output: + loss_relief: 0 + taxable_self_employment_income: 5_000 + +- name: A trading allowance year preserves unused earlier loss stock + period: 2025 + absolute_error_margin: 0.01 + input: + age: 40 + taxable_social_security_income: 0 + loss_relief: + 2024: 2_000 + self_employment_income: + 2024: 800 + 2025: 5_000 + self_employment_gross_receipts: + 2024: 900 + 2025: 6_000 + output: + loss_relief: 2_000 + trading_allowance_deduction: 0 + taxable_self_employment_income: 3_000 + +- name: Allowance treatment cannot create a carry-forward expense loss + period: 2025 + absolute_error_margin: 0.01 + input: + age: 40 + taxable_social_security_income: 0 + employment_income: + 2024: 40_000 + 2025: 0 + self_employment_income: + 2024: 800 + 2025: 5_000 + self_employment_gross_receipts: + 2024: 900 + 2025: 6_000 + trading_loss: + 2024: 200 + output: + loss_relief: 0 + trade_loss_relief_against_general_income: 0 + taxable_self_employment_income: 5_000 + +- name: A sixteen-year gap preserves nominal unrelieved loss + period: 2026 + absolute_error_margin: 0.01 + input: + age: 40 + # Isolate trading losses from unrelated historical pension defaults. + taxable_social_security_income: + 2010: 0 + 2011: 0 + 2012: 0 + 2013: 0 + 2014: 0 + 2015: 0 + 2016: 0 + 2017: 0 + 2018: 0 + 2019: 0 + 2020: 0 + 2021: 0 + 2022: 0 + 2023: 0 + 2024: 0 + 2025: 0 + 2026: 0 + employment_income: 0 + self_employment_income: + 2010: 0 + 2026: 6_000 + trading_loss: + 2010: 5_000 + trading_allowance_deduction: + 2010: 0 + 2026: 0 + output: + loss_relief: 5_000 + trade_loss_relief_against_general_income: 0 + taxable_self_employment_income: 1_000 + +- name: Pension net-pay reconstruction ignores a loss supplied for last year + period: 2026 + absolute_error_margin: 0.01 + input: + age: 45 + taxable_social_security_income: 0 + employment_income_before_lsr: + 2025: 40_000 + 2026: 40_000 + pension_contributions_via_salary_sacrifice: 0 + employer_pension_contributions: 0 + employee_pension_contributions_reported: + 2025: 0 + 2026: 1_000 + trading_loss: + 2025: 10_000 + output: + loss_relief: 0 + trade_loss_relief_against_general_income: 0 + pension_annual_allowance_threshold_income: 39_000 + pension_annual_allowance_adjusted_income: 40_000 + +- name: A negative loss input does not give negative current relief + period: 2026 + absolute_error_margin: 0.01 + input: + employment_income: 40_000 + trading_loss: -200 + output: + trade_loss_relief_against_general_income: 0 + net_income: 40_000 + +- name: New loss use does not add the same loss to an old balance + period: 2026 + absolute_error_margin: 0.01 + input: + age: 40 + taxable_social_security_income: 0 + employment_income: + 2024: 0 + 2025: 10_000 + 2026: 0 + self_employment_income: + 2024: 0 + 2025: 2_000 + 2026: 4_000 + trading_loss: + 2024: 5_000 + 2025: 3_000 + trading_allowance_deduction: + 2024: 0 + 2025: 0 + 2026: 0 + output: + loss_relief: 3_000 + trade_loss_relief_against_general_income: 0 + taxable_self_employment_income: 1_000 diff --git a/policyengine_uk/tests/policy/baseline/gov/hmrc/income_tax/reliefs/trade_loss_net_pay_carry_forward.yaml b/policyengine_uk/tests/policy/baseline/gov/hmrc/income_tax/reliefs/trade_loss_net_pay_carry_forward.yaml new file mode 100644 index 0000000000..3641479b7b --- /dev/null +++ b/policyengine_uk/tests/policy/baseline/gov/hmrc/income_tax/reliefs/trade_loss_net_pay_carry_forward.yaml @@ -0,0 +1,58 @@ +- name: Ordinary net-pay relief leaves only the remaining pay for current loss use + period: 2024 + absolute_error_margin: 0.01 + input: + age: 40 + taxable_social_security_income: 0 + employment_income: + 2024: 2_000 + 2025: 0 + employee_pension_contributions: + 2024: 1_000 + 2025: 0 + self_employment_income: + 2024: 0 + 2025: 10_000 + trading_loss: + 2024: 10_000 + trading_allowance_deduction: + 2024: 0 + 2025: 0 + output: + trade_loss_relief_against_general_income: 1_000 + loss_relief: + 2025: 9_000 + taxable_self_employment_income: + 2025: 1_000 + +- name: No ordinary net-pay deduction leaves the same income available for loss use + period: 2024 + absolute_error_margin: 0.01 + input: + age: [40, 75, 40] + taxable_social_security_income: [0, 0, 0] + employment_income: + 2024: [2_000, 2_000, 2_000] + 2025: [0, 0, 0] + employee_pension_contributions: + 2024: [0, 1_000, 0] + 2025: [0, 0, 0] + personal_pension_contributions: + 2024: [0, 0, 800] + 2025: [0, 0, 0] + self_employment_income: + 2024: [0, 0, 0] + 2025: [10_000, 10_000, 10_000] + trading_loss: + 2024: [10_000, 10_000, 10_000] + trading_allowance_deduction: + 2024: [0, 0, 0] + 2025: [0, 0, 0] + output: + # No contribution, age-ineligible contribution and RAS-only contribution. + net_pay_pension_relief: [0, 0, 0] + trade_loss_relief_against_general_income: [2_000, 2_000, 2_000] + loss_relief: + 2025: [8_000, 8_000, 8_000] + taxable_self_employment_income: + 2025: [2_000, 2_000, 2_000] diff --git a/policyengine_uk/tests/test_income_tax_loss_carry_forward.py b/policyengine_uk/tests/test_income_tax_loss_carry_forward.py new file mode 100644 index 0000000000..64ddd5cb50 --- /dev/null +++ b/policyengine_uk/tests/test_income_tax_loss_carry_forward.py @@ -0,0 +1,170 @@ +"""Income Tax loss stock, supplied-year provenance and public cache APIs. + +The conservation test follows actual income deductions, including amounts +that fall within the personal allowance. It does not count a tax saving as +loss consumption or assume that Income Tax and Class 4 stocks are equal. +""" + +from functools import lru_cache +from unittest.mock import patch + +import numpy as np +import pytest +from hypothesis import given, settings +from hypothesis import strategies as st +from policyengine_core import periods +from policyengine_core.reforms import Reform + +from policyengine_uk import CountryTaxBenefitSystem, Simulation +from policyengine_uk.utils.supplied_inputs import ( + set_model_value, + supplied_input_periods, +) + + +@lru_cache(maxsize=1) +def model_template(): + """Load source once; give every generated world independent model state.""" + return CountryTaxBenefitSystem() + + +def simulation(person): + # Match the repository's cloned_uk_tax_benefit_system fixture. The UK + # wrapper constructs its system internally, rather than accepting Core's + # tax_benefit_system constructor keyword. + with patch( + "policyengine_uk.simulation.CountryTaxBenefitSystem", + side_effect=model_template().clone, + ): + return Simulation( + situation={ + "people": {"person": person}, + "benunits": {"benunit": {"members": ["person"]}}, + "households": {"household": {"members": ["person"]}}, + } + ) + + +def value(sim, name, year): + return float(sim.calculate(name, year)[0]) + + +def history(): + return { + "age": {2024: 40}, + "taxable_social_security_income": {2024: 0}, + "employment_income": {2024: 0, 2025: 0, 2026: 0}, + "self_employment_income": {2024: 0, 2025: 2_000, 2026: 5_000}, + "trading_loss": {2024: 10_000}, + "trading_allowance_deduction": {2024: 0, 2025: 0, 2026: 0}, + } + + +@settings(max_examples=20, deadline=None, derandomize=True) +@given( + st.lists( + st.tuples( + st.integers(0, 80_000), # Profit before losses. + st.integers(0, 120_000), # Current loss in the eligible trade pool. + st.integers(0, 180_000), # Other income. + ), + min_size=2, + max_size=5, + ), + st.one_of(st.none(), st.tuples(st.integers(0, 4), st.integers(0, 100_000))), +) +def test_deductions_and_remaining_stock_conserve_each_loss_segment(years, reset): + calendar = list(range(2024, 2024 + len(years))) + person = { + "age": {2024: 40}, + "taxable_social_security_income": {2024: 0}, + "self_employment_income": dict(zip(calendar, [x[0] for x in years])), + "trading_loss": dict(zip(calendar, [x[1] for x in years])), + "employment_income": dict(zip(calendar, [x[2] for x in years])), + "trading_allowance_deduction": dict.fromkeys(calendar, 0), + } + reset_index = None if reset is None else reset[0] % len(years) + if reset is not None: + person["loss_relief"] = {calendar[reset_index]: reset[1]} + sim = simulation(person) + # Request the latest stock first: cached calculation order must not + # become an input or cause a recursive spiral through the allowance. + value(sim, "loss_relief", calendar[-1] + 1) + available = used = expected_opening = 0 + for index, (year, (profit, loss, pay)) in enumerate(zip(calendar, years)): + if index == reset_index: + available, used, expected_opening = reset[1], 0, reset[1] + opening = value(sim, "loss_relief", year) + assert opening == expected_opening + absorbed = min(opening, profit) + taxable = profit - absorbed + income = pay + taxable + # The s.24A cap restores s.83 relief; available income stays net of it. + general = min(loss, max(50_000, (pay + profit) * 0.25), income) + assert value(sim, "taxable_self_employment_income", year) == taxable + assert value(sim, "trade_loss_relief_against_general_income", year) == general + available += loss + used += absorbed + general + expected_opening = available - used + # A supplied next-year balance overrides this segment's derived carry. + next_opening = reset[1] if index + 1 == reset_index else expected_opening + assert value(sim, "loss_relief", year + 1) == next_opening + assert expected_opening >= 0 + + +@pytest.mark.parametrize("order", [(2026, 2024, 2025), (2024, 2025, 2026)]) +def test_opening_stock_is_independent_of_calculation_order(order): + sim = simulation(history()) + expected = {2024: 0, 2025: 10_000, 2026: 8_000} + for year in order: + assert value(sim, "loss_relief", year) == expected[year] + recorded = supplied_input_periods(sim.populations["person"], "loss_relief") + assert recorded == [] + + +def test_a_zero_reset_on_a_branch_does_not_change_the_parent(): + sim = simulation(history()) + assert value(sim, "loss_relief", 2026) == 8_000 + branch = sim.get_branch("external_loss_use") + branch.set_input("loss_relief", 2025, np.array([0.0])) + assert value(branch, "loss_relief", 2026) == 0 + assert value(sim, "loss_relief", 2026) == 8_000 + assert supplied_input_periods(sim.populations["person"], "loss_relief") == [] + + +def test_replacing_a_clones_loss_does_not_change_the_original(): + sim = simulation(history()) + clone = sim.clone() + clone.set_input("trading_loss", 2024, np.array([6_000.0])) + assert value(sim, "loss_relief", 2026) == 8_000 + assert value(clone, "loss_relief", 2026) == 4_000 + + +@pytest.mark.parametrize("variable", ["trading_loss", "loss_relief"]) +def test_deleted_inputs_do_not_reappear_as_supplied_history(variable): + person = history() + if variable == "loss_relief": + person.pop("trading_loss") + person["loss_relief"] = {2024: 10_000} + sim = simulation(person) + sim.delete_arrays(variable, 2024) + assert value(sim, "loss_relief", 2026) == 0 + assert supplied_input_periods(sim.populations["person"], variable) == [] + + +def test_model_written_loss_is_not_a_new_supplied_loss(): + sim = simulation(history()) + set_model_value(sim, "trading_loss", periods.period(2025), np.array([9_000.0])) + assert value(sim, "loss_relief", 2026) == 8_000 + assert value(sim, "trade_loss_relief_against_general_income", 2025) == 0 + + +def test_neutralizing_the_loss_removes_automatic_carry_forward(): + class neutralize_loss(Reform): + def apply(self): + self.neutralize_variable("trading_loss") + + sim = simulation(history()) + assert value(sim, "loss_relief", 2026) == 8_000 + sim.apply_reform(neutralize_loss) + assert value(sim, "loss_relief", 2026) == 0 diff --git a/policyengine_uk/utils/pensions.py b/policyengine_uk/utils/pensions.py index 8b5ecb3ff0..0c526ae73f 100644 --- a/policyengine_uk/utils/pensions.py +++ b/policyengine_uk/utils/pensions.py @@ -97,7 +97,11 @@ def annual_allowance_net_income(person, period, parameters): relievable_net_pay = pension_contributions_relief_amount( actual_net_pay, actual_earnings, 0, person("age", period), hmrc ) - if not np.any((relievable_net_pay > 0) & (person("trading_loss", period) > 0)): + current_loss = supplied_input(person, "trading_loss", period) + if current_loss is None: + current_loss = person.empty_array() + current_loss = np.maximum(0, current_loss) + if not np.any((relievable_net_pay > 0) & (current_loss > 0)): return net_income income_before_loss = np.maximum( @@ -125,7 +129,7 @@ def annual_allowance_net_income(person, period, parameters): loss = np.where( person("trading_allowance_deduction", period) > 0, 0, - person("trading_loss", period), + current_loss, ) # FA 2004 s.193(2) deducts relievable net pay from employment income # before the s.25(4) limit on Step 2 loss relief. Apply this ordering even diff --git a/policyengine_uk/utils/supplied_inputs.py b/policyengine_uk/utils/supplied_inputs.py index 9651d773d2..9d76219477 100644 --- a/policyengine_uk/utils/supplied_inputs.py +++ b/policyengine_uk/utils/supplied_inputs.py @@ -54,6 +54,7 @@ "pip_m_points", "local_bus_trips", "local_bus_uncapped_single_fare", + "loss_relief", "ni_class_4_losses_brought_forward", "ni_class_4_trading_loss", "tenure_type", diff --git a/policyengine_uk/variables/gov/hmrc/income_tax/reliefs/loss_relief.py b/policyengine_uk/variables/gov/hmrc/income_tax/reliefs/loss_relief.py index 0b27ae0104..1a8d9df482 100644 --- a/policyengine_uk/variables/gov/hmrc/income_tax/reliefs/loss_relief.py +++ b/policyengine_uk/variables/gov/hmrc/income_tax/reliefs/loss_relief.py @@ -1,26 +1,66 @@ from policyengine_uk.model_api import * - -""" -The section detailing some tax reliefs applicable is section 24 of the Act, but others are described in the 2003 and 2005 Acts as deductions from the respective components. -""" +from policyengine_uk.utils.pensions import trading_profits_before_losses +from policyengine_uk.utils.supplied_inputs import supplied_input, supplied_input_periods class loss_relief(Variable): value_type = float entity = Person - label = "Trade losses brought forward" + label = "Unrelieved trade losses at the start of the year" reference = dict( title="Income Tax Act 2007 s. 83", href="https://www.legislation.gov.uk/ukpga/2007/3/section/83", ) documentation = ( - "Unrelieved trade losses of earlier years deducted from this year's " - "profits of the same trade (ITA 2007 s.83). Deducted from " - "self-employment income only, and never below zero. A loss made in " - "this year goes in trading_loss, which is relieved against general " - "income instead (s.64); whatever part of it this year's income cannot " - "absorb is carried forward by entering it here in later years." + "Opening unrelieved losses available against profits of the same " + "continuing trade, or a caller-preassessed eligible trade pool " + "(ITA 2007 ss.83-84). The model assumes a carry-forward claim and " + "tracks supplied-year losses after actual general-income relief and " + "prior losses absorbed by trading profits. This stock can exceed " + "this year's deduction, which cannot reduce trading profits below " + "zero or reduce other income. An explicit input, including zero, " + "overrides the opening stock for that year and reconciles external " + "relief or earlier history. Class 4 tracks a separate loss balance." ) definition_period = YEAR unit = GBP quantity_type = FLOW + + def formula(person, period, parameters): + earlier_years = [ + supplied_period.start.year + for variable in ("trading_loss", "loss_relief") + for supplied_period in supplied_input_periods(person, variable) + if supplied_period.start.year < period.start.year + ] + if not earlier_years: + return person.empty_array() + + balance = person.empty_array() + for years_back in range(period.start.year - min(earlier_years), 0, -1): + year = period.offset(-years_back, "year") + # Resolve each opening balance before the year's allowance reads + # it. Earlier years' dependencies are already ordinarily cached; + # this also respects an explicitly supplied opening-stock reset. + opening = max_(0, person("loss_relief", year)) + profits = trading_profits_before_losses( + person, year, parameters(year).gov.hmrc + ) + absorbed = min_(opening, profits) + current_loss = supplied_input(person, "trading_loss", year) + if current_loss is None: + current_loss = person.empty_array() + eligible_loss = where( + person("trading_allowance_deduction", year) > 0, + 0, + max_(0, current_loss), + ) + used_against_general_income = person( + "trade_loss_relief_against_general_income", year + ) + balance = ( + opening + - absorbed + + max_(0, eligible_loss - used_against_general_income) + ) + return balance diff --git a/policyengine_uk/variables/gov/hmrc/income_tax/reliefs/trade_loss_relief_against_general_income.py b/policyengine_uk/variables/gov/hmrc/income_tax/reliefs/trade_loss_relief_against_general_income.py index 5f45fcbdef..325401ed0d 100644 --- a/policyengine_uk/variables/gov/hmrc/income_tax/reliefs/trade_loss_relief_against_general_income.py +++ b/policyengine_uk/variables/gov/hmrc/income_tax/reliefs/trade_loss_relief_against_general_income.py @@ -1,4 +1,5 @@ from policyengine_uk.model_api import * +from policyengine_uk.utils.supplied_inputs import supplied_input class trade_loss_relief_against_general_income(Variable): @@ -13,8 +14,10 @@ class trade_loss_relief_against_general_income(Variable): "Nothing lets a claim be restricted to keep the Personal Allowance in " "use. The model assumes the trade is commercial (s.66), that the person " "claims, and that the claim is for the loss-making year rather than " - "the year before (s.64(2)(b)); the part it cannot use is carried " - "forward only by entering it in loss_relief in later years (s.83). " + "the year before (s.64(2)(b)); the part it cannot use enters the " + "opening loss_relief stock in later years under the model's " + "same-trade carry-forward claim convention (s.83). Only a loss " + "explicitly supplied for this year is a current loss. " "A current loss is recognised only under ordinary expense treatment; " "the trading allowance election compares the raw loss supplied for " "the tax year, before net-income and relief-cap limits, with the " @@ -38,13 +41,22 @@ class trade_loss_relief_against_general_income(Variable): ] def formula(person, period, parameters): - net_income = max_(0, person("net_income_before_trade_loss_relief", period)) + # Ordinary net-pay contributions already reduce Step 1 employment + # income. That income cannot also consume a Step 2 trading loss. + net_income = max_( + 0, + person("net_income_before_trade_loss_relief", period) + - person("net_pay_pension_relief", period), + ) + current_loss = supplied_input(person, "trading_loss", period) + if current_loss is None: + current_loss = person.empty_array() # Allowance treatment cannot retain a current expense-generated loss # on another trade in the same individual's tax year. loss = where( person("trading_allowance_deduction", period) > 0, 0, - person("trading_loss", period), + max_(0, current_loss), ) return min_( loss, diff --git a/policyengine_uk/variables/input/trading_loss.py b/policyengine_uk/variables/input/trading_loss.py index 8d6ca14528..1a93a41017 100644 --- a/policyengine_uk/variables/input/trading_loss.py +++ b/policyengine_uk/variables/input/trading_loss.py @@ -19,11 +19,14 @@ class trading_loss(Variable): "against the person's other trades' profits (UC Regs 2013 reg 57(2)), " "and HB, CTR, Pension Credit and the legacy benefits not even that (HB " "Regs 2006 reg 38(10)); HBAI household income counts it as negative " - "income. Income Tax losses brought forward go in loss_relief; Class 4 " + "income. Income Tax tracks unrelieved earlier losses in loss_relief, " + "under its current-year and same-trade carry-forward claim " + "conventions; an explicit opening loss_relief overrides that stock. Class 4 " "tracks its own unrelieved balance in ni_class_4_losses_brought_forward. " - "For a one-off loss, set subsequent years explicitly to zero for " - "Income Tax and benefits; Class 4 counts only explicitly supplied " - "loss years and carries forward the unused balance automatically." + "Income Tax and Class 4 count only explicitly supplied loss years " + "and carry their unused balances forward separately. For a one-off " + "loss, set subsequent years explicitly to zero for other programmes " + "that read inherited values of this input." ) definition_period = YEAR unit = GBP From 887ba2aedf8199c8d547c82d146160afba9b0950 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Sun, 25 Oct 2026 17:59:53 +0000 Subject: [PATCH 2/6] Isolate loss carry-forward regression tests --- .../tests/test_income_tax_loss_carry_forward.py | 6 ++++++ .../tests/test_ni_class_4_profits_properties.py | 15 +++++++++++---- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/policyengine_uk/tests/test_income_tax_loss_carry_forward.py b/policyengine_uk/tests/test_income_tax_loss_carry_forward.py index 64ddd5cb50..113d288dcd 100644 --- a/policyengine_uk/tests/test_income_tax_loss_carry_forward.py +++ b/policyengine_uk/tests/test_income_tax_loss_carry_forward.py @@ -28,6 +28,12 @@ def model_template(): return CountryTaxBenefitSystem() +@pytest.fixture(scope="module", autouse=True) +def clear_model_template_cache(): + yield + model_template.cache_clear() + + def simulation(person): # Match the repository's cloned_uk_tax_benefit_system fixture. The UK # wrapper constructs its system internally, rather than accepting Core's diff --git a/policyengine_uk/tests/test_ni_class_4_profits_properties.py b/policyengine_uk/tests/test_ni_class_4_profits_properties.py index 5980c7ba22..b57db769d8 100644 --- a/policyengine_uk/tests/test_ni_class_4_profits_properties.py +++ b/policyengine_uk/tests/test_ni_class_4_profits_properties.py @@ -5,6 +5,9 @@ capital allowances (CAA 2001 s. 247) and the trading allowance (ITTOIA 2005 ss. 783AF and 783AI), less trading losses as Sch. 2 para. 3 allows. +The generated reference comparisons hold Income Tax opening losses +(`loss_relief`) at zero, isolating the separate Class 4 loss balances. + Invariants, for every generated case: 1. Differential: ni_class_4_profits_before_losses, ni_class_4_loss_relief, @@ -119,13 +122,14 @@ def reference_allowance(simulation, year): def reference_trade(profit, receipts, capital_allowances, allowance, current_loss): - """Independent profits and eligible annual Class 4 loss. + """Independent Class 4 trade values with no Income Tax opening losses. Compare ordinary-expense profit less the current loss with allowance profit, which excludes that loss (ITTOIA ss. 783AF and 783AI). Ties use - the allowance. Only a loss supplied for this year affects the allowance - election or enters the separate Class 4 balance, even if the engine - fills in a current Income Tax loss from an earlier input. + the allowance. The caller holds Income Tax opening loss_relief at zero; + only a loss supplied for this year then affects the allowance election + or enters the separate Class 4 balance. Inherited trading_loss values + are not new losses. """ ordinary_profit = max(Fraction(0), profit - capital_allowances) if receipts > 0 and receipts >= profit: @@ -233,6 +237,7 @@ def sim(request): "self_employment_gross_receipts", "capital_allowances", "trading_loss", + "loss_relief", ] }, } @@ -502,6 +507,7 @@ def test_losses_carry_forward_over_many_years(years, opening_balance, random): "age": {first_year: 40}, "self_employment_income": dict(zip(periods, (profit for profit, _ in years))), "trading_loss": dict(zip(periods, (loss for _, loss in years))), + "loss_relief": {period: 0 for period in periods}, } supplied = None if opening_balance is not None: @@ -656,6 +662,7 @@ def test_a_loss_entered_for_some_years_is_relieved_once(years, random): "self_employment_income": dict( zip(periods, (profit for profit, _, _ in years)) ), + "loss_relief": {period: 0 for period in periods}, } if entered: person["trading_loss"] = entered From d3d2bbc55b42cee47fce9b9ce7993439ad257ca0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Mon, 26 Oct 2026 11:13:42 +0000 Subject: [PATCH 3/6] Clarify same-trade loss carry-forward assumptions --- changelog.d/2087.fixed.md | 2 + docs/engineering/income-tax-trading-losses.md | 12 ++++++ .../reliefs/trade_loss_carry_forward.yaml | 41 +++++++++++++++++++ 3 files changed, 55 insertions(+) diff --git a/changelog.d/2087.fixed.md b/changelog.d/2087.fixed.md index e06bc35810..3d62bbac5c 100644 --- a/changelog.d/2087.fixed.md +++ b/changelog.d/2087.fixed.md @@ -1 +1,3 @@ Recognise Income Tax trading losses only in their supplied year and carry forward unused losses after relief already given, retaining explicit opening-stock overrides and the separate Class 4 balance. + +Clarify and pin the caller-assessed same-trade loss contract when a year has both opening stock and a new loss, including the limits of forwarded dataset inputs. diff --git a/docs/engineering/income-tax-trading-losses.md b/docs/engineering/income-tax-trading-losses.md index caf815faea..c8425aa849 100644 --- a/docs/engineering/income-tax-trading-losses.md +++ b/docs/engineering/income-tax-trading-losses.md @@ -53,3 +53,15 @@ national impacts, input coverage or population accuracy. References: [ITA 2007 sections 63–65](https://www.legislation.gov.uk/ukpga/2007/3/part/4/chapter/2), [sections 83–84](https://www.legislation.gov.uk/ukpga/2007/3/part/4/chapter/2/crossheading/carryforward-trade-loss-relief), and [section 24A](https://www.legislation.gov.uk/ukpga/2007/3/section/24A). + +## A new loss alongside profits + +The automatic carry-forward uses aggregate person inputs and does not identify trades. In every year, the caller must establish that each brought-forward loss used by the calculation is deductible from the supplied profits of that same trade, including the required ordering. The aggregate deduction must equal the sum of the permitted same-trade deductions. Supplying a pool does not establish that unrelated losses and profits are compatible. + +For example, an old £10,000 loss from trade A in 2025, followed by £8,000 profit from A and a new £4,000 loss from B in 2026, uses £8,000 of A's old stock first. With no other income, ordinary expenses rather than the trading allowance, no pensions, capital allowances or external relief, and eligible current-year claims, current general-income relief is £0. The 2027 opening inventory is £2,000 from A plus £4,000 from B, or £6,000. This balance does not authorise relief against arbitrary later profits: compatibility must be assessed again each year. + +If instead both the old and new losses belong to A while the £8,000 profit belongs to B, section 83 cannot deduct A's old stock from B's profit. Under the retained current-year section 64 convention, £4,000 of the current loss can be used, leaving £4,000 net income before personal allowances and £10,000 old stock unrelieved. These identical aggregate inputs do not identify that association, so this case is outside automatic reconstruction. Keep per-trade records externally and supply reconciled annual inputs and balances, or exclude the situation from the automatic calculation. An explicit `loss_relief: 0` resets the accounting segment; it does not suspend an old loss in a hidden ledger. Excluded stock must be explicitly reseeded when appropriate later, accounting for relief already obtained. + +## Projected dataset inputs + +If a data producer copies a supplied `trading_loss` value into later years, each physical annual input is treated as a new loss for that year. Preserve the original supplied year of a one-off loss and use assessed later inputs, including explicit zeros where appropriate; do not forward-fill it because it remains unused. Copying `loss_relief` likewise supplies a new opening-balance override each year. This conditional input-contract warning makes no claim about current certified-data columns, population coverage or national effects. diff --git a/policyengine_uk/tests/policy/baseline/gov/hmrc/income_tax/reliefs/trade_loss_carry_forward.yaml b/policyengine_uk/tests/policy/baseline/gov/hmrc/income_tax/reliefs/trade_loss_carry_forward.yaml index b045ca7c1e..f626d646d6 100644 --- a/policyengine_uk/tests/policy/baseline/gov/hmrc/income_tax/reliefs/trade_loss_carry_forward.yaml +++ b/policyengine_uk/tests/policy/baseline/gov/hmrc/income_tax/reliefs/trade_loss_carry_forward.yaml @@ -244,3 +244,44 @@ loss_relief: 3_000 trade_loss_relief_against_general_income: 0 taxable_self_employment_income: 1_000 + +# PROPOSED ONLY; conditional same-trade compatibility is externally assessed. +# 2025 old loss belongs to A; in 2026 A profits 8,000 and B loses 4,000. +# Trade identities are premises, not variables inferred by the model. +- name: Caller-assessed profitable-trade stock is used before another trade's current loss + period: 2026 + absolute_error_margin: 0.01 + input: + age: 40 + taxable_social_security_income: 0 + employment_income: 0 + employee_pension_contributions: 0 + personal_pension_contributions: 0 + employer_pension_contributions: 0 + pension_contributions_via_salary_sacrifice: 0 + self_employment_income: + 2025: 0 + 2026: 8_000 + 2027: 0 + trading_loss: + 2025: 10_000 + 2026: 4_000 + 2027: 0 + trading_allowance_deduction: + 2025: 0 + 2026: 0 + 2027: 0 + output: + loss_relief: + 2025: 0 + 2026: 10_000 + # Remaining 2,000 from A plus 4,000 from B; reassess later eligibility. + 2027: 6_000 + trade_loss_relief_against_general_income: + 2025: 0 + 2026: 0 + 2027: 0 + taxable_self_employment_income: + 2025: 0 + 2026: 0 + 2027: 0 From 16a12b93d0d5c962556cf7d0789ae66a99ffbb34 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Mon, 26 Oct 2026 19:58:29 +0000 Subject: [PATCH 4/6] Preserve monthly reads of opening trade-loss stocks --- changelog.d/2087.fixed.md | 2 ++ .../hmrc/income_tax/reliefs/trade_loss_carry_forward.yaml | 2 +- .../tests/test_income_tax_loss_carry_forward.py | 8 ++++++++ .../variables/gov/hmrc/income_tax/reliefs/loss_relief.py | 2 +- 4 files changed, 12 insertions(+), 2 deletions(-) diff --git a/changelog.d/2087.fixed.md b/changelog.d/2087.fixed.md index 3d62bbac5c..1804383572 100644 --- a/changelog.d/2087.fixed.md +++ b/changelog.d/2087.fixed.md @@ -1,3 +1,5 @@ Recognise Income Tax trading losses only in their supplied year and carry forward unused losses after relief already given, retaining explicit opening-stock overrides and the separate Class 4 balance. Clarify and pin the caller-assessed same-trade loss contract when a year has both opening stock and a new loss, including the limits of forwarded dataset inputs. + +Classify opening trade-loss balances as stocks so monthly reads retain the annual balance. diff --git a/policyengine_uk/tests/policy/baseline/gov/hmrc/income_tax/reliefs/trade_loss_carry_forward.yaml b/policyengine_uk/tests/policy/baseline/gov/hmrc/income_tax/reliefs/trade_loss_carry_forward.yaml index f626d646d6..f848a530b5 100644 --- a/policyengine_uk/tests/policy/baseline/gov/hmrc/income_tax/reliefs/trade_loss_carry_forward.yaml +++ b/policyengine_uk/tests/policy/baseline/gov/hmrc/income_tax/reliefs/trade_loss_carry_forward.yaml @@ -245,7 +245,7 @@ trade_loss_relief_against_general_income: 0 taxable_self_employment_income: 1_000 -# PROPOSED ONLY; conditional same-trade compatibility is externally assessed. +# Conditional same-trade compatibility is externally assessed. # 2025 old loss belongs to A; in 2026 A profits 8,000 and B loses 4,000. # Trade identities are premises, not variables inferred by the model. - name: Caller-assessed profitable-trade stock is used before another trade's current loss diff --git a/policyengine_uk/tests/test_income_tax_loss_carry_forward.py b/policyengine_uk/tests/test_income_tax_loss_carry_forward.py index 113d288dcd..bc17978185 100644 --- a/policyengine_uk/tests/test_income_tax_loss_carry_forward.py +++ b/policyengine_uk/tests/test_income_tax_loss_carry_forward.py @@ -174,3 +174,11 @@ def apply(self): assert value(sim, "loss_relief", 2026) == 8_000 sim.apply_reform(neutralize_loss) assert value(sim, "loss_relief", 2026) == 0 + + +def test_monthly_reads_preserve_the_annual_opening_stock(): + sim = simulation(history()) + # The 10,000 loss less 2,000 used in 2025 leaves 8,000 opening stock. + assert value(sim, "loss_relief", 2026) == 8_000 + assert value(sim, "loss_relief", "2026-01") == 8_000 + assert value(sim, "loss_relief", "2026-12") == 8_000 diff --git a/policyengine_uk/variables/gov/hmrc/income_tax/reliefs/loss_relief.py b/policyengine_uk/variables/gov/hmrc/income_tax/reliefs/loss_relief.py index 1a8d9df482..c46df90cf4 100644 --- a/policyengine_uk/variables/gov/hmrc/income_tax/reliefs/loss_relief.py +++ b/policyengine_uk/variables/gov/hmrc/income_tax/reliefs/loss_relief.py @@ -24,7 +24,7 @@ class loss_relief(Variable): ) definition_period = YEAR unit = GBP - quantity_type = FLOW + quantity_type = STOCK def formula(person, period, parameters): earlier_years = [ From bcf0fb7cdbf4de43d344761493a040ff5932ccbd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Mon, 26 Oct 2026 23:46:41 +0000 Subject: [PATCH 5/6] Clarify same-trade loss relief caveat --- docs/engineering/income-tax-trading-losses.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/engineering/income-tax-trading-losses.md b/docs/engineering/income-tax-trading-losses.md index c8425aa849..2050ebb110 100644 --- a/docs/engineering/income-tax-trading-losses.md +++ b/docs/engineering/income-tax-trading-losses.md @@ -60,7 +60,7 @@ The automatic carry-forward uses aggregate person inputs and does not identify t For example, an old £10,000 loss from trade A in 2025, followed by £8,000 profit from A and a new £4,000 loss from B in 2026, uses £8,000 of A's old stock first. With no other income, ordinary expenses rather than the trading allowance, no pensions, capital allowances or external relief, and eligible current-year claims, current general-income relief is £0. The 2027 opening inventory is £2,000 from A plus £4,000 from B, or £6,000. This balance does not authorise relief against arbitrary later profits: compatibility must be assessed again each year. -If instead both the old and new losses belong to A while the £8,000 profit belongs to B, section 83 cannot deduct A's old stock from B's profit. Under the retained current-year section 64 convention, £4,000 of the current loss can be used, leaving £4,000 net income before personal allowances and £10,000 old stock unrelieved. These identical aggregate inputs do not identify that association, so this case is outside automatic reconstruction. Keep per-trade records externally and supply reconciled annual inputs and balances, or exclude the situation from the automatic calculation. An explicit `loss_relief: 0` resets the accounting segment; it does not suspend an old loss in a hidden ledger. Excluded stock must be explicitly reseeded when appropriate later, accounting for relief already obtained. +If instead both the old and new losses belong to A while the £8,000 profit belongs to B, section 83 cannot deduct A's old stock from B's profit. Under the retained current-year section 64 convention, £4,000 of the current loss can be used, leaving £4,000 net income before personal allowances and £10,000 old stock unrelieved. If A never earns enough future profits, the part of its old loss exceeding those profits remains unrelieved under sections 83–84, while the automatic aggregate calculation has already used part of A's old stock against B's profit. These identical aggregate inputs do not identify that association, so this case is outside automatic reconstruction. Keep per-trade records externally and supply reconciled annual inputs and balances, or exclude the situation from the automatic calculation. An explicit `loss_relief: 0` resets the accounting segment; it does not suspend an old loss in a hidden ledger. Excluded stock must be explicitly reseeded when appropriate later, accounting for relief already obtained. ## Projected dataset inputs From fb4042957ceb195b98be622c75e1db5ded95127d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Mon, 2 Nov 2026 17:05:48 +0000 Subject: [PATCH 6/6] Refresh loss relief and per-period input caches --- changelog.d/2087.fixed.md | 4 + policyengine_uk/simulation.py | 5 +- .../tests/test_scenario_modifier_inputs.py | 61 ++++++++ .../test_trade_loss_relief_short_circuits.py | 147 ++++++++++++++++++ policyengine_uk/utils/measurement_branches.py | 25 +-- ...rade_loss_relief_against_general_income.py | 25 +-- 6 files changed, 237 insertions(+), 30 deletions(-) create mode 100644 policyengine_uk/tests/test_trade_loss_relief_short_circuits.py diff --git a/changelog.d/2087.fixed.md b/changelog.d/2087.fixed.md index c227b365ae..50d6a61145 100644 --- a/changelog.d/2087.fixed.md +++ b/changelog.d/2087.fixed.md @@ -5,3 +5,7 @@ Clarify and pin the caller-assessed same-trade loss contract when a year has bot Classify opening trade-loss balances as stocks so monthly reads retain the annual balance. Prevent current losses from carrying forward when the trading allowance deduction applies only to miscellaneous income. + +Avoid unnecessary income-tax counterfactuals when the current year has no eligible trading loss. + +Recompute calculated years after input changes and resets while preserving supplied and model-owned input cells. diff --git a/policyengine_uk/simulation.py b/policyengine_uk/simulation.py index e41093f979..8bab48f1fc 100644 --- a/policyengine_uk/simulation.py +++ b/policyengine_uk/simulation.py @@ -1004,11 +1004,8 @@ def _dataset_cache_key(self, source: str): ) def reset_calculations(self): - retained = retained_input_variables(self) self._external_input_change_pending = False - for variable in self.tax_benefit_system.variables: - if variable not in retained: - self.delete_arrays(variable) + drop_calculated_values(self) def get_known_variables(self): variables = [] diff --git a/policyengine_uk/tests/test_scenario_modifier_inputs.py b/policyengine_uk/tests/test_scenario_modifier_inputs.py index 59b0fad68b..73cd9a763b 100644 --- a/policyengine_uk/tests/test_scenario_modifier_inputs.py +++ b/policyengine_uk/tests/test_scenario_modifier_inputs.py @@ -13,6 +13,12 @@ from policyengine_uk import Microsimulation, Simulation from policyengine_uk.model_api import Scenario +from policyengine_uk.utils.measurement_branches import measurement_branch +from policyengine_uk.utils.supplied_inputs import ( + set_model_value, + supplied_input, + supplied_input_periods, +) pytestmark = pytest.mark.usefixtures("cloned_uk_tax_benefit_system") @@ -732,3 +738,58 @@ def observe_clone(owner, *args, **kwargs): values(simulation, "income_tax"), expected_tax, atol=0.01 ) assert not simulation._external_input_change_pending + + +@pytest.mark.parametrize("cleanup", ["automatic", "reset", "measurement"]) +def test_cleanup_preserves_inputs_only_in_their_actual_periods(cleanup): + situation = family((2024, 2025, 2026)) + situation["benunits"]["benunit"][CHILD_BENEFIT] = {2024: 500} + parent = Simulation(situation=situation) + parent_flag = getattr(parent, "changed_from_baseline", None) + parent_2025 = values(parent, CHILD_BENEFIT, 2025) + assert parent_2025[0] > 0 + + branch = parent.get_branch("mixed_period_inputs", clone_system=True) + branch.set_input(CHILD_BENEFIT, 2024, np.array([700.0])) + branch.set_input(CHILD_BENEFIT, 2026, np.array([0.0])) + # This is a registered model-owned physical input, not a supplied stock. + # Routine cleanup must retain both its stored amount and that provenance. + model_stock = np.array([11.0, 0.0]) + set_model_value(branch, "loss_relief", period(2025), model_stock) + assert supplied_input(branch.person, "loss_relief", period(2025)) is None + assert supplied_input_periods(branch.person, "loss_relief") == [] + assert values(branch, CHILD_BENEFIT, 2025)[0] > 0 + # Both False and None occur in callers; routine cleanup must not mark + # either one as a change from the baseline merely for clearing caches. + unchanged_flag = None if cleanup == "measurement" else False + branch.changed_from_baseline = unchanged_flag + + if cleanup == "measurement": + target = measurement_branch( + branch, + "mixed_period_measurement", + 2025, + {"would_claim_child_benefit": np.array([False])}, + ) + else: + target = branch + target.set_input("would_claim_child_benefit", 2025, np.array([False])) + if cleanup == "reset": + target.reset_calculations() + + # A formula input in 2024 or 2026 does not freeze its computed 2025. + # The local 2024 input shadows the parent's, and the future zero is real. + np.testing.assert_array_equal(values(target, CHILD_BENEFIT, 2024), [700]) + np.testing.assert_array_equal(values(target, CHILD_BENEFIT, 2025), [0]) + np.testing.assert_array_equal(values(target, CHILD_BENEFIT, 2026), [0]) + np.testing.assert_array_equal(values(target, "loss_relief", 2025), model_stock) + assert supplied_input(target.person, "loss_relief", period(2025)) is None + assert supplied_input_periods(target.person, "loss_relief") == [] + assert target.changed_from_baseline is unchanged_flag + + np.testing.assert_array_equal(values(parent, CHILD_BENEFIT, 2024), [500]) + np.testing.assert_array_equal(values(parent, CHILD_BENEFIT, 2025), parent_2025) + np.testing.assert_array_equal(values(parent, "loss_relief", 2025), [0, 0]) + assert getattr(parent, "changed_from_baseline", None) is parent_flag + if cleanup == "measurement": + np.testing.assert_array_equal(values(branch, CHILD_BENEFIT, 2025), parent_2025) diff --git a/policyengine_uk/tests/test_trade_loss_relief_short_circuits.py b/policyengine_uk/tests/test_trade_loss_relief_short_circuits.py new file mode 100644 index 0000000000..8321a1ed50 --- /dev/null +++ b/policyengine_uk/tests/test_trade_loss_relief_short_circuits.py @@ -0,0 +1,147 @@ +"""Zero current relief preserves real carry, elections and public mutations. + +ITA 2007 ss.64, 24A and 83 distinguish the current loss deduction from the +opening same-trade stock. ITTOIA 2005 s.783AF makes an allowance year's +current loss nil. These tests check public amounts, not evaluation order. +""" + +import numpy as np +import pytest + +from policyengine_uk import Simulation + +pytestmark = pytest.mark.usefixtures("cloned_uk_tax_benefit_system") + +YEAR = 2024 +RELIEF = "trade_loss_relief_against_general_income" +ALLOWANCE = "gov.hmrc.income_tax.allowances.trading_allowance" + + +def simulate(people): + return Simulation( + situation={ + "people": { + name: {"age": {YEAR: 40}, **inputs} for name, inputs in people.items() + }, + "benunits": {f"unit_{name}": {"members": [name]} for name in people}, + "households": {f"household_{name}": {"members": [name]} for name in people}, + } + ) + + +def values(simulation, variable, year=YEAR): + return np.asarray(simulation.calculate(variable, year), dtype=float) + + +@pytest.mark.parametrize("raw_loss", [None, 0, -50], ids=["absent", "zero", "negative"]) +def test_no_new_loss_preserves_positive_opening_stock(raw_loss): + person = { + "employment_income": {year: 0 for year in range(2024, 2027)}, + "self_employment_income": {year: 3_000 for year in range(2024, 2027)}, + "self_employment_gross_receipts": {year: 4_000 for year in range(2024, 2027)}, + "loss_relief": {2024: 7_000}, + } + if raw_loss is not None: + person["trading_loss"] = {2024: raw_loss} + simulation = simulate({"person": person}) + # No new eligible loss gives no current deduction. The separate opening + # stock still absorbs 3,000 in each of 2024 and 2025: 7,000 - 6,000 = 1,000. + for year in range(2024, 2027): + assert values(simulation, RELIEF, year) == pytest.approx([0], abs=0.01) + assert values(simulation, "loss_relief", 2026) == pytest.approx([1_000], abs=0.01) + assert values(simulation, "taxable_self_employment_income", 2026) == ( + pytest.approx([2_000], abs=0.01) + ) + + +def test_mixed_loss_masks_preserve_net_pay_and_relief_cap(): + # The first two have no eligible loss. The third naturally takes full + # allowance relief: receipts 900, profit 800 and raw loss 200. The fourth + # has only 2,000 - 1,000 net-pay pension = 1,000 income to relieve. The + # last is limited by the s.24A cap: max(50,000, 25% * 300,000) = 75,000. + rows = [ + (0, 500, 0, 0, 0), + (-50, 500, 0, 0, 0), + (200, 40_000, 800, 900, 0), + (3_000, 2_000, 0, 0, 1_000), + (200_000, 300_000, 0, 0, 0), + ] + simulation = simulate( + { + f"person{i}": { + "trading_loss": {YEAR: loss}, + "employment_income": {YEAR: pay}, + "self_employment_income": {YEAR: profit}, + "self_employment_gross_receipts": {YEAR: receipts}, + "employee_pension_contributions": {YEAR: net_pay}, + } + for i, (loss, pay, profit, receipts, net_pay) in enumerate(rows) + } + ) + np.testing.assert_array_equal( + values(simulation, "uses_trading_allowance"), [False, False, True, False, False] + ) + assert values(simulation, "net_pay_pension_relief") == pytest.approx( + [0, 0, 0, 1_000, 0], abs=0.01 + ) + assert values(simulation, "income_tax_relief_cap") == pytest.approx( + [50_000, 50_000, 50_000, 50_000, 75_000], abs=0.05 + ) + assert values(simulation, RELIEF) == pytest.approx( + [0, 0, 0, 1_000, 75_000], abs=0.05 + ) + assert values(simulation, "loss_relief", 2025) == pytest.approx( + [0, 0, 0, 2_000, 125_000], abs=0.05 + ) + + +def test_zero_and_positive_relief_refresh_after_public_changes(): + simulation = simulate( + { + "person": { + "employment_income": {YEAR: 40_000}, + "trading_loss": {YEAR: 0}, + "loss_relief": {YEAR: 7_000}, + } + } + ) + assert values(simulation, RELIEF) == pytest.approx([0], abs=0.01) + assert values(simulation, "loss_relief", 2025) == pytest.approx([7_000], abs=0.01) + simulation.set_input("trading_loss", YEAR, np.array([50_000.0])) + assert values(simulation, RELIEF) == pytest.approx([40_000], abs=0.01) + assert values(simulation, "loss_relief", 2025) == pytest.approx([17_000], abs=0.01) + + branch = simulation.get_branch("current_loss_reset") + branch.set_input("trading_loss", YEAR, np.array([0.0])) + assert values(branch, RELIEF) == pytest.approx([0], abs=0.01) + assert values(branch, "loss_relief", 2025) == pytest.approx([7_000], abs=0.01) + branch.set_input("trading_loss", YEAR, np.array([500.0])) + assert values(branch, RELIEF) == pytest.approx([500], abs=0.01) + assert values(branch, "loss_relief", 2025) == pytest.approx([7_000], abs=0.01) + assert values(simulation, RELIEF) == pytest.approx([40_000], abs=0.01) + + simulation.set_input("trading_loss", YEAR, np.array([0.0])) + assert values(simulation, RELIEF) == pytest.approx([0], abs=0.01) + # A supplied final relief remains an engine override even with raw loss0. + simulation.set_input(RELIEF, YEAR, np.array([123.0])) + assert values(simulation, RELIEF) == pytest.approx([123], abs=0.01) + assert values(simulation, "loss_relief", 2025) == pytest.approx([7_000], abs=0.01) + + election = simulate( + { + "person": { + "employment_income": {YEAR: 40_000}, + "self_employment_income": {YEAR: 800}, + "self_employment_gross_receipts": {YEAR: 900}, + "trading_loss": {YEAR: 200}, + } + } + ) + np.testing.assert_array_equal(values(election, "uses_trading_allowance"), [True]) + assert values(election, RELIEF) == pytest.approx([0], abs=0.01) + election.apply_reform({ALLOWANCE: {str(YEAR): 0}}) + np.testing.assert_array_equal(values(election, "uses_trading_allowance"), [False]) + assert values(election, RELIEF) == pytest.approx([200], abs=0.01) + election.apply_reform({ALLOWANCE: {str(YEAR): 1_000}}) + np.testing.assert_array_equal(values(election, "uses_trading_allowance"), [True]) + assert values(election, RELIEF) == pytest.approx([0], abs=0.01) diff --git a/policyengine_uk/utils/measurement_branches.py b/policyengine_uk/utils/measurement_branches.py index 672eca5eac..eca3092ad6 100644 --- a/policyengine_uk/utils/measurement_branches.py +++ b/policyengine_uk/utils/measurement_branches.py @@ -10,6 +10,7 @@ from typing import Dict import numpy as np +from policyengine_core.simulations import Simulation as CoreSimulation # Every behavioural response. Each is measured from the position before any # response, so one response's measurement does not include another response, @@ -43,25 +44,15 @@ def retained_input_variables(simulation) -> set: def drop_calculated_values(simulation) -> None: - """Delete the values a simulation has calculated, keeping its inputs. + """Drop calculated arrays while preserving each actual input cell. - Inputs are variables without a formula, variables the simulation was built - from, and variables set since through set_input, as a scenario's - simulation modifier does to formula variables. Only variables the - simulation holds values for are visited. + An input for one period does not protect calculated values for other + periods of the same variable. Core keeps each stored set_input cell, + including model-owned values, using its period and branch records. """ - supplied = retained_input_variables(simulation) - variables = simulation.tax_benefit_system.variables - held = { - name - for population in simulation.populations.values() - for name in getattr(population, "_holders", {}) - } - for name in held: - variable = variables.get(name) - if variable is None or name in supplied or variable.is_input_variable(): - continue - simulation.delete_arrays(name) + # Routine cache cleanup does not change changed_from_baseline, as the + # UK wrapper's public drop_computed_arrays method would. + CoreSimulation.drop_computed_arrays(simulation) def held_behavioural_responses(person, period) -> dict: diff --git a/policyengine_uk/variables/gov/hmrc/income_tax/reliefs/trade_loss_relief_against_general_income.py b/policyengine_uk/variables/gov/hmrc/income_tax/reliefs/trade_loss_relief_against_general_income.py index 23fe7acab5..9a9084dafd 100644 --- a/policyengine_uk/variables/gov/hmrc/income_tax/reliefs/trade_loss_relief_against_general_income.py +++ b/policyengine_uk/variables/gov/hmrc/income_tax/reliefs/trade_loss_relief_against_general_income.py @@ -41,22 +41,29 @@ class trade_loss_relief_against_general_income(Variable): ] def formula(person, period, parameters): - # Ordinary net-pay contributions already reduce Step 1 employment - # income. That income cannot also consume a Step 2 trading loss. - net_income = max_( - 0, - person("net_income_before_trade_loss_relief", period) - - person("net_pay_pension_relief", period), - ) current_loss = supplied_input(person, "trading_loss", period) if current_loss is None: - current_loss = person.empty_array() + return person.empty_array() + loss = max_(0, current_loss) + # No new loss means no relief, without resolving an allowance + # election that can itself read earlier opening-loss balances. + if not loss.any(): + return person.empty_array() # Allowance treatment cannot retain a current expense-generated loss # on another trade in the same individual's tax year. loss = where( person("uses_trading_allowance", period), 0, - max_(0, current_loss), + loss, + ) + if not loss.any(): + return person.empty_array() + # Ordinary net-pay contributions already reduce Step 1 employment + # income. That income cannot also consume a Step 2 trading loss. + net_income = max_( + 0, + person("net_income_before_trade_loss_relief", period) + - person("net_pay_pension_relief", period), ) return min_( loss,