2024-07-16 09:26:49 -04:00
|
|
|
class Security::Price < ApplicationRecord
|
2024-08-01 19:43:23 -04:00
|
|
|
include Provided
|
|
|
|
|
2024-10-29 15:37:59 -04:00
|
|
|
belongs_to :security
|
2024-08-01 19:43:23 -04:00
|
|
|
|
2024-10-30 09:51:05 -04:00
|
|
|
validates :price, :currency, presence: true
|
|
|
|
|
2024-08-01 19:43:23 -04:00
|
|
|
class << self
|
2024-10-29 15:37:59 -04:00
|
|
|
def find_price(security:, date:, cache: true)
|
|
|
|
result = find_by(security:, date:)
|
2024-08-01 19:43:23 -04:00
|
|
|
|
2024-10-29 15:37:59 -04:00
|
|
|
result || fetch_price_from_provider(security:, date:, cache:)
|
2024-08-01 19:43:23 -04:00
|
|
|
end
|
|
|
|
|
2024-10-29 15:37:59 -04:00
|
|
|
def find_prices(security:, start_date:, end_date: Date.current, cache: true)
|
|
|
|
prices = where(security_id: security.id, date: start_date..end_date).to_a
|
2024-08-01 19:43:23 -04:00
|
|
|
all_dates = (start_date..end_date).to_a.to_set
|
|
|
|
existing_dates = prices.map(&:date).to_set
|
|
|
|
missing_dates = (all_dates - existing_dates).sort
|
|
|
|
|
|
|
|
if missing_dates.any?
|
2024-10-29 15:37:59 -04:00
|
|
|
prices += fetch_prices_from_provider(
|
|
|
|
security: security,
|
|
|
|
start_date: missing_dates.first,
|
|
|
|
end_date: missing_dates.last,
|
|
|
|
cache: cache
|
|
|
|
)
|
2024-08-01 19:43:23 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
prices
|
|
|
|
end
|
|
|
|
end
|
2024-07-16 09:26:49 -04:00
|
|
|
end
|