How can I QUICKLY get a string from one of the fir

2019-07-19 11:03发布

问题:

I'm working on an assignment where I retrieve several stock prices from online, using Yahoo's stock price system. Unfortunately, the Yahoo API I'm required to use returns a .csv file that apparently contains a line for every single day that stock has been traded, which is at least 5 thousand lines for the stocks I'm working with, and over 10 thousand lines for some of them (example).

I only care about the current price, though, which is in the second line.

I'm currently doing this:

require 'open-uri'
def get_ticker_price(stock)
   open("http://ichart.finance.yahoo.com/table.csv?s=#{stock}") do |io|
      io.read.split(',')[10].to_f
   end
end

…but it's really slow.

  1. Is all the delay coming from getting the file, or is there some from the way I'm handling it? Is io.read reading the entire file?

  2. Is there a way to download only the first couple lines from the Yahoo CSV file?

  3. If the answers to questions 1 & 2 don't render this one irrelevant, is there a better way to process it that doesn't require looking at the entire file (assuming that's what io.read is doing)?

回答1:

You can use query string parameters to reduce the data to the current date, by using date range parameters.

example for MO on 7/13/2012: (start/end month starts w/ a zero-index, { 00 - 11 } ).

http://ichart.finance.yahoo.com/table.csv?s=MO&a=06&b=13&c=2012&d=6&e=13&f=2012&g=d

api description here: http://etraderzone.com/free-scripts/47-historical-quotes-yahoo.html