diff --git a/changelog.d/2087.fixed.md b/changelog.d/2087.fixed.md new file mode 100644 index 0000000000..50d6a61145 --- /dev/null +++ b/changelog.d/2087.fixed.md @@ -0,0 +1,11 @@ +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. + +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/docs/engineering/income-tax-trading-losses.md b/docs/engineering/income-tax-trading-losses.md new file mode 100644 index 0000000000..2050ebb110 --- /dev/null +++ b/docs/engineering/income-tax-trading-losses.md @@ -0,0 +1,67 @@ +# 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). + +## 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. 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 + +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/simulation.py b/policyengine_uk/simulation.py index f32010b536..6a73bbad95 100644 --- a/policyengine_uk/simulation.py +++ b/policyengine_uk/simulation.py @@ -1114,14 +1114,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_years( - self, retained.intersection(self.tax_benefit_system.variables) - ) + drop_calculated_values(self) def get_known_variables(self): variables = [] 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..60184e6d85 --- /dev/null +++ b/policyengine_uk/tests/policy/baseline/gov/hmrc/income_tax/reliefs/trade_loss_carry_forward.yaml @@ -0,0 +1,411 @@ +- 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 + +# 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 + +# ITTOIA 2005 ss.783AE(1), 783AF(2), 783AG and 783AL: +# https://www.legislation.gov.uk/ukpga/2005/5/section/783AF +# Relevant receipts are £400 trade + £600 Chapter 8 income = £1,000. +# The loss-making trade has £600 expenses and a £200 loss; the model's +# positive-profit input is zero. No allowance exclusion applies. +- name: Shared trading allowance carry-forward under full relief on miscellaneous income + period: 2026 + input: + age: + 2025: 40 + 2026: 41 + employment_income: + 2025: 0 + 2026: 0 + taxable_social_security_income: + 2025: 0 + 2026: 0 + capital_allowances: + 2025: 0 + 2026: 0 + employee_pension_contributions: + 2025: 0 + 2026: 0 + personal_pension_contributions: + 2025: 0 + 2026: 0 + employer_pension_contributions: + 2025: 0 + 2026: 0 + pension_contributions_via_salary_sacrifice: + 2025: 0 + 2026: 0 + self_employment_gross_receipts: + 2025: 400 + 2026: 6_000 + self_employment_income: + 2025: 0 + 2026: 5_000 + trading_loss: + 2025: 200 + 2026: 0 + miscellaneous_income: + 2025: 600 + 2026: 0 + income_not_otherwise_charged: + 2025: 600 + 2026: 0 + output: + uses_trading_allowance: + 2025: true + trading_allowance_deduction: + 2025: 0 + miscellaneous_income_trading_allowance_deduction: + 2025: 600 + taxable_miscellaneous_income: + 2025: 0 + trade_loss_relief_against_general_income: + 2025: 0 + # Full relief makes the trade's loss nil, even though only the + # miscellaneous-income deduction is positive. None carries into 2026. + loss_relief: 0 + taxable_self_employment_income: 5_000 + +# The same £400 receipts with £1,200 expenses gives an £800 trade loss. +# Ordinary treatment wins over the £600 allowance saving; £600 of actual +# general-income relief leaves £200 for the next year's same-trade profit. +- name: Shared trading allowance carry-forward after ordinary treatment preserves the unused loss + period: 2026 + input: + age: + 2025: 40 + 2026: 41 + employment_income: + 2025: 0 + 2026: 0 + taxable_social_security_income: + 2025: 0 + 2026: 0 + capital_allowances: + 2025: 0 + 2026: 0 + employee_pension_contributions: + 2025: 0 + 2026: 0 + personal_pension_contributions: + 2025: 0 + 2026: 0 + employer_pension_contributions: + 2025: 0 + 2026: 0 + pension_contributions_via_salary_sacrifice: + 2025: 0 + 2026: 0 + self_employment_gross_receipts: + 2025: 400 + 2026: 6_000 + self_employment_income: + 2025: 0 + 2026: 5_000 + trading_loss: + 2025: 800 + 2026: 0 + miscellaneous_income: + 2025: 600 + 2026: 0 + income_not_otherwise_charged: + 2025: 600 + 2026: 0 + output: + uses_trading_allowance: + 2025: false + trading_allowance_deduction: + 2025: 0 + miscellaneous_income_trading_allowance_deduction: + 2025: 0 + taxable_miscellaneous_income: + 2025: 600 + trade_loss_relief_against_general_income: + 2025: 600 + loss_relief: 200 + # £5,000 profit less the £200 remaining old loss; known 2026 expenses + # equal the allowance, so no extra trading-allowance deduction applies. + taxable_self_employment_income: 4_800 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..bc17978185 --- /dev/null +++ b/policyengine_uk/tests/test_income_tax_loss_carry_forward.py @@ -0,0 +1,184 @@ +"""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() + + +@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 + # 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 + + +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/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 diff --git a/policyengine_uk/tests/test_projection_horizon.py b/policyengine_uk/tests/test_projection_horizon.py index 6b2ff922c0..7b1166acd4 100644 --- a/policyengine_uk/tests/test_projection_horizon.py +++ b/policyengine_uk/tests/test_projection_horizon.py @@ -458,3 +458,75 @@ def test_tax_free_savings_formula_takes_over_after_the_horizon(): assert simulation.calculate( "tax_free_savings_income", PROJECTION_END_YEAR + 1 ).values == pytest.approx(np.zeros(len(HOUSEHOLDS))) + + +def test_positive_effective_losses_preserve_the_projection_horizon(record_property): + """The horizon constructor also works when allowance election leaves a loss. + + Change only the loss column of the public fixture. Qualify the 2024 + election explicitly: later years retain their actual policy, including + the allowance increase from 2027. + """ + import json + + from policyengine_core.periods import period + from policyengine_uk.utils.supplied_inputs import supplied_input + + dataset = _dataset() + dataset.person["trading_loss"] = 2_000.0 + simulation = Microsimulation(dataset=dataset) + years = list(range(BASE_YEAR, PROJECTION_END_YEAR + 1)) + assert [int(year) for year in simulation.dataset.years] == years + + uses_allowance = np.asarray( + simulation.calculate("uses_trading_allowance", BASE_YEAR), dtype=bool + ) + supplied_loss = supplied_input( + simulation.populations["person"], "trading_loss", period(BASE_YEAR) + ) + assert supplied_loss is not None + supplied_loss = np.asarray(supplied_loss, dtype=float) + effective_loss = np.where(uses_allowance, 0, np.maximum(0, supplied_loss)) + record_property( + "positive_effective_loss_premise", + json.dumps( + { + "base_year": BASE_YEAR, + "uses_trading_allowance": uses_allowance.tolist(), + "supplied_trading_loss": supplied_loss.tolist(), + "effective_current_loss": effective_loss.tolist(), + }, + sort_keys=True, + ), + ) + np.testing.assert_array_equal(uses_allowance, np.zeros(len(HOUSEHOLDS), dtype=bool)) + np.testing.assert_array_equal(supplied_loss, np.full(len(HOUSEHOLDS), 2_000)) + np.testing.assert_array_equal(effective_loss, np.full(len(HOUSEHOLDS), 2_000)) + general_relief = np.asarray( + simulation.calculate("trade_loss_relief_against_general_income", BASE_YEAR), + dtype=float, + ) + record_property("actual_general_income_relief", json.dumps(general_relief.tolist())) + assert np.isfinite(general_relief).all() + assert ((general_relief >= 0) & (general_relief <= effective_loss)).all() + assert (general_relief > 0).all() + horizon_stock = np.asarray( + simulation.calculate("loss_relief", PROJECTION_END_YEAR), dtype=float + ) + record_property( + "positive_effective_loss_qualification", + json.dumps( + { + "base_year": BASE_YEAR, + "uses_trading_allowance": uses_allowance.tolist(), + "supplied_trading_loss": supplied_loss.tolist(), + "effective_current_loss": effective_loss.tolist(), + "actual_general_income_relief": general_relief.tolist(), + "horizon_year": PROJECTION_END_YEAR, + "horizon_opening_stock": horizon_stock.tolist(), + }, + sort_keys=True, + ), + ) + assert np.isfinite(horizon_stock).all() + assert (horizon_stock >= 0).all() 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 27b5997c6d..769d36d4fb 100644 --- a/policyengine_uk/utils/measurement_branches.py +++ b/policyengine_uk/utils/measurement_branches.py @@ -10,6 +10,7 @@ from typing import Dict, Iterable 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, @@ -73,32 +74,15 @@ def drop_calculated_years(simulation, names: Iterable[str]) -> None: def drop_calculated_values(simulation) -> None: - """Delete the values a simulation has calculated, keeping its inputs. - - 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. It keeps only the years of - each input variable that the data or a caller supplied (see - drop_calculated_years). It visits only the variables the simulation holds - values for. + """Drop calculated arrays while preserving each actual input cell. + + 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", {}) - } - inputs = set() - for name in held: - variable = variables.get(name) - if variable is None: - continue - if name in supplied or variable.is_input_variable(): - inputs.add(name) - continue - simulation.delete_arrays(name) - drop_calculated_years(simulation, inputs) + # 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/utils/pensions.py b/policyengine_uk/utils/pensions.py index 67d8799828..ba437c1b72 100644 --- a/policyengine_uk/utils/pensions.py +++ b/policyengine_uk/utils/pensions.py @@ -98,7 +98,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( @@ -126,7 +130,7 @@ def annual_allowance_net_income(person, period, parameters): loss = np.where( person("uses_trading_allowance", period), 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 a5d5f05ab6..1a1bc1c2a3 100644 --- a/policyengine_uk/utils/supplied_inputs.py +++ b/policyengine_uk/utils/supplied_inputs.py @@ -97,6 +97,7 @@ "pip_m_points", "local_bus_trips", "local_bus_uncapped_single_fare", + "loss_relief", "miscellaneous_income_trading_allowance_deduction", "monthly_domestic_energy_consumption", "ni_class_4_losses_brought_forward", 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..885fe2e11a 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,72 @@ 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" - reference = dict( - title="Income Tax Act 2007 s. 83", - href="https://www.legislation.gov.uk/ukpga/2007/3/section/83", - ) + 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", + ), + dict( + title="Income Tax (Trading and Other Income) Act 2005 s. 783AF", + href="https://www.legislation.gov.uk/ukpga/2005/5/section/783AF", + ), + ] 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 + quantity_type = STOCK + + 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("uses_trading_allowance", year), + 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 a63ba805ae..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 @@ -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,29 @@ 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)) + current_loss = supplied_input(person, "trading_loss", period) + if current_loss is None: + 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, - person("trading_loss", period), + 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, 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