Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippet to grab historical data for stocks (See related posts)

This is a quick little snippet I'm whipping up to import some historical data in for a graphing app we're building for stock data. I figured I'd post this snippet before I maul it into something application-specific...

It downloads a csv file through yahoo's finance site and then parses it and prints out the date and adjusted close for each business day that has data.

   1  
   2  require 'open-uri'
   3  require 'csv'
   4  
   5  def get_adjusted_close stock_symbol
   6    puts "-- #{stock_symbol} Adjusted Close - Historical --"
   7    url = "http://ichart.finance.yahoo.com/table.csv?s=#{stock_symbol}&d=7&e=1&f=2006&g=d&a=2&b=26&c=1990&ignore=.csv"
   8    puts "Connecting to #{url}\n"
   9  
  10    csv = CSV.parse(open(url).read)
  11  
  12    csv.each{|row|
  13      puts "#{row[0]} - #{row.last}"
  14    }
  15    puts "---------------------------------"
  16  end
  17  
  18  example_stocks = "CSCO GOOG"
  19  print "Enter a series of stock symbols separated by spaces (example: #{example_stocks}) to retrieve the historical adjusted close.\n"
  20  stock_symbols = gets
  21  stock_symbols ||= example_stocks
  22  
  23  stock_symbols.split.each{|symbol|
  24    get_adjusted_close(symbol)
  25  }

Comments on this post

jennykim posts on Aug 02, 2006 at 00:34
this is a tag
transparentech posts on Sep 04, 2007 at 08:54
Alternatively, you can use the YahooFinance ruby module to do this.
See http://www.transparentech.com/projects/yahoofinance
It is available as a tarball or a gem.


You need to create an account or log in to post comments to this site.


Click here to browse all 5545 code snippets

Related Posts