Spaces:
Running
on
Zero
A newer version of the Gradio SDK is available:
6.1.0
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 periodis_long_term_holding()- Determine if holding is long-termget_capital_gains_rate()- Get applicable tax ratecalculate_tax_liability()- Calculate total tax oweddetect_wash_sales()- Detect wash sale violationsadd_tax_lot()- Add purchase to trackingcalculate_sale_fifo/lifo/hifo/average()- Calculate gains using different methodsget_unrealised_gains()- Calculate unrealised gains/losses
TaxOptimizer
Optimisation and strategy class:
Methods:
identify_tax_loss_harvesting_opportunities()- Find harvesting opportunitiesoptimize_lot_selection()- Select optimal lots to sellsuggest_rebalancing_strategy()- Tax-efficient rebalancingcheck_qualified_dividend_holding_period()- Verify dividend qualificationcompare_cost_basis_methods()- Compare all methodsgenerate_tax_optimization_report()- Comprehensive analysis
Important Notes
Disclaimers
Not Tax Advice: This calculator is for educational and informational purposes only. It does not constitute tax, legal, or financial advice.
Consult Professionals: Always consult qualified tax professionals before making investment decisions.
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)
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
- Hold > 365 Days: Qualify for long-term rates when possible
- Harvest Losses: Offset gains with losses before year-end
- Avoid Wash Sales: Wait 31 days before repurchasing
- Use HIFO: Minimises gains when selling
- Track Lots: Maintain detailed records of all purchases
- Consider Timing: Year-end planning for tax optimisation
For Implementation
- Maintain State: Keep accurate tax lot tracking
- Record Transactions: Log all buys, sells, and corporate actions
- Regular Updates: Check for tax law changes annually
- Validate Inputs: Ensure data quality for accurate calculations
- Test Thoroughly: Use the test suite to validate changes
- 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
- Check this README and INTEGRATION_GUIDE.md
- Review test files for usage examples
- Check source code documentation
- Consult IRS publications for tax rules
Contributing
When adding features:
- Add comprehensive tests
- Update documentation
- Follow existing code style
- Use British English spelling
- Include Google-style docstrings
- 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!