C# Code, Tutorials and Full Visual Studio Projects

Get Historical Stock Data From Yahoo

Posted by on Mar 11, 2011 in API | 21 comments

Get Historical Stock Data From Yahoo

Need to download historical stock data? Need a large amount ie: since 1962? Well look no further, I got you covered!

How to Download Historical Stock Information from Yahoo

Yahoo has a secret API they use on there own pages that lets you display historical stock data. The API is REST based and very easy to use.

You need to specify each stock ticker your looking for and the start date you want the history from. (The oldest date appears to be around 1962.)

An example of an historical query on Apple (AAPL) looks like so:
http://ichart.finance.yahoo.com/table.csv?s=AAPL&c=1962

C# Historical Stock Downloading Code

To use the undocumented Yahoo! API to download historical stock data you will need to define a stock like so:

HistoricalStock.cs

using System;

namespace Jarloo.YahooHistoricalLoader
{
    public class HistoricalStock
    {
        public DateTime Date { get; set; }
        public double Open { get; set; }
        public double High { get; set; }
        public double Low { get; set; }
        public double Close { get; set; }
        public double Volume { get; set; }
        public double AdjClose { get; set; }
    }
}

The code to actually download and parse the results of the historical stock data, you will need something similiar to the C# code below:

HistoricalStockDownloader.cs

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

namespace Jarloo.YahooHistoricalLoader
{
    public class HistoricalStockDownloader
    {
        public static List<HistoricalStock> DownloadData(string ticker, int yearToStartFrom)
        {
            List<HistoricalStock> retval = new List<HistoricalStock>();

            using (WebClient web = new WebClient())
            {
                string data = web.DownloadString(string.Format("http://ichart.finance.yahoo.com/table.csv?s={0}&c={1}", ticker, yearToStartFrom));
                
                data =  data.Replace("r","");

                string[] rows = data.Split('n');

                //First row is headers so Ignore it
                for (int i = 1; i < rows.Length; i++)
                {
                    if (rows[i].Replace("n","").Trim() == "") continue;

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

                    HistoricalStock hs = new HistoricalStock();
                    hs.Date = Convert.ToDateTime(cols[0]);
                    hs.Open = Convert.ToDouble(cols[1]);
                    hs.High = Convert.ToDouble(cols[2]);
                    hs.Low = Convert.ToDouble(cols[3]);
                    hs.Close = Convert.ToDouble(cols[4]);
                    hs.Volume = Convert.ToDouble(cols[5]);
                    hs.AdjClose = Convert.ToDouble(cols[6]);
                    
                    retval.Add(hs);
                }

                return retval;
            }
        }
    }
}

Example of using the C# Historical Stock Downloader

Create a simple C# console application then add this code:

using System;
using System.Collections.Generic;

namespace Jarloo.YahooHistoricalLoader
{
    class Program
    {
        static void Main(string[] args)
        {
            List<HistoricalStock> data = HistoricalStockDownloader.DownloadData("AAPL", 1962);

            foreach (HistoricalStock stock in data)
            {
                Console.WriteLine(string.Format("Date={0} High={1} Low={2} Open={3} Close{4}",stock.Date,stock.High,stock.Low,stock.Open,stock.Close));
            }

            Console.Read();
        }
    }
}


21 Comments

