Skip to content

fix(wash-sale): stop short covers, empty sales and spin-offs from moving deferred losses to the wrong year - #459

Merged
GeiserX merged 3 commits into
mainfrom
fix/wash-sale-cr455
Nov 18, 2026
Merged

GeiserX merged 3 commits into
mainfrom
fix/wash-sale-cr455

Conversation

@GeiserX

@GeiserX GeiserX commented Nov 18, 2026 •

Copy link
Copy Markdown
Owner

Problem

#455 shipped in v0.66.6 before CodeRabbit finished. Its late review found cases where a pending anti-churning loss came back too early, too late or never. It also found wording that promised more than the engine does.

  1. Closing a short position released pending losses from earlier long sales. A cover sells no shares the user held.
  2. A zero-share SELL row counted as a total exit and released everything pending.
  3. Spin-off and merger shares inherit the parent's tax acquisition date. So the "sold everything" check saw them as held before they existed.
  4. The release loop rescanned spent queue entries: 10,000 one-share lots took 20.6 s.
  5. A buy that covers a short counted as a repurchase. It could block a loss that nothing would ever release.
  6. The help told users to file a «complementaria». For tax year 2024 onward, the procedure is the «autoliquidación rectificativa».

Fix

  • A short cover releases nothing and is not an exit. The shares its buy covers go straight back to the lender, so they are not a repurchase.
  • Zero-share rows are skipped.
  • Spin-off and merger lots carry a separate entry date for the holding check. The tax acquisition date does not change.
  • The release loop keeps a cursor: 10,000 lots now take 0.2 s.
  • A property test over random long and short histories checks that every blocked euro comes back exactly once, in all three FX methods.

Warnings

No file can show a repurchase made after the uploaded data ends. A sale whose window runs past the data now gets a warning, and no amount is held back.

  • With several brokers, each security is checked against the files of the brokers that trade it.
  • For a window that ends after the 30 June filing deadline, the warning says the window is still open. If the user buys the same security before it closes, the warning points to an autoliquidación rectificativa.

Wording

AEAT, Manual práctico de Renta 2025: «Este nuevo sistema de rectificación se configura como el procedimiento general de modificación de declaraciones de IRPF desde el período impositivo 2024».
https://sede.agenciatributaria.gob.es/Sede/ayuda/manuales-videos-folletos/manuales-practicos/irpf-2025/c18-cuota-liquida-resultante-autoliquidacion/regularizacion-situaciones-tributarias/general.html

What users see

  • No fixture's tax figures move, in any FX method. The output is byte-identical apart from the new warnings.
  • Users with short positions can see a loss that a cover used to block become deductible.
  • Users with zero-share rows, or spin-off and merger shares around a pending loss, can see the release move to the right sale or year.

Left on purpose

Follow-up to #455, from the CodeRabbit review of its exact diff on the fork mirror.

Summary by CodeRabbit

  • New Features
    • Reports now warn when uploaded transaction data does not cover the end of an anti-churning window, including when the window remains open at the filing deadline. Warnings reflect broker-specific data coverage and indicate when later transactions may be needed.
  • Bug Fixes
    • Deferred losses are now released proportionally for shares not covered by repurchases, with older losses released first. Short covers and zero-share disposals no longer trigger releases, and corporate-action dates are accounted for in holding-period checks.
  • Documentation
    • Updated guidance clarifies loss-release rules and correction procedures by tax year.

…easing deferred losses early

Follow-up to #455 from its late review.

- A short cover transmits no held shares: it no longer seeks rebuys as a gain
  lot, releases pending long losses or counts as a total exit. Its own loss
  still blocks.
- A zero-share disposal no longer drains the queue as a total exit.
- The total-exit holding test reads the date shares entered the security
  (new optional entryDate on spin-off and merger lots and their disposals),
  not the parent's inherited tax acquireDate.
- The release walks the queue with a cursor: 10,000 one-share lots go from
  20.6 s to 0.2 s.
- One shared warning (report.antichurning_window_past_data, 5 locales) for a
  year's sale whose window ends after the last date the upload covers and
  whose block or release a later buy could change. Nothing is withheld.
