I needed a way to get stock quote data into my rails app. I decided to go with the yahoofinance gem.
1. install it: sudo gem install yahoofinance
2. require it in your environment file - for rails 2.1 do config.gem ‘yahoofinance’
3. Use the following code to add it to your database (make sure you have a field in your database called last_trade
YahooFinance::get_standard_quotes(params[:stock][:symbol]).each do |stock, quote| params[:stock][:last_trade] = quote.lastTrade end @stock = current_user.stocks.new(params[:stock])
Note: the yahoofinacne gem hasn’t been updated for quite a while. It might not be the best way to do things anymore. It might be better to use the yahoo api to access the information you need. Plus, it might be faster. Here’s an example snippet. I’ve republished this here to make sure it doesn’t go anywhere.
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)
}