The personal finance app for everyone (by everyone)
Ruby
feat(accounts): add Gains / ROI chart view for investment accounts (#2660)
Antoine ππββοΈ6b6ae0ca31d2
diff --git a/app/components/UI/account/chart.html.erb b/app/components/UI/account/chart.html.erbindex 8e88e3445c..aedc04abf1 100644--- a/app/components/UI/account/chart.html.erb+++ b/app/components/UI/account/chart.html.erb@@ -9,10 +9,10 @@<% end %></div><div class="flex flex-row gap-2 items-baseline">- <%= tag.p view_balance_money.format, class: "text-primary text-3xl font-medium truncate privacy-sensitive" %>+ <%= tag.p view_balance_display, class: "text-primary text-3xl font-medium truncate privacy-sensitive" %>- <% if converted_balance_money %>- <%= tag.p converted_balance_money.format, class: "text-sm font-medium text-secondary privacy-sensitive" %>+ <% if converted_balance_display %>+ <%= tag.p converted_balance_display, class: "text-sm font-medium text-secondary privacy-sensitive" %><% end %></div></div>@@ -21,7 +21,7 @@<% if account.supports_trades? %><%= form_with url: account_path(account), method: :get, data: { controller: "auto-submit-form" } do |form| %><%= form.select :chart_view,- [[t(".views.total_value"), "balance"], [t(".views.holdings"), "holdings_balance"], [t(".views.cash"), "cash_balance"]],+ [[t(".views.total_value"), "balance"], [t(".views.holdings"), "holdings_balance"], [t(".views.cash"), "cash_balance"], [t(".views.gains"), "gains"]],{ selected: view },class: "bg-container border border-secondary rounded-lg text-sm pr-7 cursor-pointer text-primary focus:outline-hidden focus:ring-0",data: { "auto-submit-form-target": "auto" } %>diff --git a/app/components/UI/account/chart.rb b/app/components/UI/account/chart.rbindex 25c5880aba..9b14715512 100644--- a/app/components/UI/account/chart.rb+++ b/app/components/UI/account/chart.rb@@ -15,6 +15,7 @@ class UI::Account::Chart < ApplicationComponentaccount.balance_money - account.cash_balance_moneyend+ # Money value shown as the main indicator for the selected chart view.def view_balance_moneycase viewwhen "balance"@@ -23,9 +24,24 @@ class UI::Account::Chart < ApplicationComponentholdings_value_moneywhen "cash_balance"account.cash_balance_money+ when "gains"+ gains_moneyendend+ # Formatted main indicator. Gains are signed explicitly (e.g. "+β¬79.53") since+ # a gain of zero-or-more is otherwise indistinguishable from a balance.+ def view_balance_display+ signed_format(view_balance_money)+ end++ # Formatted family-currency amount for foreign-currency accounts, signed the+ # same way as the main indicator. Nil when no conversion applies.+ def converted_balance_display+ converted_balance_money&.then { |money| signed_format(money) }+ end++ # Label displayed above the main indicator, based on account type and chart view.def titlecase account.accountable_typewhen "Investment", "Crypto"@@ -36,6 +52,8 @@ class UI::Account::Chart < ApplicationComponentI18n.t("UI.account.chart.title.holdings_value")when "cash_balance"I18n.t("UI.account.chart.title.cash_value")+ when "gains"+ I18n.t("UI.account.chart.title.total_gains")endwhen "Property"I18n.t("UI.account.chart.title.estimated_property_value")@@ -54,11 +72,14 @@ class UI::Account::Chart < ApplicationComponentaccount.currency != account.family.currencyend+ # Main indicator converted to the family currency for foreign-currency accounts,+ # or nil when no conversion applies (same currency or missing exchange rate).def converted_balance_moneyreturn nil unless foreign_currency?begin- account.balance_money.exchange_to(account.family.currency)+ base_money = view == "gains" ? gains_money : account.balance_money+ base_money.exchange_to(account.family.currency)rescue Money::ConversionErrornilend@@ -72,6 +93,12 @@ class UI::Account::Chart < ApplicationComponentaccount.balance_series(period: period, view: view)end+ # Current total unrealized gains, taken from the series so the main indicator+ # always matches the last point of the chart (there is no stored gains column).+ def gains_money+ series.values.last&.value || Money.new(0, account.currency)+ end+def trendseries.trendend@@ -86,4 +113,12 @@ class UI::Account::Chart < ApplicationComponentperiod.comparison_labelendend++ private+ # Prefixes positive gains with "+"; other views keep plain Money formatting.+ def signed_format(money)+ return money.format unless view == "gains" && money.amount.positive?++ "+#{money.format}"+ endenddiff --git a/app/models/account/chartable.rb b/app/models/account/chartable.rbindex 59bc85c2a1..d84b43d9c7 100644--- a/app/models/account/chartable.rb+++ b/app/models/account/chartable.rb@@ -6,8 +6,10 @@ module Account::Chartableclassification == "asset" ? "up" : "down"end+ # Returns the chart Series for this account over the given period.+ # Supported views: :balance, :cash_balance, :holdings_balance, :gains.def balance_series(period: Period.last_30_days, view: :balance, interval: nil)- raise ArgumentError, "Invalid view type" unless [ :balance, :cash_balance, :holdings_balance ].include?(view.to_sym)+ raise ArgumentError, "Invalid view type" unless [ :balance, :cash_balance, :holdings_balance, :gains ].include?(view.to_sym)@balance_series ||= {}diff --git a/app/models/balance/chart_series_builder.rb b/app/models/balance/chart_series_builder.rbindex b6aa9f7bc8..ae24e9cbaa 100644--- a/app/models/balance/chart_series_builder.rb+++ b/app/models/balance/chart_series_builder.rb@@ -32,6 +32,35 @@ class Balance::ChartSeriesBuilderraiseend+ # Unrealized gains series: for each date, sum of (market value - cost basis) across+ # the latest holding snapshot per security. Holdings without a usable cost basis+ # (nil, or unlocked zero from providers) contribute a gain of 0.+ def gains_series+ values = gains_query_data.map do |datum|+ Series::Value.new(+ date: datum.date,+ date_formatted: I18n.l(datum.date, format: :long),+ value: Money.new(datum.end_gains, currency),+ trend: Trend.new(+ current: Money.new(datum.end_gains, currency),+ previous: Money.new(datum.start_gains, currency),+ favorable_direction: favorable_direction+ )+ )+ end++ Series.new(+ start_date: period.start_date,+ end_date: period.end_date,+ interval: interval,+ values: values,+ favorable_direction: favorable_direction+ )+ rescue => e+ Rails.logger.error "Gains series error: #{e.message} for accounts #{@account_ids}"+ raise+ end+privateattr_reader :account_ids, :currency, :period, :favorable_direction, :account_active_until_dates@@ -87,6 +116,25 @@ class Balance::ChartSeriesBuilderraiseend+ # Executes the gains query and memoizes the per-date rows+ # (date, end_gains, start_gains) used to build the gains series.+ def gains_query_data+ @gains_query_data ||= Balance.find_by_sql([+ gains_query,+ {+ account_ids: account_ids,+ target_currency: currency,+ start_date: period.start_date,+ end_date: period.end_date,+ interval: interval,+ account_active_until_dates_json: account_active_until_dates.to_json+ }+ ])+ rescue => e+ Rails.logger.error "Gains query data error: #{e.message} for accounts #{account_ids}, period #{period.start_date} to #{period.end_date}"+ raise+ end+# Since the query aggregates the *net* of assets - liabilities, this means that if we're looking at# a single liability account, we'll get a negative set of values. This is not what the user expects# to see. When favorable direction is "down" (i.e. liability, decrease is "good"), we need to invert@@ -176,4 +224,100 @@ class Balance::ChartSeriesBuilderORDER BY d.dateSQLend++ # Mirrors the balance query structure: for each date in the series, find the latest+ # holding snapshot per (account, security) on or before that date (LOCF), convert to+ # the target currency, and aggregate unrealized gains (amount - cost_basis * qty).+ # Holdings only exist on asset accounts, so no liability sign handling is needed.+ def gains_query+ <<~SQL+ WITH dates AS (+ SELECT generate_series(DATE :start_date, DATE :end_date, :interval::interval)::date AS date+ UNION DISTINCT+ SELECT :end_date::date -- Ensure end date is included+ ),+ account_windows AS (+ SELECT+ account_window.account_id::uuid AS account_id,+ account_window.active_until_date::date AS active_until_date+ FROM jsonb_each_text(CAST(:account_active_until_dates_json AS jsonb))+ AS account_window(account_id, active_until_date)+ ),+ selected_accounts AS (+ SELECT accounts.*, account_windows.active_until_date+ FROM accounts+ LEFT JOIN account_windows ON account_windows.account_id = accounts.id+ WHERE accounts.id = ANY(array[:account_ids]::uuid[])+ ),+ account_securities AS (+ SELECT DISTINCT h.account_id, h.security_id+ FROM holdings h+ WHERE h.account_id = ANY(array[:account_ids]::uuid[])+ ),+ daily_gains AS (+ SELECT+ d.date,+ COALESCE(SUM(+ CASE+ WHEN last_basis.cost_basis IS NOT NULL+ THEN (last_h.amount - (last_basis.cost_basis * last_h.qty)) * COALESCE(er.rate, 1)+ ELSE 0+ END+ ), 0) AS gains+ FROM dates d+ LEFT JOIN selected_accounts accounts+ ON accounts.active_until_date IS NULL OR d.date <= accounts.active_until_date+ LEFT JOIN account_securities sec ON sec.account_id = accounts.id+ LEFT JOIN LATERAL (+ SELECT h.amount, h.qty, h.currency+ FROM holdings h+ WHERE h.account_id = accounts.id+ AND h.security_id = sec.security_id+ AND h.date <= d.date+ ORDER BY h.date DESC+ LIMIT 1+ ) last_h ON TRUE+ -- Cost basis is looked up separately from the latest row that has a usable one:+ -- gap-filled holding rows (weekends, price-history gaps) are persisted without+ -- cost_basis even though the position and basis are unchanged, so the basis is+ -- carried forward from the last real snapshot instead of zeroing those points.+ LEFT JOIN LATERAL (+ SELECT h2.cost_basis+ FROM holdings h2+ WHERE h2.account_id = accounts.id+ AND h2.security_id = sec.security_id+ AND h2.date <= d.date+ AND h2.cost_basis IS NOT NULL+ AND (h2.cost_basis_locked OR h2.cost_basis > 0)+ ORDER BY h2.date DESC+ LIMIT 1+ ) last_basis ON TRUE+ LEFT JOIN LATERAL (+ SELECT COALESCE(+ (SELECT er.rate+ FROM exchange_rates er+ WHERE er.from_currency = last_h.currency+ AND er.to_currency = :target_currency+ AND er.date <= d.date+ ORDER BY er.date DESC+ LIMIT 1),+ (SELECT er.rate+ FROM exchange_rates er+ WHERE er.from_currency = last_h.currency+ AND er.to_currency = :target_currency+ AND er.date > d.date+ ORDER BY er.date ASC+ LIMIT 1)+ ) AS rate+ ) er ON TRUE+ GROUP BY d.date+ )+ SELECT+ dg.date,+ dg.gains AS end_gains,+ COALESCE(LAG(dg.gains) OVER (ORDER BY dg.date), dg.gains) AS start_gains+ FROM daily_gains dg+ ORDER BY dg.date+ SQL+ endenddiff --git a/config/locales/views/components/en.yml b/config/locales/views/components/en.ymlindex a8a96ad681..dabd8fce59 100644--- a/config/locales/views/components/en.yml+++ b/config/locales/views/components/en.yml@@ -70,8 +70,10 @@ en:holdings_value: Holdings valueremaining_principal_balance: Remaining principal balancetotal_account_value: Total account value+ total_gains: Total gainsviews:cash: Cash+ gains: Gains / ROIholdings: Holdingstotal_value: Total valuevs_available_history: vs. available historydiff --git a/test/components/UI/account/chart_test.rb b/test/components/UI/account/chart_test.rbnew file mode 100644index 0000000000..8245ff20b6--- /dev/null+++ b/test/components/UI/account/chart_test.rb@@ -0,0 +1,57 @@+require "test_helper"++class UI::Account::ChartTest < ViewComponent::TestCase+ setup do+ @account = accounts(:investment)+ @account.holdings.destroy_all+ end++ test "renders positive gains with explicit plus sign" do+ create_holding(cost_basis: 90)++ render_inline(UI::Account::Chart.new(account: @account, view: "gains"))++ assert_text "+$100.00"+ end++ test "does not sign non-gains views" do+ component = UI::Account::Chart.new(account: @account, view: "balance")++ assert_equal @account.balance_money.format, component.view_balance_display+ refute component.view_balance_display.start_with?("+")+ end++ test "negative gains keep plain money formatting" do+ create_holding(cost_basis: 110)++ component = UI::Account::Chart.new(account: @account, view: "gains")++ assert_equal "-$100.00", component.view_balance_display+ end++ test "converted amount is signed like the main indicator for foreign-currency accounts" do+ @account.update!(currency: "EUR")+ create_holding(cost_basis: 90)+ ExchangeRate.create!(date: Date.current, from_currency: "EUR", to_currency: "USD", rate: 1.1)++ component = UI::Account::Chart.new(account: @account, view: "gains")++ assert_equal "+β¬100.00", component.view_balance_display+ assert_equal "+$110.00", component.converted_balance_display+ end++ private+ # 10 shares at $100 market price; gain = 1000 - cost_basis * 10+ def create_holding(cost_basis:)+ Holding.create!(+ account: @account,+ security: securities(:aapl),+ date: Date.current,+ qty: 10,+ price: 100,+ amount: 1000,+ currency: @account.currency,+ cost_basis: cost_basis+ )+ end+enddiff --git a/test/controllers/accounts_controller_test.rb b/test/controllers/accounts_controller_test.rbindex a3858f305e..5f2fb06eb5 100644--- a/test/controllers/accounts_controller_test.rb+++ b/test/controllers/accounts_controller_test.rb@@ -139,6 +139,14 @@ class AccountsControllerTest < ActionDispatch::IntegrationTestassert_select "turbo-frame##{dom_id(trade_entry)} p.privacy-sensitive", text: expected_amount, count: 1end+ test "renders investment account with gains chart view" do+ get account_url(accounts(:investment), chart_view: "gains")++ assert_response :success+ assert_select "option[value=gains][selected]"+ assert_select "p", text: I18n.t("UI.account.chart.title.total_gains")+ end+test "activity pagination keeps activity tab when loaded from holdings tab" doinvestment = accounts(:investment)diff --git a/test/models/account/chartable_test.rb b/test/models/account/chartable_test.rbindex 103b244b70..cb7b524d0b 100644--- a/test/models/account/chartable_test.rb+++ b/test/models/account/chartable_test.rb@@ -44,6 +44,26 @@ class Account::ChartableTest < ActiveSupport::TestCasememoized_series2_holdings_view = account.balance_series(period: Period.last_90_days, view: :holdings_balance)end+ test "supports gains view and rejects unknown views" do+ account = accounts(:investment)++ test_series = Series.new(+ start_date: Period.last_30_days.start_date,+ end_date: Period.last_30_days.end_date,+ interval: "1 day",+ values: [],+ favorable_direction: account.favorable_direction+ )++ builder = mock+ Balance::ChartSeriesBuilder.expects(:new).returns(builder)+ builder.expects(:gains_series).returns(test_series)++ assert_equal test_series, account.balance_series(view: :gains)++ assert_raises(ArgumentError) { account.balance_series(view: :bogus) }+ end+test "trims placeholder history for linked investment accounts without trades" doaccount = accounts(:investment)account.entries.destroy_alldiff --git a/test/models/balance/chart_series_builder_test.rb b/test/models/balance/chart_series_builder_test.rbindex 47049964f3..5ae56071f5 100644--- a/test/models/balance/chart_series_builder_test.rb+++ b/test/models/balance/chart_series_builder_test.rb@@ -338,4 +338,160 @@ class Balance::ChartSeriesBuilderTest < ActiveSupport::TestCaseassert_equal 1, linked_account.balances.where(currency: "USD").countassert_equal 0, linked_account.balances.where(currency: "EUR").countend++ test "gains series computes unrealized gains from holdings with locf" do+ account = accounts(:investment)+ account.holdings.destroy_all+ security = securities(:aapl)++ # 10 shares with avg cost of $90/share+ create_holding(account: account, security: security, date: 3.days.ago.to_date, qty: 10, price: 100, cost_basis: 90)+ create_holding(account: account, security: security, date: 1.day.ago.to_date, qty: 10, price: 110, cost_basis: 90)+ create_holding(account: account, security: security, date: Date.current, qty: 10, price: 105, cost_basis: 90)++ builder = Balance::ChartSeriesBuilder.new(+ account_ids: [ account.id ],+ currency: "USD",+ period: Period.custom(start_date: 4.days.ago.to_date, end_date: Date.current),+ interval: "1 day"+ )++ expected = [+ 0, # No holdings yet+ 100, # 1000 - 900+ 100, # Last observation carried forward+ 200, # 1100 - 900+ 150 # 1050 - 900+ ]++ assert_equal expected, builder.gains_series.map { |v| v.value.amount }+ end++ test "gains series treats unusable cost basis as zero gain" do+ account = accounts(:investment)+ account.holdings.destroy_all++ # Unlocked zero cost basis (provider "unknown") -> no gain contribution+ create_holding(account: account, security: securities(:aapl), date: Date.current, qty: 10, price: 100, cost_basis: 0)+ # Nil cost basis -> no gain contribution+ create_holding(account: account, security: securities(:msft), date: Date.current, qty: 5, price: 50, cost_basis: nil)++ builder = Balance::ChartSeriesBuilder.new(+ account_ids: [ account.id ],+ currency: "USD",+ period: Period.custom(start_date: Date.current, end_date: Date.current),+ interval: "1 day"+ )++ assert_equal [ 0 ], builder.gains_series.map { |v| v.value.amount }++ # Locked zero cost basis (e.g. airdrop) is trusted -> full amount is gain+ account.holdings.where(security: securities(:aapl)).update_all(cost_basis_locked: true)++ builder = Balance::ChartSeriesBuilder.new(+ account_ids: [ account.id ],+ currency: "USD",+ period: Period.custom(start_date: Date.current, end_date: Date.current),+ interval: "1 day"+ )++ assert_equal [ 1000 ], builder.gains_series.map { |v| v.value.amount }+ end++ test "gains series converts holding gains to target currency with locf rates" do+ family = families(:dylan_family)+ account = family.accounts.create!(+ name: "EUR Investment",+ balance: 1000,+ currency: "EUR",+ accountable: Investment.new+ )+ security = securities(:aapl)++ # Gains in EUR: 100 yesterday (1000 - 900), 200 today (1100 - 900)+ create_holding(account: account, security: security, date: 1.day.ago.to_date, qty: 10, price: 100, cost_basis: 90)+ create_holding(account: account, security: security, date: Date.current, qty: 10, price: 110, cost_basis: 90)++ # Single EUR -> USD rate; LOCF applies it to today as well+ ExchangeRate.create!(date: 1.day.ago.to_date, from_currency: "EUR", to_currency: "USD", rate: 1.1)++ builder = Balance::ChartSeriesBuilder.new(+ account_ids: [ account.id ],+ currency: "USD",+ period: Period.custom(start_date: 1.day.ago.to_date, end_date: Date.current),+ interval: "1 day"+ )++ expected = [+ 110, # 100 EUR * 1.1+ 220 # 200 EUR * 1.1 (rate carried forward)+ ]++ assert_equal expected, builder.gains_series.map { |v| v.value.amount }+ end++ test "gains series carries cost basis forward over gap-filled holdings" do+ account = accounts(:investment)+ account.holdings.destroy_all+ security = securities(:aapl)++ create_holding(account: account, security: security, date: 2.days.ago.to_date, qty: 10, price: 100, cost_basis: 90)+ # Gap-filled rows (weekends, price gaps) are persisted without cost_basis+ create_holding(account: account, security: security, date: 1.day.ago.to_date, qty: 10, price: 100, cost_basis: nil)+ create_holding(account: account, security: security, date: Date.current, qty: 10, price: 110, cost_basis: nil)++ builder = Balance::ChartSeriesBuilder.new(+ account_ids: [ account.id ],+ currency: "USD",+ period: Period.custom(start_date: 2.days.ago.to_date, end_date: Date.current),+ interval: "1 day"+ )++ expected = [+ 100, # 1000 - 900+ 100, # basis carried forward from 2 days ago, not zeroed+ 200 # 1100 - 900+ ]++ assert_equal expected, builder.gains_series.map { |v| v.value.amount }+ end++ test "gains series values carry trend vs previous point" do+ account = accounts(:investment)+ account.holdings.destroy_all+ security = securities(:aapl)++ create_holding(account: account, security: security, date: 1.day.ago.to_date, qty: 10, price: 100, cost_basis: 90)+ create_holding(account: account, security: security, date: Date.current, qty: 10, price: 110, cost_basis: 90)++ builder = Balance::ChartSeriesBuilder.new(+ account_ids: [ account.id ],+ currency: "USD",+ period: Period.custom(start_date: 1.day.ago.to_date, end_date: Date.current),+ interval: "1 day"+ )++ series = builder.gains_series++ # First point has no prior point, so trend is flat+ assert_equal 100, series.values.first.trend.previous.amount+ assert_equal 100, series.values.first.trend.current.amount++ assert_equal 100, series.values.last.trend.previous.amount+ assert_equal 200, series.values.last.trend.current.amount+ end++ private+ def create_holding(account:, security:, date:, qty:, price:, cost_basis:)+ Holding.create!(+ account: account,+ security: security,+ date: date,+ qty: qty,+ price: price,+ amount: qty * price,+ currency: account.currency,+ cost_basis: cost_basis+ )+ endend