- Docs and the 5 locales say only the shares no rebuy covers are definitive,
  a sale that empties the position releases everything only with no rebuy,
  the FAQ gives the 1-year window for unlisted securities, and a filed year
  is corrected with an autoliquidación rectificativa from 2024 on
  (complementaria / solicitud de rectificación for 2023 and earlier).
- The lifetime-total property sums Decimals before rounding.
…an release

Review of the #455 follow-up.

- The shares a buy-to-cover acquires go straight back to the lender and never
  stay in the patrimony, so they are no repurchase. The detector now indexes a
  C / C;O BUY only for what FIFO leaves after its short disposals that day, and
  a C buy with no open short not at all, as FIFO and fx-fifo already do. Before,
  a cover buy could block a loss, and once the position stayed flat nothing
  released it (lifetime blocked 20, released 0). A property over random
  long/short histories now pins blocked = released in all 3 FX methods.
- The window-past-data warning checks each merged broker on its own: a security
  is covered up to the earliest end among the brokers that trade it, so a
  DEGIRO file ending on its December loss no longer hides behind an IBKR
  statement that runs into the next year.
- From tax year 2024, a sale whose window ends after the 30 June filing
  deadline gets its own warning (5 locales): the window is still open when the
  return is filed, so it never says the result is already correct, and a later
  buy means an autoliquidación rectificativa.
- annex.wash_hint (shown on every blocked sale) no longer reads as a
  whole-sale rule, in the 5 locales.
- The FAQ states art. 33.5.g's real test (not admitted to an EU regulated
  market) and the engine's ISIN heuristic as a limit (#452).
- Merger entry-date regression tests next to the spin-off ones.
@coderabbitai

coderabbitai Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Caution

Review failed

The pull request is closed.

Walkthrough

The changes update anti-churning loss release rules for short covers, partial repurchases, and zero-quantity disposals. FIFO lots carry security-entry dates. Reports warn when repurchase windows extend beyond uploaded data or remain open at the filing deadline. Documentation, locale guidance, and tests cover these behaviors and tax-year-specific correction procedures.

Changes: Anti-churning behavior and guidance

