fix(holdings): an acquisition fee is part of what the position cost

Merged
DG
2mo ago
+107-10

Closes #4022

Problem

Providers record a trade's fee in trades.fee, but nothing reads it, so the cost basis — and every gain derived from it — understates what the purchase cost. The only way to get a fee-inclusive basis today is to fold the fee into price by hand, which loses the fee as a separate fact.

Fix

effective_trade_price in Holding::TradeCalculatorHelpers, used by both calculators, adds an acquisition's fee to its per-unit price. A trade's price and fee are converted at the rate of the trade's own day, so the basis does not drift with today's rate.

Only acquisitions are adjusted. The cost-basis tracker relieves a disposal at the running average and never reads its price, so a disposal's fee has no effect on the basis. That fee belongs on the proceeds side, which does not deduct it yet; that is the follow-up below.

Scope

Not provider-specific. This changes the basis on every investment account that has fees recorded. IBKR and Questrade book commissions as separate cash transactions, so their basis is unchanged.

Release note

Calculated cost basis now includes acquisition fees. Holdings whose cost basis Sure calculates from trades will show a higher basis, and a correspondingly lower gain, after their next sync, wherever the provider records the fee on the trade (Binance, Kraken, SnapTrade, Trade Republic, and trades entered by hand). If you folded fees into a trade's price by hand, remove them from the price, or they will be counted twice.

Tests

Both calculators, both directions: an acquisition fee raises the basis, and a foreign-currency price and fee are converted at the trade's own rate. A disposal's price is pinned on the helper directly, since the basis cannot observe it. create_trade in the test helper gains a fee: keyword, defaulting to 0 rather than nil because trades.fee is NOT NULL.

Follow-up

One PR, as agreed in review: deduct a disposal's fee from the proceeds in Trade#calculate_realized_gain_loss; include the fee in Trade#unrealized_gain_loss and in the SQL fallback of Holding#calculate_avg_cost; decide whether IBKR and Questrade commissions should land in trades.fee; and treat a missing rate as unknown in convert_to_account_currency instead of counting at 1:1.

Summary by CodeRabbit

  • Bug Fixes
    • Acquisition fees are now included in per-unit cost basis, giving a more accurate view of investment costs.
    • Foreign-currency trade prices and fees use the exchange rate for the trade date rather than the current rate.
    • Fees are excluded from disposal prices, and missing fees are treated as zero. When currency conversion is unavailable, calculations fall back to the original trade amount.