alensiljak / gnucash-portfolio

Tools for managing an investment portfolio in a GnuCash book
http://portfolio.alensiljak.tk
GNU General Public License v3.0
17 stars 1 forks source link

Virtual lots #33

Open alensiljak opened 6 years ago

alensiljak commented 6 years ago

As the Lots feature in GnuCash modifies the original records, and is therefore risky to use multiple times, the same concept could be recalculated on the fly. This would create virtual lots, used just for the purpose of calculating the capital gains on the sold stock, and average price for the remaining stock.

The calculation would be based on the current state in the account. Meaning that, if there are any changes in the original transactions, the numbers would be recalculated based on the new state. This is not the case with Lots in GnuCash, where transactions get duplicated when Scrubbing is used, effectively making it extremely difficult to track the changes in the account visually.

Instructions:

Note: this calculation already exists in GnuCash Lots view. It is shown in Splits Free window.

The Virtual Lots model should be the base for any calculation on the remaining portion of the stock.

alensiljak commented 6 years ago

image

alensiljak commented 6 years ago

Solution (FIFO)

The easiest implementation of the first-in, first-out (FIFO) calculation using virtual lots only (no real lots needed in GnuCash book) is to calculate backwards:

In the chart above:

Note that this calculation has to be done per each holding account. It also does not take into account any stock splits or repricings.

alensiljak commented 6 years ago

image

There are only two cases - the one above where we split the last lot, and this one, where we have full lots before reaching the one to be split.

In this, more complex example, we will take as many as full lots as we have (slot E, Lot 3 and/or more), before reaching Lot 2, which gets split. Then we calculate the value for the remaining part of Lot 2 and add to the other, previously calculated ones.

image

alensiljak commented 6 years ago

Test Cases

  1. Same Amounts

Buy 100 @ 10 = €-1000 Sell 100 @ 15 = €1500 Calculate CG, find matching transactions, if any. €500

  1. Different Amounts, 2 Tx

Buy 100 @ 10 = €-1000 Sell 50 @ 20 = €1000 Calculate realized CG = €1000 Calculate unrealized CG = €1000

  1. Different Amounts, 3 Tx

Buy 100 @ 10 = €-1000 Sell 50 @ 20 = €1000 Calculate realized CG = €1000 Calculate unrealized CG = €1000 Sell 50 @ 15 = €750 Calculate realized CG = €250. Unrealized = €0.