Make FIFO accounting_method linear time #115
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
The
FIFO
accounting method is unfortunately quadratic time, even in trivial cases:The "One In, One Out" alternates
n
pairs ofBUY, SELL
such that there is only everk=1
active lots. This represents the most trivial case for any accounting method. A potential worst case is represented by "Buys, then Sells" which createsn
BUYS
followed byn
SELLS
. This creates a worst case scenario ofk=n
.In the first case, the
LIFO
method is roughly linear; in the second case, it is clearly quadratic. The quadratic behavior ofLIFO
andHIFO
will be addressed in a separate PR by usingheapq
.It is relatively straightforward to make
FIFO
linear time in both of these cases by simply advancing an index of the next, un-exhausted lot onAcquiredLotCandidates
and persisting this object between invocations ofget_acquired_lot_for_taxable_event()
. In the event of different accounting methods being used for different tax years, a one-time scan is performed for each switch of accounting method to find the appropriate index.With this PR,
FIFO
performance improves to linear time in both cases: