BrianIsaac's picture
feat: implement P1 features and production infrastructure
76897aa

A newer version of the Gradio SDK is available: 6.1.0

Upgrade

Tax Impact Calculator

Comprehensive tax impact calculator for portfolio operations with support for multiple cost basis methods, wash sale detection, and tax-loss harvesting optimisation.

Features

1. Capital Gains Calculation

  • Holding Period Tracking: Accurately calculates holding periods following IRS rules (day after acquisition to sale date inclusive)
  • Long-Term vs Short-Term: Automatically classifies gains/losses based on > 365 day threshold
  • 2024-2025 Federal Tax Rates: Up-to-date tax brackets for all filing statuses

2. Cost Basis Methods

Supports all major cost basis calculation methods:

  • FIFO (First In, First Out): Default method, sells oldest shares first
  • LIFO (Last In, First Out): Sells newest shares first
  • HIFO (Highest In, First Out): Sells highest-cost shares first (tax-optimised)
  • Average Cost: Uses average cost of all shares
  • Specific ID: Manual lot selection (via optimiser)

3. Wash Sale Detection

  • Implements full 61-day window rule (30 days before + 30 days after)
  • Tracks disallowed losses and basis adjustments
  • Identifies substantially identical securities

4. Tax-Loss Harvesting

  • Identifies opportunities to harvest tax losses
  • Calculates potential tax savings
  • Considers wash sale risks
  • Prioritises opportunities by tax benefit

5. Tax Optimisation

  • Lot selection optimisation for sales
  • Tax-efficient rebalancing strategies
  • Qualified dividend holding period verification
  • Cost basis method comparison

Tax Rates (2024-2025)

Long-Term Capital Gains (Holdings > 365 Days)

Filing Status Income Range Tax Rate
Single $0 - $47,025 0%
$47,025 - $518,900 15%
> $518,900 20%
Married Filing Jointly $0 - $94,050 0%
$94,050 - $583,750 15%
> $583,750 20%
Married Filing Separately $0 - $47,025 0%
$47,025 - $291,850 15%
> $291,850 20%
Head of Household $0 - $63,000 0%
$63,000 - $551,350 15%
> $551,350 20%

Short-Term Capital Gains (Holdings ≀ 365 Days)

Taxed as ordinary income at rates from 10% to 37% based on income and filing status.

Quick Start

Basic Usage

from backend.tax import TaxCalculator, TaxFilingStatus
from decimal import Decimal
from datetime import date

# Initialise calculator
calc = TaxCalculator(
    filing_status=TaxFilingStatus.SINGLE,
    taxable_income=Decimal("75000"),
    tax_year=2024,
)

# Add tax lots (purchases)
calc.add_tax_lot(
    ticker="AAPL",
    acquisition_date=date(2023, 1, 1),
    quantity=Decimal("100"),
    cost_basis_per_share=Decimal("150.00"),
)

# Calculate sale using FIFO
gains = calc.calculate_sale_fifo(
    ticker="AAPL",
    sale_date=date(2024, 11, 16),
    quantity=Decimal("50"),
    sale_price=Decimal("175.00"),
)

# Calculate tax liability
tax_liability, summary = calc.calculate_tax_liability(gains)

print(f"Tax liability: ${tax_liability}")
print(f"Net long-term gain: ${summary.net_long_term}")

Tax Optimisation

from backend.tax import TaxOptimizer

# Create optimiser
optimizer = TaxOptimizer(calc)

# Identify tax-loss harvesting opportunities
opportunities = optimizer.identify_tax_loss_harvesting_opportunities(
    current_prices={"AAPL": Decimal("175.00")},
    min_loss_threshold=Decimal("100"),
)

# Optimise lot selection for sale
optimised_sale = optimizer.optimize_lot_selection(
    ticker="AAPL",
    quantity_to_sell=Decimal("50"),
    current_price=Decimal("175.00"),
    goal="minimize_tax",  # or "harvest_losses", "maximize_long_term"
)

print(f"Selected lots: {optimised_sale.lots_to_sell}")
print(f"Estimated tax: ${optimised_sale.estimated_tax}")

Standalone Demo

Run the standalone tax calculator demo:

python tax_demo.py

This launches a Gradio interface with:

  • Portfolio input
  • Tax settings (filing status, income, cost basis method)
  • Tax analysis results
  • Cost basis method comparison
  • Tax-loss harvesting opportunities

Integration with Main App

See INTEGRATION_GUIDE.md for detailed instructions on integrating the tax calculator into the main Portfolio Intelligence Platform.

Testing

Run the comprehensive test suite:

# Run all tests
pytest backend/tax/tests/ -v

# Run specific test file
pytest backend/tax/tests/test_calculator.py -v

# Run with coverage
pytest backend/tax/tests/ --cov=backend.tax --cov-report=html

Test coverage includes:

  • Holding period calculations
  • All cost basis methods
  • Tax rate determination
  • Wash sale detection
  • Tax liability calculations
  • Optimisation strategies
  • Edge cases and error handling

Module Structure

