Skip to content

fix(wash-sale): keep a deferred loss pending until a sale with no repurchase in its window - #455

Merged
GeiserX merged 7 commits into
mainfrom
fix/wash-sale-definitive
Nov 18, 2026
Merged

GeiserX merged 7 commits into
mainfrom
fix/wash-sale-definitive

Conversation

@GeiserX

@GeiserX GeiserX commented Nov 18, 2026

Copy link
Copy Markdown
Owner

Problem

DeclaRenta released a deferred anti-churning loss as soon as you sold the shares you bought back. It never checked whether that sale was itself bought back within 2 months. The DGT keeps the loss pending until a «transmisión definitiva»: a sale with no new purchase of the same security in the 2 months before or after it (V3282-18, V2481-20, V1760-23, V0754-26, and the AEAT Manual IRPF 2025).

In the example from #451 (sell at −20, buy back, sell at −5, buy back again), 2025 deducted 20 € that should stay deferred.

The old engine also tied each loss to one purchase lot. Some losses then never came back: 200 € in V1760-23, and 1,933.30 € in V0046-20.

Fix

  • Pending losses wait in a queue per security, counted in shares.
  • Each sale day uses the purchases in its window that no earlier sale used. Loss lots always use them. Gain lots use them only while losses are pending.
  • The shares left over are definitive. Each one releases the loss of one pending share, oldest first.
  • A definitive sale that leaves no shares releases everything still pending. Scrip-dividend and merger shares still count as held.
  • blockedLossEur, reintegratedLossEur and the Modelo 100 formula keep their meaning. Only the year of a deduction can move. The lifetime total stays the same.

Each consulta is now a test that failed on the old engine: the #451 example, V3282-18, V0571-21, V1760-23 (with the total exit), V0754-26, V0913-08, V0046-20, V1294-22, plus a gain sale bought back in its window. A seeded property test checks that blocked equals released over closed positions.

