Capital Gains Tax Calculator
Estimate your federal short-term or long-term capital gains tax liability and net after-tax investment proceeds.
Unlike conventional calculator sites that send your financial numbers, payload data, or code snippets across remote web servers, Affi-Chain processes all mathematical derivations, algorithms, and data parsing 100% locally within your browser sandbox. No tracking cookies, no server-side retention, and zero transmission lag.
What is Capital Gains Tax?
Capital Gains Tax is an excise levy imposed by federal, state, and municipal tax authorities on the realized financial profit generated from the sale or exchange of a capital asset. Defined under the Internal Revenue Code (IRC), capital assets encompass publicly traded equities, exchange-traded funds (ETFs), mutual funds, cryptocurrencies (Bitcoin, Ethereum), private venture equity, precious metals, and investment real estate.
A capital gain occurs when an asset is liquidated for a price that exceeds its Adjusted Cost Basis. Conversely, if an asset is sold for less than its acquisition basis, the investor realizes a capital loss, which can be deployed to offset other investment gains or ordinary earned income through tax-loss harvesting.
Understanding the mathematical mechanics of capital gains taxation—specifically the critical distinction between Short-Term and Long-Term holding periods, the Net Investment Income Tax (NIIT), and state tax conformity—is essential to preserving after-tax wealth and timing portfolio rebalancing.
The Mathematical Framework: Basis, Holding Periods & Net Gains
flowchart TD
Acquisition["Acquire Asset at Cost Basis: B (Purchase Price + Fees)"] --> TimeElapsed["Holding Period Horizon: Time between Buy and Sell"]
TimeElapsed --> Sale["Sell Asset at Gross Proceeds: P"]
Sale --> ComputeGain["Calculate Realized Gain: Π = P - B"]
ComputeGain --> HoldingThreshold{"Holding Duration Threshold"}
HoldingThreshold -- "1 Year or Less (<= 365 Days)" --> ShortTerm["Short-Term Capital Gain: Taxed at Ordinary Income Rates (10% to 37%)"]
HoldingThreshold -- "More than 1 Year (> 365 Days)" --> LongTerm["Long-Term Capital Gain: Preferential Rates (0%, 15%, 20%)"]
ShortTerm & LongTerm --> SurtaxCheck{"Does Modified AGI Exceed NIIT Threshold?"}
SurtaxCheck -- "Yes (> $200k Single / > $250k MFJ)" --> AddNIIT["Add 3.8% Net Investment Income Tax (NIIT)"]
SurtaxCheck -- "No" --> BaseTax["Standard Rate Applied"]
AddNIIT & BaseTax --> StateTax["Add State & Local Capital Gains Taxes"]
StateTax --> FinalLiability["Total Combined Capital Gains Tax Liability"]
1. Cost Basis & Gain Calculation
Let $P$ represent net sales proceeds after broker commissions, and $B$ represent the adjusted cost basis (purchase price + acquisition transaction fees + allowable capital improvements):
$$\text{Realized Capital Gain } (\Pi) = P - B$$
If $\Pi > 0$, the investor owes tax on the net profit. If $\Pi < 0$, the investor incurs a deductible capital loss.
2. Short-Term vs. Long-Term Holding Classification
- Short-Term Capital Gains ($\le 365\text{ days}$): Treated identically to ordinary wage compensation. Gains are taxed at your marginal federal income tax bracket (10%, 12%, 22%, 24%, 32%, 35%, or 37%).
- Long-Term Capital Gains ($> 365\text{ days}$): Rewarded with preferential, lower statutory tax tiers (0%, 15%, or 20%) to incentivize long-term productive capital formation.
3. The 3.8% Net Investment Income Tax (NIIT Surtax)
Under Section 1411 of the Affordable Care Act, high-net-worth investors pay an additional 3.8% NIIT surtax on the lesser of net investment income or the amount by which Modified Adjusted Gross Income (MAGI) exceeds:
- $200,000 for Single Filers and Heads of Household
- $250,000 for Married Couples Filing Jointly
(For high-earning investors, the top federal long-term rate is effectively $20% + 3.8% = \mathbf{23.8%}$).
2024 Federal Long-Term Capital Gains Tax Brackets
Unlike ordinary income brackets which apply to gross wages, long-term capital gains brackets are determined by your Total Taxable Income (including ordinary salary plus the capital gains themselves):
| Long-Term Federal Rate | Single Filers (Taxable Income) | Married Filing Jointly (MFJ) | Head of Household (HOH) |
|---|---|---|---|
| 0.0% (Zero Tax) | $0 to $47,025 | $0 to $94,050 | $0 to $63,000 |
| 15.0% | $47,026 to $518,900 | $94,051 to $583,750 | $63,001 to $551,350 |
| 20.0% | $518,901 or more | $583,751 or more | $551,351 or more |
| 23.8% (With NIIT) | Top tier where MAGI exceeds $200,000 | Top tier where MAGI exceeds $250,000 | Top tier where MAGI exceeds $200,000 |
State Capital Gains Tax Rates: Conformity & Traps
State taxation dramatically impacts after-tax net investment returns. Most US states do not offer preferential rates for long-term gains, taxing capital gains as standard ordinary income:
| State Jurisdiction | Long-Term Capital Gains Treatment | Top State Capital Gains Rate | Combined Max Federal + State Tax |
|---|---|---|---|
| California | No preferential rate; taxed as ordinary income | 13.3% | 37.1% ($23.8% + 13.3%$) |
| New York (NYC) | State (10.9%) + City (3.876%) ordinary tax | 14.776% | 38.58% |
| New Jersey | Taxed as ordinary income | 10.75% | 34.55% |
| Washington State | 7.0% excise tax on long-term capital gains $> $250,000$ | 7.0% | 30.8% |
| Texas / Florida / Nevada | Zero state income tax | 0.0% | 23.8% (Federal Only) |
Practical Implementation Examples
Python: Full-Spectrum Capital Gains Tax Liability Engine
from typing import Dict
def calculate_capital_gains_tax(
purchase_price: float,
selling_price: float,
holding_days: int,
ordinary_taxable_income: float,
filing_status: str = "single",
state_tax_pct: float = 6.0
) -> Dict[str, any]:
gain = selling_price - purchase_price
if gain <= 0:
return {
"realized_gain": round(gain, 2),
"status": "CAPITAL LOSS",
"net_tax_liability": 0.0,
"loss_deduction_available": min(abs(gain), 3000.0)
}
is_long_term = holding_days > 365
total_taxable_income = ordinary_taxable_income + gain
# 1. Federal Capital Gains Tax Calculation
if not is_long_term:
# Short-term: Approximate marginal bracket on gain
if total_taxable_income <= 47150:
federal_rate = 0.12
elif total_taxable_income <= 100525:
federal_rate = 0.22
elif total_taxable_income <= 191950:
federal_rate = 0.24
elif total_taxable_income <= 243725:
federal_rate = 0.32
elif total_taxable_income <= 609350:
federal_rate = 0.35
else:
federal_rate = 0.37
else:
# Long-term 2024 Brackets (Single)
threshold_0 = 47025.0 if filing_status.lower() == "single" else 94050.0
threshold_15 = 518900.0 if filing_status.lower() == "single" else 583750.0
if total_taxable_income <= threshold_0:
federal_rate = 0.0
elif total_taxable_income <= threshold_15:
federal_rate = 0.15
else:
federal_rate = 0.20
base_federal_tax = gain * federal_rate
# 2. Net Investment Income Tax (NIIT 3.8%)
niit_threshold = 200000.0 if filing_status.lower() == "single" else 250000.0
niit_tax = 0.0
if total_taxable_income > niit_threshold:
taxable_niit_portion = min(gain, total_taxable_income - niit_threshold)
niit_tax = taxable_niit_portion * 0.038
# 3. State Tax
state_tax = gain * (state_tax_pct / 100.0)
total_tax = base_federal_tax + niit_tax + state_tax
after_tax_proceeds = selling_price - total_tax
return {
"cost_basis": round(purchase_price, 2),
"gross_proceeds": round(selling_price, 2),
"realized_capital_gain": round(gain, 2),
"holding_period_days": holding_days,
"classification": "LONG-TERM (> 365 Days)" if is_long_term else "SHORT-TERM (<= 365 Days)",
"effective_federal_rate": f"{(federal_rate * 100):.1f}%",
"federal_capital_gains_tax": round(base_federal_tax, 2),
"niit_3_8_pct_surtax": round(niit_tax, 2),
"state_capital_gains_tax": round(state_tax, 2),
"total_tax_liability": round(total_tax, 2),
"net_after_tax_proceeds": round(after_tax_proceeds, 2),
"effective_total_tax_rate": f"{((total_tax / gain) * 100):.2f}%"
}
# Example: $50,000 gain on stock held 450 days, salary $160,000 in a 6% state
audit = calculate_capital_gains_tax(
purchase_price=50000.0,
selling_price=100000.0,
holding_days=450,
ordinary_taxable_income=160000.0,
state_tax_pct=6.0
)
for k, v in audit.items():
print(f"{k.ljust(28)}: {v}")
TypeScript / JavaScript Implementation
export interface CapitalGainsInput {
costBasis: number;
salePrice: number;
isLongTerm: boolean;
marginalIncomeTaxPct: number;
stateTaxPct: number;
}
export function computeCapitalGains(input: CapitalGainsInput) {
const gain = Math.max(0, input.salePrice - input.costBasis);
const fedRate = input.isLongTerm ? 0.15 : input.marginalIncomeTaxPct / 100;
const stateRate = input.stateTaxPct / 100;
const fedTax = gain * fedRate;
const stateTax = gain * stateRate;
const totalTax = fedTax + stateTax;
return {
netProfit: Math.round(gain * 100) / 100,
federalTax: Math.round(fedTax * 100) / 100,
stateTax: Math.round(stateTax * 100) / 100,
totalTaxLiability: Math.round(totalTax * 100) / 100,
afterTaxCash: Math.round((input.salePrice - totalTax) * 100) / 100
};
}
Critical Edge Cases & Common Tax Traps
1. The IRS Wash-Sale Rule Trap (IRC § 1091)
Under the Wash-Sale Rule, if an investor sells a stock or mutual fund at a loss and purchases a "substantially identical" security within a 61-day window (30 days before the sale, the day of the sale, or 30 days after):
- The capital loss is completely disallowed for current tax deductions.
- The disallowed loss is added onto the cost basis of the newly purchased shares.
- Crypto Exception: Historically, digital assets like Bitcoin were exempt from the wash-sale rule because they were classified as property rather than securities, though legislative proposals frequently target this loophole.
2. Section 121 Primary Residence Real Estate Exclusion
Homeowners selling their primary residence receive one of the largest tax shelters in the tax code: under IRC § 121, an individual can exclude up to $250,000 of capital gain (or $500,000 for married couples filing jointly) completely tax-free, provided they owned and occupied the property as their principal residence for at least 2 of the 5 years preceding the sale.
3. The Annual $3,000 Capital Loss Cap
If your net capital losses exceed your capital gains, the IRS allows you to deduct only a maximum of $3,000 per year against ordinary salary income ($1,500 if married filing separately). Any remaining net loss is rolled forward indefinitely into future tax years.