class YFi::QuoteCollection

Attributes

raw_quotes[RW]
tickers[RW]

Public Class Methods

new(tickers) click to toggle source

@param [Array<String>] - An array of tickers, such as ['AAPL'] @return [YFi::Quote, to_a, find, each] - an array of Api::ExteralFunds

# File lib/y_fi/quote_collection.rb, line 23
def initialize(tickers)
  validate_ticker_format(tickers)
  self.tickers = tickers
  self.raw_quotes = self.class.get("", url_query_options)
end

Public Instance Methods

each(&block) click to toggle source
# File lib/y_fi/quote_collection.rb, line 47
def each(&block)
  to_a.each(&block)
end
find(ticker) click to toggle source

@return [YFi::Quote]

# File lib/y_fi/quote_collection.rb, line 43
def find(ticker)
  to_a.find{|ef| ef.ticker == ticker.to_s.upcase}
end
to_a() click to toggle source

@return [Array] - an array of YFi::Quote

# File lib/y_fi/quote_collection.rb, line 30
def to_a
  response_array.each_with_object([]) do |raw_quote, arr|
    next unless valid_quote?(raw_quote)
    arr << Quote.new(
      ticker: raw_quote.fetch("symbol"),
      price: raw_quote["LastTradePriceOnly"].to_f,
      updated_at: parse_updated_at(raw_quote.fetch("LastTradeDate")),
      issuer_name: raw_quote.fetch("Name")
    )
  end
end

Private Instance Methods

parse_updated_at(updated_at) click to toggle source
# File lib/y_fi/quote_collection.rb, line 63
def parse_updated_at(updated_at)
  Date.strptime(updated_at, '%m/%d/%Y')
rescue
  YFi.configuration.logger("Unable to parse date: #{updated_at}")
  Date.new(1976,1,1)
end
response_array() click to toggle source
# File lib/y_fi/quote_collection.rb, line 57
def response_array
  arr = raw_quotes.fetch("query", {}).fetch("results", {}).fetch("quote", {})
  arr = [arr] unless arr.is_a?(Array)
  arr
end
url_query_options() click to toggle source
# File lib/y_fi/quote_collection.rb, line 76
def url_query_options
  { 
    query: {
      format: 'json', 
      q: yql_query_string, 
      env: "store://datatables.org/alltableswithkeys"
    }
  }
end
valid_quote?(raw_quote) click to toggle source
# File lib/y_fi/quote_collection.rb, line 86
def valid_quote?(raw_quote)
  unless raw_quote.is_a?(Hash)
    YFi.configuration.logger.error("Expected a hash but got: #{raw_quote}")
    return false
  end
  unless raw_quote["LastTradePriceOnly"]
    YFi.configuration.logger.error("Unable to fetch a price from #{raw_quote}")
    return false
  end
  true
end
validate_ticker_format(tickers) click to toggle source
# File lib/y_fi/quote_collection.rb, line 70
def validate_ticker_format(tickers)
  unless tickers.is_a?(Array) && tickers.all?{|f| f.is_a?(String)} && tickers.size
    raise(ArgumentError, "Please provide an array of tickers") 
  end
end
yql_query_string() click to toggle source
# File lib/y_fi/quote_collection.rb, line 52
def yql_query_string
  funds = self.tickers.map{|f| "\"#{f}\""}.join(',')
  "select * from yahoo.finance.quotes where symbol in(#{funds})"
end