Wednesday, January 14, 2009

A Truly Simple Stock API

I would have thought that stock quote API's would be everywhere. It seems like getting a stock quote is among the most obvious 3rd party services out there. Yet, when I needed to find one, I was at a loss.

There's the Google Finance API - but that seems overkill. It will get information about a stock portfolio. But, what if I don't want a portfolio? What if I just want to know what the current price of a stock is?

Yahoo also has a finance developer section. But, theirs is focused on giving you RSS feeds for company information. Interesting, but again, if all I want to know is the current price of a stock - this doesn't help.

After much poking around, I found that Yahoo does offer a solution. It's even a refreshingly simple one. You can get stock data in CSV format by hitting the following URL:

  http://finance.yahoo.com/d/quotes.csv?s=RHT+MSFT&f=sb2b3jk

Which in this case, returns:

"RHT",15.50,14.74,7.50,24.84
"MSFT",19.62,19.58,17.50,35.00

More generally, the URL has the parameter s which takes in stock symbols (which would be space URL encoded - or + separated), and f is set to a format string. If you visit this page you can see all the format string options.

I'm a little bit confused by Yahoo doesn't advertise this capability more. But, it seems there and just what I need, so I may end up using.

Seeing It In Action

Here's some trivial code to grab back stock quotes using Scheme

(require (planet neil/csv:1:2/csv)
         net/url)

