The personal finance app for everyone (by everyone)
Ruby
Import SnapTrade share movements that carry no cash (#4505)
Yong Cong Sin1b12dcb5eae8
diff --git a/app/models/snaptrade_account/activities_processor.rb b/app/models/snaptrade_account/activities_processor.rbindex cf121be52e..009fbc2977 100644--- a/app/models/snaptrade_account/activities_processor.rb+++ b/app/models/snaptrade_account/activities_processor.rb@@ -1,9 +1,14 @@class SnaptradeAccount::ActivitiesProcessorinclude SnaptradeAccount::DataHelpers+ # Two legs whose units differ by no more than this are taken to cancel:+ # providers can report the same quantity with a float's rounding.+ CANCELLING_QUANTITY_TOLERANCE = BigDecimal("0.000001")+# Declarative configuration for SnapTrade activity types.- # Defines category (:trade, :unit_dependent, or :cash), investment activity label,- # quantity signing convention (:buy, :sell, or :preserve), and amount handling (:unconditional, :if_absent, or nil).+ # Defines category (:trade, :unit_dependent, :share_movement, or :cash), investment activity label+ # (trade_label, when given, labels a row imported as a trade instead), quantity signing convention+ # (:buy, :sell, or :preserve), and amount handling (:unconditional, :if_absent, or nil).ACTIVITY_RULES = {# Buys"BUY" => { category: :trade, label: "Buy", sign: :buy },@@ -47,14 +52,23 @@ class SnaptradeAccount::ActivitiesProcessor"MERGER" => { category: :unit_dependent, label: "Other", sign: :preserve, zero_amount: :if_absent, cash_flow: :invert },"CORP_ACTION" => { category: :unit_dependent, label: "Other", sign: :preserve, zero_amount: :if_absent, cash_flow: :invert },+ # Share-movement types (a journal, a transfer or an unclassified activity can move cash or shares):+ # When units are present and non-zero and the row carries no cash, treated as shares moving+ # in or out, such as a stock plan depositing vested shares: a zero-cash trade with signed units,+ # labelled Transfer because the shares were neither bought nor sold.+ # Otherwise treated as a cash activity, since beside cash what the units mean is unknown+ # (a 401(k) payroll contribution arrives as a TRANSFER with units and its cash amount).+ "JOURNAL" => { category: :share_movement, label: "Other", trade_label: "Transfer", sign: :preserve, zero_amount: :unconditional },+ "OTHER" => { category: :share_movement, label: "Other", trade_label: "Transfer", sign: :preserve, zero_amount: :unconditional },+ "TRANSFER" => { category: :share_movement, label: "Transfer", sign: :preserve, zero_amount: :unconditional, cash_flow: :invert },+ "TRANSFER_IN" => { category: :share_movement, label: "Transfer", sign: :buy, zero_amount: :unconditional, cash_flow: :inflow },+ "TRANSFER_OUT" => { category: :share_movement, label: "Transfer", sign: :sell, zero_amount: :unconditional, cash_flow: :outflow },+# Cash activities"DIVIDEND" => { category: :cash, label: "Dividend", cash_flow: :inflow },"DIV" => { category: :cash, label: "Dividend", cash_flow: :inflow },"CONTRIBUTION" => { category: :cash, label: "Contribution", cash_flow: :inflow },"WITHDRAWAL" => { category: :cash, label: "Withdrawal", cash_flow: :outflow },- "TRANSFER" => { category: :cash, label: "Transfer", cash_flow: :invert },- "TRANSFER_IN" => { category: :cash, label: "Transfer", cash_flow: :inflow },- "TRANSFER_OUT" => { category: :cash, label: "Transfer", cash_flow: :outflow },"INTERNAL_CASH_TRANSFER_IN" => { category: :cash, label: "Transfer", cash_flow: :inflow },"INTERNAL_CASH_TRANSFER_OUT" => { category: :cash, label: "Transfer", cash_flow: :outflow },"INTEREST" => { category: :cash, label: "Interest", cash_flow: :inflow },@@ -64,9 +78,7 @@ class SnaptradeAccount::ActivitiesProcessor"REBATE" => { category: :cash, label: "Other", cash_flow: :inflow },"RETURN_OF_CAPITAL" => { category: :cash, label: "Dividend", cash_flow: :inflow },"DISTRIBUTION" => { category: :cash, label: "Dividend", cash_flow: :inflow },- "SUBSTITUTE_DIVIDEND" => { category: :cash, label: "Dividend", cash_flow: :inflow },- "JOURNAL" => { category: :cash, label: "Other" },- "OTHER" => { category: :cash, label: "Other" }+ "SUBSTITUTE_DIVIDEND" => { category: :cash, label: "Dividend", cash_flow: :inflow }}.freezeSNAPTRADE_TYPE_TO_LABEL = ACTIVITY_RULES.transform_values { |r| r[:label] }.freeze@@ -84,6 +96,11 @@ class SnaptradeAccount::ActivitiesProcessor@trades_count = 0@transactions_count = 0@failed_count = 0+ movement_legs = share_movement_legs(activities_data)+ # A movement whose stored trade is protected from sync is left as the+ # user has it: neither matched nor imported again+ @protected_movement_ids = protected_trade_ids(movement_legs.map { |leg| leg[:id] })+ @cancelled_movement_ids = cancelled_share_movement_ids(movement_legs.reject { |leg| @protected_movement_ids.include?(leg[:id]) })activities_data.each do |activity_data|process_activity(activity_data.with_indifferent_access)@@ -151,7 +168,13 @@ class SnaptradeAccount::ActivitiesProcessorRails.logger.info "SnaptradeAccount::ActivitiesProcessor - Processing activity: type=#{activity_type}, id=#{external_id}"# Determine if this is a trade or cash activity- if trade_activity?(activity_type, data)+ if @protected_movement_ids.include?(external_id)+ Rails.logger.info("SnaptradeAccount::ActivitiesProcessor - Keeping share movement #{external_id}, protected from sync")+ elsif @cancelled_movement_ids.include?(external_id)+ remove_cancelled_movement(external_id)+ elsif emptied_share_movement?(activity_type, data)+ remove_emptied_movement(external_id)+ elsif trade_activity?(activity_type, data)process_trade(data, activity_type, external_id)elseprocess_cash_activity(data, activity_type, external_id)@@ -166,18 +189,137 @@ class SnaptradeAccount::ActivitiesProcessorwhen :tradetruewhen :unit_dependent- units = parse_decimal(data[:units]) || parse_decimal(data["units"]) ||- parse_decimal(data[:quantity]) || parse_decimal(data["quantity"])- units&.nonzero? ? true : false+ nonzero_units?(data)+ when :share_movement+ # Only rows that name no cash at all, which the cash path skips+ nonzero_units?(data) && !carries_cash?(data)elsefalseendend- def process_trade(data, activity_type, external_id)- # Check `option_symbol` first: if present, this is an option contract trade.- # Prioritizing `option_symbol` prevents brokerages like Robinhood (which populate- # plain `symbol` with the underlying equity) from importing options as common stock.+ def units(data)+ parse_decimal(data[:units]) || parse_decimal(data["units"]) ||+ parse_decimal(data[:quantity]) || parse_decimal(data["quantity"])+ end++ def nonzero_units?(data)+ units(data)&.nonzero? ? true : false+ end++ def carries_cash?(data)+ !cash_amount(data).nil?+ end++ # A share-movement row that now reports no units (zero or none) and no+ # cash: whatever an earlier sync imported for it moves nothing any more.+ # Units that are there but unreadable say nothing either way, so such a+ # row leaves what an earlier sync imported alone.+ def emptied_share_movement?(activity_type, data)+ return false unless ACTIVITY_RULES.dig(activity_type, :category) == :share_movement && !carries_cash?(data)++ quantity = units(data)+ quantity ? quantity.zero? : [ data[:units], data[:quantity] ].all?(&:blank?)+ end++ def signed_quantity(quantity, rule)+ case rule[:sign]+ when :preserve+ quantity+ when :sell+ -quantity.abs+ else+ quantity.abs+ end+ end++ # Trades are dated by settlement. A share movement has no settlement cycle+ # of its own, and a brokerage can date a deposit after the sale of the very+ # shares it delivered, which would leave the history short of them in+ # between. Shares coming in take the earlier of the two dates and shares+ # going out the later, so a trade dated between the two falls after a+ # deposit and before a withdrawal, never the other way round.+ def activity_date_for(data, rule, quantity)+ settlement_date = parse_date(data[:settlement_date]) || parse_date(data["settlement_date"])+ trade_date = parse_date(data[:trade_date]) || parse_date(data["trade_date"])++ date = if rule[:category] == :share_movement+ dates = [ settlement_date, trade_date ].compact+ quantity.negative? ? dates.max : dates.min+ else+ settlement_date || trade_date+ end++ date || Date.current+ end++ # Share movements that undo each other: two legs moving the same number of+ # shares of one security in opposite directions on the same day, such as a+ # journal between two parts of the account. Together they move nothing,+ # and imported, the inbound leg would still leave the position's cost basis+ # unknown until it is sold out, so neither is imported. Only pairs are+ # matched: three legs that net to nothing are all imported.+ #+ # A leg whose stored trade is protected from sync stays as the user has it,+ # so it is left out of the matching (see #process) and its counterpart is+ # imported too: together they still move nothing. A protected cash entry+ # holds no shares, and its leg is matched as usual.+ def cancelled_share_movement_ids(legs)+ legs.group_by { |leg| leg[:day] }.each_value.with_object(Set.new) do |day_legs, ids|+ inbound, outbound = day_legs.partition { |leg| leg[:qty].positive? }++ outbound.each do |out_leg|+ in_leg = inbound.find { |leg| (leg[:qty] + out_leg[:qty]).abs <= CANCELLING_QUANTITY_TOLERANCE }+ next unless in_leg++ inbound.delete(in_leg)+ ids << in_leg[:id] << out_leg[:id]+ end+ end+ end++ # The rows imported as share movements, each with the day and quantity it+ # is matched on+ def share_movement_legs(activities_data)+ activities_data.filter_map do |activity_data|+ next unless activity_data.is_a?(Hash)++ data = activity_data.with_indifferent_access+ activity_type = data[:type].to_s.upcase+ rule = ACTIVITY_RULES[activity_type]+ next unless rule && rule[:category] == :share_movement && trade_activity?(activity_type, data)++ # Matched on the ticker the trade would be booked on, as two rows of+ # one security can carry its symbol in different shapes, and on the+ # exchange the row names: one ticker on two exchanges can be two+ # securities+ ticker, symbol_data = trade_ticker_and_symbol_data(data)+ next if ticker.blank? || data[:id].blank?++ qty = signed_quantity(units(data), rule)+ # The legs of a journal carry the same dates. Matched on both, as the+ # leg in is booked on the earlier and the leg out on the later: legs+ # that differ in either would not be booked on the same day.+ day = [+ ticker.to_s.upcase,+ extract_exchange(symbol_data).to_s.upcase.presence,+ parse_date(data[:trade_date]),+ parse_date(data[:settlement_date])+ ]+ { id: data[:id].to_s, day: day, qty: qty }+ rescue => e+ # A row the matching cannot read is left to the import below, which+ # skips and logs it, rather than failing every other row with it+ Rails.logger.warn("SnaptradeAccount::ActivitiesProcessor - Not matching activity #{activity_data.try(:[], "id")} as a share movement: #{e.class}")+ nil+ end+ end++ # The ticker an activity trades, the symbol data to resolve it with and+ # the option contract's data: the contract's ticker when the row names+ # one, else the symbol's, whose shape differs between activities and+ # holdings.+ def trade_ticker_and_symbol_data(data)ticker, option_data = option_ticker_and_data(data)# Extract and normalize symbol data@@ -215,6 +357,45 @@ class SnaptradeAccount::ActivitiesProcessorsymbol_data = underlying_symbol_dataend+ [ ticker, symbol_data, option_data ]+ end++ # The ids of the stored trades among these that a sync must leave in place+ def protected_trade_ids(external_ids)+ # Without a linked account nothing is stored; the import below skips each row+ return Set.new if external_ids.empty? || account.nil?++ account.entries.trades.where(source: "snaptrade", external_id: external_ids)+ .select(&:protected_from_sync?).to_set(&:external_id)+ end++ # A leg imported before the one that cancels it arrived would otherwise+ # stay behind: a trade moving shares on its own, or, stored as cash while+ # the row carried some, cash the row no longer reports.+ def remove_cancelled_movement(external_id)+ entry = account.entries.find_by(external_id: external_id, source: "snaptrade")+ return if entry.nil? || entry.protected_from_sync?++ Rails.logger.info("SnaptradeAccount::ActivitiesProcessor - Removing share movement #{external_id}, cancelled by its counterpart")+ entry.destroy!+ end++ # The trade an earlier sync imported for a share movement whose row now+ # reports no units and no cash+ def remove_emptied_movement(external_id)+ entry = account.entries.trades.find_by(external_id: external_id, source: "snaptrade")+ return if entry.nil? || entry.protected_from_sync?++ Rails.logger.info("SnaptradeAccount::ActivitiesProcessor - Removing share movement #{external_id}, now reported with no units and no cash")+ entry.destroy!+ end++ def process_trade(data, activity_type, external_id)+ # Check `option_symbol` first: if present, this is an option contract trade.+ # Prioritizing `option_symbol` prevents brokerages like Robinhood (which populate+ # plain `symbol` with the underlying equity) from importing options as common stock.+ ticker, symbol_data, option_data = trade_ticker_and_symbol_data(data)+# Must have a symbol for tradesif ticker.blank?capture_skipped_trade("missing_symbol", "no symbol", external_id: external_id, activity_type: activity_type)@@ -230,8 +411,7 @@ class SnaptradeAccount::ActivitiesProcessorend# Parse trade values- quantity = parse_decimal(data[:units]) || parse_decimal(data["units"]) ||- parse_decimal(data[:quantity]) || parse_decimal(data["quantity"])+ quantity = units(data)price = parse_decimal(data[:price]) || parse_decimal(data["price"])amount = parse_decimal(data[:amount]) || parse_decimal(data["amount"]) ||parse_decimal(data[:trade_value]) || parse_decimal(data["trade_value"])@@ -246,14 +426,7 @@ class SnaptradeAccount::ActivitiesProcessorrule = ACTIVITY_RULES[activity_type] || {}# Determine sign based on activity type (sell-side should be negative)- quantity = case rule[:sign]- when :preserve- quantity- when :sell- -quantity.abs- else- quantity.abs- end+ quantity = signed_quantity(quantity, rule)# SnapTrade reports option `units` in contracts while quoting `price` per# underlying share. Normalize `price` to per-contract so `qty * price`@@ -307,8 +480,7 @@ class SnaptradeAccount::ActivitiesProcessorend# Get the activity date- activity_date = parse_date(data[:settlement_date]) || parse_date(data["settlement_date"]) ||- parse_date(data[:trade_date]) || parse_date(data["trade_date"]) || Date.current+ activity_date = activity_date_for(data, rule, quantity)# Extract currency - handle both nested object and stringcurrency_data = data[:currency] || data["currency"] || symbol_data[:currency] || symbol_data["currency"]@@ -337,14 +509,23 @@ class SnaptradeAccount::ActivitiesProcessordate: activity_date,name: description,source: "snaptrade",- activity_label: label_from_type(activity_type)+ activity_label: rule[:trade_label] || label_from_type(activity_type))@trades_count += 1 if result++ # Recorded once, on first import: for these types the units are the only+ # sign that the row moves shares, so support can see which rows were read that way+ if rule[:category] == :share_movement && result&.previously_new_record?+ capture_debug_log(+ level: "info",+ message: "Imported #{activity_type} activity #{external_id} as a share movement of #{quantity.to_s('F')} #{ticker}",+ metadata: { activity_id: external_id, activity_type: activity_type, ticker: ticker, quantity: quantity.to_s("F"), reason: "share_movement" }+ )+ endenddef process_cash_activity(data, activity_type, external_id)- amount = parse_decimal(data[:amount]) || parse_decimal(data["amount"]) ||- parse_decimal(data[:net_amount]) || parse_decimal(data["net_amount"])+ amount = cash_amount(data)return if amount.nil? || amount.zero?# Get the activity date@@ -388,6 +569,14 @@ class SnaptradeAccount::ActivitiesProcessor@transactions_count += 1 if resultend+ # The cash a row names: its amount, or its net amount when the amount is+ # missing or zero. Nil when it names none.+ def cash_amount(data)+ [ data[:amount], data["amount"], data[:net_amount], data["net_amount"] ]+ .map { |value| parse_decimal(value) }+ .find { |amount| amount&.nonzero? }+ end+def reclassify_entry_if_needed(external_id, expected_type)return true if external_id.blank?diff --git a/test/models/snaptrade_account/activities_processor_test.rb b/test/models/snaptrade_account/activities_processor_test.rbindex c441f3bac5..aba30705bb 100644--- a/test/models/snaptrade_account/activities_processor_test.rb+++ b/test/models/snaptrade_account/activities_processor_test.rb@@ -924,6 +924,347 @@ class SnaptradeAccount::ActivitiesProcessorTest < ActiveSupport::TestCaseassert_equal "Other", remove_entry.entryable.investment_activity_labelend+ test "imports OTHER and JOURNAL share movements that carry no cash as zero-cash Transfer trades preserving signed units" do+ process_activities(+ # Shaped like a stock-plan vest: the shares arrive with price and amount both 0.0+ build_trade_activity(id: "other_shares_in", type: "OTHER", symbol: "RSUCO", units: 10.0, price: 0.0, amount: 0.0),+ build_trade_activity(id: "journal_shares_out", type: "JOURNAL", symbol: "RSUCO", units: -4.0, price: 25.0)+ )++ shares_in = snaptrade_entry("other_shares_in")+ shares_out = snaptrade_entry("journal_shares_out")++ assert_not_nil shares_in, "units with no cash are shares moving in"+ assert_not_nil shares_out, "negative units with no cash are shares moving out"+ assert shares_in.entryable.is_a?(Trade)+ assert shares_out.entryable.is_a?(Trade)+ assert_equal BigDecimal("10"), shares_in.entryable.qty+ assert_equal BigDecimal("-4"), shares_out.entryable.qty+ assert_equal BigDecimal("0"), shares_in.amount+ assert_equal BigDecimal("0"), shares_out.amount+ assert_equal BigDecimal("0"), shares_in.entryable.price+ assert_equal BigDecimal("25"), shares_out.entryable.price, "a reported price is kept"+ assert_equal "Transfer", shares_in.entryable.investment_activity_label, "shares that arrive at no known cost leave the cost basis unknown"+ assert_equal "Transfer", shares_out.entryable.investment_activity_label, "shares that leave without cash are not a sale"+ end++ test "resyncing an OTHER share movement updates its trade rather than adding another" do+ activity = build_trade_activity(id: "other_resync", type: "OTHER", symbol: "RSUCO", units: 10.0, price: 0.0, amount: 0.0)+ process_activities(activity)+ first_import = snaptrade_entry("other_resync")+ assert_not_nil first_import++ assert_no_difference -> { @account.entries.count } do+ process_activities(activity)+ end++ entry = snaptrade_entry("other_resync")+ assert_equal first_import.id, entry.id+ assert_equal first_import.entryable_id, entry.entryable_id+ assert_equal BigDecimal("10"), entry.entryable.qty+ assert_equal BigDecimal("0"), entry.amount+ end++ test "keeps OTHER and JOURNAL rows that carry cash on the cash path, with or without units" do+ process_activities(+ build_trade_activity(id: "other_units_and_cash", type: "OTHER", symbol: "RSUCO", units: 5.0, price: 50.0, amount: -250.0),+ build_cash_activity(id: "journal_cash", type: "JOURNAL", amount: 100.0, settlement_date: Date.current.to_s)+ )++ with_units = snaptrade_entry("other_units_and_cash")+ cash_only = snaptrade_entry("journal_cash")++ assert with_units.entryable.is_a?(Transaction), "beside cash, what the units mean is unknown, so only the cash is booked"+ assert cash_only.entryable.is_a?(Transaction)+ assert_equal BigDecimal("-250"), with_units.amount+ assert_equal BigDecimal("100"), cash_only.amount+ assert_equal "Other", with_units.entryable.investment_activity_label+ assert_equal "Other", cash_only.entryable.investment_activity_label+ end++ test "skips OTHER and JOURNAL rows that carry neither units nor cash" do+ assert_no_difference -> { @account.entries.count } do+ process_activities(+ build_cash_activity(id: "other_no_units", type: "OTHER", amount: 0.0, settlement_date: Date.current.to_s),+ build_trade_activity(id: "journal_zero_units", type: "JOURNAL", symbol: "RSUCO", units: 0, price: 0.0)+ )+ end++ assert_nil snaptrade_debug_log("journal_zero_units"), "a row without units never reaches the trade path"+ end++ test "replaces a Transaction stored under the same id when the row arrives as a share movement" do+ stale_entry = @account.entries.create!(+ external_id: "other_reclass",+ source: "snaptrade",+ amount: 250.0,+ currency: "USD",+ date: Date.current,+ name: "OTHER RSUCO",+ entryable: Transaction.new(investment_activity_label: "Other")+ )++ process_activities(+ build_trade_activity(id: "other_reclass", type: "OTHER", symbol: "RSUCO", units: 5.0, price: 0.0, amount: 0.0)+ )++ entry = snaptrade_entry("other_reclass")+ assert_not_equal stale_entry.id, entry.id, "the stale transaction is replaced"+ assert entry.entryable.is_a?(Trade)+ assert_equal BigDecimal("5"), entry.entryable.qty+ assert_equal BigDecimal("0"), entry.amount+ assert_nil snaptrade_debug_log("other_reclass", category: "provider_sync_error", level: "error")+ end++ test "skips an OTHER share movement without a symbol and creates debug log" do+ assert_no_difference -> { @account.entries.count } do+ process_activities(+ build_trade_activity(id: "other_no_symbol", type: "OTHER", symbol: nil, units: 3.0, price: 0.0, amount: 0.0)+ )+ end++ assert_equal "missing_symbol", snaptrade_debug_log("other_no_symbol")&.metadata&.dig("reason")+ end++ test "imports TRANSFER rows that move shares without cash as Transfer trades signed by direction" do+ process_activities(+ build_trade_activity(id: "transfer_shares_in", type: "TRANSFER", symbol: "RSUCO", units: 10.0, price: 0.0),+ build_trade_activity(id: "transfer_shares_out", type: "TRANSFER", symbol: "RSUCO", units: -4.0, price: 0.0, amount: 0.0),+ build_trade_activity(id: "transfer_in_shares", type: "TRANSFER_IN", symbol: "RSUCO", units: 5.0, price: 0.0),+ build_trade_activity(id: "transfer_out_shares", type: "TRANSFER_OUT", symbol: "RSUCO", units: 3.0, price: 0.0)+ )++ expected = { "transfer_shares_in" => 10, "transfer_shares_out" => -4, "transfer_in_shares" => 5, "transfer_out_shares" => -3 }+ expected.each do |id, qty|+ entry = snaptrade_entry(id)+ assert entry&.entryable.is_a?(Trade), "#{id}: a transfer of shares with no cash moves shares"+ assert_equal BigDecimal(qty.to_s), entry.entryable.qty, id+ assert_equal BigDecimal("0"), entry.amount, id+ assert_equal "Transfer", entry.entryable.investment_activity_label, id+ end+ end++ test "does not import share movements that cancel each other out on the same day" do+ process_activities(+ build_trade_activity(id: "journal_out", type: "JOURNAL", symbol: "RSUCO", units: -100.0, price: 110.0, amount: 0.0),+ build_trade_activity(id: "journal_in", type: "JOURNAL", symbol: "RSUCO", units: 100.0, price: 110.0, amount: 0.0),+ build_trade_activity(id: "journal_in_later", type: "JOURNAL", symbol: "RSUCO", units: 100.0, price: 110.0, amount: 0.0,+ settlement_date: Date.yesterday.to_s),+ build_trade_activity(id: "journal_out_settles_later", type: "JOURNAL", symbol: "RSUCO", units: -7.0, price: 0.0, amount: 0.0,+ settlement_date: Date.yesterday.to_s).merge("trade_date" => 2.days.ago.to_date.to_s),+ build_trade_activity(id: "journal_in_settles_later", type: "JOURNAL", symbol: "RSUCO", units: 7.0, price: 0.0, amount: 0.0,+ settlement_date: Date.yesterday.to_s).merge("trade_date" => 2.days.ago.to_date.to_s)+ )++ assert_nil snaptrade_entry("journal_out"), "moved out and back in the same day, the shares never left"+ assert_nil snaptrade_entry("journal_in")+ assert_equal BigDecimal("100"), snaptrade_entry("journal_in_later")&.entryable&.qty, "a movement on another day is not a counterpart"+ assert_nil snaptrade_entry("journal_out_settles_later"), "legs with the same dates are a pair, though a leg out is booked on the later"+ assert_nil snaptrade_entry("journal_in_settles_later")+ end++ test "a row the share-movement matching cannot read does not stop the other rows" do+ process_activities(+ build_trade_activity(id: "odd_type", type: "JOURNAL", symbol: "RSUCO", units: 5.0, price: 0.0, amount: 0.0).merge("type" => 123),+ build_trade_activity(id: "journal_alone", type: "JOURNAL", symbol: "RSUCO", units: 100.0, price: 0.0, amount: 0.0)+ )++ assert_equal BigDecimal("100"), snaptrade_entry("journal_alone")&.entryable&.qty+ end++ test "share movements that cancel but for a float's rounding are not imported" do+ process_activities(+ build_trade_activity(id: "rounded_out", type: "JOURNAL", symbol: "RSUCO", units: -99.99999999999999, price: 0.0, amount: 0.0),+ build_trade_activity(id: "rounded_in", type: "JOURNAL", symbol: "RSUCO", units: 100.0, price: 0.0, amount: 0.0)+ )++ assert_nil snaptrade_entry("rounded_out")+ assert_nil snaptrade_entry("rounded_in")+ end++ test "share movements of one ticker on different exchanges do not cancel" do+ on_exchange = ->(activity, mic) { activity.tap { |a| a["symbol"] = a["symbol"].merge("exchange" => { "code" => mic, "mic_code" => mic }) } }++ process_activities(+ on_exchange.(build_trade_activity(id: "nyse_out", type: "JOURNAL", symbol: "DUAL", units: -30.0, price: 0.0, amount: 0.0), "XNYS"),+ on_exchange.(build_trade_activity(id: "tsx_in", type: "JOURNAL", symbol: "DUAL", units: 30.0, price: 0.0, amount: 0.0), "XTSE"),+ on_exchange.(build_trade_activity(id: "nyse_back_out", type: "JOURNAL", symbol: "DUAL", units: -5.0, price: 0.0, amount: 0.0), "XNYS"),+ on_exchange.(build_trade_activity(id: "nyse_back_in", type: "JOURNAL", symbol: "DUAL", units: 5.0, price: 0.0, amount: 0.0), "xnys")+ )++ assert_equal BigDecimal("-30"), snaptrade_entry("nyse_out")&.entryable&.qty, "one ticker on two exchanges can be two securities"+ assert_equal BigDecimal("30"), snaptrade_entry("tsx_in")&.entryable&.qty+ assert_nil snaptrade_entry("nyse_back_out"), "on the same exchange they still cancel"+ assert_nil snaptrade_entry("nyse_back_in")+ end++ test "share movements on the same trade date that settle on different days do not cancel" do+ process_activities(+ build_trade_activity(id: "settles_early_in", type: "JOURNAL", symbol: "RSUCO", units: 12.0, price: 0.0, amount: 0.0,+ settlement_date: 2.days.ago.to_date.to_s).merge("trade_date" => 2.days.ago.to_date.to_s),+ build_trade_activity(id: "settles_late_out", type: "JOURNAL", symbol: "RSUCO", units: -12.0, price: 0.0, amount: 0.0,+ settlement_date: Date.yesterday.to_s).merge("trade_date" => 2.days.ago.to_date.to_s)+ )++ assert_equal 2.days.ago.to_date, snaptrade_entry("settles_early_in")&.date, "booked on different days, the legs are not a pair"+ assert_equal Date.yesterday, snaptrade_entry("settles_late_out")&.date+ end++ test "share movements of one ticker cancel though their symbol data differs" do+ out_leg = build_trade_activity(id: "shape_out", type: "JOURNAL", symbol: "RSUCO", units: -40.0, price: 0.0, amount: 0.0)+ in_leg = build_trade_activity(id: "shape_in", type: "JOURNAL", symbol: "RSUCO", units: 40.0, price: 0.0, amount: 0.0)+ in_leg["symbol"] = in_leg["symbol"].merge("description" => "RSU Co (vested)", "id" => "sym-2")++ process_activities(out_leg, in_leg)++ assert_nil snaptrade_entry("shape_out")+ assert_nil snaptrade_entry("shape_in")+ end++ test "removes a share movement once the leg that cancels it arrives" do+ out_leg = build_trade_activity(id: "journal_late_pair_out", type: "JOURNAL", symbol: "RSUCO", units: -100.0, price: 0.0)+ process_activities(out_leg)+ assert_not_nil snaptrade_entry("journal_late_pair_out")++ process_activities(out_leg, build_trade_activity(id: "journal_late_pair_in", type: "JOURNAL", symbol: "RSUCO", units: 100.0, price: 0.0))++ assert_nil snaptrade_entry("journal_late_pair_out")+ assert_nil snaptrade_entry("journal_late_pair_in")+ end++ test "imports the counterpart of a share movement protected from sync rather than cancelling the pair" do+ out_leg = build_trade_activity(id: "journal_kept_out", type: "JOURNAL", symbol: "RSUCO", units: -100.0, price: 0.0)+ process_activities(out_leg)+ snaptrade_entry("journal_kept_out").mark_user_modified!++ process_activities(out_leg, build_trade_activity(id: "journal_kept_in", type: "JOURNAL", symbol: "RSUCO", units: 100.0, price: 0.0))++ assert_equal BigDecimal("-100"), snaptrade_entry("journal_kept_out")&.entryable&.qty, "a protected entry is not removed"+ assert_equal BigDecimal("100"), snaptrade_entry("journal_kept_in")&.entryable&.qty, "so its counterpart is imported too, and together they move nothing"+ end++ test "leaves a share movement protected from sync as the user has it" do+ leg = build_trade_activity(id: "journal_edited", type: "JOURNAL", symbol: "RSUCO", units: -100.0, price: 0.0)+ process_activities(leg)+ entry = snaptrade_entry("journal_edited")+ entry.entryable.update!(qty: -90)+ entry.update!(name: "Corrected by hand")+ entry.mark_user_modified!++ process_activities(leg)++ entry.reload+ assert_equal BigDecimal("-90"), entry.entryable.qty, "a sync does not import a protected movement again"+ assert_equal "Corrected by hand", entry.name+ end++ test "removes a share movement once its row reports no units and no cash" do+ process_activities(+ build_trade_activity(id: "journal_emptied", type: "JOURNAL", symbol: "RSUCO", units: 10.0, price: 0.0, amount: 0.0),+ build_trade_activity(id: "journal_emptied_kept", type: "JOURNAL", symbol: "RSUCO", units: 4.0, price: 0.0, amount: 0.0)+ )+ snaptrade_entry("journal_emptied_kept").mark_user_modified!++ process_activities(+ build_trade_activity(id: "journal_emptied", type: "JOURNAL", symbol: "RSUCO", units: 0.0, price: 0.0, amount: 0.0),+ build_trade_activity(id: "journal_emptied_kept", type: "JOURNAL", symbol: "RSUCO", units: 0.0, price: 0.0, amount: 0.0)+ )++ assert_nil snaptrade_entry("journal_emptied"), "the row moves nothing any more"+ assert_not_nil snaptrade_entry("journal_emptied_kept"), "a movement protected from sync stays"+ end++ test "removes a share movement once its row reports no units at all and no cash" do+ leg = build_trade_activity(id: "other_units_dropped", type: "OTHER", symbol: "RSUCO", units: 10.0, price: 0.0, amount: 0.0)+ process_activities(leg)+ assert_not_nil snaptrade_entry("other_units_dropped")++ process_activities(leg.merge("units" => nil))++ assert_nil snaptrade_entry("other_units_dropped")+ end++ test "keeps a share movement whose row reports units it cannot read" do+ leg = build_trade_activity(id: "other_units_garbled", type: "OTHER", symbol: "RSUCO", units: 10.0, price: 0.0, amount: 0.0)+ process_activities(leg)++ process_activities(leg.merge("units" => "pending"))++ assert_equal BigDecimal("10"), snaptrade_entry("other_units_garbled")&.entryable&.qty, "unreadable units are not a row emptied of them"+ end++ test "cancels a share movement against a leg that is not protected from sync" do+ kept_in = build_trade_activity(id: "transfer_in_kept", type: "TRANSFER_IN", symbol: "RSUCO", units: 100.0, price: 0.0)+ cancelled_in = build_trade_activity(id: "transfer_in_cancelled", type: "TRANSFER_IN", symbol: "RSUCO", units: 100.0, price: 0.0)+ process_activities(kept_in, cancelled_in)+ snaptrade_entry("transfer_in_kept").update!(excluded: true)++ process_activities(kept_in, cancelled_in, build_trade_activity(id: "transfer_out_cancelling", type: "TRANSFER_OUT", symbol: "RSUCO", units: 100.0, price: 0.0))++ assert_not_nil snaptrade_entry("transfer_in_kept")+ assert_nil snaptrade_entry("transfer_in_cancelled"), "the leg out pairs with the inbound leg that can go"+ assert_nil snaptrade_entry("transfer_out_cancelling")+ end++ test "removes a cash entry stored for a share movement that its counterpart cancels" do+ process_activities(+ build_trade_activity(id: "journal_was_cash", type: "JOURNAL", symbol: "RSUCO", units: -100.0, price: 110.0, amount: -11000.0)+ )+ assert snaptrade_entry("journal_was_cash").entryable.is_a?(Transaction)++ process_activities(+ build_trade_activity(id: "journal_was_cash", type: "JOURNAL", symbol: "RSUCO", units: -100.0, price: 110.0, amount: 0.0),+ build_trade_activity(id: "journal_was_cash_in", type: "JOURNAL", symbol: "RSUCO", units: 100.0, price: 110.0, amount: 0.0)+ )++ assert_nil snaptrade_entry("journal_was_cash"), "the cash the row no longer reports goes too"+ assert_nil snaptrade_entry("journal_was_cash_in")+ end++ test "books the cash of an OTHER row whose net amount carries it" do+ process_activities(+ build_trade_activity(id: "other_net_cash", type: "OTHER", symbol: "RSUCO", units: 10.0, price: 5.0, amount: 0.0).merge("net_amount" => 50.0)+ )++ entry = snaptrade_entry("other_net_cash")+ assert entry&.entryable.is_a?(Transaction), "a row that names cash anywhere is not a share movement"+ assert_equal BigDecimal("50"), entry.amount+ end++ test "records a debug entry the first time a row is imported as a share movement" do+ activity = build_trade_activity(id: "other_logged", type: "OTHER", symbol: "RSUCO", units: 10.0, price: 0.0, amount: 0.0)++ process_activities(activity)+ process_activities(activity)++ logs = DebugLogEntry.where(provider_key: "snaptrade", level: "info").select { |log| log.metadata["activity_id"] == "other_logged" }+ assert_equal 1, logs.size, "logged once, not on every sync"+ assert_equal "share_movement", logs.first.metadata["reason"]+ assert_equal "10.0", logs.first.metadata["quantity"]+ assert_equal "RSUCO", logs.first.metadata["ticker"]+ end++ test "dates a share movement in by the earlier of its trade and settlement dates, and one out by the later" do+ process_activities(+ build_trade_activity(id: "other_settles_late", type: "OTHER", symbol: "RSUCO", units: 10.0, price: 0.0, amount: 0.0,+ settlement_date: 1.day.ago.to_date.to_s).merge("trade_date" => 3.days.ago.to_date.to_s),+ build_trade_activity(id: "other_settles_early", type: "OTHER", symbol: "RSUCO", units: 10.0, price: 0.0, amount: 0.0,+ settlement_date: 5.days.ago.to_date.to_s).merge("trade_date" => 2.days.ago.to_date.to_s),+ build_trade_activity(id: "transfer_out_settles_late", type: "TRANSFER_OUT", symbol: "RSUCO", units: 4.0, price: 0.0,+ settlement_date: 2.days.ago.to_date.to_s).merge("trade_date" => 4.days.ago.to_date.to_s),+ build_trade_activity(id: "other_out_settles_early", type: "OTHER", symbol: "RSUCO", units: -3.0, price: 0.0, amount: 0.0,+ settlement_date: 6.days.ago.to_date.to_s).merge("trade_date" => 4.days.ago.to_date.to_s),+ build_trade_activity(id: "sell_settles_late", type: "SELL", symbol: "RSUCO", units: -10.0, price: 100.0, amount: 1000.0,+ settlement_date: 1.day.ago.to_date.to_s).merge("trade_date" => 3.days.ago.to_date.to_s)+ )++ assert_equal 3.days.ago.to_date, snaptrade_entry("other_settles_late").date, "shares are never sold before they arrive"+ assert_equal 5.days.ago.to_date, snaptrade_entry("other_settles_early").date+ assert_equal 2.days.ago.to_date, snaptrade_entry("transfer_out_settles_late").date, "nor moved out before the buy that delivered them"+ assert_equal 4.days.ago.to_date, snaptrade_entry("other_out_settles_early").date+ assert_equal 1.day.ago.to_date, snaptrade_entry("sell_settles_late").date, "a trade keeps its settlement date"+ end+test "ignores cash activities with zero or nil amount" doassert_no_difference -> { @account.entries.count } doprocess_activities(@@ -1053,6 +1394,17 @@ class SnaptradeAccount::ActivitiesProcessorTest < ActiveSupport::TestCaseassert_equal 0, Entry.where(external_id: "trade_orphan").countend+ test "skips processing a share movement when no linked account" do+ @snaptrade_account.account_provider&.destroy+ @snaptrade_account.reload+ @snaptrade_account.update!(raw_activities_payload: [+ build_trade_activity(id: "movement_orphan", type: "OTHER", symbol: "RSUCO", units: 10.0, price: 0.0, amount: 0.0)+ ])++ assert_nothing_raised { SnaptradeAccount::ActivitiesProcessor.new(@snaptrade_account).process }+ assert_equal 0, Entry.where(external_id: "movement_orphan").count+ end+test "a trade resolves to the security the account already holds when its ticker has duplicate rows" doheld = Security.create!(ticker: "DUPT", name: "Held row")Security.create!(ticker: "DUPT", name: "Priced row", exchange_operating_mic: "XNYS", price_provider: "yahoo_finance")diff --git a/test/models/snaptrade_account_processor_test.rb b/test/models/snaptrade_account_processor_test.rbindex 8520bbb978..39b06f4edf 100644--- a/test/models/snaptrade_account_processor_test.rb+++ b/test/models/snaptrade_account_processor_test.rb@@ -1110,6 +1110,191 @@ class SnaptradeAccountProcessorTest < ActiveSupport::TestCaseassert_equal 0.0, entry.entryable.price.to_fend+ test "reverse-synced history holds shares deposited as OTHER only until they are sold" do+ # Twice, shares vest with no price and no cash, are sold, and the proceeds+ # leave the account; nothing is held now. The second deposit settles before+ # its trade date.+ @snaptrade_account.update!(+ current_balance: 0,+ cash_balance: 0,+ raw_holdings_payload: [],+ raw_activities_payload: [+ snaptrade_activity("vest_1", "OTHER", 40, units: 10, price: 0, amount: 0),+ snaptrade_activity("sale_1", "SELL", 39, units: -10, price: 100, amount: 1000),+ snaptrade_activity("payout_1", "TRANSFER", 37, amount: -1000),+ snaptrade_activity("vest_2", "OTHER", 20, trade_days_ago: 17, units: 5, price: 0, amount: 0),+ snaptrade_activity("sale_2", "SELL", 16, units: -5, price: 90, amount: 449, fee: 1),+ snaptrade_activity("payout_2", "TRANSFER", 14, amount: -449)+ ]+ )++ reverse_sync!++ held = [ 41, 40, 39, 30, 21, 20, 17, 16, 0 ].index_with { |days_ago| held_qty(days_ago) }+ assert_equal({ 41 => 0, 40 => 10, 39 => 0, 30 => 0, 21 => 0, 20 => 5, 17 => 5, 16 => 0, 0 => 0 }, held)++ # With no market prices, a deposit day is valued at the nearest price the+ # account has: the first at the sale that follows it, the second at the+ # last one before it.+ balance = [ 41, 40, 39, 38, 37, 30, 20, 17, 16, 15, 14, 0 ].index_with { |days_ago| balance_on(days_ago) }+ assert_equal({ 41 => 0, 40 => 1000, 39 => 1000, 38 => 1000, 37 => 0, 30 => 0, 20 => 500, 17 => 500, 16 => 449, 15 => 449, 14 => 0, 0 => 0 }, balance,+ "the shares until their sale, then the proceeds until they leave")+ assert_no_negative_history++ sale = @account.entries.find_by!(external_id: "sale_1").entryable+ assert_nil sale.realized_gain_loss, "shares that arrived at no known cost claim no gain when sold"++ synced_once = synced_series+ reverse_sync!+ assert_equal synced_once, synced_series, "a second sync changes nothing"+ end++ test "a position held across a share movement at no price keeps its value without market prices" do+ @snaptrade_account.update!(+ current_balance: 10945,+ cash_balance: 0,+ raw_holdings_payload: [ snaptrade_position("RSUCO", 99.5, 110) ],+ raw_activities_payload: [+ snaptrade_activity("deposit", "CONTRIBUTION", 61, amount: 10000),+ snaptrade_activity("buy", "BUY", 60, units: 100, price: 100, amount: -10000),+ snaptrade_activity("removed", "OTHER", 30, units: -0.5, price: 0, amount: 0)+ ]+ )++ reverse_sync!++ assert_equal BigDecimal("100"), held_qty(31)+ assert_equal BigDecimal("99.5"), held_qty(30)+ assert_equal 9950, holdings_value(30), "valued at the last price the account has, not at the movement's zero"+ assert_equal 9950, holdings_value(1)+ end++ test "shares kept from a vest with a same-day sell-to-cover are valued at the sale price" do+ @snaptrade_account.update!(+ current_balance: 3600,+ cash_balance: 0,+ raw_holdings_payload: [ snaptrade_position("RSUCO", 60, 60) ],+ raw_activities_payload: [+ snaptrade_activity("vest", "OTHER", 30, units: 100, price: 0, amount: 0),+ snaptrade_activity("sell_to_cover", "SELL", 30, units: -40, price: 50, amount: 2000),+ snaptrade_activity("tax_out", "TRANSFER", 29, amount: -2000)+ ]+ )++ reverse_sync!++ assert_equal BigDecimal("0"), held_qty(31)+ assert_equal BigDecimal("60"), held_qty(30)+ assert_equal 3000, holdings_value(30), "the deposit's zero is not the day's price"+ assert_equal 3000, holdings_value(1)+ end++ test "a same-day journal out and back in leaves the cost basis and realized gain alone" do+ @snaptrade_account.update!(+ current_balance: 12500,+ cash_balance: 6000,+ raw_holdings_payload: [ snaptrade_position("RSUCO", 50, 130) ],+ raw_activities_payload: [+ snaptrade_activity("deposit", "CONTRIBUTION", 61, amount: 10000),+ snaptrade_activity("buy", "BUY", 60, units: 100, price: 100, amount: -10000),+ snaptrade_activity("journal_out", "JOURNAL", 30, units: -100, price: 110, amount: 0),+ snaptrade_activity("journal_in", "JOURNAL", 30, units: 100, price: 110, amount: 0),+ snaptrade_activity("sale", "SELL", 10, units: -50, price: 120, amount: 6000)+ ]+ )++ reverse_sync!++ assert_equal BigDecimal("100"), @account.holdings.find_by!(date: 20.days.ago.to_date).cost_basis+ gain = @account.entries.find_by!(external_id: "sale").entryable.realized_gain_loss+ assert_equal Money.new(1000, "USD"), gain&.value+ end++ test "shares deposited as OTHER and moved out as TRANSFER both move the history" do+ security = Security.create!(ticker: "RSUCO", name: "RSU Co")+ (71.days.ago.to_date..Date.current).each { |date| Security::Price.create!(security: security, date: date, price: 100) }++ @snaptrade_account.update!(+ current_balance: 100,+ cash_balance: 100,+ raw_holdings_payload: [],+ raw_activities_payload: [+ snaptrade_activity("deposit", "CONTRIBUTION", 70, amount: 100),+ snaptrade_activity("vest", "OTHER", 40, units: 10, price: 0, amount: 0),+ snaptrade_activity("moved_out", "TRANSFER", 35, units: -10, price: 0)+ ]+ )++ reverse_sync!++ held = [ 50, 41, 40, 36, 35, 0 ].index_with { |days_ago| held_qty(days_ago) }+ assert_equal({ 50 => 0, 41 => 0, 40 => 10, 36 => 10, 35 => 0, 0 => 0 }, held)+ assert_equal 100, balance_on(50)+ assert_equal 1100, balance_on(38)+ assert_no_negative_history+ end++ test "a deposit dated after the sale of its own shares does not leave negative holdings" do+ @snaptrade_account.update!(+ current_balance: 0,+ cash_balance: 0,+ raw_holdings_payload: [],+ raw_activities_payload: [+ snaptrade_activity("vest", "OTHER", 28, trade_days_ago: 30, units: 10, price: 0, amount: 0),+ snaptrade_activity("sale", "SELL", 29, trade_days_ago: 30, units: -10, price: 100, amount: 1000),+ snaptrade_activity("payout", "TRANSFER", 25, amount: -1000)+ ]+ )++ reverse_sync!++ held = [ 31, 30, 29, 28, 0 ].index_with { |days_ago| held_qty(days_ago) }+ assert_equal({ 31 => 0, 30 => 10, 29 => 0, 28 => 0, 0 => 0 }, held)+ assert_equal 1000, balance_on(30)+ assert_no_negative_history+ end++ test "shares moved out are not booked before the buy that delivered them" do+ @snaptrade_account.update!(+ current_balance: 0,+ cash_balance: 0,+ raw_holdings_payload: [],+ raw_activities_payload: [+ snaptrade_activity("deposit", "CONTRIBUTION", 10, amount: 1000),+ snaptrade_activity("buy", "BUY", 4, trade_days_ago: 5, units: 10, price: 100, amount: -1000),+ snaptrade_activity("moved_out", "TRANSFER_OUT", 3, trade_days_ago: 5, units: 10, price: 0)+ ]+ )++ reverse_sync!++ held = [ 5, 4, 3, 0 ].index_with { |days_ago| held_qty(days_ago) }+ assert_equal({ 5 => 0, 4 => 10, 3 => 0, 0 => 0 }, held)+ assert_no_negative_history+ end++ test "shares moved in after the provider priced the position at nothing are not valued at an older price" do+ security = Security.create!(ticker: "RSUCO", name: "RSU Co")+ # An earlier sync's snapshot, once the position had become worthless+ @account.holdings.create!(security: security, date: 20.days.ago.to_date, qty: 100, price: 0, amount: 0, currency: "USD",+ account_provider: @snaptrade_account.account_provider)++ @snaptrade_account.update!(+ current_balance: 0,+ cash_balance: 0,+ raw_holdings_payload: [ snaptrade_position("RSUCO", 150, 0) ],+ raw_activities_payload: [+ snaptrade_activity("buy", "BUY", 40, units: 100, price: 10, amount: -1000),+ snaptrade_activity("moved_in", "TRANSFER_IN", 10, units: 50, price: 0)+ ]+ )++ reverse_sync!++ assert_equal BigDecimal("150"), held_qty(5)+ assert_equal 0, holdings_value(5), "the provider's zero, not the price paid before it"+ end+privateOCC = "AAPL 261218C00240000".freeze@@ -1146,4 +1331,59 @@ class SnaptradeAccountProcessorTest < ActiveSupport::TestCase"units" => units, "price" => price, "cost_basis" => cost_basis, "currency" => currency}end++ # A SnapTrade activity settling `days_ago`, in the made-up security RSUCO when it has units+ def snaptrade_activity(id, type, days_ago, trade_days_ago: days_ago, units: nil, price: nil, amount: nil, fee: nil)+ {+ "id" => id,+ "type" => type,+ "symbol" => (units ? { "symbol" => "RSUCO", "description" => "RSU Co" } : nil),+ "units" => units,+ "price" => price,+ "amount" => amount,+ "fee" => fee,+ "trade_date" => trade_days_ago.days.ago.to_date.to_s,+ "settlement_date" => days_ago.days.ago.to_date.to_s,+ "currency" => { "code" => "USD" }+ }+ end++ def snaptrade_position(ticker, units, price)+ {+ "symbol" => { "symbol" => { "symbol" => ticker, "description" => "#{ticker} Co" } },+ "units" => units.to_s,+ "price" => price.to_s,+ "currency" => "USD"+ }+ end++ def reverse_sync!+ SnaptradeAccount::Processor.new(@snaptrade_account.reload).process+ Balance::Materializer.new(@account.reload, strategy: :reverse).materialize_balances+ end++ def held_qty(days_ago)+ @account.holdings.where(date: days_ago.days.ago.to_date).sum(:qty)+ end++ def holdings_value(days_ago)+ @account.holdings.where(date: days_ago.days.ago.to_date).sum(:amount)+ end++ def balance_on(days_ago)+ @account.balances.find_by!(date: days_ago.days.ago.to_date).balance+ end++ def assert_no_negative_history+ assert @account.balances.where("balance < 0 OR cash_balance < 0").none?, "no day has a negative balance"+ assert @account.holdings.where("qty < 0").none?, "no day holds negative shares"+ end++ def synced_series+ [+ @account.entries.order(:id).pluck(:id, :amount),+ @account.holdings.order(:date).pluck(:date, :qty, :amount),+ @account.balances.order(:date).pluck(:date, :balance, :cash_balance)+ ]+ endend