Hello quants, here's a hopefully interesting question.

So, LEAN uses the “cost averaging accounting method”, which determines the cost of your holdings by taking a weighted average of the sum of all your BUY prices. (Ref: https://www.quantconnect.com/docs/v2/writing-algorithms/portfolio/key-concepts#03-Cost-Averaging-Accounting). It could really be called AverageBuyPrice, because In this logic any SELL operations are not accounted for.

However, I would like to find a metric – and I believe it must exists, hence my question – to account for sales too.

Let's make an example of how QC averagePrice will printout:

buy  +10 stocks @ 5 usd : averagePrice =             ( 10*5 ) / 10 = 5    
buy   +2        @ 4     : averagePrice =       ( 10*5 + 2*4 ) / 12 = 4.83 
sell  -2        @ 4.5   : averagePrice =       ( 10*5 + 2*4 ) / 12 = 4.83  # we completely ignore this sale
buy   +2        @ 4     : averagePrice = ( 10*5 + 2*4 + 2*4 ) / 12 = 5.5  

Intuitively speaking, how can it be that my averagePrice is now higher than the value I ever bought the stock at (which was at 5)?

I am trying to find a metric that includes the sales, however I am not an economist, and don't know if there is a terminology for this.
Look at the following now:

buy  +10 stocks @ 5 usd : averagePrice =                     ( 10*5 ) / 10 = 5
buy   +2        @ 4     : averagePrice =               ( 10*5 + 2*4 ) / 12 = 4.83
sell  -2        @ 4.5   : averagePrice =       ( 10*5 + 2*4 - 2*4.5 ) / 10 = 4.9  # this time we consider this sale
buy   +2        @ 4     : averagePrice = ( 10*5 + 2*4 - 2*4.5 + 2*4 ) / 12 = 4.75

Again, intuitively, this makes more sense:

  • we sold stocks and made a profit over the second operation, since now we have less stocks that are at a lower value than 5, the average price should go up as it does
  • and then we bought again at a lower price, lowering the average to 4.75. To me this makes more sense than 5.5.

    I hope I make sense. This sounds terribly silly and I fear I am overseeing something very obvious.
    Hence why I'd like to ask people here. 

    Paul