Home › Calculators › Cost Basis Calculator

Cost Basis Calculator

Bought the same stock, fund or coin several times and sold part of it? Enter every buy and sell and see the cost basis and realized gain under each method side by side, split into short-term and long-term, with the lots you still hold.

Last updated:

Buys and sells

Buy fees are added to the cost basis; sell fees reduce the sale proceeds. Rows are sorted by date for the calculation.

Compare methods

Details for

Sales matched to lots

Shares still held

Advertisement
Advertisement

How to use the Cost Basis Calculator

  1. Add each buy and sell with its date, number of shares, price per share and fees, or paste them with Import CSV.
  2. Optionally enter the current price to see the unrealized gain on shares you still hold.
  3. Compare the methods in the summary table: realized gain, short- and long-term amounts and remaining basis.
  4. Open a method's details to see which lots each sale used; for Specific ID, choose the lots yourself.
  5. Download the sales CSV for your records or your tax software.

How each method picks the shares you sold

MethodShares sold firstTypical effect when prices have risen
FIFOOldest purchasesLargest gains, but more of them long-term
LIFONewest purchasesSmaller gains, more likely short-term
HIFOHighest cost per shareSmallest gains (or largest losses) now, lower basis left for later
Average costAll shares at one average basis; oldest first for holding periodBetween FIFO and HIFO
Specific IDThe lots you chooseWhatever you select, as confirmed with your broker

Formulas used

  • Lot cost basis = shares × price + buy fees. Cost per share = lot basis ÷ shares.
  • Net proceeds = shares sold × sale price − sell fees.
  • Realized gain = net proceeds − cost basis of the shares matched to the sale.
  • Average cost per share = total basis of shares held ÷ shares held, recalculated after each purchase.
  • Long-term when the sale date is more than one year after the purchase date.

Worked example

The example loaded on this page buys 100 shares at $40, 50 at $55 and 80 at $48 (each with a $5 fee), sells 120 at $60, buys 40 more at $52, then sells 60 at $70 (sale fees $7). With all 90 remaining shares valued at $66:

MethodRealized gainShort-term partBasis of 90 shares held
FIFO$3,184.13$96.83$4,488.13
Average cost$2,990.17$276.66$4,294.17
LIFO$2,300.50$1,854.33$3,604.50
HIFO$2,300.50$1,783.96$3,604.50

The total gain over the whole holding is the same in the end; the method only moves gain between this year and later years, and between short-term and long-term. A smaller realized gain now leaves a lower basis, and a larger unrealized gain, in the shares you keep.

Frequently asked questions

What is cost basis?

Cost basis is what you paid for an investment, including purchase fees and commissions. When you sell, your capital gain or loss is the sale proceeds (after selling fees) minus the cost basis of the shares sold. If you bought at different prices, the method used to decide which shares were sold changes the basis and the gain.

What is the difference between FIFO, LIFO and HIFO?

FIFO (first in, first out) sells your oldest shares first, LIFO (last in, first out) sells the newest first, and HIFO (highest in, first out) sells the shares with the highest cost first. In a rising market FIFO usually gives the largest gain and HIFO the smallest. LIFO and HIFO are applied through specific identification of lots with your broker.

How does the average cost method work?

Average cost divides the total cost of all shares you hold by the number of shares, so every share sold has the same basis. After a sale the average stays the same for the remaining shares; a new purchase changes it. In the US it is allowed for mutual fund shares and shares in dividend reinvestment plans, and the shares sold are treated as the oldest for the holding period.

When is a gain long-term?

In the US a gain is long-term when you held the shares for more than one year: the holding period starts the day after you bought them, so shares bought on March 5, 2024 become long-term if sold on or after March 6, 2025. Long-term gains are usually taxed at lower rates than short-term gains, which are taxed as ordinary income.

Can I choose any method I like?

You can generally pick specific lots at the time of each sale if your broker confirms the identification, otherwise brokers default to FIFO. Once you use average cost for a mutual fund, switching usually requires notifying the broker. Rules differ by country and by asset, so check with your broker or a tax professional.

