Formatting Stock Data from Yahoo Finance

Thursday, January 28th, 2010 | Business | by

Yesterday I was playing with manipulating information pulled from stocks.  I ended up pulling data from Yahoo Finance, because it is just so easy to do in PHP.  I ran into a problem, how would I pull all the data I needed?

I found very little documentation online, it seems that pulling data from Yahoo Finance is more of a clever manipulation of Yahoo offering CSV downloads of financial data.  Yahoo mentions on discussion boards that it does not support, or help, those who use Yahoo Finance like this.  I don’t believe it is against any agreements.

The Setup

Pulling data is easy enough.  Examples here will be in PHP but it can be done in any language of course.

Yahoo’s finance URL is:

http://quote.yahoo.com/d/quotes.csv

That will get you a CSV (comma separated values) result.  You can query multiple stock symbols, they are returned on different lines.

Some basic PHP code to get you up and running:

// Setup Variables
$stockList = "GOOG,YHOO,T,AAPL";
$stockFormat = "snl1d1t1c1hgw";
$host = "http://quote.yahoo.com/d/quotes.csv";
$requestUrl = $host."?s=".$stockList."&f=".$stockFormat."&e=.csv";

// Pull data (download CSV as file)
$filesize=2000;
$handle = fopen($requestUrl, "r");
$raw = fread($handle, $filesize);
fclose($handle);

// Split results, trim way the extra line break at the end
$quotes = explode("\n",trim($raw));

foreach($quotes as $quoteraw) {
$quoteraw = str_replace(", I", " I", $quoteraw);
$quote = explode(",", $quoteraw);

echo $quote[0]."
"; // output the first element of the array, the Company Name
}

As you can see, it is very easy.  Some interesting parts of the sample:

  • Line 3 – You can change the stockFormat just like a date format to pull different values.  The list of options is at the end of this post
  • Line 9 – This is being handled like a file download
  • Line 14 – I trim the results before splitting by lines, because I always have an extra line break at the end
  • Line 17 – One HUGE problem with this, is it may contain commas.  There is probably an easy regular expression to write, but for my purposes doing the replace on the “, Inc.” was enough for me.  I had 2 companies whose name included a comma, so I just filter that out so we don’t break the array indexes.  In doing searches online people complain that this is a problem, it really isn’t with a little more than basic parsing.
  • Line 20 – Our final result, of course you can display whichever field you want.  Below you will see what fields are being pulled

Yahoo Finance CSV Formatting Options

On the example above you can see on line 3, that we set the format to be returned.  It is just like working with date and their formatting.  Below is a list of options I finally found after scouring the web (Yahoo documentation does NOT help with this):

  • s – Symbol
  • n – Name
  • l – Last Trade (with time)
  • l1 – Last Trade (without time)
  • d1 – Last Trade Date
  • t1 – Last Trade Time
  • k3 – Last Trade Size
  • c – Change and Percent Change
  • c1 – Change
  • p2 – Change in Percent
  • t7 – Ticker Trend
  • v – Volume
  • a2 – Average Daily Volume
  • i – More Info
  • t6 – Trade Links
  • b – Bid
  • b6 – Bid Size
  • a – Ask
  • a5 – Ask Size
  • p – Previous Close
  • o – Open
  • m – Day’s Range
  • w – 52 Week Range
  • j5 – Change from 52 Week Low
  • j6 – Percent Change from 52 Week Low
  • k4 – Change from 52 Week High
  • k5 – Percent Change from 52 Week High
  • e – Earnings/Share
  • r – P/E Ratio
  • s7 – Short Ratio
  • r1 – Dividend Pay Date
  • q – Ex-Dividend Date
  • d – Dividend/Share
  • y – Dividend Yield
  • f6 – Float Shares
  • j1 – Market Capitalization
  • t8 – 1 Year Target Price
  • e7 – EPS Est. Current Year
  • e8 – EPS Est. Next Year
  • e9 – EPS Est. Next Quarter
  • r6 – Price/EPS Est. Current Year
  • r7 – Price/EPS Est. Next Year
  • r5 – PEG Ratio
  • b4 – Book Value
  • p6 – Price/Book
  • p5 – Price/Sales
  • j4 – EBITDA
  • m3 – 50 Day Moving Average
  • m7 – Change from 50 Day Moving Average
  • m8 – Percent Change from 50 Day Moving Average
  • m4 – 200 Day Moving Average
  • m5 – Change from 200 Day Moving Average
  • m6 – Percent Change from 200 Day Moving Average
  • s1 – Shares Owned
  • p1 – Price Paid
  • c3 – Commission
  • v1 – Holdings Value
  • w1 – Day’s Value Change
  • g1 – Holdings Gain Percent
  • g4 – Holdings Gain
  • d2 – Trade Date
  • g3 – Annualized Gain
  • l2 – High Limit
  • l3 – Low Limit
  • n4 – Notes
  • k1 – Last Trade (Real-time) with Time
  • b3 – Bid (Real-time)
  • b2 – Ask (Real-time)
  • k2 – Change Percent (Real-time)
  • c6 – Change (Real-time)
  • v7 – Holdings Value (Real-time)
  • w4 – Day’s Value Change (Real-time)
  • g5 – Holdings Gain Percent (Real-time)
  • g6 – Holdings Gain (Real-time)
  • m2 – Day’s Range (Real-time)
  • j3 – Market Cap (Real-time)
  • r2 – P/E (Real-time)
  • c8 – After Hours Change (Real-time)
  • i5 – Order Book (Real-time)
  • x – Stock Exchange

