mirror of
https://github.com/maybe-finance/maybe.git
synced 2025-08-02 20:15:22 +02:00
Remove dependency on stock exchange table (#1368)
This commit is contained in:
parent
b75b41a5e2
commit
45935db5f3
6 changed files with 37 additions and 22 deletions
|
@ -40,7 +40,8 @@ class Provider::Marketstack
|
|||
{
|
||||
name: ticker["name"],
|
||||
symbol: ticker["symbol"],
|
||||
exchange: exchange_mic || ticker.dig("stock_exchange", "mic"),
|
||||
exchange_mic: exchange_mic || ticker.dig("stock_exchange", "mic"),
|
||||
exchange_acronym: ticker.dig("stock_exchange", "acronym"),
|
||||
country_code: ticker.dig("stock_exchange", "country_code")
|
||||
}
|
||||
end
|
||||
|
|
|
@ -3,7 +3,8 @@ class Security < ApplicationRecord
|
|||
|
||||
has_many :trades, dependent: :nullify, class_name: "Account::Trade"
|
||||
|
||||
validates :ticker, presence: true, uniqueness: { case_sensitive: false }
|
||||
validates :ticker, presence: true
|
||||
validates :ticker, uniqueness: { scope: :exchange_mic, case_sensitive: false }
|
||||
|
||||
def current_price
|
||||
@current_price ||= Security::Price.find_price(ticker:, date: Date.current)
|
||||
|
|
|
@ -7,21 +7,24 @@ class Security::Importer
|
|||
def import
|
||||
securities = @provider.fetch_tickers(exchange_mic: @stock_exchange)&.tickers
|
||||
|
||||
stock_exchanges = StockExchange.where(mic: securities.map { |s| s[:exchange] }).index_by(&:mic)
|
||||
existing_securities = Security.where(ticker: securities.map { |s| s[:symbol] }, stock_exchange_id: stock_exchanges.values.map(&:id)).pluck(:ticker, :stock_exchange_id).to_set
|
||||
# Deduplicate securities based on ticker and exchange_mic
|
||||
securities_to_create = securities
|
||||
.map do |security|
|
||||
{
|
||||
name: security[:name],
|
||||
ticker: security[:symbol],
|
||||
country_code: security[:country_code],
|
||||
exchange_mic: security[:exchange_mic],
|
||||
exchange_acronym: security[:exchange_acronym]
|
||||
}
|
||||
end
|
||||
.compact
|
||||
.uniq { |security| [ security[:ticker], security[:exchange_mic] ] }
|
||||
|
||||
securities_to_create = securities.map do |security|
|
||||
stock_exchange_id = stock_exchanges[security[:exchange]]&.id
|
||||
next if existing_securities.include?([ security[:symbol], stock_exchange_id ])
|
||||
|
||||
{
|
||||
name: security[:name],
|
||||
ticker: security[:symbol],
|
||||
stock_exchange_id: stock_exchange_id,
|
||||
country_code: security[:country_code]
|
||||
}
|
||||
end.compact
|
||||
|
||||
Security.insert_all(securities_to_create) unless securities_to_create.empty?
|
||||
Security.upsert_all(
|
||||
securities_to_create,
|
||||
unique_by: [ :ticker, :exchange_mic ],
|
||||
update_only: [ :name, :country_code, :exchange_acronym ]
|
||||
) unless securities_to_create.empty?
|
||||
end
|
||||
end
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue