Question
How do I figure the cost basis when the shares I'm selling were purchased at various times and at different prices?
Answer
The basis of stocks or bonds you own generally is the purchase price plus the costs of purchase, such as commissions and recording or transfer fees. When selling securities, you should be able to identify the specific shares you are selling.
If you can identify which shares of stock you sold, your basis generally is:
What you paid for the shares sold plus any costs of purchase.
If you can't adequately identify the shares you sold and you bought the shares at various times for different prices, the basis of the stock sold is:
The basis of the shares you acquired first, then the basis of the stock later acquired, and so forth (first-in first-out). Except for certain mutual fund shares and certain dividend reinvestment plans, you can't use the average basis per share to figure gain or loss on the sale of stock.
https://www.irs.gov/faqs/capital-gains-losses-and-sale-of-home/stocks-options-splits-traders/stocks-options-splits-traders-1