The personal finance app for everyone (by everyone)
Ruby
fix(investments): convert a foreign-currency quote to the trade's or holding's currency (#4181)
GFRfd4cefabd754
diff --git a/app/helpers/securities_helper.rb b/app/helpers/securities_helper.rbnew file mode 100644index 0000000000..1fc5a5027b--- /dev/null+++ b/app/helpers/securities_helper.rb@@ -0,0 +1,15 @@+module SecuritiesHelper+ # The security's current price in `currency`, the currency the trade or+ # position beside it is carried in, with the quote in its listing currency+ # in brackets so it compares with the purchase price and value next to it.+ # Without a rate only the quote shows, never relabelled as `currency`.+ def current_price_with_quote(security, currency)+ quote = security.current_price+ return if quote.nil?++ converted = security.current_price_in(currency)+ return format_money(quote) if converted.nil? || converted.currency == quote.currency++ safe_join([ format_money(converted), " ", tag.span("(#{format_money(quote)})", class: "text-secondary") ])+ end+enddiff --git a/app/helpers/transactions_helper.rb b/app/helpers/transactions_helper.rbindex 390767fc68..9add70ea7e 100644--- a/app/helpers/transactions_helper.rb+++ b/app/helpers/transactions_helper.rb@@ -439,6 +439,35 @@ module TransactionsHelpervalue.to_send+ # Options for the convert-to-trade security picker: label, id and the data+ # its price check reads. That check compares against the price the+ # transaction implies, so only a positive quote converted to `currency`+ # carries data-price-cents. Without a rate the quote is still shown, under its own+ # currency. The securities share one rate lookup per quote currency and day.+ def convert_to_trade_security_options(securities, currency)+ rates = {}+ securities.map do |security|+ price = security.current_price_in(currency, rates: rates)+ shown_price = price || security.current_price+ label = security.ticker.to_s.dup+ label << " (#{format_money(shown_price)})" if shown_price+ label << " - #{security.name.truncate(25)}" if security.name.present?+ # Fractional cents are kept: a converted quote can be worth less than a+ # cent (1 JPY in USD), and a zero would make the check divide by zero.+ price_cents = price_cents_for_check(price)+ [ label, security.id, { "data-price-cents" => price_cents, "data-ticker" => security.ticker } ]+ end+ end++ # @param price [Money, nil] a quote in the transaction's currency+ # @return [Integer, Float, nil] the quote in cents, whole cents as an integer+ def price_cents_for_check(price)+ return unless price&.amount&.positive?++ cents = price.amount.to_d * 100+ cents.frac.zero? ? cents.to_i : cents.to_f+ end+# A pending transfer match as the viewer may see it from `transaction`'s# row. The accounts and transactions pages set @accessible_account_ids;# a view that does not, such as the turbo stream that redraws a match,diff --git a/app/models/security.rb b/app/models/security.rbindex 6d75ae00f2..55dfc46e58 100644--- a/app/models/security.rb+++ b/app/models/security.rb@@ -333,6 +333,25 @@ class Security < ApplicationRecordMoney.new(@current_price.price, @current_price.currency)end+ # The current price in `currency`. A quote comes in the listing's currency,+ # which need not be the one a trade or position is carried in. Converted at+ # the quote's own date, as the holdings are. nil when there is no price or no+ # rate to convert it at, rather than the unconverted figure read as if it+ # were in `currency`. Memoised per currency, a miss included, because a page+ # asks for the same figure more than once and a missing rate is a provider+ # call each time.+ #+ # A page listing several securities passes one `rates` hash to all of them,+ # so quotes in the same currency on the same day share one rate lookup+ # instead of each making its own.+ def current_price_in(currency, rates: {})+ @current_price_in ||= {}+ return @current_price_in[currency] if @current_price_in.key?(currency)++ price = current_price+ @current_price_in[currency] = price && convert_quote(price, currency, rates)+ end+# Stores user-supplied closes for a security no provider tracks. See Security::ManualPriceImport.def import_manual_prices!(rows, accounts:)Security::ManualPriceImport.new(security: self, rows: rows, accounts: accounts).import!@@ -366,6 +385,20 @@ class Security < ApplicationRecordendprivate+ def convert_quote(price, currency, rates)+ to = Money::Currency.new(currency).iso_code+ return price if price.currency.iso_code == to++ date = @current_price&.date || Date.current+ key = [ price.currency.iso_code, to, date ]+ rate = rates.fetch(key) do+ rates[key] = ExchangeRate.find_or_fetch_rate(from: key.first, to: to, date: date)&.rate+ end+ return nil unless rate&.positive?++ price.exchange_to(to, date: date, custom_rate: rate)+ end+def stored_logo_urlSetting.transform_brand_fetch_url(logo_url).presencediff --git a/app/models/trade.rb b/app/models/trade.rbindex cc33300601..9edb5f867a 100644--- a/app/models/trade.rb+++ b/app/models/trade.rb@@ -141,7 +141,7 @@ class Trade < ApplicationRecorddef unrealized_gain_lossreturn nil unless qty.positive?- current_price = security.current_price+ current_price = security.current_price_in(currency)return nil if current_price.nil?current_value = current_price * qty.absdiff --git a/app/views/holdings/show.html.erb b/app/views/holdings/show.html.erbindex 6d1ea3f16a..35a9838a21 100644--- a/app/views/holdings/show.html.erb+++ b/app/views/holdings/show.html.erb@@ -84,7 +84,7 @@<dt class="text-secondary"><%= t(".current_market_price_label") %></dt><dd id="<%= dom_id(@holding, :current_market_price) %>" class="text-primary"><% begin %>- <%= @holding.security.current_price ? format_money(@holding.security.current_price) : t(".unknown") %>+ <%= @holding.security.current_price ? current_price_with_quote(@holding.security, @holding.currency) : t(".unknown") %><% rescue ActiveRecord::RecordInvalid %><%= t(".unknown") %><% rescue StandardError => e %>diff --git a/app/views/holdings/sync_prices.turbo_stream.erb b/app/views/holdings/sync_prices.turbo_stream.erbindex 98ab65d432..984b1993e6 100644--- a/app/views/holdings/sync_prices.turbo_stream.erb+++ b/app/views/holdings/sync_prices.turbo_stream.erb@@ -2,7 +2,7 @@<%= turbo_stream.replace dom_id(@holding, :current_market_price) do %><dd id="<%= dom_id(@holding, :current_market_price) %>" class="text-primary"><% begin %>- <%= @holding.security.current_price ? format_money(@holding.security.current_price) : t("holdings.show.unknown") %>+ <%= @holding.security.current_price ? current_price_with_quote(@holding.security, @holding.currency) : t("holdings.show.unknown") %><% rescue ActiveRecord::RecordInvalid %><%= t("holdings.show.unknown") %><% rescue StandardError => e %>diff --git a/app/views/trades/_header.html.erb b/app/views/trades/_header.html.erbindex c7aff25b24..ff4fb38724 100644--- a/app/views/trades/_header.html.erb+++ b/app/views/trades/_header.html.erb@@ -69,7 +69,7 @@<% if trade.qty.positive? && trade.security.current_price.present? %><div class="flex items-center justify-between text-sm"><dt class="text-secondary"><%= t(".current_market_price_label") %></dt>- <dd class="text-primary privacy-sensitive"><%= format_money trade.security.current_price %></dd>+ <dd class="text-primary privacy-sensitive"><%= current_price_with_quote(trade.security, trade.currency) %></dd></div><% end %>diff --git a/app/views/transactions/convert_to_trade.html.erb b/app/views/transactions/convert_to_trade.html.erbindex cd021333b1..c3ec031b6d 100644--- a/app/views/transactions/convert_to_trade.html.erb+++ b/app/views/transactions/convert_to_trade.html.erb@@ -54,15 +54,7 @@.uniq(&:ticker).sort_by(&:ticker)- # Build options with price data for validation- security_options_with_prices = account_securities.map do |s|- price = s.current_price- price_display = price ? " (#{format_money(price)})" : ""- label = "#{s.ticker}#{price_display}"- label += " - #{s.name.truncate(25)}" if s.name.present?- price_cents = price ? (price.amount * 100).to_i : nil- [label, s.id, { "data-price-cents" => price_cents, "data-ticker" => s.ticker }]- end+ security_options_with_prices = convert_to_trade_security_options(account_securities, @entry.currency)%><% if account_securities.any? %><%= f.select :security_id,diff --git a/test/controllers/holdings_controller_test.rb b/test/controllers/holdings_controller_test.rbindex 39d23632ae..92be7f9f62 100644--- a/test/controllers/holdings_controller_test.rb+++ b/test/controllers/holdings_controller_test.rb@@ -52,6 +52,19 @@ class HoldingsControllerTest < ActionDispatch::IntegrationTestassert_select "##{dom_id(@holding, :shares)}", text: "10.374"end+ # The quote is in the listing's currency; the value and cost beside it are in+ # the holding's. Showing the quote alone put a foreign figure among them.+ test "shows a quote in another currency converted to the holding's, with the quote beside it" do+ Security.any_instance.stubs(:current_price).returns(Money.new(200, "EUR"))+ ExchangeRate.create!(from_currency: "EUR", to_currency: @holding.currency, date: Date.current, rate: 1.1)++ get holding_path(@holding)++ price = css_select("##{dom_id(@holding, :current_market_price)}").text.squish+ assert_includes price, Money.new(220, @holding.currency).format+ assert_includes price, "(#{Money.new(200, "EUR").format})"+ end+test "shows the exact stored quantity for a small crypto holding in the holdings list" doaccount = accounts(:crypto)security = Security.create!(diff --git a/test/controllers/trades_controller_test.rb b/test/controllers/trades_controller_test.rbindex a8ff91f678..ab4609f275 100644--- a/test/controllers/trades_controller_test.rb+++ b/test/controllers/trades_controller_test.rb@@ -24,6 +24,22 @@ class TradesControllerTest < ActionDispatch::IntegrationTestassert_select "span.text-secondary.text-sm", text: I18n.t("trades.header.buy"), count: 0end+ # A quote in the listing's currency was shown and netted against the trade's+ # price as if both were in the trade's currency. 10 bought at 180 EUR, quoted+ # at 200 USD, USD->EUR 0.9: the position is worth what it cost.+ test "the header converts a quote in another currency to the trade's" do+ @entry.update!(amount: 1800, currency: "EUR")+ @entry.trade.update!(qty: 10, price: 180, fee: 0, currency: "EUR")+ Security.any_instance.stubs(:current_price).returns(Money.new(200, "USD"))+ ExchangeRate.create!(from_currency: "USD", to_currency: "EUR", date: Date.current, rate: 0.9)++ get trade_url(@entry)++ assert_response :success+ assert_select "dd", text: /#{Regexp.escape(Money.new(180, "EUR").format)}\s*\(#{Regexp.escape(Money.new(200, "USD").format)}\)/+ assert_select "dd p", text: I18n.t("shared.trend_change.no_change")+ end+test "the German header localizes supported provider activity labels" do@user.update!(locale: "de")diff --git a/test/controllers/transactions_trade_conversion_test.rb b/test/controllers/transactions_trade_conversion_test.rbindex f29ee68b9c..9b2c2de875 100644--- a/test/controllers/transactions_trade_conversion_test.rb+++ b/test/controllers/transactions_trade_conversion_test.rb@@ -24,6 +24,41 @@ class TransactionsTradeConversionTest < ActionDispatch::IntegrationTestendend+ # The picker's price feeds a sanity check against the price the transaction+ # implies, which is in the transaction's currency. A quote left in the+ # listing's currency warned on a sound price, or kept quiet on a wrong one.+ test "the security picker shows a quote in another currency converted to the transaction's" do+ Security.stubs(:providers).returns([])+ Security.any_instance.stubs(:current_price).returns(Money.new(200, "EUR"))+ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: Date.current, rate: 1.1)+ entry = create_transaction(account: accounts(:investment), currency: "USD")++ get convert_to_trade_transaction_url(entry.transaction),+ params: { activity_label: "Buy" }, headers: { "Turbo-Frame" => "modal" }++ assert_response :success+ option = css_select("option[data-price-cents]").first+ assert_equal "22000", option["data-price-cents"]+ assert_includes option.text, Money.new(220, "USD").format+ end++ # Without a rate the quote is still worth showing, under its own currency,+ # but it cannot feed a check against a price in another one.+ test "the security picker keeps an unconvertible quote out of the price check" do+ Security.stubs(:providers).returns([])+ ExchangeRate.stubs(:provider).returns(nil)+ Security.any_instance.stubs(:current_price).returns(Money.new(200, "EUR"))+ entry = create_transaction(account: accounts(:investment), currency: "USD")++ get convert_to_trade_transaction_url(entry.transaction),+ params: { activity_label: "Buy" }, headers: { "Turbo-Frame" => "modal" }++ assert_response :success+ option = css_select("option[data-ticker]").first+ assert_nil option["data-price-cents"]+ assert_includes option.text, Money.new(200, "EUR").format+ end+test "conversion action follows the account's trade capability" do[ @account, accounts(:investment), accounts(:depository) ].each do |account|entry = create_transaction(account: account)diff --git a/test/helpers/securities_helper_test.rb b/test/helpers/securities_helper_test.rbnew file mode 100644index 0000000000..bf1b5882bd--- /dev/null+++ b/test/helpers/securities_helper_test.rb@@ -0,0 +1,37 @@+require "test_helper"++class SecuritiesHelperTest < ActionView::TestCase+ include ApplicationHelper++ setup do+ @security = securities(:aapl)+ @security.stubs(:current_price).returns(Money.new(200, "USD"))+ end++ test "shows the converted price with the quote beside it" do+ @security.stubs(:current_price_in).with("EUR").returns(Money.new(180, "EUR"))++ html = current_price_with_quote(@security, "EUR")++ assert_includes html, Money.new(180, "EUR").format+ assert_includes html, "(#{Money.new(200, "USD").format})"+ end++ test "shows only the quote when it is in the currency asked for" do+ @security.stubs(:current_price_in).with("USD").returns(Money.new(200, "USD"))++ assert_equal Money.new(200, "USD").format, current_price_with_quote(@security, "USD")+ end++ test "shows only the quote, under its own currency, without a rate" do+ @security.stubs(:current_price_in).with("EUR").returns(nil)++ assert_equal Money.new(200, "USD").format, current_price_with_quote(@security, "EUR")+ end++ test "shows nothing without a quote" do+ @security.stubs(:current_price).returns(nil)++ assert_nil current_price_with_quote(@security, "EUR")+ end+enddiff --git a/test/helpers/transactions_helper_test.rb b/test/helpers/transactions_helper_test.rbindex 7d0239f831..52683fbe9c 100644--- a/test/helpers/transactions_helper_test.rb+++ b/test/helpers/transactions_helper_test.rb@@ -2,6 +2,7 @@ require "test_helper"require "ostruct"class TransactionsHelperTest < ActionView::TestCase+ include ApplicationHelperinclude EntriesTestHelper# build_transaction_extra_details reads `extra` off a Transaction (or anything@@ -258,6 +259,40 @@ class TransactionsHelperTest < ActionView::TestCaseassert_equal({ "someprovider" => { "a" => 1 } }, JSON.parse(details[:raw]))end+ test "the convert-to-trade picker looks a shared rate up once for all its securities" do+ securities = [ securities(:aapl), securities(:msft) ]+ securities.each do |security|+ security.stubs(:find_or_fetch_price).returns(Security::Price.new(price: 200, currency: "USD", date: Date.current))+ end+ ExchangeRate.expects(:find_or_fetch_rate).once.returns(ExchangeRate.new(rate: 0.9))++ options = convert_to_trade_security_options(securities, "EUR")++ assert_equal [ "18000", "18000" ], options.map { |option| option.last["data-price-cents"].to_s }+ end++ # Regression: a quote worth less than a cent after conversion (1 JPY is about+ # 0.0066 USD) was truncated to 0 cents, so the price check divided by zero+ # and warned about a mismatch even when the entered price matched the quote.+ test "the convert-to-trade picker keeps fractional cents of a converted quote" do+ security = securities(:aapl)+ security.stubs(:find_or_fetch_price).returns(Security::Price.new(price: 1, currency: "JPY", date: Date.current))+ ExchangeRate.stubs(:find_or_fetch_rate).returns(ExchangeRate.new(rate: 0.0066))++ options = convert_to_trade_security_options([ security ], "USD")++ assert_in_delta 0.66, options.first.last["data-price-cents"], 0.0001+ end++ test "the convert-to-trade picker omits the price check for a zero quote" do+ security = securities(:aapl)+ security.stubs(:find_or_fetch_price).returns(Security::Price.new(price: 0, currency: "USD", date: Date.current))++ options = convert_to_trade_security_options([ security ], "USD")++ assert_nil options.first.last["data-price-cents"]+ end+test "investment_activity_label_name translates the stored label" doI18n.with_locale(:ru) doassert_equal "Перевод", investment_activity_label_name("Transfer")diff --git a/test/models/security_test.rb b/test/models/security_test.rbindex b96a192efc..240ddc5ed8 100644--- a/test/models/security_test.rb+++ b/test/models/security_test.rb@@ -430,4 +430,52 @@ class SecurityTest < ActiveSupport::TestCaseassert_nil security.crypto_base_assetend++ # The convert-to-trade picker lists every security in the account. Each+ # asking for the same rate was a lookup per security, and with the rate+ # missing a provider call per security.+ test "securities quoted in the same currency on the same day share one rate lookup" do+ aapl, msft = securities(:aapl), securities(:msft)+ [ aapl, msft ].each do |security|+ security.stubs(:find_or_fetch_price).returns(Security::Price.new(price: 200, currency: "USD", date: Date.current))+ end+ ExchangeRate.expects(:find_or_fetch_rate)+ .with(from: "USD", to: "EUR", date: Date.current).once+ .returns(ExchangeRate.new(rate: 0.9))++ rates = {}+ assert_equal Money.new(180, "EUR"), aapl.current_price_in("EUR", rates: rates)+ assert_equal Money.new(180, "EUR"), msft.current_price_in("EUR", rates: rates)+ end++ test "a shared missing rate converts nothing and is not looked up again" do+ aapl, msft = securities(:aapl), securities(:msft)+ [ aapl, msft ].each do |security|+ security.stubs(:find_or_fetch_price).returns(Security::Price.new(price: 200, currency: "USD", date: Date.current))+ end+ ExchangeRate.expects(:find_or_fetch_rate).once.returns(nil)++ rates = {}+ assert_nil aapl.current_price_in("EUR", rates: rates)+ assert_nil msft.current_price_in("EUR", rates: rates)+ end++ test "a quote from an earlier day is converted at that day's rate" do+ security = securities(:aapl)+ quote_date = 3.days.ago.to_date+ security.stubs(:find_or_fetch_price).returns(Security::Price.new(price: 200, currency: "USD", date: quote_date))+ ExchangeRate.expects(:find_or_fetch_rate)+ .with(from: "USD", to: "EUR", date: quote_date).once+ .returns(ExchangeRate.new(rate: 0.9))++ assert_equal Money.new(180, "EUR"), security.current_price_in("EUR")+ end++ test "a quote already in the currency asked for needs no rate" do+ security = securities(:aapl)+ security.stubs(:find_or_fetch_price).returns(Security::Price.new(price: 200, currency: "USD", date: Date.current))+ ExchangeRate.expects(:find_or_fetch_rate).never++ assert_equal Money.new(200, "USD"), security.current_price_in("USD")+ endenddiff --git a/test/models/trade_test.rb b/test/models/trade_test.rbindex af9e255612..cb92ccff02 100644--- a/test/models/trade_test.rb+++ b/test/models/trade_test.rb@@ -50,6 +50,29 @@ class TradeTest < ActiveSupport::TestCaseassert_equal BigDecimal(180), buy.unrealized_gain_loss.value.amountend+ # A quote comes in the listing's currency, which need not be the trade's.+ # `Money#-` takes the right operand's bare amount, so a 200 USD quote against+ # a 180 EUR purchase price read as a 20 "EUR" gain per share. 10 bought at+ # 180 EUR, quoted at 200 USD with USD->EUR 0.9: worth 1,800 EUR, no gain.+ test "a purchase's unrealized gain converts a quote in another currency to the trade's" do+ buy = cross_currency_purchase+ ExchangeRate.create!(from_currency: "USD", to_currency: "EUR", date: Date.current, rate: 0.9)++ gain = buy.unrealized_gain_loss++ assert_equal BigDecimal(0), gain.value.amount+ assert_equal "EUR", gain.value.currency.iso_code+ assert_equal BigDecimal(1800), gain.current.amount+ end++ # No rate means the gain is unknown, not the figure a rate of 1.0 would give.+ test "a purchase quoted in another currency with no rate has no unrealized gain" do+ buy = cross_currency_purchase+ ExchangeRate.stubs(:provider).returns(nil)++ assert_nil buy.unrealized_gain_loss+ 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@@ -428,6 +451,16 @@ class TradeTest < ActiveSupport::TestCase[ account, security ]end+ def cross_currency_purchase+ account = families(:empty).accounts.create!(+ name: "Depot", balance: 10_000, currency: "EUR", accountable: Investment.new+ )+ security = Security.create!(ticker: "USX#{SecureRandom.hex(3)}", name: "Dollar Listed")+ buy = create_trade(security, account: account, qty: 10, date: Date.current, price: 180, currency: "EUR").entryable+ buy.security.stubs(:current_price).returns(Money.new(200, "USD"))+ buy+ end+test "label_for_side follows the side for Buy, Sell and a missing label, and keeps any other activity" dotrade = Trade.new(investment_activity_label: "Buy")assert_equal "Sell", trade.label_for_side(sell: true)