backend/tax/
β”œβ”€β”€ __init__.py              # Package exports
β”œβ”€β”€ models.py                # Pydantic models
β”œβ”€β”€ calculator.py            # Core calculation logic
β”œβ”€β”€ optimizer.py             # Optimisation strategies
β”œβ”€β”€ interface.py             # Gradio UI components
β”œβ”€β”€ README.md                # This file
β”œβ”€β”€ INTEGRATION_GUIDE.md     # Integration documentation
└── tests/
    β”œβ”€β”€ __init__.py
    β”œβ”€β”€ test_calculator.py   # Calculator tests
    └── test_optimizer.py    # Optimiser tests

Key Classes

TaxCalculator

Main calculator class for tax computations:

Methods:

  • calculate_holding_period_days() - Calculate holding period
  • is_long_term_holding() - Determine if holding is long-term
  • get_capital_gains_rate() - Get applicable tax rate
  • calculate_tax_liability() - Calculate total tax owed
  • detect_wash_sales() - Detect wash sale violations
  • add_tax_lot() - Add purchase to tracking
  • calculate_sale_fifo/lifo/hifo/average() - Calculate gains using different methods
  • get_unrealised_gains() - Calculate unrealised gains/losses

TaxOptimizer

Optimisation and strategy class:

Methods:

  • identify_tax_loss_harvesting_opportunities() - Find harvesting opportunities
  • optimize_lot_selection() - Select optimal lots to sell
  • suggest_rebalancing_strategy() - Tax-efficient rebalancing
  • check_qualified_dividend_holding_period() - Verify dividend qualification
  • compare_cost_basis_methods() - Compare all methods
  • generate_tax_optimization_report() - Comprehensive analysis

Important Notes

Disclaimers

  1. Not Tax Advice: This calculator is for educational and informational purposes only. It does not constitute tax, legal, or financial advice.

  2. Consult Professionals: Always consult qualified tax professionals before making investment decisions.

  3. Limitations:

    • Uses simulated data for demonstrations
    • Does not include state/local taxes
    • Does not account for Alternative Minimum Tax (AMT)
    • Does not include Net Investment Income Tax (3.8% NIIT)
    • Simplified wash sale detection
    • Does not handle complex securities (options, futures, certain crypto)
  4. Tax Law Changes: Tax laws change frequently. This implementation is based on 2024-2025 federal tax rates.

Holding Period Rules

Per IRS Publication 550:

  • Holding period begins the day after acquisition
  • Holding period ends on the sale date (inclusive)
  • Long-term status requires > 365 days
  • Special rules apply for gifted property, inherited property, and stock dividends

Wash Sale Rules

Per IRC Section 1091:

  • Applies to sales at a loss
  • 61-day window (30 days before + day of sale + 30 days after)
  • Substantially identical securities include same stock, options on same stock
  • Loss is deferred, not permanently lost
  • Deferred loss increases basis of replacement shares

Cost Basis Methods

Per IRS Publication 551:

  • Most brokers default to FIFO
  • Average cost only allowed for mutual funds and dividend reinvestment plans
  • Specific identification requires contemporaneous records
  • Must be consistent within same account

Best Practices

For Tax Efficiency

  1. Hold > 365 Days: Qualify for long-term rates when possible
  2. Harvest Losses: Offset gains with losses before year-end
  3. Avoid Wash Sales: Wait 31 days before repurchasing
  4. Use HIFO: Minimises gains when selling
  5. Track Lots: Maintain detailed records of all purchases
  6. Consider Timing: Year-end planning for tax optimisation

For Implementation

  1. Maintain State: Keep accurate tax lot tracking
  2. Record Transactions: Log all buys, sells, and corporate actions
  3. Regular Updates: Check for tax law changes annually
  4. Validate Inputs: Ensure data quality for accurate calculations
  5. Test Thoroughly: Use the test suite to validate changes
  6. Document Assumptions: Note any simplifications or limitations

References

IRS Publications

  • Publication 550: Investment Income and Expenses
  • Publication 551: Basis of Assets
  • Publication 564: Mutual Fund Distributions
  • Form 8949: Sales and Other Dispositions of Capital Assets
  • Schedule D: Capital Gains and Losses

Tax Rate Sources

Legal References

  • IRC Section 1(h): Tax on Net Capital Gain
  • IRC Section 1091: Loss from Wash Sales
  • IRC Section 1012: Basis of Property
  • IRC Section 1223: Holding Period of Property

Support and Contributing

Getting Help

  1. Check this README and INTEGRATION_GUIDE.md
  2. Review test files for usage examples
  3. Check source code documentation
  4. Consult IRS publications for tax rules

Contributing

When adding features:

  1. Add comprehensive tests
  2. Update documentation
  3. Follow existing code style
  4. Use British English spelling
  5. Include Google-style docstrings
  6. Add type hints

Known Issues

  • Wash sale detection requires complete transaction history
  • Does not handle stock splits automatically
  • Crypto and complex securities need additional logic
  • State tax calculations not included

Licence

Part of the Portfolio Intelligence Platform.


Remember: Always consult a qualified tax professional for personal tax advice!