Does this calculator handle wash sales, splits or dividends?

No. It does not adjust for wash-sale disallowed losses, stock splits, return of capital or reinvested dividends. For a split, enter the lots with split-adjusted shares and prices; record each reinvested dividend as a separate buy. Treat the results as an estimate and compare them with your broker's 1099-B.

Is my data private?

Yes. All calculations run in your browser and your transactions are saved only in this browser's local storage on this device. Nothing is uploaded.

Are all the tools on FreeToolCabin tested for quality and accuracy?

Yes! Every tool on our site undergoes automated Q/A testing in real browser environments to ensure high precision, correct output, and zero errors. If you happen to spot a bug or have a suggestion, please contact us at [email protected] and our team will review it right away.

Related tools

Capital Gains CalculatorGain or loss on a sale, short- or long-term tax at your rates, net proceeds and return.Stock Average CalculatorAverage cost of several stock buys, plus how many shares to buy to reach a target average.Crypto Portfolio Profit & Loss TrackerLog crypto buys and sells to see holdings, average cost and realized and unrealized P&L.Crypto Tax CalculatorUS tax on a crypto sale: short- or long-term gain tax from your income and filing status.Tip CalculatorWork out the tip and split the bill between any number of people.Discount CalculatorSale price, percent off, stacked discounts and sales tax.Budget CalculatorMonthly budget planner with the 50/30/20 rule and a donut chart.Emergency Fund CalculatorFind how big your emergency fund should be and how long it takes to save it, with interest.Wedding Budget PlannerSplit a wedding budget by category, then track estimated, actual and paid costs with a chart.Split Bill CalculatorSplit a bill with tax and tip equally, by shares, or by what each person ordered.50/30/20 Budget CalculatorSplit take-home pay into needs, wants and savings with the 50/30/20 rule or your own split.TikTok Money CalculatorEstimate TikTok sponsored post rates and Creator Rewards earnings from your views.Rent Split CalculatorSplit rent fairly between up to 6 roommates by room size, income or equally.Grocery Budget CalculatorRecommended weekly or monthly grocery budget and cost per meal for your household.Latte Factor CalculatorSee what a small daily habit costs per year and what it could grow to if invested.Money CounterCount cash by bill and coin: subtotals, grand total, piece count and a printable count sheet.Savings Rate CalculatorFind your savings rate on net or gross pay and estimate years to financial independence.Sinking Fund CalculatorPlan monthly and biweekly savings for several goals with due dates and progress bars.Subscription Cost CalculatorTotal your subscriptions per month, year and decade, and see what the money could grow to.CBM CalculatorCarton cubic meters and cubic feet, 20ft/40ft/40HC container fit and sea/air chargeable weight.Cost of Living CalculatorCompare living costs in two US cities and find the salary you need after a move.52 Week Savings ChallengePlan a 52-week money challenge, tick off each deposit and print the savings chart as a PDF.Income Percentile CalculatorSee where your household or individual income ranks in the US, with an age-group option.Life Insurance CalculatorEstimate how much life insurance you need with the DIME method: debts, income, mortgage, education.Baby Cost CalculatorFirst-year baby budget: diapers, formula, childcare, gear and healthcare, monthly and yearly.Bank Statement AnalyzerUpload a bank CSV to sort spending into categories, see monthly charts and your top merchants.Change CalculatorEnter the amount due and cash paid to get the change owed and the bills and coins to give back.Christmas Budget CalculatorPlan holiday spending: gift list, decor, food and travel vs your budget and income.Couple Expense Split CalculatorSplit shared household bills between partners by income, 50/50, equal leftover or custom %.Weighted Decision MatrixScore options against weighted criteria to get a ranked total, a score heatmap and a CSV.Financial Ratio AnalyzerEnter an income statement and balance sheet once and get 30 liquidity, leverage and profit ratios.Freight Class CalculatorEstimate LTL freight class from density (lb per cubic foot) for one or many pallets.FSA CalculatorFlexible spending account tax savings, use-it-or-lose-it risk and the best amount to elect.FTE CalculatorConvert part-time hours into full-time equivalents, FTE into headcount, plus an ACA FTE count.Global Income Percentile CalculatorSee how your income per person compares with the whole world, adjusted for PPP.Coinsurance CalculatorWhat you pay on a medical bill after deductible, copay, coinsurance and out-of-pocket max.Health Insurance Plan Comparison CalculatorCompare health plans' total yearly cost at low, medium and high medical use, with break-even points.100 Envelope ChallengeTrack the 100 envelope savings challenge ($5,050), pick random envelopes and print the chart.Insurance Deductible CalculatorCompare a low vs high deductible: break-even claims, premium savings and expected yearly cost.Option Greeks CalculatorDelta, gamma, theta, vega and rho for calls and puts, with position Greeks and sensitivity charts.OTE Calculator (On-Target Earnings)On-target earnings, pay mix and total pay at any attainment with accelerators.Overhead Rate CalculatorOverhead rate per labor hour, machine hour or % of direct cost, applied to a job's cost.PERT CalculatorThree-point PERT estimates: expected duration, standard deviation and confidence ranges.Pivot Point CalculatorClassic, Fibonacci, Camarilla, Woodie and DeMark pivots with support and resistance levels.PPC Budget CalculatorAd budget and daily spend to hit a conversion or revenue goal from CPC and conversion rate.Project Budget CalculatorLine-item project budget: labor hours × rates, materials, overhead and contingency by phase.Repeat Purchase Rate CalculatorRepeat customer rate, purchase frequency and average days between purchases from your orders.Student Aid Index (SAI) EstimatorSimplified FAFSA Student Aid Index from income, assets and family size, with a Pell Grant hint.Utility Bill SplitterSplit electric, gas, water and internet bills among roommates by days, room size or shares.Absenteeism Rate CalculatorAbsence rate from days lost vs scheduled, cost of absenteeism and Bradford factor.Bank Reconciliation ToolMatch book and bank transactions, list outstanding checks and deposits, reconcile the balance.Pareto Analysis Tool (80/20)Paste categories and values to get a sorted Pareto chart, cumulative %, and the vital few.Expense TrackerLog expenses by category and date, see monthly totals and charts, import or export CSV.Financial Health Score CalculatorScore your finances out of 100 and get a prioritized to-do list for savings, debt and more.Incoterms Responsibility ChartPick an Incoterm (EXW to DDP) to see seller vs buyer costs, risk transfer and who pays duties.RACI Chart MakerBuild a RACI matrix of tasks × roles, check one Accountable per task, export PNG or CSV.Remote Work Savings CalculatorMoney and time you save working from home: commute, gas, lunch and more, minus home costs.Recurring Charges FinderOpen a bank CSV to find recurring subscriptions by merchant and interval, with annual costs.T-Account & Journal Entry GeneratorEnter debit and credit journal entries to get T-accounts and a balanced trial balance.Warehouse Space CalculatorSquare footage and rent for your pallets from rack levels, aisle %, staging and office space.Pallet CalculatorFind how many boxes fit on a pallet: boxes per layer, layers, total, height and weight.Pet Cost CalculatorMonthly, yearly and lifetime cost of a dog or cat: food, vet, insurance, grooming and more.1031 Exchange CalculatorDeferred and taxable gain on a like-kind exchange, with boot, recapture and new basis.Twitch Earnings CalculatorEstimate a streamer's monthly and yearly Twitch income from subs, bits, ads and sponsors.Zero-Based Budget CalculatorGive every dollar a job: assign income to categories until zero is left, with % and chart.Kids Allowance CalculatorKids weekly allowance by age, chore bonus and Save / Spend / Give jar split.Altman Z-Score CalculatorBankruptcy-risk Z-score for public, private and non-manufacturing companies, with zones.Budget Variance CalculatorBudget vs. actual by line: dollar and percent variance with favorable or unfavorable flags.
See all 70 Personal Finance & Budget Calculators →