Yahoo Finance API & YQL

Yahoo Finance is nice enough to expose an open API to access stock detail information through the use of YQL. The Yahoo Query Language (YQL) platform enables developers to query, filter, and combine data through a single web interface. It exposes a SQL like syntax that is both familiar to developers and expressive enough to get the right data. You can read more about YQL here, here, and here. You can also play around or test drive working with YQL through the YQL Console (if you are interested).

TLDR;


Objective

Provide a search mechanism for the end user to search for stocks based on ticker symbol. When the user clicks the Search button, pull the stock information from Yahoo Finance API and display it back to user.

1. Create the Controller

The Controller is where the bulk of the work takes place in this example. The following list walks through what the code does, and below the walk through the full ActionResult method from the Controller is shown.

  • The code makes a web request (via a URL) for stock information to be returned in JSON format
  • The JSON is deserialized into an object of type stockdetails - which we will create in the next step
  • The stockdetails Model (aka s variable) is passed back to the View
Note:


        public ActionResult Details(string symbol)
        {
            stockdetails s;
            ViewBag.StockLoaded = false;
            try
            {
                string sYahooAPI = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22" + symbol + "%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=";
                string json; 
                using (WebClient web = new WebClient())
                {
                    json = web.DownloadString(sYahooAPI);
                }
                JObject jo = JObject.Parse(json);
                s = JsonConvert.DeserializeObject(jo.SelectToken("query.results.quote").ToString());
                //Stock successfully loaded.
                ViewBag.StockLoaded = true;
            }
            catch(Exception ex)
            {
                ViewBag.exErr = ex.Message.ToString();
                return View();
            }
            return View(s);
        } 
        


2. Create the Model

I cheated a little bit here. I captured the return JSON from Yahoo (in the debugger) and entered it at json2csharp to create the model, because I was too lazy to type up the entire model manually. Once the model was created I then added some DisplayName data annotations to the Model for use in the View.


    public class stockdetails
    {
        public string symbol { get; set; }
        public string Ask { get; set; }
        [DisplayName("Avg Daily Volume")]
        public string AverageDailyVolume { get; set; }
        public string Bid { get; set; }
        public object AskRealtime { get; set; }
        public object BidRealtime { get; set; }
        public string BookValue { get; set; }
        public string Change_PercentChange { get; set; }
        public string Change { get; set; }
        public object Commission { get; set; }
        public string Currency { get; set; }
        public object ChangeRealtime { get; set; }
        public object AfterHoursChangeRealtime { get; set; }
        [DisplayName("Dividend Per Share")]
        public string DividendShare { get; set; }
        public string LastTradeDate { get; set; }
        public object TradeDate { get; set; }
        [DisplayName("Earnings Per Share")]
        public string EarningsShare { get; set; }
        public object ErrorIndicationreturnedforsymbolchangedinvalid { get; set; }
        [DisplayName("EPS Current Yr")]
        public string EPSEstimateCurrentYear { get; set; }
        [DisplayName("EPS Next Yr")]
        public string EPSEstimateNextYear { get; set; }
        [DisplayName("EPS Next Qtr")]
        public string EPSEstimateNextQuarter { get; set; }
        public string DaysLow { get; set; }
        public string DaysHigh { get; set; }
        public string YearLow { get; set; }
        public string YearHigh { get; set; }
        public object HoldingsGainPercent { get; set; }
        public object AnnualizedGain { get; set; }
        public object HoldingsGain { get; set; }
        public object HoldingsGainPercentRealtime { get; set; }
        public object HoldingsGainRealtime { get; set; }
        public object MoreInfo { get; set; }
        public object OrderBookRealtime { get; set; }
        [DisplayName("Market Capitalization")]
        public string MarketCapitalization { get; set; }
        public object MarketCapRealtime { get; set; }
        public string EBITDA { get; set; }
        public string ChangeFromYearLow { get; set; }
        public string PercentChangeFromYearLow { get; set; }
        public object LastTradeRealtimeWithTime { get; set; }
        public object ChangePercentRealtime { get; set; }
        public string ChangeFromYearHigh { get; set; }
        public string PercebtChangeFromYearHigh { get; set; }
        public string LastTradeWithTime { get; set; }
        public string LastTradePriceOnly { get; set; }
        public object HighLimit { get; set; }
        public object LowLimit { get; set; }
        [DisplayName("Day's Range")]
        public string DaysRange { get; set; }
        public object DaysRangeRealtime { get; set; }
        [DisplayName("50 day Moving Avg")]
        public string FiftydayMovingAverage { get; set; }
        [DisplayName("200 day Moving Avg")]
        public string TwoHundreddayMovingAverage { get; set; }
        public string ChangeFromTwoHundreddayMovingAverage { get; set; }
        public string PercentChangeFromTwoHundreddayMovingAverage { get; set; }
        public string ChangeFromFiftydayMovingAverage { get; set; }
        public string PercentChangeFromFiftydayMovingAverage { get; set; }
        public string Name { get; set; }
        public object Notes { get; set; }
        public string Open { get; set; }
        [DisplayName("Previous Close")]
        public string PreviousClose { get; set; }
        public object PricePaid { get; set; }
        public string ChangeinPercent { get; set; }
        [DisplayName("Price To Sales")]
        public string PriceSales { get; set; }
        [DisplayName("Price To Book")]
        public string PriceBook { get; set; }
        public string ExDividendDate { get; set; }
        [DisplayName("PE (ttm)")]
        public string PERatio { get; set; }
        public string DividendPayDate { get; set; }
        public object PERatioRealtime { get; set; }
        [DisplayName("PEG Ratio")]
        public string PEGRatio { get; set; }
        [DisplayName("Price to EPS Current Yr")]
        public string PriceEPSEstimateCurrentYear { get; set; }
        [DisplayName("Price to EPS Next Yr")]
        public string PriceEPSEstimateNextYear { get; set; }
        public string Symbol { get; set; }
        public object SharesOwned { get; set; }
        public string ShortRatio { get; set; }
        public string LastTradeTime { get; set; }
        public object TickerTrend { get; set; }
        [DisplayName("Target Price 1yr")]
        public string OneyrTargetPrice { get; set; }
        public string Volume { get; set; }
        public object HoldingsValue { get; set; }
        public object HoldingsValueRealtime { get; set; }
        [DisplayName("Year Range")]
        public string YearRange { get; set; }
        public object DaysValueChange { get; set; }
        public object DaysValueChangeRealtime { get; set; }
        [DisplayName("Stock Exchange")]
        public string StockExchange { get; set; }
        [DisplayName("Dividend Yield")]
        public string DividendYield { get; set; }
        public string PercentChange { get; set; }
    }
        


3. Create the View

The View acts strictly as the presentation layer. It displays data from the Model. Below a small snippet can be seen from the View that shows the HTML and Razor code working together to display the Model information.



All working together

With everything in place the user only needs to enter a ticker symbol (below) into the text box and click the Search button.