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

Related Posts

Tags: , , , , , ,

32 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?

Kade
July 30, 2012

any clues on the tags for ROE and BETA?

Rajib
August 11, 2012

I am facing problem to get the data for ^DJI, ^DJT etc. US indices. Please help me. I am using following format:

http://download.finance.yahoo.com/d/quotes.csv?s=%5EDJI&f=nl

Getting Error: Missing symbol list.

Please help me

seangw
August 12, 2012

A few of the indices aren’t allowed to be shown in the Yahoo feeds. Specifically I remember it was some of the indices, particularly DJI

Alex
August 31, 2012

Hey Sean, I’ve been pulling in yahoo finance data for years, but this morning one of the tags “t8″ (1 Year Target Price) returns NA for every stock. it was working fine yesterday, any ideas on what the issue is?

Alex
September 2, 2012

hey Sean, it is working again, must have been a glitch with their database.

Greg
September 3, 2012

This morning, I have encountered the same problem with t8 and a couple of other special tags not working. Any idea what is going on?

seangw
September 3, 2012

No idea, my bet is they’re redoing something and we’ll see some big changes shortly. We’ll see…

Alex
September 3, 2012

ruh roh! I hope they don’t remove this fantastic and convenient feature of importing into excel. The “T8″ tag is only working for some stocks now, while for other stocks “NA” is downloaded like before. sigh.

sajid
September 12, 2012

I have tried the same code but it says missing format variable

osman
September 21, 2012

The company name returns in 17 character max no matter what. For instance msft returns Microsoft Corpora

Do you know the solution for this or is it related with yahoo ?

Brian
September 24, 2012

anyone figure out the new tags yet? I am getting a number of NAs or 0s for r7, r5, t8, and e8. All these worked fine a couple weeks ago. Seems that many of the other tags I use still work so it is not a total loss.

George Fisher
December 11, 2012

A PHP function that returns an array of all the nodes available in any of several Yahoo Finance XML streams is available here:

http://www.philadelphia-reflections.com/blog/2380.htm

for Treasury yields, try

http://www.philadelphia-reflections.com/blog/2381.htm

[...] there are valid PHP codes you can copy to do that just. For example, Sean Weather’s post for formatting stock data from Yahoo! Finance is a great place to start. So why go through the hassle of making your own code when there are [...]

wdj
March 27, 2013

Anyone know of a way to pull a quote from a particular date instead of just today’s date?

Thanks!

George Fisher
April 6, 2013

Have a look at what I’ve done here:

http://www.philadelphia-reflections.com/topic/230.htm

What you’ve asked for is there plus quite a bit more, besides.

CACody
April 6, 2013

I’m not familiar with PHP but will look into it. This file on the Internet and it works well in Excel. The macro may provide some assistance on how to extract historical information from Yahoo!Finance. You’ll need to pull the file from the following site:
http://www.mathfinance.cn/download-multiple-stock-quotes-from-yahoo-finance/
I downloaded and used, so it works and does not appear to have any malware attached.
Hope this helps.

Mayank
November 6, 2013

Hi Sean,
First of all thanks for your article. Is it possible that I can get the data in some other format like JSON, PHP or XML format?

Thanks
Mayank Jaitly

Leave a comment

*


Please share, it makes me happy:

Subscribe to Email Alerts

Popular Posts

Google Analytics Popular Posts Alert :
Please check/recheck/enter your Google Analytics account details (username and password).

Follow Me

Follow seangw on twitter

Archives

Categories

prestashop theme

virtuemart template