
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.Text;
using System.IO;
using System.Globalization;

/// <summary>
/// Summary description for Stock
/// </summary>
public class Stock
{
    public Stock()
    {
        //
        // TODO: Add constructor logic here
        //
    }
    public float Open { get; set; }
    public float Close { get; set; }
    public float High { get; set; }
    public float Low { get; set; }
    public float Volume { get; set; }
    public float PE { get; set; }
    public bool Valid { get; set; }
    public string Symbol { get; set; }
    public string Name { get; set; }
    public DateTime Date { get; set; }
}
public class Stocks
{
    public static List<Stock> GetStocks(string Symbols)
    {
        List<Stock> lst = new List<Stock>();
        string yahooURL = @"http://download.finance.yahoo.com/d/quotes.csv?s=" + Symbols + "&f=ophgvre1sn";
        string[] symbols = Symbols.Replace(",", " ").Split(' ');

        // Initialize a new WebRequest.
        HttpWebRequest webreq = (HttpWebRequest)WebRequest.Create(yahooURL);
        // Get the response from the Internet resource.
        HttpWebResponse webresp = (HttpWebResponse)webreq.GetResponse();
        // Read the body of the response from the server.
        StreamReader strm = new StreamReader(webresp.GetResponseStream(), Encoding.ASCII);


        string content = "";
        for (int i = 0; i < symbols.Length; i++)
        {
            // Loop through each line from the stream, building the return XML Document string
            if (symbols[i].Trim() == "")
                continue;

            content = strm.ReadLine().Replace("\"", "");
            string[] contents = content.ToString().Split(',');
            // If contents[2] = "N/A". the stock symbol is invalid.
            if (contents[7] == "N/A")
            {
                Stock stock = new Stock();
                stock.Valid = false;
            }
            else
            {

                Stock stock = new Stock();
                if (contents[0] != "N/A")
                {
                    stock.Open = float.Parse(contents[0], CultureInfo.InvariantCulture);
                }
                if (contents[1] != "N/A")
                {
                    stock.Close = float.Parse(contents[1], CultureInfo.InvariantCulture);
                }
                if (contents[2] != "N/A")
                {
                    stock.High = float.Parse(contents[2], CultureInfo.InvariantCulture);
                }
                if (contents[3] != "N/A")
                {
                    stock.Low = float.Parse(contents[3], CultureInfo.InvariantCulture);
                }
                if (contents[4] != "N/A")
                {
                    stock.Volume = float.Parse(contents[4], CultureInfo.InvariantCulture);
                }
                if (contents[5] != "N/A")
                {
                    stock.PE = float.Parse(contents[5], CultureInfo.InvariantCulture);
                }
                stock.Valid = true;
                if (contents[7] != "N/A")
                {
                    stock.Symbol = contents[7];
                }
                if (contents[8] != "N/A")
                {
                    stock.Name = contents[8];
                }
                stock.Date = DateTime.Now.Date;
                lst.Add(stock);
            }
        }

        strm.Close();
        return lst;
    }

    public static List<Stock> GetStockHistory(string symbol, DateTime startDate, DateTime endDate)
    {
        List<Stock> list = new List<Stock>();

        var fmt = "https://www.quandl.com/api/v3/datasets/WIKI/{0}.csv?auth_token={1}&start_date={2}&end_date={3}";
        // 0: stock symbol
        // auth_token 1: token
        // start_date 2: date yyyy-MM-dd
        // auth_token 3: date yyyy-MM-dd
        var token = "n5zwD2oCokRjh96x_yxV";
        var url = string.Format(fmt, symbol, token, startDate.ToString("yyyy-MM-dd"), endDate.ToString("yyyy-MM-dd"));

        // get content
        var sb = new StringBuilder();
        var wc = new WebClient();

        IWebProxy defaultProxy = WebRequest.DefaultWebProxy;
        if (defaultProxy != null)
        {
            defaultProxy.Credentials = CredentialCache.DefaultCredentials;
            wc.Proxy = defaultProxy;
        }

        using (var sr = new StreamReader(wc.OpenRead(url)))
        {
            // skip headers
            sr.ReadLine();

            int i = 0;
            // read each line
            for (var line = sr.ReadLine(); line != null; line = sr.ReadLine())
            {
                var items = line.Split(',');

                var stock = new Stock();
                stock.Open = float.Parse(items[1], CultureInfo.InvariantCulture);
                stock.Close = float.Parse(items[4], CultureInfo.InvariantCulture);
                stock.High = float.Parse(items[2], CultureInfo.InvariantCulture);
                stock.Low = float.Parse(items[3], CultureInfo.InvariantCulture);
                stock.Volume = float.Parse(items[5], CultureInfo.InvariantCulture);
                stock.Valid = true;
                stock.Symbol = symbol;
                stock.Date = DateTime.Parse(items[0], CultureInfo.InvariantCulture);

                list.Add(stock);
            }
        }

        return list;
    }
}