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.

25 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
  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. Ben
    Is there a way to get Stock Market info.

    ReplyDelete
  6. @anonymous -

    What do you mean by stock marketing info?

    ReplyDelete
  7. 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. Anyone know if you can get RSI numbers from the API? Thx.

    ReplyDelete
  9. 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
  10. 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
  11. Great trick! I was surprised the google API doesn't offer something this flexible.

    ReplyDelete
  12. 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
  13. This comment has been removed by the author.

    ReplyDelete
  14. 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
  15. 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
  16. 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
  17. 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
  18. 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
  19. 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
  20. Hello ,
    Very nice article .
    But i want to know the terms of use.

    ReplyDelete
  21. hi,

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

    ReplyDelete
  22. 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
  23. 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
  24. 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

Related Posts with Thumbnails