(define-struct sq (symbol price last-closed opened) #:prefab)
  
(define (stock-quote stock-symbol)
  (let ([url (format "http://download.finance.yahoo.com/d/quotes.csv?s=~a&f=sl1po" stock-symbol)])
    (apply make-sq (first (csv->list (port->string (get-pure-port (string->url url))))))))

With the stock-quote function defined, you can say:

 (define q1 (stock-quote "MSFT"))
 (printf "Current price: ~a\n" (sq-price q1))

Definitely not rocket science. But, pulling down a CSV feed from a URL and cramming it into a data structure shouldn't be. It should be easy, and as the above code shows, it is.

30 comments:

  1. You should encourage folks to show how simple it is to perform this operation in their favorite languages. It might be interesting...

    ReplyDelete
  2. I've been told this isn't real-time data. That it could be up to 20 minutes behind, and that you must utilize your persisted login cookie to yahoo.com (finance.yahoo.com / login.yahoo.com) to actually recieve the "real-time" data. Is this true?

    ReplyDelete
    Replies
    1. Real time stock data is not usually "real time" it costs quite a premium to get truly real time data.

      Delete
  3. ape -

    I believe there was real time data in this feed. But, I came to that conclusion only by logging into Google Finance and watching the numbers change there and on this feed, and seeing that they essentially matched.

    But that's not as nice as an official statement from Yahoo saying they are real time.

    -Ben

    ReplyDelete
  4. Hey Ben,
    One thing to note...not all api functions are available in every market (for instance, Book Value [b4] returns 0 for Canadian equities.

    ReplyDelete
  5. Anonymous2:27 PM

    Ben
    Is there a way to get Stock Market info.

    ReplyDelete
  6. @anonymous -

    What do you mean by stock marketing info?

    ReplyDelete
  7. Anonymous4:13 PM

    Nice blog, i stumbled on this article while searching for stock quote api.

    yahoo finance, google finance and most free sites have a 15 mins delay.

    you can get real time quotes via your broker or by looking at level2 movements.

    http://www.level2stockquotes.com/level-ii-quotes.html

    They have a java applet but it doesn't look like they are willing to share...

    Too bad, it's exactly what i would like to have for the applet that i want to develop for our internal portal.

    You just reminded of just how elegant and intuitive scheme code can be. Too bad i can't use it at work.

    off to continue my searche >>>

    ReplyDelete
  8. Anonymous5:47 PM

    Anyone know if you can get RSI numbers from the API? Thx.

    ReplyDelete
  9. Sorry, I don't.

    -Ben

    ReplyDelete
  10. Anonymous1:09 PM

    Hey Ben,
    Great thanks for sharing the info..I feel lucky that I stumbled scross this site. No other method is simple like this..I will do some further research and storing it in a database.

    Regards
    Ashis

    ReplyDelete
  11. Good post, as I understand it both Yahoo and Google offer free REAL-TIME stock quotes as of 2007, before this SEC (US Securities and Exchange Commission) prevented them from offering real-time services. They also seem to match up pretty well with CNN Money. Additionally, why would there be second-by-second changes if it wasn't updated immediately? Unless of course it's updated immediately just with a 15 minute delay, which wouldn't make a lot of sense since the SEC no longer requires them to do this. Anyway, is there a way to get previous stock quotes similar to this? Such as Time X on Day Y. Thanks.

    ReplyDelete
  12. boourns12:59 PM

    Great trick! I was surprised the google API doesn't offer something this flexible.

    ReplyDelete
  13. Anonymous10:06 AM

    I've used this regularly and it's very useful, but take care since if yahoo detects to many requests from your ip address you will get locked out for a period of time. I download the components for an index rather than each individual stock separately, which helps prevent this.

    ReplyDelete
    Replies
    1. Sandeep4:39 PM

      And how did you do that?

      Thanks.

      Delete
  14. This comment has been removed by the author.

    ReplyDelete
  15. Anonymous2:48 AM

    It might take a bit, but since RSI is simply based on prices within a period of time, if you can download past prices, you can do the computation for RSI yourself.
    http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:relative_strength_index_rsi

    ReplyDelete
  16. Anonymous4:12 PM

    I had been hand copying monthly stock quotes since 04/2005 into a spreadsheet representing my Vanguard 401(k). After reading your blog, I realize that I can download historical monthly quotes for mutual funds. Now I can write an app to import the .csv and do the return/volatility/VAR analysis that my spreadsheet is currently doing without having to worry about running out of memory.

    ReplyDelete
  17. What do the various parts of the "f=" portion in the URL mean? And are there more options that you've seen?

    Thanks for the article, good stuff.

    ReplyDelete
  18. The only info I have about what the URL parameters are here: http://www.gummy-stuff.org/Yahoo-data.htm

    Sorry, I don't have any more light to shed on this.

    -Ben

    ReplyDelete
  19. An example in Ruby

    require 'open-uri'
    require 'net/http'
    uri = URI.parse "http://download.finance.yahoo.com/d/quotes.csv"
    http = Net::HTTP.new(uri.host)
    resp = http.get(uri.path + "?s=ZOOM&f=k1&e=.csv").body

    ReplyDelete
  20. Anonymous8:59 PM

    Thanks, Ben!
    I used this in PERL and call it as follows:

    %get_quotes.pl msft aapl
    MSFT => 26.11
    AAPL => 344.00

    Code listing:

    #!/usr/bin/perl -w
    use LWP::Simple;
    use strict;

    foreach my $ticker (@ARGV) { #list of quotes
    my $url = "http://finance.yahoo.com/d/quotes.csv?s=${ticker}&f=sb2b3jk";
    my $content = LWP::Simple::get ($url);
    $content =~ s/"//g; # get rid of double-quotes
    my @data = split (/,/, $content);

    print "$data[0] => $data[1] \n";
    }

    ReplyDelete
  21. Anonymous1:52 AM

    Hello ,
    Very nice article .
    But i want to know the terms of use.

    ReplyDelete
  22. Anonymous4:08 AM

    hi,

    I want to know stock prices by Categories, Let say IT Industry. Is there any API available for this?...

    ReplyDelete
  23. Nice article.
    I created component for retrieving stock history
    data using c#. Have a look at my blog
    http://gregnozik.blogspot.com/2011/09/yahoo-finance-api.html

    ReplyDelete
  24. Sorry I did mistake it the post
    My article about it placed in
    http://gregnozik.blogspot.com/2011/09/yahoo-finance-api_23.html

    ReplyDelete
  25. Is there a way to get a stock quote over X period of time? For example, daily prices for GOOG over last 365 days.

    ReplyDelete
  26. Anonymous2:43 PM

    The yahoo solution works but if you're using it for commercial use and start to get a little attention, the exchanges start harassing you with cease & desists and asking you for owed intellectual property fees.
    I've licensed from FinancialContent: http://www.financialcontent.com/xml.php and Xignite.

    ReplyDelete
  27. Did any one actually find a free real-time level 2 data source? I think that is the differentiator between our retailers and the big and powerful market makers. Without level 2 market data, a single real-time stock quote is useless.

    ReplyDelete
  28. I need the stock prices on my course project, so I search the blog, however, Yahoo's API seems not give the delayed "real-time" data now, do you know other resource? thank you!

    ReplyDelete

LinkWithin

Related Posts with Thumbnails