If you look at our original format string:

snl1d1t1c1w

You can see that it will return, in this order, the following values per stock queried:

  1. Symbol
  2. Name
  3. Last Trade (Price Only)
  4. Last Trade Date
  5. Last Trade Time
  6. Change
  7. 52-Week Range

Tags: , , , , , ,

15 Comments to Formatting Stock Data from Yahoo Finance

Daniel P
July 30, 2010

Hey good article, one question, what GMT is the “t1″(Last Trade time) option?

seangw
July 30, 2010

I believe it’s GMT+0, but I could be wrong — I’d just verify with a comparison to the live Yahoo Finance site.

Andy
September 22, 2010

How to use this? How to show fields on my site?

Trading Options Online
November 29, 2010

Wow, very interesting. Never saw this, despite playing around quite a bit with Yahoo Finance data…

I wonder if there is a way of integrating this into MetaTrader so it would download the data into the software directly?

Dr Senthil Kumar S
February 1, 2011

Very useful and well drafted material. Really useful

Milan
February 14, 2011

Great article, Yahoo site as of late has become a little unrealiable. Does the author now of any other sites ?
also fopen sometimes returns errors when prices can not be achieved, as such you might want to use error_reporting in PHP to hide errors that fopen may encounter

Adam
April 14, 2011

There is a small problem with some data bits, such as a5 b6 and k6 ..they have commas in the data, and no way of telling you it’s not a delimiter and no way of setting a different delimiter!

caleb
April 25, 2011

any clue how to get data for stock options?

e.g. AAPL130119C00330000 (AAPL Jan 2013 330.000)

Thanks!

Anonymous
May 27, 2011

[...] [...]

[...] for their respective project. Yahoo Finance related sites are in abundance and eventually I found Sean Walter’s Blog, now I was making headway. It seems that the old method of accessing Yahoo Finance is still [...]

charles
June 6, 2011

can you download the stock price history using php and work with that instead of having to download the .csv from the yahoo website? Because this only retrieves the day’s quote doesn’t it?

mambajoe
July 3, 2011

if you do not want to work with a csv file, you can get the same information using the following command which will return an xml.
http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20%28%22xel.l%22%29 &diagnostics=false&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys

ballterrier
October 7, 2011

Hi,

Is there a way downloading 1mth, 3mths, 1 Yr and 5 Yr performance data. I cannot see any option codes above and/or acticles to get this data in csv/php format

seangw
October 7, 2011

I’m working on a writeup. I currently have a site pulling all of this information and generating it on the fly (including historical stock data).

hector delgado
January 16, 2012

whats the tag for the beta number?

Leave a comment

*


Please share, it makes me happy:

Subscribe to Email Alerts

Make a Donation

Follow Me

Follow seangw on twitter

Archives

Categories

prestashop theme

virtuemart template