Jarloo

Menu

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 DownloadData(string ticker, int yearToStartFrom)
        {
            List retval = new List();

            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 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();
        }
    }
}

 

Categories:   Code, Finance

Comments

  • Posted: April 9, 2011 20:09

    tom

    Good info
  • Posted: April 22, 2011 16:05

    stockrants

    Hells yes! Big fan of your articles on stock market data. Thanks you for being so open Kellas.
  • Posted: April 26, 2011 19:26

    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
  • Posted: May 3, 2011 09:58

    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
  • Posted: May 23, 2011 21:54

    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
  • Posted: June 4, 2011 22:22

    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.
  • Posted: November 3, 2011 14:36

    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.
  • Posted: February 18, 2012 11:15

    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.....
  • Posted: March 2, 2012 03:33

    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=250x100&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....
  • Posted: July 29, 2012 05:34

    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
  • Posted: September 20, 2012 05:29

    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?
  • Posted: March 7, 2013 13:38

    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');
  • Posted: May 9, 2013 06:53

    jf

    I had to make one change: //string[] rows = data.Split('n'); string[] rows = Regex.Split(data, @"\n");
  • Posted: July 19, 2013 10:34

    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
  • Posted: November 18, 2013 00:57

    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.
  • Posted: November 20, 2013 11:55

    rishi

    guys, does anyone knows how to get time along with date in table.csv downloaded from icharts.yahoo.finance.com ? thanks & regards
  • Posted: November 20, 2013 11:56

    rishi

    i meant closing time of the exchange, for example NSE closing time could appear as 15:30
  • Posted: January 3, 2014 00:32

    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...
  • Posted: January 6, 2014 20:07

    ND

    The Yahoo ichart API quit working for me. Is anyone else having trouble?
  • Posted: January 8, 2014 20:14

    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)....
  • Posted: March 15, 2014 11: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!
  • Posted: May 15, 2014 10:55

    Michael Good

    Great piece of code! :D However I noticed that Yahoo changed the character that they use for new lines since you wrote this. To keep the code working, replace the line in the HistoricalStockDownloader class: string[] rows = data.Split('n'); with this line of code: string[] rows = data.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);