Friday 15 January 2016

MVC - How to get Yahoo financial data

watch this example on YouTube:


1. Modify Web.Config, add:
  <system.net>
    <defaultProxy useDefaultCredentials="true"></defaultProxy>
  </system.net>

2. add StockInfo class to Models folder:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _MvcApplicationYahooTest2.Models
{
    public class StockInfo
    {
        public string Symbol { get; set; }
        public decimal AverageVolume { get; set; }
        public decimal LastTradePrice { get; set; }
    }
    public static class YahooFinance
    {
        public static List<StockInfo> Parse(string csvData)
        {
            try
            {
                List<StockInfo> stocks = new List<StockInfo>();
                string[] rows = csvData.Replace("r", "").Replace("\"", "").Split('\n');
                foreach (string row in rows)
                {
                    if (string.IsNullOrEmpty(row)) continue;
                    string[] cols = row.Split(',');
                    StockInfo s = new StockInfo();
                    s.Symbol = cols[0].Trim();
                    s.AverageVolume = Convert.ToDecimal((cols[1] == "N/A") ? "0" : cols[1]);
                    s.LastTradePrice = Convert.ToDecimal((cols[2] == "N/A") ? "0" : cols[2]);
                    stocks.Add(s);
                }
                return stocks;
            }
            catch (Exception ex)
            {
                //handle error
                string error = ex.Message.ToString();
            }
            return null;
        }
    }
}
3. View will look like this:

@model List<_MvcApplicationYahooTest2.Models.StockInfo>
          
<table>
    <tr>
        <th>---------SYMBOL-----------------------</th>
        <th>---------AVG VOLUME-------------------</th>
        <th>---------LAST TRADE PRICE-------------</th>
    </tr>
    @foreach (var item in Model)
    {
        <tr>
            <td>@Html.DisplayFor(modelItem => item.Symbol)</td>
            <td>@Html.DisplayFor(modelItem => item.AverageVolume)</td>
            <td>@Html.DisplayFor(modelItem => item.LastTradePrice)</td>
        </tr>
    }
</table>

4. finally - controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using System.Net;
using _MvcApplicationYahooTest2.Models;
using System.Text;
using System.IO;

namespace _MvcApplicationYahooTest2.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            string csvData;
            string symbols = "GOOG, IBM, FB";
            using (WebClient web = new WebClient())
            {
                csvData = web.DownloadString("http://finance.yahoo.com/d/quotes/csv?s=" + symbols + "&f=sa2l1");
                List<StockInfo> stocks = YahooFinance.Parse(csvData);
                return View(stocks);
            }
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your app description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}

2 comments:

  1. Hey, i get this error when i run the code "System.Net.WebException: 'The remote name could not be resolved: 'download.finance.yahoo.com'' What does it mean? i have typed in the exact same as you.

    ReplyDelete
  2. an error the get method returns null

    ReplyDelete