# module YahooFinance

Module for retrieving quote data ('live' and 'historical') from YahooFinance!

This module is made up of 2 parts:

    1. Retrieving 'live' quote data. 'Live' quotes are the current

data available for a given stock. Most often delayed 20mins.

    2. Retrieving 'historical' quote data.  'Historical' quotes are

for past pricings of a given stock.

Module for retrieving quote data ('live' and 'historical') from YahooFinance!

This module is made up of 2 parts:

    1. Retrieving 'live' quote data. 'Live' quotes are the current

data available for a given stock. Most often delayed 20mins.

    2. Retrieving 'historical' quote data.  'Historical' quotes are

for past pricings of a given stock.

Module for retrieving quote data ('live' and 'historical') from YahooFinance!

This module is made up of 2 parts:

    1. Retrieving 'live' quote data. 'Live' quotes are the current

data available for a given stock. Most often delayed 20mins.

    2. Retrieving 'historical' quote data.  'Historical' quotes are

for past pricings of a given stock.

### Constants

DEFAULT_READ_TIMEOUT
EXTENDEDHASH
REALTIMEHASH
STDHASH

  'Live' quote data retrieval.

### Public Class Methods

get( symbols, format, timeout=DEFAULT_READ_TIMEOUT ) click to toggle source

Return a string containing the results retrieved from YahooFinance. If there was an error during the execution of this method, the string "" is returned. In practice, this means that no *Quote objects will be created (empty hashes will be returned from get_*_quotes methods).

    # File lib/assets/yfinadaptor/yfinadaptor.rb, line 173
    def YahooFinance.get( symbols, format, timeout=DEFAULT_READ_TIMEOUT )
      return "" if symbols == nil
      symbols = symbols.join( "," ) if symbols.class == Array
      simba = symbols.dup
      simba.strip!
      return "" if symbols == ""

      # Catch any exceptions that might occur here.  Possible exceptions
      # are the read_timeout and...
      #

      #
      # Don't catch any exceptions!  Just let them be thrown.
      #
      proxy = ENV['http_proxy'] ? URI.parse( ENV['http_proxy'] ) : OpenStruct.new
      Net::HTTP::Proxy( proxy.host, proxy.port,
                        proxy.user, proxy.password ).start( "download.finance.yahoo.com",
                                                            80 ) do |http|
        http.read_timeout = timeout
        response = nil
        response = http.get( "/d/quotes.csv?s=#{symbols}&f=#{format}&e=.csv" )
        return "" if !response
        response.body.chomp
      end
    end

get_HistoricalQuotes( symbol, startDate, endDate ) { |historical_quote| ... } click to toggle source

    # File lib/assets/yfinadaptor/yfinadaptor.rb, line 530
    def YahooFinance.get_HistoricalQuotes( symbol, startDate, endDate )
      ret = []
      YahooFinance.get_historical_quotes( symbol, startDate, endDate ) { |row|
        if block_given?
          yield HistoricalQuote.new( symbol, row )
        else
          ret << HistoricalQuote.new( symbol, row )
        end
      }
      if block_given?
        return nil
      else
        return ret
      end
    end

get_HistoricalQuotes_days( symbol, days, &block ) click to toggle source

    # File lib/assets/yfinadaptor/yfinadaptor.rb, line 546
    def YahooFinance.get_HistoricalQuotes_days( symbol, days, &block )
      endDate = Date.today()
      startDate = Date.today() - days
      YahooFinance.get_HistoricalQuotes( symbol, startDate, endDate, &block )
    end

get_candlestick_data(ticker) click to toggle source

    # File lib/assets/yfinadaptor/yfinadaptor.rb, line 525
    def YahooFinance.get_candlestick_data(ticker)
      data = YahooFinance::get_historical_quotes_days(ticker, 1000)
      return data.map{|new_data| [Time.parse(new_data[0]).to_i*1000, new_data[1].to_f, new_data[2].to_f, new_data[3].to_f, new_data[4].to_f]}.sort_by{|d| d[0]}
    end

get_extended_quotes( symbols ) { |qt| ... } click to toggle source

    # File lib/assets/yfinadaptor/yfinadaptor.rb, line 224
    def YahooFinance.get_extended_quotes( symbols )
      csvquotes = YahooFinance::get( symbols, EXTENDEDHASH.keys.join )
      ret = Hash.new
      CSV.parse( csvquotes ) do |row|
        qt = ExtendedQuote.new( row )
        if block_given?
          yield qt
        end
        ret[qt.symbol] = qt
      end
      ret
    end

get_graph_data(ticker) click to toggle source

    # File lib/assets/yfinadaptor/yfinadaptor.rb, line 520
    def YahooFinance.get_graph_data(ticker)
      data = YahooFinance::get_historical_quotes_days(ticker, 1000)
      return data.map{|new_data| [Time.parse(new_data[0]).to_i*1000, new_data[4].to_f]}.sort_by{|d| d[0]}
    end

