Friday, September 23, 2011

Yahoo Download Stock Data


Almost everyone knows that Yahoo has API to retrieve financial data.We will write a client that will
consume Yahoo API to retrieve history stock data. Let's start to develop set of classes
that will handle required functionality.


First we define an Enum that holds different period types. The name of the class "PeriodType".
Yahoo stock data can be retrieved for various period types. It can be daily,monthly and etc..
Than we will define a class that holds information about single piece of data.
If we will request daily data , than class will holds single day, and if we request data by month
it will holds single month . The class name "Bar".

The main class that uses Yahoo API is class that named "YahooHistoryDownloader".
The class knows how to retrieve a stock data for different periods and different intervals.
The main function "GetBarHistory"  .
Input parameters:

  •    string stockName  - ticker name of the stock . "GOOG" for example.
  •    PeriodType periodType - enum that represent interval
  •    DateTime frDate - start date
  •    DateTime toDate -  from date

In order to test I created a console application that will print  the downloaded data to console.
The test function knows how to download data for the half year. 

  private static void GetDataFromStock(string stockName,PeriodType periodType)
            YahooHistoryDownloader historyDown = new YahooHistoryDownloader();
            List<Bar> listBar = historyDown.GetBarHistory(stockName,periodType, DateTime.Now.AddMonths(-6), DateTime.Now);
            foreach (Bar bar in listBar)

In order to use it
   string stockName = "GOOG";
   GetDataFromStock(stockName, PeriodType.Weekly );

Than you can collect the stock data and develop your  trading strategy

Here is UML

All the code can be downloaded from hereDownload

Please see how this component can be used to display stock graph in my next blog Click here !


  1. Hello I'm looking to implement a way to have my performance tracked on my site at . I'm looking for the stock portfolio to be as up to date as yahoo streaming quotes are. I want the P/L to be calculated automatically as the values change on yahoo. In a seperate piece I'm looking to stream a few pivot levels onto my site. Can you email me at if you can help?


  2. Fantastic - I've never used the WebRequest stuff in .NET before.. I recently realised that I need to read current stock prices for a little program I'm writing. Your code has come to the rescue !