Download Stock Quotes, Free, Easy and with Source Code

Every once in a while, I need stock quotes for some idea I need to try out. There are several methods for downloading quotes that cost money – but the data is freely available from  Yahoo so I figured I’d use that.

Turns out that 93 rows of code is enough – and that includes downloading a list of Nasdaq stock symbols.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Cluster.ConsoleApp
{
    public static class MinimalStockDownloader
    {
        public static void DownloadStocks(string path)
        {
            // Allows you to download more items in parallel
            ServicePointManager.DefaultConnectionLimit = 10;
            List<string> symbols = GetStockSymbols();

            // Run in parallel - speeds things up considerably...
            Parallel.ForEach(
                symbols,
                symbol =>
                {
                    Console.WriteLine("Downloading {0}: Working...", symbol);
                    string suri = string.Format(
                        "http://ichart.finance.yahoo.com/table.csv?s={0}&g=d&ignore=.csv", 
                        symbol);                    
                    try
                    {
                        string quotes = Get(new Uri(suri));
                        File.WriteAllText(path + @"\" + symbol + ".csv", quotes);                    
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(
                            "  Failed to download {0} with exception: \n{1}", 
                            symbol, 
                            e);
                    }
                    
                    Console.WriteLine(
                        "Downloading {0}: Done!", 
                        symbol);
                });
        }

        public static List<string> GetStockSymbols()
        {
            // You'll find a complete list of stocks at
            // http://www.nasdaq.com/screening/companies-by-industry.aspx?exchange=NASDAQ&render=download
            // referrred to by http://www.nasdaq.com/screening/companies-by-industry.aspx?exchange=NASDAQ
            string stocksCsv = Get(new Uri("http://www.nasdaq.com/screening/companies-by-industry.aspx?exchange=NASDAQ&render=download"));

            List<string> symbols = new List<string>();
            Regex regexObj = new Regex("^\"(.*?)\"", RegexOptions.Singleline | RegexOptions.Multiline);
            Match matchResult = regexObj.Match(stocksCsv);
            while (matchResult.Success)
            {
                symbols.Add(matchResult.Groups[1].Value);
                matchResult = matchResult.NextMatch();
            }

            // First item is the text "Symbol".
            symbols = symbols.Skip(1).ToList();
            Console.WriteLine("Found {0} symbols", symbols.Count);
            return symbols;
        }

        public static string Get(Uri address)
        {
            Console.WriteLine("  Get {0}...", address);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);
            request.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.CacheIfAvailable);

            try
            {
                using (WebResponse response = request.GetResponse())
                using (var stream = response.GetResponseStream())
                using (var reader = new StreamReader(stream, Encoding.Default))
                {
                    return reader.ReadToEnd();
                }
            }
            catch
            {
                request.Abort();
                throw;
            }
        }
    }
}

About mfagerlund
Writes code in my sleep - and sometimes it even compiles!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: