You don't profit from stocks until you sell your appreciated shares, but when you do, Uncle Sam wants his cut by way of capital gains taxes. By default, the IRS uses the "first in, first out" rule for the calculation of capital gain on sales of shares, which means you sell shares of a single stock beginning with the ones you acquired first. This doesn't always work to your advantage. However, you can also specify the shares you are selling — by having your broker notate that the sale of stock applies to shares purchased on a specific date — for optimal tax benefits. As an example, you might choose to sell shares that result in the lowest capital gain, or you might want the largest capital gain during a tax year when you have capital losses to defray capital gains.
TL;DR (Too Long; Didn't Read)
Minimize your tax liability by recording the smallest gains possible.
Step 1: Calculate the Purchase Total
Multiply the number of shares in every single purchase by the per-share purchase price, then add any brokerage fees. For example, if you purchased 100 shares of XYZ stock at $50 per share and later purchased 80 more at $60 per share, multiply $50 times 100 and $60 times 80. If you incurred a $20 brokerage fee on each of these transactions, add $20 to each result. Doing so results in totals of $5,020 and $4,820, respectively.
Step 2: Calculate the Adjusted Cost Basis Per Share
Divide the purchase totals by the number of shares to calculate the adjusted cost basis of each share. Extending the example, divide $5,020 by 100 to calculate the first purchase group's cost basis -- $50.20 per share. Divide $4,820 by 80 to calculate the second group's basis -- $60.25.
Step 3: Calculate the Sales Total
Multiply the number of shares sold by the per-share sales price and then subtract any broker fees to calculate the sales total. Continuing the example, if you sell 120 shares of stock XYZ for $70 per share and incur another $20 brokerage fee, multiply 120 times $70 and subtract $20. The sales total is $8,380.
Step 4: Calculate the Total Cost Basis
Multiply the number of shares sold in from each purchase group in the sale of stock times the per-share cost basis. If you specified more than one group, add the totals. If you used the default "first in, first out" rule in the example, the first 100 shares sold come from the first group, and the remaining 20 come from the second group. Therefore, multiply 100 by $50.20 and the remaining 20 by $60.25. Add the resulting $5,020 and $1,205 figures for a total cost basis of $6,225 for the sale.
Step 5: Calculate the Capital Gains on Stocks
Subtract the total cost basis from the purchase total to calculate the capital gain. In the example, subtract $6,225 from $8,380 to find that your capital gain is $2,155.