1
$\begingroup$

Setting aside the fact that tax lots (using specific id) should usually be assigned at the time of the trade (for stocks in the USA), let's assume instead we want an algorithm to optimally allocate them once we have the whole list of trades in hand for a single security. Each trade comprises: date-time, number-of-shares, total-dollar-amount and can be either buy or sell.

Our goal is to maximize the capital gains allocated to long term rather than short term, defined when a matching buy and sell are more than a year apart. A capital gain is the proceeds from the sale of the shares less the cost of those shares.

Example:

Buys

100 shares on Jan 01 2020 total cost \$100

200 shares on Aug 01 2020 total cost \$125

Sells

150 shares on Sep 01 2020 total proceeds \$110

150 shares on Mar 01 2021 total proceeds \$185

Total capital gain is \$(185+110-125-100) ie. \$70 which will be partly short term and partly long term such that short term capital gains + long term capital gains = \$70.

What's the optimal algorithm to allocate tax lots when doing it in retrospect, ie.

What is a general algorithm identifying which share purchase to match to each share sold in order to maximize the long term capital gain portion?

So output might be something like, for the 150 shares sold on 9/1/2020, 100 should come from the first buy, 50 from the second buy. For the 150 sold on 3/1/2021, all 150 come from the 2nd buy.

$\endgroup$
2
  • 1
    $\begingroup$ What's the definition of long term capital gain, as a function of the allocation? What is the condition under which a capital gain is considered long-term vs short-term? $\endgroup$
    – D.W.
    Apr 13 at 23:55
  • $\begingroup$ Its a bit complex on edge cases like leap year but the simple version which works in most cases is that if the sale is at least one numerical day after in the following year, then it's long term. eg. selling on Jun 22 would be long term if you bought on Jun 21 in the preceding year, but selling on Jun 21 would be short term. $\endgroup$ Apr 14 at 0:54
3
$\begingroup$

There's a natural greedy algorithm. Scan through the buy/sell orders in chronological order. At each sell order:

  • Sell as many shares that would be classified as long-term as possible, until you've sold the number required by the sell order.

  • If you still need to sell more shares, and there are no more shares that would be classified long-term sales, sell the youngest (newest / most recently bought) shares first.

I suggest trying to verify whether that leads to a correct algorithm or not. See How to prove greedy algorithm is correct.

$\endgroup$
1
  • $\begingroup$ Sorry, you're absolutely right! I'll delete my comment. $\endgroup$ Apr 14 at 10:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.