-
Notifications
You must be signed in to change notification settings - Fork 292
Fix holding cost basis to relieve sells under weighted-average method #2087
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
philluiz2323
wants to merge
2
commits into
we-promise:main
Choose a base branch
from
philluiz2323:fix/holding-cost-basis-sell-relief
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| # Tracks weighted-average cost basis for a single security as trades are | ||
| # applied in chronological order. | ||
| # | ||
| # Buys add to the running cost and quantity. Sells relieve quantity at the | ||
| # current average cost (leaving the per-share average unchanged), and once the | ||
| # position is fully closed the tracker resets so a later repurchase starts from | ||
| # a clean basis. Without this relief, cost basis would be averaged over every | ||
| # buy the account ever made for the security — corrupting the figure after a | ||
| # position is sold off and bought again. | ||
| # | ||
| # Prices are expected in the account's currency (callers convert before | ||
| # applying), so the tracker itself is currency-agnostic. | ||
| class Holding::CostBasisTracker | ||
| def initialize | ||
| @total_cost = BigDecimal("0") | ||
| @total_qty = BigDecimal("0") | ||
| end | ||
|
|
||
| # Applies a trade by its signed quantity: positive is a buy, negative a sell. | ||
| def apply(price, qty) | ||
| return if qty.nil? | ||
|
|
||
| qty = qty.to_d | ||
| return if qty.zero? | ||
|
|
||
| qty.positive? ? buy(price, qty) : sell(qty) | ||
| end | ||
|
|
||
| def buy(price, qty) | ||
| price = price&.to_d | ||
| qty = qty&.to_d | ||
| return if price.nil? || qty.nil? || !qty.positive? | ||
|
|
||
| @total_cost += price * qty | ||
| @total_qty += qty | ||
| end | ||
|
|
||
| def sell(qty) | ||
| qty = qty&.to_d | ||
| return if qty.nil? || qty.zero? || @total_qty.zero? | ||
|
|
||
| # Relieve at the current average cost so the per-share average is unchanged. | ||
| # Guard against over-selling more than is currently held. | ||
| relieved_qty = [ qty.abs, @total_qty ].min | ||
| @total_cost -= average_cost * relieved_qty | ||
| @total_qty -= relieved_qty | ||
|
|
||
| # Coercing to BigDecimal keeps arithmetic exact, so a full liquidation lands | ||
| # on exactly zero and the reset fires (Float math could leave a tiny remainder). | ||
| reset if @total_qty <= 0 | ||
| end | ||
|
|
||
| # Current weighted-average cost per share, or nil when nothing is held. | ||
| def average_cost | ||
| return nil if @total_qty.zero? | ||
|
|
||
| @total_cost / @total_qty | ||
| end | ||
|
|
||
| private | ||
| def reset | ||
| @total_cost = BigDecimal("0") | ||
| @total_qty = BigDecimal("0") | ||
| end | ||
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| # Shared helpers for holding calculators (ForwardCalculator / ReverseCalculator). | ||
| # Expects the including class to expose an `account` reader. | ||
| module Holding::TradeCalculatorHelpers | ||
| private | ||
| # Converts a trade's price into the account's currency, falling back to the | ||
| # raw price when no exchange rate is available. | ||
| def converted_trade_price(trade) | ||
| Money.new(trade.price, trade.currency).exchange_to(account.currency).amount | ||
| rescue Money::ConversionError | ||
| trade.price | ||
| end | ||
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,66 @@ | ||
| require "test_helper" | ||
|
|
||
| class Holding::CostBasisTrackerTest < ActiveSupport::TestCase | ||
| setup do | ||
| @tracker = Holding::CostBasisTracker.new | ||
| end | ||
|
|
||
| test "average cost is nil with no trades" do | ||
| assert_nil @tracker.average_cost | ||
| end | ||
|
|
||
| test "weighted average across multiple buys" do | ||
| @tracker.apply(BigDecimal("100"), BigDecimal("10")) | ||
| @tracker.apply(BigDecimal("200"), BigDecimal("10")) | ||
|
|
||
| assert_equal BigDecimal("150"), @tracker.average_cost | ||
| end | ||
|
|
||
| test "a partial sell leaves the per-share average unchanged" do | ||
| @tracker.apply(BigDecimal("100"), BigDecimal("10")) | ||
| @tracker.apply(BigDecimal("200"), BigDecimal("10")) # avg 150 | ||
|
|
||
| # Sell price is irrelevant to cost basis; shares are relieved at the average. | ||
| @tracker.apply(BigDecimal("999"), BigDecimal("-5")) | ||
|
|
||
| assert_equal BigDecimal("150"), @tracker.average_cost | ||
| end | ||
|
|
||
| test "cost basis resets after a full liquidation and repurchase" do | ||
| @tracker.apply(BigDecimal("100"), BigDecimal("10")) | ||
| @tracker.apply(BigDecimal("300"), BigDecimal("-10")) # fully sold | ||
|
|
||
| assert_nil @tracker.average_cost | ||
|
|
||
| @tracker.apply(BigDecimal("300"), BigDecimal("10")) # repurchased | ||
|
|
||
| # Only the repurchased lot is held — not (100 + 300) / 2 = 200. | ||
| assert_equal BigDecimal("300"), @tracker.average_cost | ||
| end | ||
|
|
||
| test "over-selling cannot drive quantity or basis negative" do | ||
| @tracker.apply(BigDecimal("100"), BigDecimal("5")) | ||
| @tracker.apply(BigDecimal("100"), BigDecimal("-10")) # sell more than held | ||
|
|
||
| assert_nil @tracker.average_cost | ||
| end | ||
|
|
||
| test "selling with no position is a no-op" do | ||
| @tracker.apply(BigDecimal("100"), BigDecimal("-5")) | ||
|
|
||
| assert_nil @tracker.average_cost | ||
| end | ||
|
|
||
| test "coerces float quantities so a full liquidation still resets" do | ||
| # Float inputs must not accumulate rounding error that leaves a tiny | ||
| # residual quantity and bypasses the reset-on-full-liquidation. | ||
| @tracker.apply(100.0, 10.0) | ||
| @tracker.apply(300.0, -10.0) | ||
|
|
||
| assert_nil @tracker.average_cost | ||
|
|
||
| @tracker.apply(300.0, 10.0) | ||
|
|
||
| assert_equal BigDecimal("300"), @tracker.average_cost | ||
| end | ||
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Make same-day trade ordering explicit before snapshotting.
Now that sells mutate the running tracker, replay order matters.
sort_by(&:date)leaves same-day buy/sell sequences ambiguous, so a sell-all + repurchase on one date can still snapshot the wrong end-of-day basis unless this loop uses a deterministic intra-day tiebreaker fromtrade_entry/trade(execution timestamp, sequence, id, etc.).🤖 Prompt for AI Agents