C# Code, Tutorials and Full Visual Studio Projects

Using the Yahoo Finance API for CSV

Posted by on Feb 25, 2012 in API, Code Snippets, Featured, Financial | 34 comments

Using the Yahoo Finance API for CSV

How the Free Yahoo Finance API Works

Yahoo finance provides a great and simple way to download free stock quotes. This service returns stock data in a CSV. (comma delimited format, you can just open it in Excel if you like)

The service Yahoo finance provides for free stock quotes is REST based. (love REST based stuff) So all you need to do is assemble the URL you want and it will give you the data your looking for.

The API lets you specify multiple symbols to download with a maximum of 200 per call. (You can make multiple calls, but if you call too fast it will lock your IP so be warned)


How to call the free Yahoo Finance API

The base url your going to call is http://finance.yahoo.com/d/quotes.csv

Then you add a ?s= and the stock symbols your interested in such as APPL, GOOG and MSFT like so

http://finance.yahoo.com/d/quotes.csv?s=AAPL+GOOG+MSFT

Then you specify the info you want. There is a large list of stuff you can specify, just look at the list below for more info.

http://finance.yahoo.com/d/quotes.csv?s=AAPL+GOOG+MSFT&f=nab

This will get the name of the stock, the ask price and bid price (the “nab” = name,ask and bid)


Financial Data you can Download

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




Getting Stock Data in C#

Since this is a REST based finance API, to get the data using C# is easy. You can simply use a WebClient.DownloadString(myurl) to get the data. Once you get the data, it’s also easy to parse being a simple CSV format.

Download Source Code

Here is a quick example of how you can use the free Yahoo Finance API in your C# code.

Application Entry Point (main)

using System;
using System.Collections.Generic;
using System.Net;
using jarloo;

namespace Jarloo
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            string csvData;

            using (WebClient web = new WebClient())
            {
                csvData = web.DownloadString("http://finance.yahoo.com/d/quotes.csv?s=AAPL+GOOG+MSFT&f=snbaopl1");
            }

            List<Price> prices = YahooFinance.Parse(csvData);

            foreach (Price price in prices)
            {
                Console.WriteLine(string.Format("{0} ({1})  Bid:{2} Offer:{3} Last:{4} Open: {5} PreviousClose:{6}",price.Name,price.Symbol,price.Bid,price.Ask,price.Last,price.Open,price.PreviousClose));
            }

            Console.Read();

        }
    }
}

Parsing Class and State Bag

using System;
using System.Collections.Generic;

namespace jarloo
{
    public static class YahooFinance
    {
        public static List<Price> Parse(string csvData)
        {
            List<Price> prices = new List<Price>();

            string[] rows = csvData.Replace("\r", "").Split('\n');

            foreach (string row in rows)
            {
                if (string.IsNullOrEmpty(row)) continue;

                string[] cols = row.Split(',');

                Price p = new Price();
                p.Symbol = cols[0];
                p.Name = cols[1];
                p.Bid = Convert.ToDecimal(cols[2]);
                p.Ask = Convert.ToDecimal(cols[3]);
                p.Open = Convert.ToDecimal(cols[4]);
                p.PreviousClose = Convert.ToDecimal(cols[5]);
                p.Last = Convert.ToDecimal(cols[6]);

                prices.Add(p);
            }

            return prices;
        }
    }

    public class Price
    {
        public string Symbol { get; set; }
        public string Name { get; set; }
        public decimal Bid { get; set; }
        public decimal Ask { get; set; }
        public decimal Open { get; set; }
        public decimal PreviousClose { get; set; }
        public decimal Last { get; set; }
    }
}

34 Comments

