Ruby Weekly is a weekly newsletter covering the latest Ruby and Rails news.

Getting stock quotes in 1 line of Ruby code

By Peter Cooper / June 14, 2006

The RubyExamples page is a few years old now, but I just came across a great example which still works, and which demonstrates the intense power of Ruby. Please note that Justin Bishop deserves all the credit for this one.

Here's the routine:

class RubyStock
	require 'net/http'
    def RubyStock::getStocks(*symbols)
        Hash[*(symbols.collect{|symbol|[symbol,Hash[\
        *(Net::HTTP.get('quote.yahoo.com','/d?f=nl1&s='+symbol).chop\
        .split(',').unshift("Name").insert(2,"Price"))]];}.flatten)];
    end
end

Using it is simple:

puts RubyStock::getStocks("MSFT", "IBM", "GOOG").inspect 

=> {"GOOG"=>{"Name"=>""GOOGLE"", "Price"=>"386.525"}, "IBM"=>{"Name"=>""INTL BUSINESS MAC"", "Price"=>"76.93"}, "MSFT"=>{"Name"=>""MICROSOFT CP"", "Price"=>"21.51"}}

Amazing! It returns within half a second on my machine, and I can't believe the same scraping logic works after three years.

Comments

  1. Chris says:

    Well, it's not really scraping because it relies on Yahoo's very nice API. That URL spits out just raw CSV, so it's easy to parse.

    But thanks for the reference, I _was_ using screenscraping to get quotes, and it did break often. Using that CSV API is much, much nicer. (BTW you can tweak the 'f' parameter to change what data gets included (and the order). Try appending 'o', 'c', 'v', 'g', 't1', d1' and more to get opening price, change, high, low, time, date, etc.)

  2. Peter Cooper says:

    Oh cool, I didn't reverse engineer down to the URL, but that's interesting to know. I'm surprised they offer that access to the data. Sweet. I think I'll remove the word 'scraping', as yeah, it's a bit out of place :)

Other Posts to Enjoy

Twitter Mentions