Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Refetch the carried-forward tail so a late quote replaces it (#5628)

jaysbeekayac19725d8214
diff --git a/app/models/security/manual_price_import.rb b/app/models/security/manual_price_import.rb
index 538849ea96..8ebefc94ac 100644
--- a/app/models/security/manual_price_import.rb
+++ b/app/models/security/manual_price_import.rb
@@ -56,8 +56,9 @@ class Security::ManualPriceImport
# Offline with no reason and no assigned provider means no provider ever
# matched the ticker. Any other offline security is a listed one that is
# down for now ("health_check_failed", "provider_disabled",
- # "resolution_pending"). The importer keeps non-provisional rows, so closes
- # written there would outlast the provider's own once it came back.
+ # "resolution_pending"). The importer keeps real (not carried-forward)
+ # rows, so closes written there would outlast the provider's own once it
+ # came back.
def untracked?
security.offline? && security.offline_reason.blank? && security.price_provider.blank?
end
diff --git a/app/models/security/price.rb b/app/models/security/price.rb
index e1af77b991..200709c9b1 100644
--- a/app/models/security/price.rb
+++ b/app/models/security/price.rb
@@ -9,13 +9,4 @@ class Security::Price < ApplicationRecord
validates :date, :price, :currency, presence: true
validates :date, uniqueness: { scope: %i[security_id currency] }
-
- # Provisional prices from recent days that should be re-fetched
- # - Must be provisional (gap-filled)
- # - Must be from the last few days (configurable, default 7)
- # - Includes weekends: they get fixed via cascade when weekday prices are fetched
- scope :refetchable_provisional, ->(lookback_days: 7) {
- where(provisional: true)
- .where(date: lookback_days.days.ago.to_date..Date.current)
- }
end
diff --git a/app/models/security/price/importer.rb b/app/models/security/price/importer.rb
index 1365ec4002..644d760ad6 100644
--- a/app/models/security/price/importer.rb
+++ b/app/models/security/price/importer.rb
@@ -3,6 +3,11 @@ class Security::Price::Importer
MissingStartPriceError = Class.new(StandardError)
PROVISIONAL_LOOKBACK_DAYS = 7
+ # How far back the carried-forward tail (see refetchable_dates) is asked for
+ # again. It bounds a security the provider has stopped quoting, whose tail
+ # grows every day. PROVISIONAL_LOOKBACK_DAYS would not do: every tail row
+ # that recent is already provisional.
+ CARRIED_FORWARD_REFETCH_DAYS = 30
attr_reader :provider_error
@@ -91,14 +96,13 @@ class Security::Price::Importer
# stored history before its first price is kept.
replace_db_price = clear_cache && earliest_provider_price.present? && date >= earliest_provider_price.date
- kept_db_price = false
- chosen_price, chosen_currency = if replace_db_price || is_provisional
- # For provisional/cache clear: only use provider price, let gap-fill handle missing
+ chosen_price, chosen_currency = if replace_db_price || is_provisional || db_price&.carried_forward
+ # For provisional/carried-forward/cache clear: only use provider price, let gap-fill handle missing.
+ # A carried-forward row is recomputed, so it follows a corrected price before it.
# This ensures stale DB values don't persist when provider has no weekend data
[ provider_price_value, provider_currency ]
elsif has_db_price
- # For non-provisional with valid DB price: preserve existing value (user edits)
- kept_db_price = true
+ # For a real DB price: preserve existing value (user edits)
[ db_price_value, db_price&.currency ]
else
# Fill gaps with provider data
@@ -129,9 +133,7 @@ class Security::Price::Importer
price: chosen_price,
currency: chosen_currency || "USD",
provisional: provisional,
- # A kept row keeps its own mark; any other row is carried forward
- # exactly when it repeats an earlier price.
- carried_forward: kept_db_price ? db_price.carried_forward : used_locf
+ carried_forward: used_locf
}
end
@@ -234,7 +236,7 @@ class Security::Price::Importer
end
def all_prices_exist?
- return false if has_refetchable_provisional_prices?
+ return false if refetchable_dates.any?
# Count only prices in the clamped range so pre-listing / pre-IPO gaps
# don't perpetually trip the "expected_count mismatch" re-sync. Query
@@ -247,10 +249,24 @@ class Security::Price::Importer
persisted_count == expected_count
end
- def has_refetchable_provisional_prices?
- Security::Price.where(security_id: security.id, date: start_date..end_date)
- .refetchable_provisional(lookback_days: PROVISIONAL_LOOKBACK_DAYS)
- .exists?
+ # The stored dates the provider is asked for again: provisional prices from
+ # the last PROVISIONAL_LOOKBACK_DAYS, and the carried-forward tail -- the
+ # carried prices after the security's last real quote, from the last
+ # CARRIED_FORWARD_REFETCH_DAYS. A carried price with a real quote after it
+ # is settled (a weekend, a holiday or a day without trades, whichever days
+ # the market keeps) and is not asked for again.
+ def refetchable_dates
+ @refetchable_dates ||= begin
+ last_quote_on = Security::Price.where(security_id: security.id, carried_forward: false).where("price > 0").maximum(:date)
+ tail_from = [ last_quote_on&.next_day, CARRIED_FORWARD_REFETCH_DAYS.days.ago.to_date ].compact.max
+
+ Security::Price
+ .where(security_id: security.id, date: start_date..end_date)
+ .where("(provisional AND date >= :lookback) OR (carried_forward AND date >= :tail_from)",
+ lookback: PROVISIONAL_LOOKBACK_DAYS.days.ago.to_date, tail_from: tail_from)
+ .pluck(:date)
+ .to_set
+ end
end
def expected_count
@@ -270,7 +286,7 @@ class Security::Price::Importer
end
# Skip over ranges that already exist unless clearing cache
- # Also includes dates with refetchable provisional prices.
+ # Also includes dates with refetchable provisional or carried-forward prices.
#
# Iterates from clamped_start_date (not start_date) so pre-listing /
# pre-IPO gaps don't perpetually trip "first missing date = start_date"
@@ -280,11 +296,6 @@ class Security::Price::Importer
def effective_start_date
return start_date if clear_cache
- refetchable_dates = Security::Price.where(security_id: security.id, date: clamped_start_date..end_date)
- .refetchable_provisional(lookback_days: PROVISIONAL_LOOKBACK_DAYS)
- .pluck(:date)
- .to_set
-
(clamped_start_date..end_date).detect do |d|
!db_prices.key?(d) || refetchable_dates.include?(d)
end || end_date
@@ -301,32 +312,36 @@ class Security::Price::Importer
def start_price_value
# When processing full range (first sync), use original behavior
if fill_start_date == start_date
- provider_price_value = provider_prices.select { |date, _| date <= start_date }
- .max_by { |date, _| date }
- &.last&.price
+ provider_date, provider_price = provider_prices.select { |date, _| date <= start_date }
+ .max_by { |date, _| date }
+ provider_price_value = provider_price&.price
db_price_value = db_prices[start_date]&.price
- return provider_price_value if provider_price_value.present? && provider_price_value.to_f > 0
+ if provider_price_value.present? && provider_price_value.to_f > 0
+ return stored_quote_anchor(start_date, provider_date) || provider_price_value
+ end
return db_price_value if db_price_value.present? && db_price_value.to_f > 0
return nil
end
# For partial range or clamped range, use the most recent data before fill_start_date
cutoff_date = fill_start_date
+ currency = prev_price_currency || db_price_currency
# First try provider prices (most recent before cutoff)
- provider_price_value = provider_prices
+ provider_date, provider_price = provider_prices
.select { |date, _| date < cutoff_date }
.max_by { |date, _| date }
- &.last&.price
+ provider_price_value = provider_price&.price
- return provider_price_value if provider_price_value.present? && provider_price_value.to_f > 0
+ if provider_price_value.present? && provider_price_value.to_f > 0
+ return stored_quote_anchor(cutoff_date, provider_date) || provider_price_value
+ end
# Fall back to the most recent real DB price before cutoff, or the most
# recent carried-forward one when there is no real one. Without any, the
# caller would take the stored history for pre-listing and advance
# first_provider_price_on past it.
- currency = prev_price_currency || db_price_currency
Security::Price
.where(security_id: security.id)
.where("date < ?", cutoff_date)
@@ -337,6 +352,23 @@ class Security::Price::Importer
.pick(:price)
end
+ # A refetched carried row repeats the stored real quote before it, which
+ # the fill keeps over the provider's (user edits), so the tail anchors on
+ # that quote unless the provider has a later close. Every
+ # provisional row is carried forward.
+ def stored_quote_anchor(date, provider_date)
+ return unless db_prices[date]&.carried_forward
+
+ currency = prev_price_currency || db_price_currency
+ stored_quote = Security::Price
+ .where(security_id: security.id, carried_forward: false)
+ .where("date < ? AND price > 0", date)
+ .then { |q| currency.present? ? q.where(currency: currency) : q }
+ .order(date: :desc)
+ .first
+ stored_quote.price if stored_quote && stored_quote.date >= provider_date
+ end
+
def determine_provisional_status(date:, has_provider_price:, used_locf:, existing_provisional:)
# Provider returned real price => NOT provisional
return false if has_provider_price
diff --git a/test/models/security/manual_price_import_test.rb b/test/models/security/manual_price_import_test.rb
index 561a56d069..57e6c97b25 100644
--- a/test/models/security/manual_price_import_test.rb
+++ b/test/models/security/manual_price_import_test.rb
@@ -41,6 +41,20 @@ class Security::ManualPriceImportTest < ActiveSupport::TestCase
assert_not existing.reload.carried_forward
end
+ test "a close over a carried-forward price is not replaced by a later provider quote" do
+ date = 3.days.ago.to_date
+ @security.prices.create!(date: date, price: 20, currency: "AUD", carried_forward: true)
+ import([ row(date, "23") ])
+ provider = mock
+ provider.stubs(:fetch_security_prices).returns(provider_success_response([
+ OpenStruct.new(security: @security, date: date, price: 99, currency: "AUD")
+ ]))
+
+ Security::Price::Importer.new(security: @security, security_provider: provider, start_date: date, end_date: date).import_provider_prices
+
+ assert_equal BigDecimal("23"), @security.prices.find_by!(date: date, currency: "AUD").price
+ end
+
test "one bad row leaves every row in the batch unwritten" do
@security.prices.create!(date: 5.days.ago.to_date, price: 19, currency: "AUD")
diff --git a/test/models/security/price/importer_test.rb b/test/models/security/price/importer_test.rb
index 069c65b4d2..e30c2c95ff 100644
--- a/test/models/security/price/importer_test.rb
+++ b/test/models/security/price/importer_test.rb
@@ -691,29 +691,6 @@ class Security::Price::ImporterTest < ActiveSupport::TestCase
end
end
- test "a carried-forward price kept by a later import stays carried forward" do
- Security::Price.delete_all
-
- start_date = 20.days.ago.to_date
- carried_date = start_date + 1.day
- Security::Price.create!(security: @security, date: carried_date, price: 100, currency: "USD", carried_forward: true)
-
- @provider.expects(:fetch_security_prices).returns(provider_success_response([
- OpenStruct.new(security: @security, date: start_date, price: 100, currency: "USD"),
- OpenStruct.new(security: @security, date: carried_date, price: 105, currency: "USD")
- ]))
-
- Security::Price::Importer.new(
- security: @security,
- security_provider: @provider,
- start_date: start_date,
- end_date: carried_date
- ).import_provider_prices
-
- kept = Security::Price.find_by!(security: @security, date: carried_date)
- assert_equal [ 100, true ], [ kept.price, kept.carried_forward ]
- end
-
# The quote's day was re-closed at 110 after 100 had been carried past it.
test "a fill anchors on the last real quote, not a carried-forward one" do
Security::Price.delete_all
@@ -762,6 +739,172 @@ class Security::Price::ImporterTest < ActiveSupport::TestCase
assert_nil @security.reload.first_provider_price_on, "the stored history is not treated as pre-listing"
end
+ # Crypto trades at the weekend: a carried Saturday at the end of the
+ # stored prices is asked for again whatever the day.
+ test "a carried-forward tail is replaced by a quote the provider publishes later" do
+ Security::Price.delete_all
+
+ saturday = recent_day(:saturday?, at_least: 8)
+ import_with([ [ saturday - 1.day, 100, false ], [ saturday, 100, true ] ],
+ quotes: { saturday => 104 }, fetch_from: saturday)
+
+ price = Security::Price.find_by!(security: @security, date: saturday)
+ assert_equal [ 104, false ], [ price.price, price.carried_forward ]
+ end
+
+ test "a carried weekday before later quotes, a holiday, is not asked for again" do
+ Security::Price.delete_all
+
+ monday = recent_day(:monday?, at_least: 14)
+ rows = (0..4).map { |day| [ monday + day.days, 100, day == 2 ] }
+ import_with(rows, quotes: nil)
+ end
+
+ # A Sunday-to-Thursday market: Friday and Saturday are its weekend.
+ test "a carried Friday before the next quote is settled" do
+ Security::Price.delete_all
+
+ thursday = recent_day(:thursday?, at_least: 14)
+ rows = [ [ thursday, 100, false ], [ thursday + 1.day, 100, true ], [ thursday + 2.days, 100, true ], [ thursday + 3.days, 101, false ] ]
+ import_with(rows, quotes: nil)
+ end
+
+ test "a provisional weekend price older than the lookback is not asked for again" do
+ Security::Price.delete_all
+
+ saturday = recent_day(:saturday?, at_least: 8)
+ rows = (-1..2).map { |day| [ saturday + day.days, 100, day.zero? ] }
+ import_with(rows, quotes: nil, provisional: saturday)
+ end
+
+ test "the tail is asked for only within the refetch window, and the days after a new quote follow it" do
+ Security::Price.delete_all
+
+ window = Security::Price::Importer::CARRIED_FORWARD_REFETCH_DAYS
+ last_quote = (window + 5).days.ago.to_date
+ outside = (window + 2).days.ago.to_date
+ inside = (window - 1).days.ago.to_date
+ rows = (last_quote..Date.current).map { |date| [ date, 100, date != last_quote ] }
+
+ import_with(rows, quotes: { outside => 90, inside => 110 }, fetch_from: window.days.ago.to_date, end_date: Date.current)
+
+ stored = Security::Price.where(security: @security, date: [ outside, inside, Date.current ]).order(:date)
+ assert_equal [ [ 100, true ], [ 110, false ], [ 110, true ] ], stored.map { |p| [ p.price, p.carried_forward ] }
+ end
+
+ # Friday was carried at 100; the provider now has its close at 110.
+ test "carried prices an import passes through follow a corrected price before them" do
+ Security::Price.delete_all
+
+ monday = recent_day(:monday?, at_least: 8)
+ wednesday, thursday, friday = monday - 5.days, monday - 4.days, monday - 3.days
+ stored = [ [ thursday, 100, false ], [ friday, 100, true ], [ friday + 1.day, 100, true ], [ friday + 2.days, 100, true ], [ monday, 100, false ] ]
+ import_with(stored, quotes: { wednesday => 100, thursday => 100, friday => 110 }, start_date: wednesday)
+
+ rows = Security::Price.where(security: @security, date: friday..monday).order(:date)
+ assert_equal [ [ 110, false ], [ 110, true ], [ 110, true ], [ 100, false ] ], rows.map { |p| [ p.price, p.carried_forward ] }
+ end
+
+ test "a stored real quote survives a contradicting provider quote" do
+ Security::Price.delete_all
+
+ tail = recent_day(:tuesday?, at_least: 8)
+ real = tail - 1.day
+ start = tail - 2.days
+ import_with([ [ real, 120, false ], [ tail, 100, true ] ], quotes: { start => 100, real => 999, tail => 104 }, start_date: start)
+
+ assert_equal [ 120, 104 ], Security::Price.where(security: @security, date: [ real, tail ]).order(:date).map(&:price)
+ end
+
+ # The fill starts at the carried day, after the real quote, so it never
+ # passes the day the provider contradicts.
+ test "a refetched tail anchors on the stored real quote, not a contradicting provider close" do
+ Security::Price.delete_all
+
+ real = 9.days.ago.to_date
+ import_with([ [ real, 120, false ], [ real + 1.day, 120, true ] ], quotes: { real => 100 })
+
+ assert_equal [ 120, 120 ], Security::Price.where(security: @security).order(:date).map(&:price)
+ end
+
+ # A stored zero is no quote: the fill would not carry it either.
+ test "a refetched tail does not anchor on a stored zero" do
+ Security::Price.delete_all
+
+ real = 10.days.ago.to_date
+ import_with([ [ real, 120, false ], [ real + 1.day, 0, false ], [ real + 2.days, 120, true ] ], quotes: { real => 100 })
+
+ assert_equal 120, Security::Price.find_by!(security: @security, date: real + 2.days).price
+ end
+
+ # The import starts on the carried day itself, so the fill starts at its
+ # requested start date.
+ test "an import starting on a carried day anchors on the stored real quote before it" do
+ Security::Price.delete_all
+
+ real = 9.days.ago.to_date
+ Security::Price.create!(security: @security, date: real, price: 120, currency: "USD")
+ import_with([ [ real + 1.day, 120, true ] ], quotes: { real => 100 })
+
+ assert_equal 120, Security::Price.find_by!(security: @security, date: real + 1.day).price
+ end
+
+ test "an import starting on a carried day takes the provider's quote for that day" do
+ Security::Price.delete_all
+
+ real = 9.days.ago.to_date
+ Security::Price.create!(security: @security, date: real, price: 120, currency: "USD")
+ import_with([ [ real + 1.day, 120, true ] ], quotes: { real => 100, real + 1.day => 104 })
+
+ assert_equal [ 104, false ], Security::Price.find_by!(security: @security, date: real + 1.day).then { |p| [ p.price, p.carried_forward ] }
+ end
+
+ # A stored zero is no quote, so the carried price before it is still the tail.
+ test "a stored zero does not settle the carried price before it" do
+ Security::Price.delete_all
+
+ real = 20.days.ago.to_date
+ import_with([ [ real, 120, false ], [ real + 1.day, 120, true ], [ real + 2.days, 0, false ] ], quotes: { real + 1.day => 125 })
+
+ assert_equal [ 125, false ], Security::Price.find_by!(security: @security, date: real + 1.day).then { |p| [ p.price, p.carried_forward ] }
+ end
+
+ # A quote in another currency is no anchor for prices in the provider's.
+ test "a refetched tail does not anchor on a stored quote in another currency" do
+ Security::Price.delete_all
+
+ real = 9.days.ago.to_date
+ Security::Price.create!(security: @security, date: real, price: 90, currency: "EUR")
+ import_with([ [ real + 1.day, 120, true ] ], quotes: { real - 1.day => 100 }, start_date: real)
+
+ assert_equal [ 100, "USD" ], Security::Price.find_by!(security: @security, date: real + 1.day).then { |p| [ p.price, p.currency ] }
+ end
+
+ # Beyond the refetch window the carried days stay as stored, so a provider
+ # close among them is newer than the stored real quote and anchors the tail.
+ test "a refetched tail anchors on a provider close newer than the stored real quote" do
+ Security::Price.delete_all
+
+ real = 40.days.ago.to_date
+ rows = [ [ real, 120, false ] ] + (1..11).map { |day| [ real + day.days, 120, true ] }
+ import_with(rows, quotes: { 31.days.ago.to_date => 130 })
+
+ tail = Security::Price.where(security: @security, date: 30.days.ago.to_date..).order(:date)
+ assert_equal [ 130, 130 ], tail.map(&:price)
+ end
+
+ # A first import whose start date holds only a carried price: no real quote
+ # anchors the fill, and the stored history is not pre-listing.
+ test "a first import fills from a carried price at its start date" do
+ Security::Price.delete_all
+
+ start_date = recent_day(:tuesday?, at_least: 10)
+ import_with([ [ start_date, 100, true ] ], quotes: { start_date + 3.days => 130 }, end_date: start_date + 3.days)
+
+ assert_equal [ 100, 100, 100, 130 ], Security::Price.where(security: @security).order(:date).map(&:price)
+ assert_nil @security.reload.first_provider_price_on
+ end
+
test "provisional weekend prices get fixed via cascade from Friday" do
Security::Price.delete_all
@@ -862,6 +1005,37 @@ class Security::Price::ImporterTest < ActiveSupport::TestCase
end
private
+ # The most recent day matching `predicate` at least `at_least` days ago.
+ def recent_day(predicate, at_least:)
+ date = at_least.days.ago.to_date
+ date -= 1.day until date.public_send(predicate)
+ date
+ end
+
+ # Stores [date, price, carried_forward] rows, then imports from the first
+ # (or start_date) to the last (or end_date). quotes: nil expects no
+ # provider call; fetch_from pins the requested start date.
+ def import_with(rows, quotes:, fetch_from: nil, start_date: nil, end_date: nil, provisional: nil)
+ rows.each do |date, price, carried|
+ Security::Price.create!(security: @security, date: date, price: price, currency: "USD", carried_forward: carried, provisional: date == provisional)
+ end
+ start_date ||= rows.first.first
+ end_date ||= rows.last.first
+
+ if quotes.nil?
+ @provider.expects(:fetch_security_prices).never
+ else
+ expectation = @provider.expects(:fetch_security_prices)
+ if fetch_from
+ expectation = expectation.with(symbol: @security.ticker, exchange_operating_mic: @security.exchange_operating_mic,
+ start_date: get_provider_fetch_start_date(fetch_from), end_date: end_date)
+ end
+ expectation.returns(provider_success_response(quotes.map { |date, price| OpenStruct.new(security: @security, date: date, price: price, currency: "USD") }))
+ end
+
+ Security::Price::Importer.new(security: @security, security_provider: @provider, start_date: start_date, end_date: end_date).import_provider_prices
+ end
+
def get_provider_fetch_start_date(start_date)
start_date - Security::Price::Importer::PROVISIONAL_LOOKBACK_DAYS.days
end