Join the conversation and post a comment.

  1. stockrants

    Hells yes! Big fan of your articles on stock market data. Thanks you for being so open Kellas.

  2. Simon

    Specifying the start year in the query doesn’t seem to have any effect – it still downloads the entire archive?

    For example: http://ichart.finance.yahoo.com/table.csv?s=AAPL&c=2008

  3. Brad

    To specify daily quote stop and start dates try this:

    “http://ichart.finance.yahoo.com/table.csv?s=” & ticker & “&d=” & (endDate.Month – 1) & “&e=” & endDate.Day & “&f=” & endDate.Year & “&g=d&a=” & (startDate.Month – 1) & “&b=” & startDate.Day & “&c=” & startDate.Year & “&ignore=.csv”

    So to get AAPL from Jan 1, 2008 til May 2, 2011 you could use:

    http://ichart.finance.yahoo.com/table.csv?s=AAPL&d=4&e=2&f=2011&g=d&a=0&b=1&c=2008&ignore.csv

    If you want weekly quotes you can follow the format:

    “http://ichart.finance.yahoo.com/table.csv?s=” & ticker & “&a=” & (startDate.Month – 1) & “&b=” & startDate.Day & “&c=” & startDate.Year & “&d=” & (endDate.Month – 1) & “&e=” & endDate.Day & “&f=” & endDate.Year & “&g=w&ignore=.csv”

    -Brad

  4. Daniel

    Hi,

    is there anyway to download 60 min forex data using the Yahoo API.

    I know how to fetch a quote etc and daily dats but not historical intraday data so would appreciate any pointers on this,

    Daniel

  5. Vikas

    HI, Thanks for the code. Very nice. I am coding everything in C# using visual studios. I want to create a windows form application. I passed the values of stock.date and stock.close to arrays. Now I want to plot it using the charting control in VS 2010. When I replace the console.read() part with chart1, the code does not seem to identify that i have a chart in the form. it does not recognize it? What to do?

    Thanks.

  6. Oleg

    Thanks!
    I need help! I’m using this code and it works great when i define just one ticker. But i need the data for >1000 stocks. I store tickers in the text file and run this code in the loop for tickers from file. On 2nd or 3rd iteration webexception appears telling that operatuon is timed out. Completely stocked with this problem. Anybody can advise something please.

  7. Sagar Patel

    HI!
    Can anyone suggest how can i get data Indian market data because in query “s=tcs” or “s=500463″
    or “s=sensex” doesn;t work…
    Thanks…..

  8. Sagar Patel

    Hi!
    I got API providing Historical data of Indian Stock Market.
    Yahoo API:
    http://ichart.finance.yahoo.com/table.csv?s=TCS.bo&a=02&b=11&c=2010&d=02&e=15&f=2011&g=d&ignore=.csv

    I have also found Google API to draw chart as image.
    Google API:
    https://chart.googleapis.com/chart?cht=p3&chd=t:60,40&chs=250×100&chl=Hello|world

    NOW CAN ANYONE SUGGEST HOW I CAN INPUT THAT API TO GOOGLE CHART API SO
    I CAN GET CHART IN MY WEBPAGE FINALLY…

    Thank You….

  9. Bay

    Great job but Please I want to know how to download a the call and put options from yahoo finance. Will appreciate your response. Thanks

  10. Lee

    Hi, can you please tell me how can I retrieve stocj market info such as the NIKKEI, NASDAQ and so on. All I found is company information but I need the Stock market info. Is that possible?

  11. Matt Laver

    Nice article. I had to make one minor tweak in order for the example to work with Mono on OS X, change this line:

    string[] rows = data.Split(‘n’);

    to

    string[] rows = data.Split(‘\n’);

  12. jf

    I had to make one change:

    //string[] rows = data.Split(‘n’);
    string[] rows = Regex.Split(data, @”\n”);

  13. Ganesh

    Hello:

    In addition to the historical quote data, I would like to get additional values like moving averages, prev_close etc…

    I would like to extract historical quote + &f=sa2c1d1ghjkj1m3m4rr. Pls help.

    The notations are described in gummy site…. (I am sure you know what I am talking about).

    Please help.

    -gv

  14. Shahid

    @Brad
    I am able to get stock data on daily basis by startDate=”YYYY-MM-DD” and stopDate =”YYYY-MM-DD” parameters. But how can i show data on hourly basis. I want to show graph fluctuations on hourly basis for a single day i.e 2013-11-15 10:00 am to 2013-11-15 04:00 pm. What should I do.

  15. rishi

    guys, does anyone knows how to get time along with date in table.csv downloaded from icharts.yahoo.finance.com ?

    thanks & regards

  16. rishi

    i meant closing time of the exchange, for example NSE closing time could appear as 15:30

  17. TD

    I’ve been using Yahoo’s Finance API for historical data for about ten years now–only with Perl, not C#.

    My script does a lot: unlimited tickers; auto-updating of single ticker, list of tickers, or whole database; unlimited history (with ranges), reloading of history to correct errors (any range); stock and index splits (any ratio); weekly data; error checking; ticker list sorting, and more…

    I plan to add options and futures extraction, but haven’t had the time.

    No, it’s not for sale, but I may port it to Java at some point and share it.

    Learn a little Perl. Once you’ve got the syntax down, it can be a powerhouse tool for a lot of things…

  18. ND

    The Yahoo ichart API quit working for me. Is anyone else having trouble?

  19. TD

    Yeah, it was down for a while but works fine now. This has happened before. Must be Yahoo’s engineers messing with the system (again)….

  20. Tom

    I saw Simon’s comment about API ignoring start date — this is still happening. I don’t need everything, just the past year (or two). Any solution to this by now? Nice website by the way!

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>