What users see

  • Some years show less deductible loss (the Regla de los 2 meses: una pérdida diferida se libera aunque la acción recomprada se vuelva a recomprar dentro de plazo («transmisión definitiva») #451 example: 0 instead of −20 in 2025). Others show more, because stuck losses now come back.
  • Of the sample files, only trading212-v2 (2025 reintegrated 4.86 → 0) and binance-v2 (a 0.0000016 € release) change. Byte-identity: 38 files, 205 runs, 5 modes.
  • The operations table marks a sale that releases pending losses and names the loss sales it releases.
  • The tax estimate card shows released losses, so its lines add up to the base.
  • The CSV gains a last column Perdida_Reintegrada_EUR. The CLI JSON gains perdida_bloqueada_eur and perdida_reintegrada_eur.
  • The Renta Web guide no longer says the blocked loss is added to the new cost.

Migration note

This is in the in-app guide (5 locales), docs/casillas.md and docs/faq.md.

If you filed a year with DeclaRenta 0.66.5 or earlier, that version may have deducted a loss too early. When the new version releases it in a later year, do not deduct it again, or file an «autoliquidación complementaria» for the earlier year. The new version can also release a loss in an earlier year (V0046-20). If that year is filed, you can ask for a «solicitud de rectificación».

Known gaps

These are pinned as it.fails tests:

Checks

vitest: 168 files, 3128 passed, 3 expected fail. typecheck, typecheck:tests, lint and build:web are green.

Closes #451

…uy in its window (#451)

A blocked loss was keyed on the repurchase's buy date and released as soon
as that lot was sold, even when the sale was itself rebought inside its
window. The DGT releases a pending loss only on a «transmisión definitiva»
(V3282-18, V2481-20, AEAT Manual IRPF 2025), so 2025 in the issue example
deducted 20 that should stay deferred, and the lot key orphaned losses
(V1760-23) or never released them when FIFO sold older lots (V0046-20).

Pending losses now form a per-security queue counted in shares. Every loss
sale, and every gain sale while losses are pending, uses the unused in-window
rebuys with the existing BLOCK rules; the shares left are definitive and
release the oldest pending losses one share each (V0571-21, V0754-26). A
definitive sale day that leaves no shares releases everything left. The
per-disposal fields, the invariant and the fiscal formula are unchanged.
…top telling users it adds to the cost

A pending loss no longer belongs to the lot that blocked it, so the
operations tables now mark a releasing sale and name the loss sales it
releases. The Renta Web guide said the blocked amount is added to the new
position's cost and the casilla note said releases come from prior years;
both were wrong. The guide now explains the definitive-sale rule and warns
users who filed with 0.66.5 or earlier not to deduct a released loss twice.
All five locales.
…crip shares would let it escape (#451)

Absorption ran once per FIFO lot, oldest first. In a rebought sale of an old
gain lot and a new loss lot, the gain lot took the rebuy whenever any loss was
pending, so the loss lot was deducted now. Absorption now runs once per (key,
sale day) and hands the absorbed shares to the loss lots first, newest
acquisition first: the deductible part is the first-acquired shares (V0913-08,
V1294-22), and a loss lot in a sale with a net gain stays blocked (V0279-25).
V0913-08 now matches the DGT to the euro (144,500 / 138,500 / 300).

The total exit read the position from the BUY/SELL trades only, so it released
every pending loss while scrip dividend or merged shares were still held. It
now also asks FIFO (remaining lots plus the disposals' holding spans).

V0248-18, V0754-26 with pre-sale rebuys and V2481-20 are pinned as known gaps
(it.fails on the DGT's figure): the post-sale-first pick order, and for
V2481-20 mostly the same-day exclusion.
…hares, and tell users they can claim a loss moved to an earlier year

The release hint said «Esta venta no tiene recompra en el plazo» even on a
sale that a rebuy partly covers (V0913-08: 10 rebought, 955 definitive), next
to the line naming that rebuy. It now says the shares no rebuy covers are the
definitive transmission. The year total no longer speaks of sales with no
rebuy either. The migration note in the Renta Web guide also covers the other
direction: a loss the new engine releases in an already filed earlier year
can be claimed by rectifying that return. All five locales.
…the pick-order gaps the consultas prove (#451)

The design doc and the Hard Trace now say absorption runs per sale day with
loss lots first, newest first (the lot-attribution gap is closed), and that
the total exit also reads FIFO. The pick-order gap cites V0248-18 (no same-day
buy) and the V0754-26 pre-sale timing, and credits most of V2481-20 to the
same-day exclusion. Two lines in casillas.md and modelos-fiscales.md still
described the old lot-keyed release; casillas.md and faq.md also gain the
earlier-year side of the migration note.
…imate, CSV and JSON

The tax estimate card listed blocked losses but not released ones, so a year
with 100 of gains and 25 released showed a 75 base with nothing to explain
it. It now shows «Pérdidas diferidas que ahora se integran: −25 €» (five
locales). The CSV gains a last column Perdida_Reintegrada_EUR (earlier columns
keep their positions) and the CLI JSON gains perdida_bloqueada_eur and
perdida_reintegrada_eur per operation, so an export says which sale blocked
or released what, as the web table already does.
@coderabbitai

coderabbitai Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Caution

Review failed

The pull request is closed.

  • 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

@GeiserX
GeiserX merged commit bf204e8 into main Nov 18, 2026
5 of 6 checks passed
@GeiserX
GeiserX deleted the fix/wash-sale-definitive branch November 18, 2026 18:40
@codecov

codecov Bot commented Nov 18, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.82%. Comparing base (101f60e) to head (3841172).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main     #455      +/-   ##
==========================================
+ Coverage   93.72%   93.82%   +0.09%     
==========================================
  Files          63       63              
  Lines        7733     7819      +86     
  Branches     2656     2678      +22     
==========================================
+ Hits         7248     7336      +88     
+ Misses        400      398       -2     
  Partials       85       85              
Files with missing lines Coverage Δ
src/cli/format-report.ts 71.42% <ø> (+14.28%) ⬆️
src/cli/index.ts 0.00% <ø> (ø)
src/engine/taxable-base.ts 100.00% <100.00%> (ø)
src/engine/wash-sale.ts 99.11% <100.00%> (+0.68%) ⬆️
src/generators/csv.ts 98.66% <100.00%> (ø)
src/generators/pdf-web.ts 98.76% <ø> (ø)
src/generators/report.ts 97.51% <ø> (ø)
src/i18n/locales/ca.ts 100.00% <ø> (ø)
src/i18n/locales/en.ts 100.00% <ø> (ø)
src/i18n/locales/es.ts 100.00% <ø> (ø)
... and 3 more
🚀 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 added a commit that referenced this pull request Nov 18, 2026
…ing deferred losses to the wrong year (#459)

* fix(wash-sale): stop short covers, empty sales and spin-offs from releasing 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.

* fix(wash-sale): stop a short-cover buy from blocking a loss nothing can 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.
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.

Regla de los 2 meses: una pérdida diferida se libera aunque la acción recomprada se vuelva a recomprar dentro de plazo («transmisión definitiva»)

1 participant