Join the conversation and post a comment.

  1. sebastian

    Great article! One thing I come to think off is how to use this to compare different stocks and how they are valued to each other. I was thinking about getting a list of stocks with it short names. Do u know where to find such lists?

    Keep up the good work :)

    BR
    Sebastian

  2. admin

    EODData has a good list of stock tickers if that is what you looking for. You need to sign up but it’s free and then you can download the lists. http://www.eoddata.com/download.aspx

    BATS Also has a great list you can use, I have a quick article on how to get that data here http://www.jarloo.com/download-stock-symbols/

  3. lalas

    Would it possible to make the source code for this project available for download? If i do a simple copy and paste, i would be get an error for using Jarloo.

    Sorry if that is a trivial request, but i am kinda new to C# and i would like to use your website to help me learn.

    Thank you

  4. admin

    @LALAS I posted the Visual Studio project, you can download from the big green button above.

  5. lalas

    Cheers.. :)

  6. Uri G

    Is there anyway to retrieve the stocks Beta (risk) in a specific date?
    Thanks!

  7. Tom Peirce

    Is there any way to specify a certain stock market? Some stocks codes overlap with another on a different exchange, (e.g TSCO is Tesco in UK and a tractor company in US, and this always returns the US one.)

    Thanks.

  8. Hugh Brown

    TSCO.L is the ticker Yahoo uses for Tesco in London. In general, you’ll have to look up the suffixes for the exchanges.

  9. kevin

    Hi,
    May I know how to retrieve stock option detail quotes ?
    Thanks.
    Kevin

  10. DARSH

    Hi, I would like to know whether this method is actually using yahoo finance api or Yahoo Query Language ? I’m a bit confused. Could you please give some clarification regarding the same?

  11. admin

    This uses an API and does NOT use YQL. The API has been around for years and works quite well.

  12. Thomas

    Can monthly and weekly prices be downloaded through this api? If so how is it done?

  13. admin

    As far as I am aware only dailies are available.

  14. Sam

    How do you get these information, can you share with us where is the Yahoo official documentation so we can always access the latest info from Yahoo? nevertheless this is still the best website in showing how to access Yahoo finance API. Thank.

  15. Sam

    I really like to retrieve the stock info via csv compare to YQL. Not so sure how to use YQL, but why I can’t find any documentation from Yahoo in how to use csv?

  16. admin

    As far as I am aware there is no official documentation. This information I’ve gathered from others and trial and error by working with the API.

  17. KEVIN PARK

    Yahoo,

    I’m using

    http://finance.yahoo.com/d/quotes.csv?s=DJI&f=sl1d1t1c1ohgv&e=.csv

    to try to get the Dow jones and I’m not getting the data as I was in the past. Any ideas?

    Kevin

  18. graemeb

    The Yahoo data described above appears to be current day downloads – am i wrong?
    I was looking for a way to download 5 years of daily data, so that i can then make 5 year charts. Please advise.
    thanks

  19. Charles

    Here’s some more tags:
    s6 – Revenue
    j2 – Shares Outstanding

  20. Sylvain

    I want simulate Real time to create a demo of a Trading game.
    Do you know about how many call my IP is locked ?
    Do you have a solution to simulate real time for a demo (realtime or dealayed data), there isn’t real streaming quotes for free since the dead of opentick :(

    thanks

  21. Yared

    Any idea how to get the information from the Yahoo Finance Analysts Estimates table? Here is an example:

    http://finance.yahoo.com/q/ae?s=HTZ+Analyst+Estimates

    Thanks!!

  22. Kelly Elias

    As far as I am aware there is no API but you can always scrape the data. Just use WebClient.DownloadString() to get the page and then use something the the HTML Agility Pack or even Regex to parse the data.

  23. Yared

    Thanks Kelly! Will do.

  24. Joe

    Just wanted to bring it to your attention that symbol “v” is used for both “Volume” & “More Info”.

    Thanks for this post, it’s very helpful.

  25. sajjad

    Anyway symbol to download BETA for a stock?

  26. Fabvon

    Hi Kelly! I have an Excel Macro to import around 15 stocks automatically, but when moving the XLS to Google Drive, they don’t support VBA, only Javascript (which I don’t know).

    Any way to import Yahoo Finance data to Google Drive?

  27. Kelly Elias

    I don’t have much experience with using Google drive, but if you use Google Spreadsheets you can get Google Finance data directly into your sheet, and Google will keep it up to date. Use the formula: GoogleFinance(symbol, attribute)

    More info: https://support.google.com/drive/bin/answer.py?hl=en&answer=155178

  28. rajkumar

    The Yahoo API that I’m currently referring so as to get the stock rates returns ZERO or ‘N/A’ for Canara Bank (CODE : CANARABANK.BO) but I can see the correct value for this stock on your site http://in.finance.yahoo.com… May I know why I cannot see the correct value while using the API that you provide. I think there is a problem with the API. Please do reply as soon as possible. Awaiting your response….

  29. ehsan

    Plz any one help me. I want to get Full compny name like for SODA the Full name is SodaStream International Ltd. I am waiating plz.

  30. Kelly Elias

    http://finance.yahoo.com/d/quotes.csv?s=SODA&f=snbaopl1

    That should give you what you want. The last parameter “f” sets the fields to show. The table on this page shows each of them (that I know about anyway) and you can see that “n” is the flag you want to display the full name.

  31. Alijohn

    Is there a way to get commodities from yahoo finance with csv ?

  32. Kelly Elias

    Not that I’m aware of.

  33. JefB

    I am getting the stock price using the formula:
    =WEBSERVICE(“http://finance.yahoo.com/d/quotes.csv?s=”&C2&”&f=l1″)
    (“C2″ is the cell with the stock symbol)

    However, I cannot figure out how to convert the result into a numeric so that I can use it in a formula. (Excel 2013 360) on Windows 8)

    Any suggestions?

  34. Ed

    You can get commodity futures if you know the future, exchange, and month codes-
    I don’t know how to get spot prices yet.

    Gold=GC, Month=June, Year=13, exchange=CMX (metals)

    % curl -s ‘http://download.finance.yahoo.com/d/quotes.csv?s=GCM13.CMX&f=snl1′
    “GCM13.CMX”,”Gold Jun 13″,1469.60

    Month Codes – (“F”,”G”,”H”,”J”,”K”,”M”,”N”,”Q”,”U”,”V”,”X”,”Z”)
    Energy exchange is NYM
    You can look up the future codes on the exchange web site.

    Good Luck!

Leave a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>