DZone 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

Snippets has posted 5883 posts at DZone. View Full User Profile

Snippet To Grab Historical Data For Stocks

08.01.2006
| 8318 views |
  • submit to reddit
        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.

require 'open-uri'
require 'csv'

def get_adjusted_close stock_symbol
  puts "-- #{stock_symbol} Adjusted Close - Historical --"
  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"
  puts "Connecting to #{url}\n"

  csv = CSV.parse(open(url).read)

  csv.each{|row|
    puts "#{row[0]} - #{row.last}"
  }
  puts "---------------------------------"
end

example_stocks = "CSCO GOOG"
print "Enter a series of stock symbols separated by spaces (example: #{example_stocks}) to retrieve the historical adjusted close.\n"
stock_symbols = gets
stock_symbols ||= example_stocks

stock_symbols.split.each{|symbol|
  get_adjusted_close(symbol)
}
    

Comments

Nicholas Rahn replied on Tue, 2007/09/04 - 8:51am

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.

Snippets Manager replied on Wed, 2006/08/02 - 12:33am

this is a tag