Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Convert a disposal's proceeds before subtracting its cost basis (#3616)

jaysbeekay9bdfa2edf052
diff --git a/app/controllers/reports_controller.rb b/app/controllers/reports_controller.rb
index c91f49aad2..97079b00f6 100644
--- a/app/controllers/reports_controller.rb
+++ b/app/controllers/reports_controller.rb
@@ -545,6 +545,10 @@ class ReportsController < ApplicationController
trade.instance_variable_set(:@preloaded_holdings, holdings_by_account[trade.entry.account_id] || [])
end
+ # The rates the proceeds conversion needs, in one query rather than one
+ # per foreign disposal.
+ Trade.preload_exchange_rates(sell_trades)
+
trades_by_treatment = sell_trades.group_by { |t| t.entry.account.tax_treatment || :taxable }
# Unwrap helper: Trend#value / realized_gain_loss#value are Money objects,
@@ -564,7 +568,17 @@ class ReportsController < ApplicationController
# Realized gains are locked at trade time, so convert each at its own
# entry-date FX. Mirrors InvestmentStatement::Totals, which also uses
# entry-date rates for contributions/withdrawals on this same card.
- foreign_trade_currencies = sell_trades.map(&:currency).compact.uniq.reject { |c| c == currency }
+ # A realised figure arrives in the currency the POSITION is held in, not
+ # the one the disposal was priced in: Trade#realized_gain_loss converts
+ # the proceeds into the basis's currency before subtracting, so that the
+ # two sides are comparable. All three sets are needed -- the accounts',
+ # which is what a gain usually carries, the trades' own, and the
+ # holdings', for a position carried in a third currency.
+ foreign_trade_currencies = (
+ sell_trades.map(&:currency) +
+ sell_trades.map { |t| t.entry.account.currency } +
+ holdings_by_account.values.flatten.map(&:currency)
+ ).compact.uniq.reject { |c| c == currency }
rates_by_trade_date = sell_trades.map { |t| t.entry.date }.uniq.each_with_object({}) do |date, memo|
memo[date] = ExchangeRate.rates_for(foreign_trade_currencies, to: currency, date: date)
end
@@ -584,12 +598,18 @@ class ReportsController < ApplicationController
trend ? convert_current.call(trend.value, h.currency) : 0
end
- # Sum realized gains from sell trades
- realized = trades.sum do |t|
+ # Sum realized gains from sell trades, each converted from the currency
+ # its own figure carries.
+ realized_by_trade = trades.each_with_object({}) do |t, memo|
gain = t.realized_gain_loss
- gain ? convert_trade.call(gain.value, t.currency, t.entry.date) : 0
+ next if gain.nil?
+
+ converted = convert_trade.call(gain.value, gain.value.currency.iso_code, t.entry.date)
+ memo[t.id] = Money.new(converted, currency)
end
+ realized = realized_by_trade.values.sum(Money.new(0, currency)).amount
+
# Only include treatment groups that have some activity
next if holdings.empty? && trades.empty?
@@ -598,6 +618,10 @@ class ReportsController < ApplicationController
sell_trades: trades,
unrealized_gain: Money.new(unrealized, currency),
realized_gain: Money.new(realized, currency),
+ # Per-trade figures in family currency, so the lines under the card
+ # and the card's own total are the same arithmetic. The partial used
+ # to re-label `gain.value` as family currency without converting it.
+ realized_gain_by_trade: realized_by_trade,
total_gain: Money.new(unrealized + realized, currency)
}
end
diff --git a/app/models/trade.rb b/app/models/trade.rb
index 0cce260cb1..825f0fad14 100644
--- a/app/models/trade.rb
+++ b/app/models/trade.rb
@@ -88,6 +88,74 @@ class Trade < ApplicationRecord
Trend.new(current: current_value, previous: cost_basis)
end
+ # Set by callers that list many disposals, so the proceeds conversion below
+ # reads one preloaded set instead of a query per foreign disposal. Keyed
+ # `[from, to, date]`.
+ #
+ # NOT authoritative when a key is absent, unlike preloaded_holdings: a caller
+ # that preloads rates without preloading holdings leaves the basis side
+ # unknowable without a query, so the preload keys it on the account's
+ # currency and a position carried in another one misses. Treating a miss as
+ # "no rate" would exclude a disposal that is perfectly measurable, so it
+ # falls back to the single lookup rather than to a wrong answer.
+ def preloaded_exchange_rates=(value)
+ @preloaded_exchange_rates = value
+ remove_instance_variable(:@realized_gain_loss) if defined?(@realized_gain_loss)
+ end
+
+ # One query for every rate a set of disposals can need, instead of one per
+ # disposal. The date set and the currency sets are each small; the product is
+ # a superset of the pairs actually wanted, which is cheaper to fetch than to
+ # describe pair by pair in SQL.
+ def self.preload_exchange_rates(trades)
+ return if trades.empty?
+
+ wanted = trades.flat_map do |trade|
+ from = trade.currency
+ next [] if from.blank?
+
+ # BOTH sides the conversion can target: the account's currency, which is
+ # what a position is usually carried in, and the holding's own where the
+ # caller preloaded holdings and it differs. The conversion targets the
+ # currency of the holding `realized_gain_loss` selects, so keying only on
+ # the account's left a GBP position in a USD account -- the shape this
+ # method exists to serve -- missing the preload and paying a lookup per
+ # disposal. Asking for a pair that turns out unused costs nothing: the
+ # query already fetches the product of the three sets.
+ [ trade.entry.account.currency, trade.preloaded_basis_currency ]
+ .compact_blank
+ .uniq
+ .reject { |to| to == from }
+ .map { |to| [ from, to, trade.entry.date ] }
+ end
+
+ if wanted.empty?
+ trades.each { |trade| trade.preloaded_exchange_rates = {} }
+ return
+ end
+
+ rates = ExchangeRate
+ .where(
+ from_currency: wanted.map(&:first).uniq,
+ to_currency: wanted.map(&:second).uniq,
+ date: wanted.map(&:third).uniq
+ )
+ .to_h { |rate| [ [ rate.from_currency, rate.to_currency, rate.date ], rate.rate ] }
+
+ trades.each { |trade| trade.preloaded_exchange_rates = rates }
+ end
+
+ # The currency this disposal's basis is carried in, where it can be answered
+ # without a query. `Holding#avg_cost` is Money in the HOLDING's own currency,
+ # which is not always the account's, and that is what the proceeds are
+ # converted into. nil when holdings were not preloaded: the preloader above
+ # must not issue the queries it exists to avoid.
+ def preloaded_basis_currency
+ return nil unless defined?(@preloaded_holdings)
+
+ basis_holding&.currency
+ end
+
# Calculates realized gain/loss for sell trades based on avg_cost at time of sale
# Returns nil for buy trades or when cost basis cannot be determined
def realized_gain_loss
@@ -115,34 +183,91 @@ class Trade < ApplicationRecord
end
end
- def calculate_realized_gain_loss
- return nil unless sell?
- # Moving an asset to another account you own realises nothing. Without
- # this the cost basis is compared against the day's price and the
- # difference is booked as a gain the user never made.
- return nil if internal_movement?
-
- # Use preloaded holdings if available (set by reports controller to avoid N+1)
- # Treat defined-but-empty preload as authoritative to prevent DB fallback
- holding = if defined?(@preloaded_holdings)
- # Use select + max_by for deterministic selection regardless of array order
+ # The position the disposal is measured against: the latest snapshot for
+ # this security on or before the disposal's date.
+ #
+ # Uses preloaded holdings when the caller set them, and treats a
+ # defined-but-empty preload as authoritative rather than falling back to a
+ # query. `select` + `max_by` rather than `find`, so the answer does not
+ # depend on the order the caller's array happens to be in.
+ # Not memoised: `realized_gain_loss` already is, and a memo here would hold
+ # a holding selected before a caller set `@preloaded_holdings`.
+ def basis_holding
+ if defined?(@preloaded_holdings)
(@preloaded_holdings || [])
.select { |h| h.security_id == security_id && h.date <= entry.date }
.max_by(&:date)
else
- # Fall back to database query only when not preloaded
entry.account.holdings
.where(security_id: security_id)
.where("date <= ?", entry.date)
.order(date: :desc)
.first
end
+ end
+
+ def calculate_realized_gain_loss
+ return nil unless sell?
+ # Moving an asset to another account you own realises nothing. Without
+ # this the cost basis is compared against the day's price and the
+ # difference is booked as a gain the user never made.
+ return nil if internal_movement?
+
+ holding = basis_holding
return nil unless holding&.avg_cost
cost_basis = holding.avg_cost * qty.abs
- sale_proceeds = price_money * qty.abs
+ sale_proceeds = converted_to_basis_currency(price_money * qty.abs, cost_basis.currency)
+
+ # No rate for that day means the gain is unknown, not zero and not the
+ # figure a rate of 1.0 would give.
+ return nil if sale_proceeds.nil?
Trend.new(current: sale_proceeds, previous: cost_basis)
end
+
+ # The proceeds are priced in the security's currency; the basis is carried
+ # in the one the position is held in. `Trend#value` is `current - previous`
+ # and `Money#-` keeps the left operand's currency while taking the right
+ # one's bare amount, so without this the two were subtracted as plain
+ # numbers and the difference was then labelled with the disposal's
+ # currency -- an error that scaled with the rate and changed sign either
+ # side of parity.
+ #
+ # Converted in THIS direction, and not the other, because it is the
+ # direction the data holds: MarketDataImporter's first required pair is
+ # every entry currency against its account's, so a EUR disposal in a USD
+ # account has a EUR->USD row for the day it happened, while USD->EUR is
+ # only ever there by accident of another account.
+ #
+ # Exact date, exact direction, no parity fallback and no nearest-rate
+ # lookback. A disposal happened on one known day; the rate for that day is
+ # the rate, and its absence is a fact to report rather than a 1.0 nobody
+ # can see.
+ #
+ # A rate that is present but not positive is absent for this purpose.
+ # `ExchangeRate` validates presence only -- neither the model nor the
+ # column requires a positive number -- so a provider or an import can leave
+ # a 0 behind, and multiplying by it books the disposal as a total loss the
+ # user never made. A negative one is worse: it flips the sign. Both are the
+ # missing-rate case wearing a number, and reporting no figure is the whole
+ # point of the paragraph above.
+ def converted_to_basis_currency(proceeds, basis_currency)
+ from = proceeds.currency.iso_code
+ to = basis_currency.iso_code
+ return proceeds if from == to
+
+ rate = preloaded_rate(from, to) ||
+ ExchangeRate.find_by(from_currency: from, to_currency: to, date: entry.date)&.rate
+ return nil unless rate.to_d.positive?
+
+ Money.new(proceeds.amount * rate, to)
+ end
+
+ def preloaded_rate(from, to)
+ return nil unless defined?(@preloaded_exchange_rates)
+
+ (@preloaded_exchange_rates || {})[[ from, to, entry.date ]]
+ end
end
diff --git a/app/views/reports/_investment_performance.html.erb b/app/views/reports/_investment_performance.html.erb
index efa215a2ce..c5774a6e45 100644
--- a/app/views/reports/_investment_performance.html.erb
+++ b/app/views/reports/_investment_performance.html.erb
@@ -196,10 +196,12 @@
<p class="text-secondary font-medium"><%= t("reports.investment_performance.sell_trades") %></p>
<% data[:sell_trades].first(5).each do |trade| %>
<% gain = trade.realized_gain_loss %>
- <div class="flex justify-between pl-2">
+ <%# Converted in the controller, at the trade's own date: gain.value is carried in the currency the position is held in, and labelling it family currency here was reporting a EUR figure as USD. %>
+ <% amount = data[:realized_gain_by_trade][trade.id] %>
+ <div class="flex justify-between pl-2" data-testid="realized-gain-line">
<span class="text-primary"><%= trade.security.ticker %></span>
- <span class="<%= gain ? "" : "text-secondary" %>" style="<%= gain ? "color: #{gain.color}" : "" %>">
- <%= gain ? format_money(Money.new(gain.value, Current.family.currency)) : t("reports.investment_performance.no_data") %>
+ <span class="<%= amount ? "" : "text-secondary" %>" style="<%= amount ? "color: #{gain.color}" : "" %>">
+ <%= amount ? format_money(amount) : t("reports.investment_performance.no_data") %>
</span>
</div>
<% end %>
diff --git a/test/controllers/reports_controller_test.rb b/test/controllers/reports_controller_test.rb
index eb8b4cb610..ddd3ae2ea6 100644
--- a/test/controllers/reports_controller_test.rb
+++ b/test/controllers/reports_controller_test.rb
@@ -2,12 +2,95 @@ require "test_helper"
class ReportsControllerTest < ActionDispatch::IntegrationTest
include EntriesTestHelper
+ include SqlQueryCapture
setup do
sign_in @user = users(:family_admin)
@family = @user.family
end
+ # The per-trade line under the realised-gains card rendered
+ # `Money.new(gain.value, Current.family.currency)` -- taking the number out of
+ # the Trend and re-labelling it as family currency with no conversion at all.
+ #
+ # The fixture has to be a FOREIGN ACCOUNT for that to show: a gain is carried
+ # in the currency its position is held in, so for a USD account under a USD
+ # family the re-labelling is accidentally correct and a test built on one
+ # passes either way.
+ #
+ # A USD family, a EUR account, a EUR-listed security: basis 100 EUR/share, 2
+ # sold at 150 EUR/share, EUR->USD 1.5 that day. The gain is 100 EUR, and the
+ # line must read $150.00. Re-labelled rather than converted it reads $100.00.
+ test "a foreign-account disposal is listed in family currency, not re-labelled" do
+ date = Date.current.beginning_of_month
+ account = @family.accounts.create!(name: "Brokerage EUR", balance: 10_000,
+ currency: "EUR", accountable: Investment.new)
+ security = Security.create!(ticker: "EUX#{SecureRandom.hex(3)}", name: "Euro Listed")
+
+ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: date, rate: 1.5)
+ account.holdings.create!(security: security, date: date, qty: 5, price: 150,
+ amount: BigDecimal(750), currency: "EUR", cost_basis: 100)
+ create_trade(security, account: account, qty: -2, date: date, price: 150, currency: "EUR")
+
+ get reports_path
+ assert_response :ok
+
+ line = css_select("[data-testid='realized-gain-line']").map(&:text)
+ .find { |text| text.include?(security.ticker) }
+
+ assert line, "the disposal must be listed at all, or this proves nothing"
+ assert_match "$150.00", line, "converted at the trade's own rate"
+ assert_no_match(/\$100\.00/, line, "$100.00 is the EUR figure printed with a dollar sign")
+ end
+
+ # A position carried in a THIRD currency -- not the disposal's, not the
+ # account's. 300 EUR of proceeds at 0.8 is 240 GBP, less 200 GBP of basis, so
+ # 40 GBP and $50.00 at 1.25. GBP is in neither currency set the card used to
+ # enumerate, and a currency it does not enumerate converts at the `|| 1`
+ # parity fallback: the line would read $40.00.
+ test "a disposal carried in a third currency is converted, not passed through at parity" do
+ date = Date.current.beginning_of_month
+ account = @family.accounts.create!(name: "Brokerage USD", balance: 10_000,
+ currency: "USD", accountable: Investment.new)
+ security = Security.create!(ticker: "EUX#{SecureRandom.hex(3)}", name: "Euro Listed")
+
+ ExchangeRate.create!(from_currency: "EUR", to_currency: "GBP", date: date, rate: 0.8)
+ ExchangeRate.create!(from_currency: "GBP", to_currency: "USD", date: date, rate: 1.25)
+ account.holdings.create!(security: security, date: date, qty: 5, price: 150,
+ amount: BigDecimal(750), currency: "GBP", cost_basis: 100)
+ create_trade(security, account: account, qty: -2, date: date, price: 150, currency: "EUR")
+
+ get reports_path
+ assert_response :ok
+
+ line = css_select("[data-testid='realized-gain-line']").map(&:text)
+ .find { |text| text.include?(security.ticker) }
+
+ assert line, "the disposal must be listed at all, or this proves nothing"
+ assert_match "$50.00", line
+ assert_no_match(/\$40\.00/, line, "$40.00 is the GBP figure converted at parity")
+ end
+
+ # The rates a page of disposals needs come from one query, not one per
+ # foreign disposal. The conversion itself is covered in TradeTest, which
+ # counts the queries directly; what has to hold HERE is that the card asks
+ # for the preload at all -- the page's own rate lookups share a SQL shape
+ # with `ExchangeRate.find_or_fetch_rate`, so counting them measures the rest
+ # of the page rather than this.
+ test "the card preloads the rates its disposals need" do
+ account = @family.accounts.create!(name: "Brokerage USD", balance: 50_000,
+ currency: "USD", accountable: Investment.new)
+ seed_foreign_disposals(account, 3)
+
+ Trade.expects(:preload_exchange_rates).at_least_once.with do |trades|
+ trades.any? { |trade| trade.currency == "EUR" }
+ end
+
+ get reports_path
+
+ assert_response :ok
+ end
+
test "index renders successfully" do
get reports_path
assert_response :ok
@@ -627,4 +710,21 @@ class ReportsControllerTest < ActionDispatch::IntegrationTest
assert_match I18n.t("reports.investment_performance.sells_count", count: 1), response.body
assert_no_match(/#{Regexp.escape(I18n.t("reports.investment_performance.sells_count", count: 2))}/, response.body)
end
+
+ private
+ # n EUR-priced disposals in a USD account, each on its own date with its
+ # own rate row, so every one needs a distinct lookup.
+ def seed_foreign_disposals(account, count)
+ base = Date.current.beginning_of_month
+
+ count.times do |i|
+ date = base + i
+ security = Security.create!(ticker: "EUX#{SecureRandom.hex(3)}", name: "Euro Listed #{i}")
+
+ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: date, rate: 1.5)
+ account.holdings.create!(security: security, date: date, qty: 5, price: 150,
+ amount: BigDecimal(750), currency: "USD", cost_basis: 100)
+ create_trade(security, account: account, qty: -2, date: date, price: 150, currency: "EUR")
+ end
+ end
end
diff --git a/test/models/trade_test.rb b/test/models/trade_test.rb
index a81905230a..4b06804c47 100644
--- a/test/models/trade_test.rb
+++ b/test/models/trade_test.rb
@@ -1,6 +1,134 @@
require "test_helper"
class TradeTest < ActiveSupport::TestCase
+ include EntriesTestHelper
+ include SqlQueryCapture
+ # `Trend#value` is `current - previous`, and `Money#-` keeps the left
+ # operand's currency while taking the right one's bare amount without
+ # converting or raising. So a disposal priced in the security's currency had
+ # a basis denominated in the account's subtracted from it as a plain number,
+ # and the difference was then labelled with the disposal's currency.
+ #
+ # A USD account holding a EUR-listed security: basis 100 USD/share, 2 sold at
+ # 150 EUR/share, EUR->USD 1.5 on the trade date. 300 EUR of proceeds is 450
+ # USD, less 200 USD of basis, so 250 USD. The unconverted subtraction
+ # reported 100 -- and then Reports scaled that wrong difference by the rate.
+ test "a disposal priced in another currency converts its proceeds at the trade date" do
+ sell = cross_currency_disposal(rate: 1.5)
+
+ assert_equal BigDecimal(250), sell.realized_gain_loss.value.amount
+ assert_equal "USD", sell.realized_gain_loss.value.currency.iso_code,
+ "the figure is carried in the currency the position is held in"
+ end
+
+ # The same defect at a rate below parity OVERSTATES, so a test at one rate
+ # cannot pass by accident of direction. 300 EUR at 0.7 is 210 USD, less 200
+ # USD of basis: a 10 USD gain, where the bare subtraction claimed 100.
+ test "a disposal at a rate below parity is not overstated" do
+ sell = cross_currency_disposal(rate: 0.7)
+
+ assert_equal BigDecimal(10), sell.realized_gain_loss.value.amount
+ end
+
+ # No rate for that date means the gain is unknown, not zero and not the
+ # figure a rate of 1.0 would produce.
+ test "a cross-currency disposal with no rate for its date has no figure" do
+ sell = cross_currency_disposal(rate: 1.5, rate_date: Date.new(2026, 3, 9))
+
+ assert_nil sell.realized_gain_loss, "a neighbouring day's rate is not this day's"
+ end
+
+ # `ExchangeRate` validates presence only -- no positivity at the model, and
+ # `rate` is a plain `decimal, null: false` at the column -- so a provider or
+ # an import can leave a 0 or a negative behind. Multiplying by one is not a
+ # conversion: at 0 the 300 EUR of proceeds become nothing and the disposal
+ # reports a 200 USD total loss the user never took, and at -1.5 the proceeds
+ # go negative and the loss is 650. Neither is distinguishable on the page
+ # from a real one, and both are tax-relevant.
+ #
+ # A rate that cannot convert is the missing-rate case, whatever is stored in
+ # the row, so it takes the same exit as an absent one.
+ test "a disposal whose stored rate cannot convert has no figure" do
+ [ 0, -1.5 ].each do |stored|
+ # Each case needs the same EUR->USD date, which is unique per pair.
+ ExchangeRate.where(from_currency: "EUR", to_currency: "USD").delete_all
+ sell = cross_currency_disposal(rate: stored)
+
+ assert_nil sell.realized_gain_loss, "a rate of #{stored} converts nothing"
+ end
+ end
+
+ # One query for the rates a whole page of disposals needs, rather than one
+ # per foreign disposal. Each disposal falls on its own date, because
+ # identical lookups are served by the query cache and a single-date fixture
+ # reads as flat whether the preload runs or not.
+ #
+ # The preload runs INSIDE the capture, which is the difference between
+ # counting what the page costs and counting what is left after the expensive
+ # part already happened. With it outside, the assertion was "measuring
+ # disposals issues no further rate queries" -- true, and it would stay true
+ # if `preload_exchange_rates` itself issued one query per trade. One query
+ # for the whole set is the claim, so one query for the whole set is what is
+ # counted.
+ test "preloading answers every disposal's rate in one query" do
+ account, security = cross_currency_account
+
+ trades = (0..3).map do |offset|
+ date = Date.new(2026, 3, 10) + offset
+ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: date, rate: 1.5)
+ account.holdings.create!(security: security, date: date, qty: 5, price: 150,
+ amount: BigDecimal(750), currency: "USD", cost_basis: 100)
+ create_trade(security, account: account, qty: -2, date: date, price: 150, currency: "EUR").entryable
+ end
+
+ # The ivar directly, as ReportsController does on this branch -- there is
+ # no public writer for it upstream yet. Outside the capture on purpose: the
+ # cost being counted is the rates', not the holdings'.
+ holdings = account.holdings.to_a
+ trades.each { |trade| trade.instance_variable_set(:@preloaded_holdings, holdings) }
+
+ queries = capture_sql_queries do
+ Trade.preload_exchange_rates(trades)
+ trades.each { |trade| trade.realized_gain_loss }
+ end.grep(/exchange_rates/)
+
+ assert_equal 1, queries.size,
+ "four disposals on four dates cost one rate query, not one each"
+ assert_equal [ BigDecimal(250) ] * 4, trades.map { |t| t.realized_gain_loss.value.amount }
+ end
+
+ # The preload keys its basis side on the ACCOUNT's currency; the conversion
+ # targets the currency the POSITION is carried in. Those differ in exactly the
+ # shape this change exists for -- a EUR disposal of a GBP position in a USD
+ # account -- so every such disposal missed the preload and issued the lookup
+ # the preload is here to remove. The keys have to come from the holding that
+ # `realized_gain_loss` will actually select.
+ test "preloading answers a disposal against a position carried in a third currency" do
+ account, security = cross_currency_account
+
+ trades = (0..3).map do |offset|
+ date = Date.new(2026, 3, 10) + offset
+ ExchangeRate.create!(from_currency: "EUR", to_currency: "GBP", date: date, rate: 0.8)
+ account.holdings.create!(security: security, date: date, qty: 5, price: 150,
+ amount: BigDecimal(750), currency: "GBP", cost_basis: 100)
+ create_trade(security, account: account, qty: -2, date: date, price: 150, currency: "EUR").entryable
+ end
+
+ holdings = account.holdings.to_a
+ trades.each { |trade| trade.instance_variable_set(:@preloaded_holdings, holdings) }
+
+ queries = capture_sql_queries do
+ Trade.preload_exchange_rates(trades)
+ trades.each { |trade| trade.realized_gain_loss }
+ end.grep(/exchange_rates/)
+
+ assert_equal 1, queries.size,
+ "a position in a third currency costs one rate query for the set, not one each"
+ # 2 units at 150 EUR is 300 EUR of proceeds, 240 GBP at 0.8, against a basis
+ # of 2 x 100 GBP.
+ assert_equal [ BigDecimal(40) ] * 4, trades.map { |t| t.realized_gain_loss.value.amount }
+ end
+
test "build_name generates buy trade name" do
name = Trade.build_name("buy", 10, "AAPL")
assert_equal "Buy 10.0 shares of AAPL", name
@@ -158,4 +286,26 @@ class TradeTest < ActiveSupport::TestCase
assert_includes Transaction::INTERNAL_MOVEMENT_LABELS, "Exchange"
assert_not_includes Trade::INTERNAL_MOVEMENT_LABELS, "Exchange"
end
+
+ private
+ # A USD account holding a EUR-listed security, with one disposal in it.
+ def cross_currency_disposal(rate:, rate_date: Date.new(2026, 3, 10))
+ account, security = cross_currency_account
+ date = Date.new(2026, 3, 10)
+
+ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: rate_date, rate: rate)
+ account.holdings.create!(security: security, date: date, qty: 5, price: 150,
+ amount: BigDecimal(750), currency: "USD", cost_basis: 100)
+
+ create_trade(security, account: account, qty: -2, date: date, price: 150, currency: "EUR").entryable
+ end
+
+ def cross_currency_account
+ account = families(:empty).accounts.create!(
+ name: "Brokerage", balance: 10_000, currency: "USD", accountable: Investment.new
+ )
+ security = Security.create!(ticker: "EUX#{SecureRandom.hex(3)}", name: "Euro Listed")
+
+ [ account, security ]
+ end
end