get_historical_quotes( symbol, startDate, endDate ) { |row| ... } click to toggle source

    # File lib/assets/yfinadaptor/yfinadaptor.rb, line 470
    def YahooFinance.get_historical_quotes( symbol, startDate, endDate )
      rows = []
      rowct = 0
      gotchunk = false

      #
      # Yahoo is only able to provide 200 data points at a time for Some
      # "international" markets.  We want to download all of the data
      # points between the startDate and endDate, regardless of how many
      # 200 data point chunks it comes in.  In this section we download
      # as many chunks as needed to get all of the data points.
      #
      begin
        gotchunk = false
        r = YahooFinance.retrieve_raw_historical_quotes( symbol,
                                                         startDate, endDate )
        if block_given?
          # If we were given a block, yield to it for every row of data
          # downloaded.
          r.each { |row| yield row }
        else
          rows += r
        end

        # Is this a chunk?
        if r.length == 200
          # Adjust the endDate for when we retrieve the next chunk.
          endDate = HistoricalQuote.parse_date_to_Date( r.last[0] ) - 1
          # Marke this as a chunk so do the download again with the new endDate.
          gotchunk = true
        end

      end while gotchunk

      if block_given?
        # If we have already yielded to every row, just return nil.
        return nil
      else
        # Otherwise return the big array of arrays.
        rows
      end

    end

get_historical_quotes_days( symbol, days, &block ) click to toggle source

    # File lib/assets/yfinadaptor/yfinadaptor.rb, line 514
    def YahooFinance.get_historical_quotes_days( symbol, days, &block )
      endDate = Date.today()
      startDate = Date.today() - days
      YahooFinance.get_historical_quotes( symbol, startDate, endDate, &block )
    end

get_quotes( quote_class, symbols, &block ) click to toggle source

    # File lib/assets/yfinadaptor/yfinadaptor.rb, line 199
    def YahooFinance.get_quotes( quote_class, symbols, &block )
      if quote_class == YahooFinance::StandardQuote
        return get_standard_quotes( symbols, &block )
      elsif quote_class == YahooFinance::ExtendedQuote
        return get_extended_quotes( symbols, &block )
      elsif quote_class == YahooFinance::RealTimeQuote
        return get_realtime_quotes( symbols, &block )
      else
        # Use the standard quote if the given quote_class was not recoginized.
        return get_standard_quotes( symbols, &block )
      end
    end

get_realtime_quotes( symbols ) { |qt| ... } click to toggle source

    # File lib/assets/yfinadaptor/yfinadaptor.rb, line 212
    def YahooFinance.get_realtime_quotes( symbols )
      csvquotes = YahooFinance::get( symbols, REALTIMEHASH.keys.join )
      ret = Hash.new
      CSV.parse( csvquotes ) do |row|
        qt = RealTimeQuote.new( row )
        if block_given?
          yield qt
        end
        ret[qt.symbol] = qt
      end
      ret
    end

get_standard_quotes( symbols ) { |qt| ... } click to toggle source

    # File lib/assets/yfinadaptor/yfinadaptor.rb, line 236
    def YahooFinance.get_standard_quotes( symbols )
      csvquotes = YahooFinance::get( symbols, STDHASH.keys.join )
      ret = Hash.new
      CSV.parse( csvquotes ) do |row|
        qt = StandardQuote.new( row )
        if block_given?
          yield qt
        end
        ret[qt.symbol] = qt
      end
      ret
    end

retrieve_raw_historical_quotes( symbol, startDate, endDate ) click to toggle source

    # File lib/assets/yfinadaptor/yfinadaptor.rb, line 435
    def YahooFinance.retrieve_raw_historical_quotes( symbol, startDate, endDate )

      # Don't try to download anything if the starting date is before
      # the end date.
      return [] if startDate > endDate

      proxy = ENV['http_proxy'] ? URI.parse( ENV['http_proxy'] ) : OpenStruct.new
      Net::HTTP::Proxy( proxy.host,
                        proxy.port,
                        proxy.user,
                        proxy.password ).start( "itable.finance.yahoo.com",
                                                            80 ) { |http|
        #Net::HTTP.start( "itable.finance.yahoo.com", 80 ) { |http|
        query = "/table.csv?s=#{symbol}&g=d" +
          "&a=#{startDate.month-1}&b=#{startDate.mday}&c=#{startDate.year}" +
          "&d=#{endDate.month-1}&e=#{endDate.mday}&f=#{endDate.year.to_s}"
        #puts "#{query}"
        response = http.get( query )
        #puts "#{response.body}"
        body = response.body.chomp

        # If we don't get the first line like this, there was something
        # wrong with the data (404 error, new data formet, etc).
        return [] if body !~ /Date,Open,High,Low,Close,Volume,Adj Close/

        # Parse into an array of arrays.
        rows = CSV.parse( body )
        # Remove the first array since it is just the field headers.
        rows.shift
        #puts "#{rows.length}"

        return rows
      }
    end