1
0
Fork 0
mirror of https://github.com/maybe-finance/maybe.git synced 2025-07-25 08:09:38 +02:00

Handle missing weekend stock prices in sync process (#1242)

* Don't append missing prices if already known

* Add failing test

* Handle weekend stock prices

* Fix tests and gapfill logic
This commit is contained in:
Zach Gollwitzer 2024-10-04 14:19:45 -04:00 committed by GitHub
parent e8d7ee3270
commit 24d3c0243f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 80 additions and 7 deletions

View file

@ -48,7 +48,9 @@ class Account::Holding::Syncer
end
ticker_start_dates.each do |ticker, date|
prices[ticker] = Security::Price.find_prices(ticker: ticker, start_date: date, end_date: Date.current)
fetched_prices = Security::Price.find_prices(ticker: ticker, start_date: date, end_date: Date.current)
gapfilled_prices = Gapfiller.new(fetched_prices, start_date: date, end_date: Date.current, cache: false).run
prices[ticker] = gapfilled_prices
end
prices

44
app/models/gapfiller.rb Normal file
View file

@ -0,0 +1,44 @@
class Gapfiller
attr_reader :series
def initialize(series, start_date:, end_date:, cache:)
@series = series
@date_range = start_date..end_date
@cache = cache
end
def run
gapfilled_records = []
date_range.each do |date|
record = series.find { |r| r.date == date }
if should_gapfill?(date, record)
prev_record = gapfilled_records.find { |r| r.date == date - 1.day }
if prev_record
new_record = create_gapfilled_record(prev_record, date)
gapfilled_records << new_record
end
else
gapfilled_records << record if record
end
end
gapfilled_records
end
private
attr_reader :date_range, :cache
def should_gapfill?(date, record)
date.on_weekend? && record.nil?
end
def create_gapfilled_record(prev_record, date)
new_record = prev_record.class.new(prev_record.attributes.except("id", "created_at", "updated_at"))
new_record.date = date
new_record.save! if cache
new_record
end
end

View file

@ -3,11 +3,11 @@ class Issue::PricesMissing < Issue
after_initialize :initialize_missing_prices
validates :missing_prices, presence: true
validates :missing_prices, presence: true, allow_blank: true
def append_missing_price(ticker, date)
missing_prices[ticker] ||= []
missing_prices[ticker] << date
missing_prices[ticker] << date unless missing_prices[ticker].include?(date.to_s)
end
def stale?

View file

@ -27,7 +27,6 @@ class Security::Price < ApplicationRecord
end
private
def upcase_ticker
self.ticker = ticker.upcase
end