Layer / File(s) Summary
Security-entry dates and FIFO propagation
src/types/tax.ts, src/engine/fifo.ts, src/engine/wash-sale.ts, tests/integration/antichurning-definitive-e2e.test.ts
Lots created by mergers and spin-offs retain their tax acquisition date and record when shares entered the security. Disposals carry that entry date, and holding checks use it when available.
Held-share and pending-loss release
src/engine/wash-sale.ts, tests/engine/wash-sale.test.ts, tests/integration/antichurning-definitive-e2e.test.ts, docs/casillas.md, docs/design/antichurning-proportional.md, CLAUDE.md
Short covers and zero-quantity disposals do not release pending losses or count as total exits. Repurchases affect only covered shares. Queue release advances a cursor, and tests cover short-cover behavior, queue scale, generated histories, and raw totals.
Repurchase-window coverage warnings
src/types/ibkr.ts, src/parsers/merge.ts, src/engine/wash-sale.ts, src/generators/report.ts, src/i18n/locales/*, tests/integration/antichurning-definitive-e2e.test.ts, docs/casillas.md, docs/design/antichurning-proportional.md, CLAUDE.md
The report warns when eligible sale windows extend beyond uploaded data. Broker-specific coverage uses the earliest applicable end date among brokers trading the security. A separate warning covers windows still open after the filing deadline for tax years from 2024.
Guidance and correction procedures
docs/casillas.md, docs/design/antichurning-proportional.md, docs/faq.md, src/i18n/locales/*, tests/i18n/guide-consistency.test.ts, CLAUDE.md
Documentation and locale guidance describe proportional, oldest-first releases and distinguish correction procedures for 2024 onward from those for 2023 and earlier. The FAQ also describes the ISIN-based window handling and the one-year rule for securities not admitted to trading on an EU regulated market.

Estimated code review effort: 4 (Complex) | ~45 minutes

Change: Bug fix

Possibly related issues

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@codecov

codecov Bot commented Nov 18, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.21429% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 93.96%. Comparing base (7b19cbc) to head (9322dce).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
src/engine/wash-sale.ts 97.53% 2 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main     #459      +/-   ##
==========================================
+ Coverage   93.90%   93.96%   +0.06%     
==========================================
  Files          64       64              
  Lines        8103     8201      +98     
  Branches     2790     2838      +48     
==========================================
+ Hits         7609     7706      +97     
- Misses        405      406       +1     
  Partials       89       89              
Files with missing lines Coverage Δ
src/engine/fifo.ts 96.83% <100.00%> (+0.17%) ⬆️
src/generators/report.ts 97.85% <100.00%> (+0.14%) ⬆️
src/i18n/locales/ca.ts 100.00% <ø> (ø)
src/i18n/locales/en.ts 100.00% <ø> (ø)
src/i18n/locales/es.ts 100.00% <ø> (ø)
src/i18n/locales/eu.ts 100.00% <ø> (ø)
src/i18n/locales/gl.ts 100.00% <ø> (ø)
src/parsers/merge.ts 98.68% <100.00%> (+<0.01%) ⬆️
src/engine/wash-sale.ts 98.76% <97.53%> (-0.35%) ⬇️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@GeiserX
GeiserX merged commit 3569621 into main Nov 18, 2026
7 of 8 checks passed
@GeiserX
GeiserX deleted the fix/wash-sale-cr455 branch November 18, 2026 19:53
GeiserX added a commit that referenced this pull request Nov 18, 2026
…shares, and name the EEA in the market test (#461)

* fix(wash-sale): keep short covers, same-ISIN TC rows and statement-only brokers from moving deferred losses

Late review of #459 (CodeRabbit on the exact diff):

- Same-day covers now take the short in FIFO's processing order. FIFO runs a
  C;O buy before a C buy, so an orphan C buy listed first in the file was
  indexed as a repurchase and blocked a loss with no replacement shares.
  The comparator is now exported from fifo.ts (compareFifoTradeOrder) and
  used by both.
- The total exit gives the rest of the queue to the day's last long sale,
  never to a same-day short cover.
- A TC row that names no new security is booked as a merger of the ISIN
  into itself; it no longer stamps entryDate, so held shares do not look
  bought on the TC date and an earlier sale is not a total exit.
- The window-past-data coverage index counts a broker with a statement end
  and no trades, so its later statement end cannot hide another broker's
  incomplete window.
- The short-cover unit test flags the cover buy C, as FIFO data does.

No fixture number changes in any FX method.

* docs(antichurning): stop calling NYSE and Nasdaq a deviation, they are equivalent markets (DGT V0778-25)

DGT V0778-25 (binding, 05/05/2025) reads art. 33.5.f to cover any
third-country market the European Commission declared equivalent to an EU
regulated market; Implementing Decision (EU) 2017/2320 lists NYSE and
Nasdaq. So a share listed only there gets the 2-month window, as the engine
already does. The 1-year window (33.5.g) is only for securities admitted to
neither, e.g. OTC Markets; that is the one case where the ISIN heuristic
deviates (#452).

The FAQ, casillas, modelos-fiscales and design docs, CLAUDE.md, the
anti-churning hints and the window-past-data warning (5 locales, plus the
Spanish text report.ts writes) now say this. guide-consistency pins the new
wording and rejects the EU-only one. No engine change. The design doc and
CLAUDE.md also record the late-review fixes of #459.

* fix(wash-sale): count the shares an intraday short-to-long flip keeps as a repurchase

A C;O buy runs before the day's SELL O rows in FIFO and a C buy runs after
them, so a C;O buy can only cover a short opened on an earlier day. The
detector shared one day budget between them, gave the flip's same-day short
to the C;O buy, and then indexed nothing for the C buy that FIFO keeps: a
loss FIFO-held shares replace was deducted at once. Split the covered shares
by the short's open day (the short disposal's acquireDate).

* docs(antichurning): name the EEA and only the US, Australia and Hong Kong as equivalent markets, and keep crypto out of letter g

V0778-25 places letter f's regulated markets in the whole European Economic
Area, so an Oslo-only share read as 1 year in the hints. Only Implementing
Decisions 2017/2318, 2017/2319 and 2017/2320 are in force (Switzerland's
lapsed on 30/06/2019, the UK has none), so a share listed only in London,
SIX or Toronto falls under letter g: the #452 gap is wider than OTC Markets.
Crypto is no «valor o participación»: the law applies art. 33.5.e to it,
which the engine does not (#457). Docs, CLAUDE.md, engine comments and the
hints in all 5 locales now say so; the guide test pins it.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant