Back to blog

Tax Loss Harvesting Capital Gains: How to Calculate FIFO Offsets

Tax loss harvesting calculation worksheet showing FIFO equity lots and gains

Tax loss harvesting capital gains is the deliberate realization of unrealized investment losses before year-end to offset taxable realized capital gains on a dollar-for-dollar basis. The net taxable gain is calculated as Net Capital Gain = Total Realized Gains − Qualifying Realized Losses, reducing your statutory tax liability before December 31.

While the general concept sounds straightforward, the execution is governed by rigorous mechanical accounting. Many private investors assume they can pick and choose their most deeply depreciated purchase lot to generate an artificial tax write-off. In reality, most international tax jurisdictions and standard brokerage default accounts mandate the First-In, First-Out (FIFO) accounting method. Under strict FIFO, you cannot cherry-pick losing shares: you are legally required to liquidate your oldest acquired shares first. If those early lots carry significant unrealized gains, your attempt to harvest a tax loss can backfire, producing an unintended taxable gain instead.

Understanding the mathematical interplay between FIFO lot liquidation, annual offset limitations, and strict repurchase restrictions—such as the US 30-day wash-sale rule and the European 2-month repurchase rule—is essential before executing any trades in the fourth quarter.

TL;DR:

  • Tax-loss harvesting allows you to neutralize realized capital gains dollar-for-dollar, lowering your taxable income before the tax year closes on December 31.
  • Under mandatory or default FIFO rules, liquidating shares forces the sale of your oldest lots first, which may trigger gains rather than harvest losses.
  • In jurisdictions like Spain, FIFO is statutory for equities and investment funds; in the US, FIFO is the default unless specific share identification is formally executed at the time of trade.
  • Unused capital losses in the US can offset up to $3,000 of ordinary income annually, while in Spain they can offset up to 25% of positive dividend and interest income.
  • Repurchase rules (the US 30-day wash-sale rule and Spain's 2-month anti-application rule) temporarily disallow losses if you acquire identical assets within the restricted window.
  • Managing your tax lots privately across multiple brokers prevents surprise tax liabilities and preserves total financial confidentiality.
Netclariq
Master FIFO Gains and Losses Privately
Track investment lots, calculate automated FIFO capital gains, and model tax-loss offsets securely in netclariq without linking a bank account.
Explore Netclariq

Table of Contents

The December 31 Deadline: Why Year-End Tax-Loss Harvesting Matters

Tax years for individuals in the United States, Spain, and most OECD nations measure net investment performance strictly between January 1 and December 31 (unlike in the United Kingdom, where the individual capital gains tax year runs from April 6 to April 5). Once the clock strikes midnight on New Year's Eve, your net capital gains for that calendar fiscal year become legally fixed.

Throughout the year, portfolio management naturally generates taxable events. You may have rebalanced an overweight tech position, liquidated mutual funds to fund a property purchase, or trimmed equity positions that exceeded your allocation limits. Each sale creates a realized gain or loss. If market corrections occur in other sectors toward the end of the year, those unrealized "paper" losses represent an active financial resource.

Harvesting a loss converts an unrealized market dip into an immediate tax asset. For example, if you realized €20,000 in short-term or general capital gains earlier in the year, leaving that balance untouched could expose you to top marginal capital gains rates of 20% to 28%, depending on your jurisdiction. Realizing €20,000 in qualifying losses before December 31 reduces your net taxable capital gain for the year to exactly zero.

However, executing tax-loss harvesting in the final weeks of the quarter requires precise scheduling. Trade settlement rules matter. Under the global standard T+1 settlement cycle (shortened from T+2 in the US, Canada, and Mexico in 2024, and progressively harmonized across European bourses), trades settle one business day after execution. Selling a position on December 31 may push legal settlement into the following tax year if markets close early or if public bank holidays intervene. To guarantee that a loss applies to the current tax year, transactions should be completed well in advance of the final trading days of December.

How FIFO Accounting Directly Dictates Your Realized Losses

The single most common mistake retail investors make when attempting to harvest losses is ignoring their lot accounting methodology. When you buy shares of a stock or exchange-traded fund (ETF) over time—such as through dollar-cost averaging—you create distinct purchase tranches, known as "tax lots." Each lot possesses its own acquisition date, share count, and purchase price (cost basis).

Under a First-In, First-Out (FIFO) accounting framework, the first shares you purchase are legally deemed to be the first shares you sell:

FIFO Realized Gain/Loss = Proceeds from Sale − Cost Basis of Oldest Unsold Lot

In jurisdictions such as Spain, FIFO is not merely a broker preference; it is legally required for homogeneous securities by the tax authority under Article 37.2 of Ley del IRPF (Ley 35/2006) for shares and investment funds. In the United States, the Internal Revenue Service (IRS) establishes FIFO as the default cost basis reporting method unless the taxpayer explicitly designates "Specific Identification" (Spec ID) with their custodian before trade execution.

Consider what occurs when you hold mixed lots of an asset purchased across a multi-year bull market that has recently experienced a correction:

  1. Lot A (Oldest): Purchased at $40.
  2. Lot B (Intermediate): Purchased at $110.
  3. Current Market Price: $75.

If you observe the current market price of $75 and remember buying shares at $110, you might anticipate a $35-per-share loss. But under strict FIFO, you are required to liquidate Lot A first. Selling those shares produces a realized capital gain of $35 per share ($75 sale price minus $40 cost basis). Instead of offsetting gains realized elsewhere, the sale creates an additional tax burden.

To access the $35 loss embedded in Lot B under FIFO, you must sell the entirety of Lot A plus Lot B. The resulting net realized tax impact becomes the mathematical sum of both lots:

Net Realized Tax Impact = Gain from Lot A + Loss from Lot B

Using our numbers: Net Impact = ($75 − $40) + ($75 − $110) = +$35 − $35 = $0.00.

Because of this mechanism, tax-loss harvesting under FIFO requires verifying your oldest active tranches across all accounts holding that asset. Attempting to harvest losses blindly without checking tranche history frequently leads to unforced tax errors.

Step-by-Step Calculation: Tax Loss Harvesting Capital Gains Under FIFO

Once you understand which lots will be liquidated, you must follow the statutory netting rules of your jurisdiction to calculate the exact offset limit. Tax codes do not simply dump all transactions into a single bucket without ordering rules.

The Standard Netting Framework

In the United States and jurisdictions using dual-holding frameworks, transactions are divided by holding period:

  • Short-Term Capital Gains/Losses: Assets held for one year or less.
  • Long-Term Capital Gains/Losses: Assets held for more than one year.

The netting process proceeds through four mandatory mathematical steps:

  1. Calculate Net Short-Term Position: Net Short-Term = Realized Short-Term Gains − Realized Short-Term Losses.
  2. Calculate Net Long-Term Position: Net Long-Term = Realized Long-Term Gains − Realized Long-Term Losses.
  3. Cross-Category Netting: If one category results in a net gain and the other results in a net loss, the net loss offsets the net gain: Final Net Capital Gain/Loss = Net Short-Term + Net Long-Term.
  4. Income Offset and Carryforward:
    • If the final result is a net gain, it is taxed according to applicable marginal rates.
    • If the final result is a net loss, up to $3,000 per year ($1,500 if married filing separately) can be deducted against ordinary income in the US. Any remaining net loss carries forward indefinitely to future tax years.

The European / Spanish Capital Netting Rules

If you are an expatriate, resident, or dual citizen filing taxes in Spain, the netting framework is governed by savings income (renta del ahorro) rules rather than holding-period splits:

  1. Netting of Capital Alterations: All capital gains and losses realized from the transfer of assets (equities, funds, real estate) during the calendar year are netted together: Net Alteration = Capital Gains − Capital Losses.
  2. Compensation Against Savings Income: If the net capital alteration is negative, that net loss can offset up to 25% of positive returns from movable capital (rendimientos del capital mobiliario, such as dividends and interest) earned in the same tax year.
  3. Four-Year Carryforward: Any remaining negative capital balance cannot offset general wage income. Instead, it must be carried forward to offset net capital gains (and up to 25% of movable capital income) in the subsequent four consecutive tax years. For deeper coverage of these rates, review our analysis of Spain's capital gains tax rules.
Metric / Rule United States (IRS) Spain (Agencia Tributaria) United Kingdom (HMRC)
Default Lot Method FIFO (Spec ID permitted) Strict FIFO (statutory) Share Pool (Section 104)
Short- vs Long-Term Split Yes (1-year boundary) No (flat savings brackets) No (standard CGT rates)
Ordinary Income Offset Up to $3,000/year 0% (only 25% of dividends/interest) 0%
Loss Carryforward Period Indefinite 4 Tax Years Indefinite
Repurchase Restriction 30-day Wash-Sale Rule 2-month Anti-Application Rule 30-day "Bed & Breakfast"

Worked Example: Trimming Mixed-Lot Equities Under Strict FIFO

To see how the calculations work in practice, let us examine a concrete scenario. Suppose you have realized €14,000 in capital gains during the 2026 calendar year through sales of a diversified index ETF. You want to harvest losses from an individual equity position—Global Logistics SA—to bring your net capital gain as close to zero as possible before December 31.

You hold 600 shares of Global Logistics SA across three distinct purchase lots. The current market price on November 15, 2026, is €45 per share.

Your historical purchase ledger reflects the following cost bases:

  • Lot 1 (Acquired March 2021): 200 shares at €25 per share. Total Cost Basis: €5,000.
  • Lot 2 (Acquired October 2022): 200 shares at €85 per share. Total Cost Basis: €17,000.
  • Lot 3 (Acquired June 2024): 200 shares at €60 per share. Total Cost Basis: €12,000.

Under strict FIFO rules, you must liquidate Lot 1 before you can touch Lot 2 or Lot 3. Let us model what happens at different sale volumes.

Scenario A: Selling 200 Shares

You sell 200 shares at the prevailing market price of €45.

  • Proceeds: 200 × €45 = €9,000
  • Cost Basis (Lot 1): 200 × €25 = €5,000
  • Realized Gain/Loss: €9,000 − €5,000 = +€4,000 Gain

Outcome: You intended to harvest a loss, but FIFO forced the sale of your lowest-basis shares. Your total realized gains for 2026 increase from €14,000 to €18,000, worsening your tax liability.

Scenario B: Selling 400 Shares

To access the substantial loss in Lot 2, you must sell enough shares to clear Lot 1 entirely.

  • Lot 1 Realized Result: 200 × (€45 − €25) = +€4,000 Gain
  • Lot 2 Realized Result: 200 × (€45 − €85) = −€8,000 Loss
  • Net Realized Result: +€4,000 − €8,000 = −€4,000 Loss

Tax Position Update:

  • Prior Realized Gains: €14,000
  • Harvested Loss: −€4,000
  • Updated Net Taxable Capital Gain: €14,000 − €4,000 = €10,000

You have reduced your taxable gains by €4,000, saving substantial cash at year-end, but you still have €10,000 in gains remaining.

Scenario C: Selling the Entire Position (600 Shares)

To maximize loss harvesting, you liquidate all 600 shares.

  • Lot 1 (200 shares): 200 × (€45 − €25) = +€4,000 Gain
  • Lot 2 (200 shares): 200 × (€45 − €85) = −€8,000 Loss
  • Lot 3 (200 shares): 200 × (€45 − €60) = −€3,000 Loss
  • Total Net Harvested Loss: +€4,000 − €8,000 − €3,000 = −€7,000 Loss

Final Tax Calculation:

  • Total Gross Realized Gains: €14,000
  • Total Gross Realized Losses: −€7,000
  • Final Net Taxable Gain for 2026: €14,000 − €7,000 = €7,000

By liquidating all 600 shares, you cut your taxable gains in half. However, this worked example demonstrates why tracking your exact FIFO lot bases is vital: liquidating 600 shares was necessary to extract €7,000 of net loss, because the €4,000 gain in Lot 1 directly absorbed more than a third of the €11,000 in paper losses sitting in Lots 2 and 3.

Tax authorities recognize that investors might sell losing positions solely for tax benefits and immediately repurchase the shares. To prevent this, most tax codes enforce strict anti-abuse rules that disallow or defer the harvested loss if the asset is repurchased within a specific window.

The US 30-Day Wash-Sale Rule (IRC Section 1091)

In the United States, an investor cannot claim a loss on the sale of stock or securities if they purchase a "substantially identical" security within 30 days before or 30 days after the sale date. This creates an unbending 61-day restriction window (the 30 days prior, the day of sale, and the 30 days following).

When a wash sale occurs:

  1. The loss is disallowed for current-year tax deduction.
  2. The disallowed loss is added directly to the cost basis of the newly acquired replacement shares.
  3. The holding period of the sold shares is added to the holding period of the new shares.

Crucially, wash-sale rules apply across all accounts controlled by the taxpayer, including taxable brokerage accounts, traditional IRAs, and Roth IRAs. If you harvest a loss on an equity in your taxable account and repurchase it inside a Roth IRA within 30 days, the loss is permanently forfeited—it cannot even be added to the IRA basis.

The Spanish 2-Month Rule (Norma Antiaplicación)

In Spain, the anti-avoidance rule is governed by Article 33.5.f of the Ley del IRPF. The statute states that capital losses arising from the transfer of listed securities (valores admitidos a negociación) will not be computed if the taxpayer acquired homogeneous securities within the two months prior or two months following the transfer. For unlisted securities, this exclusion window expands to one full year.

The critical mechanics of the Spanish rule differ from the US wash-sale rule:

  • Temporary Suspension: The loss is not permanently erased, nor is it simply rolled into the basis of the new shares. Instead, the loss is suspended and remains deferred.
  • Subsequent Unlocking: The harvested loss can only be claimed in the tax year in which the repurchased replacement shares are subsequently sold and permanently leave the taxpayer’s balance sheet.

Strategies to Maintain Market Exposure Safely

If you sell a position to harvest a loss, how can you remain invested in the broader market without violating the 30-day or 2-month rules?

  1. Swap to an Uncorrelated Index: If you harvest a loss in an S&P 500 ETF, purchasing a total US stock market index or a broad international ETF generally avoids the "substantially identical" or "homogeneous" trigger, as they track different underlying indices and have different constituent weightings.
  2. Substitute with a Peer Competitor: If harvesting an individual stock loss (e.g., selling an automaker), you can immediately deploy the capital into a direct competitor within the same sector. This maintains your tactical sector allocation while sidestepping the repurchase rule.
  3. Hold Cash or High-Yield Equivalents for 31/61 Days: If you want to hold the exact same asset again, you must wait out the full statutory period before rebuying. If selling on December 15 in the US, you cannot repurchase until January 16. In Spain, an equity sold on December 15 cannot be repurchased until February 16.

Tracking Unrealized Cost Basis Across Portfolios Without Broker Sync

The mathematical complexity of tax-loss harvesting grows rapidly if you manage multiple investment accounts. Many investors hold shares of the same company or ETF across a traditional domestic broker, a secondary fintech brokerage, and an offshore or expatriate custody platform.

Most brokerage platforms calculate FIFO positions only within the boundary of their own account. A broker has no visibility into lots purchased on another platform. If you hold shares of an international asset across multiple custodians, tax authorities (such as the Spanish Tax Agency under Article 37.2 of Ley del IRPF) require you to apply the FIFO rule globally across your total portfolio of homogeneous securities, regardless of where the shares are deposited.

Relying on individual broker statements often produces contradictory lot dates, leading to inaccurate tax returns. Furthermore, linking all your personal accounts to third-party data aggregators introduces security and privacy liabilities. Many aggregators maintain persistent credentials, monetize user spending patterns, or suffer connection outages that corrupt lot purchase dates.

To calculate FIFO capital offsets accurately and securely, you need an independent, private tracking system:

  • Record Complete Lot Histories: Document the precise execution date, total gross consideration, commissions, and share counts for every purchase.
  • Maintain Private Accounting: Keeping your records in a secure net worth and portfolio system lets you track unified FIFO cost bases without handing broker passwords to aggregators. Platforms like netclariq allow you to record or import transactions via CSV, automatically tracking prices and calculating FIFO cost basis privately.
  • Isolate Tax-Advantaged Accounts: Keep retirement accounts (401ks, IRAs, Spanish pension plans) strictly separate from your taxable harvesting worksheets to prevent accidental wash-sale contamination.
  • Reconcile Annually Before Rebalancing: Compare your internal lot tracking against annual trade confirmations to verify your cost basis before executing final December trades. For investors managing mixed assets, our guide on how to track crypto and stocks in one place outlines the necessary separation rules.

Year-End Portfolio Rebalancing Checklist Before the Cutoff Date

Before initiating year-end trades, use this systematic checklist to ensure every transaction satisfies legal lot matching and produces real tax savings:

  1. Calculate Total Year-to-Date Realized Capital Gains Sum all short-term and long-term gains realized between January 1 and today across all taxable investment platforms.
  2. Audit All Open Positions for Unrealized Losses Sort your holdings by current unrealized performance. Identify positions where current market valuations sit below average purchase prices.
  3. Map Each Target Position Down to Its Individual FIFO Lots Determine the cost basis of Lot 1. Verify whether liquidating the oldest tranche produces a gain or a loss. Calculate how many total shares must be liquidated to produce the targeted net loss.
  4. Inspect the Prior 30-Day (or 2-Month) Trading History Check your transaction ledgers to confirm you have not purchased shares of that security within the restricted pre-sale window (e.g., automated dividend reinvestment plans or recurring monthly buys). Turn off automated reinvestment features on those securities immediately.
  5. Establish the Reinvestment Plan Decide where the proceeds will go. Will you park the cash in high-yield instruments for 31 to 61 days, or immediately buy a non-identical sector proxy to retain market exposure?
  6. Verify Market Settlement Dates Confirm that your planned execution date settles on or before the final business day of December under T+1 settlement rules. Avoid waiting until December 31.
  7. Document the Trade for Tax Reporting Save trade execution confirmations showing execution time, price per share, and lot allocation. These records serve as your audit trail for Schedule D (US) or Modelo 100 (Spain).

Executing a successful tax-loss harvesting strategy requires precise mathematical discipline. When you calculate your offsets using strict FIFO rules and respect statutory repurchase windows, you convert portfolio volatility into durable, legitimate tax savings. If your tax situation involves cross-border assets or complex estate planning, consult a qualified tax professional to evaluate your individual exposure.

FAQ

What happens if I harvest more capital losses than my total gains for the year?

In the United States, net capital losses exceeding capital gains can offset up to $3,000 of ordinary income per year ($1,500 if married filing separately), with any remaining loss carried forward indefinitely. In Spain, net capital losses cannot offset wage income, but they can offset up to 25% of positive dividend and interest income (rendimientos de capital mobiliario), with excess losses carried forward for up to four consecutive tax years.

Can I choose which lots to sell instead of using FIFO?

Under US tax regulations, you can select specific lots using the Specific Identification (Spec ID) method, provided you document the specific lot to your broker prior to trade settlement. In contrast, under Spanish tax law (Article 37.2 of Ley del IRPF) and several other jurisdictions, FIFO is statutory and mandatory for homogeneous securities: you must always liquidate your oldest shares first, with no exceptions permitted.

Does the wash-sale rule apply if I sell an individual stock and buy an index ETF?

No. Selling an individual stock (such as an energy company) and immediately buying a broad energy sector ETF does not trigger the US 30-day wash-sale rule or the Spanish 2-month rule. The ETF represents a diversified basket of securities and is not legally "substantially identical" or "homogeneous" to an individual company's equity.

How does dividend reinvestment affect my tax-loss harvesting plans?

Automated dividend reinvestment plans (DRIPs) frequently cause accidental wash sales. If you harvest a loss on a stock, and a dividend paid within 30 days automatically purchases fractional shares of that same stock, that automated purchase triggers the repurchase rule and disallows a proportional amount of your harvested loss. Always disable DRIP on target holdings before harvesting.

Sources