The personal finance app for everyone (by everyone)
Ruby
Combine SimpleFIN holding lots into a single position (#3539)
Brian Espinozaa46c774db7a5
diff --git a/app/models/simplefin_account/investments/holdings_processor.rb b/app/models/simplefin_account/investments/holdings_processor.rbindex ed23a8352d..888822b141 100644--- a/app/models/simplefin_account/investments/holdings_processor.rb+++ b/app/models/simplefin_account/investments/holdings_processor.rb@@ -7,6 +7,14 @@ class SimplefinAccount::Investments::HoldingsProcessorreturn if holdings_data.empty?return unless [ "Investment", "Crypto" ].include?(account&.accountable_type)+ # SimpleFIN reports one record per LOT, so a single position can arrive as+ # several records sharing a security -- a 401k that splits employee deferral+ # from employer match is the common case. `holdings` is uniquely indexed on+ # (account_id, security_id, date, currency), so importing lots one at a time+ # makes each overwrite the last and the account silently loses the value of+ # every lot but one. Combine them into the position they represent first.+ positions = {}+holdings_data.each do |simplefin_holding|beginsymbol = simplefin_holding["symbol"].presence@@ -75,26 +83,83 @@ class SimplefinAccount::Investments::HoldingsProcessor# Skip zero positions with no value to avoid invisible rowsnext if qty.to_d.zero? && computed_amount.to_d.zero?- saved = import_adapter.import_holding(+ currency = simplefin_holding["currency"].presence || "USD"+ position = positions[[ security.id, currency, holding_date ]] ||= {security: security,- quantity: qty,- amount: computed_amount,- currency: simplefin_holding["currency"].presence || "USD",+ currency: currency,date: holding_date,- price: price,- cost_basis: cost_basis,- external_id: "simplefin_#{holding_id}",- account_provider_id: simplefin_account.account_provider&.id,- source: "simplefin",- delete_future_holdings: false # SimpleFin tracks each holding uniquely- )-- Rails.logger.debug({ event: "simplefin.holding.saved", account_id: account&.id, holding_id: saved.id, security_id: saved.security_id, qty: saved.qty.to_s, amount: saved.amount.to_s, currency: saved.currency, date: saved.date, external_id: saved.external_id }.to_json)+ qty: 0.to_d,+ amount: 0.to_d,+ # cost_basis is stored PER SHARE, so lots combine into a+ # share-weighted average rather than a sum. That average is only+ # meaningful if EVERY lot reported one -- see basis_complete.+ basis_value: 0.to_d,+ basis_qty: 0.to_d,+ basis_complete: true,+ fallback_price: nil,+ external_ids: []+ }++ position[:qty] += qty.to_d+ position[:amount] += computed_amount.to_d+ position[:external_ids] << "simplefin_#{holding_id}"+ position[:fallback_price] ||= price if price.to_d.positive?++ if qty.to_d.positive?+ if cost_basis.present?+ position[:basis_value] += cost_basis.to_d * qty.to_d+ position[:basis_qty] += qty.to_d+ else+ # Averaging over only the lots that reported a basis would apply+ # that figure to shares whose cost is genuinely unknown, inventing+ # cost and therefore inventing gain/loss. Unknown has to stay+ # unknown for the whole position.+ position[:basis_complete] = false+ end+ endrescue => ectx = (defined?(symbol) && symbol.present?) ? " #{symbol}" : ""Rails.logger.error "Error processing SimpleFin holding#{ctx}: #{e.message}"endend++ positions.each_value do |position|+ qty = position[:qty]+ amount = position[:amount]++ price = if qty.positive? && amount.positive?+ amount / qty+ else+ position[:fallback_price] || 0+ end++ cost_basis = if position[:basis_complete] && position[:basis_qty].positive?+ position[:basis_value] / position[:basis_qty]+ end++ # Sorted so the identifier stays stable across syncs when a provider+ # reorders lots. If the chosen lot later disappears, import_holding falls+ # back to matching on security/date/currency and updates the same row.+ external_id = position[:external_ids].sort.first++ saved = import_adapter.import_holding(+ security: position[:security],+ quantity: qty,+ amount: amount,+ currency: position[:currency],+ date: position[:date],+ price: price,+ cost_basis: cost_basis,+ external_id: external_id,+ account_provider_id: simplefin_account.account_provider&.id,+ source: "simplefin",+ delete_future_holdings: false # SimpleFin tracks each holding uniquely+ )++ Rails.logger.debug({ event: "simplefin.holding.saved", account_id: account&.id, holding_id: saved.id, security_id: saved.security_id, qty: saved.qty.to_s, amount: saved.amount.to_s, currency: saved.currency, date: saved.date, external_id: saved.external_id, lots: position[:external_ids].size }.to_json)+ rescue => e+ Rails.logger.error "Error importing SimpleFin position #{position[:security]&.ticker}: #{e.message}"+ endendprivatediff --git a/test/models/simplefin_account/investments/holdings_processor_test.rb b/test/models/simplefin_account/investments/holdings_processor_test.rbindex 759f0965b1..852d4daa0b 100644--- a/test/models/simplefin_account/investments/holdings_processor_test.rb+++ b/test/models/simplefin_account/investments/holdings_processor_test.rb@@ -177,4 +177,104 @@ class SimplefinAccount::Investments::HoldingsProcessorTest < ActiveSupport::Testassert_nil source_keyassert_nil cost_basisend++ test "lots of the same security combine into one position" do+ # SimpleFIN reports one record per lot. A 401k splitting employee deferral+ # from employer match sends two records for the same fund, and `holdings` is+ # uniquely indexed on (account_id, security_id, date, currency), so importing+ # them separately made the second overwrite the first.+ security = securities(:aapl)+ processor = SimplefinAccount::Investments::HoldingsProcessor.new(nil)++ processor.stubs(:holdings_data).returns([+ { "id" => "lot-b", "symbol" => "AAPL", "shares" => "11.891485", "market_value" => "3070.14", "cost_basis" => "200.00" },+ { "id" => "lot-a", "symbol" => "AAPL", "shares" => "2.378397", "market_value" => "614.05", "cost_basis" => "250.00" }+ ])+ processor.stubs(:account).returns(accounts(:investment))+ processor.stubs(:resolve_security).returns(security)+ processor.stubs(:institution_reports_total_basis?).returns(false)++ # The processor logs simplefin_account.id per lot, so the stub has to+ # answer it as well as account_provider.+ processor.stubs(:simplefin_account).returns(+ stub(id: "sfa-test", name: "Test Investment Account", account_provider: nil)+ )++ # A plain recorder rather than a mocha argument matcher, so the assertions+ # read against the real keyword arguments.+ recorder = Class.new do+ attr_reader :calls++ def initialize = @calls = []++ def import_holding(**kwargs)+ @calls << kwargs+ Struct.new(:id, :security_id, :qty, :amount, :currency, :date, :external_id)+ .new("h", kwargs[:security].id, kwargs[:quantity], kwargs[:amount],+ kwargs[:currency], kwargs[:date], kwargs[:external_id])+ end+ end.new++ processor.stubs(:import_adapter).returns(recorder)++ processor.process++ assert_equal 1, recorder.calls.size, "expected the two lots to collapse into a single position"++ position = recorder.calls.first+ assert_in_delta 14.269882, position[:quantity].to_f, 0.000001+ assert_in_delta 3684.19, position[:amount].to_f, 0.01++ # cost_basis is stored per share, so lots combine as a share-weighted+ # average: (11.891485*200 + 2.378397*250) / 14.269882+ assert_in_delta 208.333, position[:cost_basis].to_f, 0.01++ # price is re-derived from the combined position+ assert_in_delta 258.1781, position[:price].to_f, 0.01+ end++ test "a position with any unknown-basis lot reports no aggregate basis" do+ # Averaging only the lots that reported a basis would apply that figure to+ # shares whose cost is unknown, fabricating cost and gain/loss.+ security = securities(:aapl)+ processor = SimplefinAccount::Investments::HoldingsProcessor.new(nil)++ processor.stubs(:holdings_data).returns([+ { "id" => "lot-known", "symbol" => "AAPL", "shares" => "10", "market_value" => "2000.00", "cost_basis" => "100.00" },+ { "id" => "lot-unknown", "symbol" => "AAPL", "shares" => "10", "market_value" => "2000.00" }+ ])+ processor.stubs(:account).returns(accounts(:investment))+ processor.stubs(:resolve_security).returns(security)+ processor.stubs(:institution_reports_total_basis?).returns(false)+ processor.stubs(:simplefin_account).returns(+ stub(id: "sfa-test", name: "Test Investment Account", account_provider: nil)+ )++ recorder = Class.new do+ attr_reader :calls++ def initialize = @calls = []++ def import_holding(**kwargs)+ @calls << kwargs+ Struct.new(:id, :security_id, :qty, :amount, :currency, :date, :external_id)+ .new("h", kwargs[:security].id, kwargs[:quantity], kwargs[:amount],+ kwargs[:currency], kwargs[:date], kwargs[:external_id])+ end+ end.new++ processor.stubs(:import_adapter).returns(recorder)++ processor.process++ assert_equal 1, recorder.calls.size+ position = recorder.calls.first++ # quantity and value still aggregate+ assert_in_delta 20.0, position[:quantity].to_f, 0.000001+ assert_in_delta 4000.0, position[:amount].to_f, 0.01++ # but the basis is unknown for the position as a whole, NOT $100/share+ assert_nil position[:cost_basis]+ endend