27 July 2013

Get Stock Quotes with Yahoo! Query Language (YQL)

Code
 <b>Result</b>  
 <div id="yqlResult"></div>  
 <script>  
 // prepare the request  
 var yqlUrl = "http://query.yahooapis.com/v1/public/yql";  
 // this query will retrieve the Name, Symbol and LastTradePriceOnly for Semb Corp, CDL HTrust and Sheng Siong  
 var yqlQuery = encodeURIComponent("select Name, Symbol, LastTradePriceOnly from yahoo.finance.quote where symbol in ('U96.SI','J85.SI','OV8.SI')");  
 var format = "json";  
 var env = encodeURIComponent("store://datatables.org/alltableswithkeys");  
 var request = yqlUrl +  
                "?q=" +  
                yqlQuery +   
                "&format=" +  
                format +   
                "&env=" +   
                env;  
 // initialize the XMLHttpRequest object  
 var xmlhttp;  
 if (window.XMLHttpRequest) {  
      // for new browsers  
      xmlhttp=new XMLHttpRequest();  
 } else {  
      // for IE5 and 6  
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");  
 }  
 // readyState==4 means request finished and response is ready  
 xmlhttp.onreadystatechange=function() {  
      if(xmlhttp.readyState==4) {  
           // responseText is the JSON string, JSON.parse converts it into an object so you can manipulate using dots  
           var myObject = JSON.parse(xmlhttp.responseText);  
           // get the quote  
           var quote = myObject.query.results.quote;  
           // this is the size of the quotes, we have 3 symbols so it's 3  
           var quoteLength = quote.length;  
           // print out the Name, Symbol and LastTradePriceOnly  
           for (var i=0; i<quoteLength; i++) {  
                yqlResult = document.getElementById('yqlResult');  
                yqlResult.innerHTML += "Name: " + quote[i].Name;  
                yqlResult.innerHTML += ",&nbsp;";  
                yqlResult.innerHTML += "Symbol: " + quote[i].Symbol;  
                yqlResult.innerHTML += ",&nbsp;";  
                yqlResult.innerHTML += "LastTradePriceOnly: " + quote[i].LastTradePriceOnly;  
                yqlResult.innerHTML += "<br />";  
           }  
      }  
 }  
 // send the request  
 xmlhttp.open("GET",request,true);  
 xmlhttp.send(null);  
 </script>  

Result

JSON String Details
 {  
      "query":{  
           "count":3,"created":"2013-07-27T06:00:39Z","lang":"en-US","results":{  
                "quote":[{  
                     "LastTradePriceOnly":"5.02","Name":"Semb Corp","Symbol":"U96.SI"  
                },{  
                     "LastTradePriceOnly":"1.675","Name":"CDL HTrust","Symbol":"J85.SI"  
                },{  
                     "LastTradePriceOnly":"0.70","Name":"Sheng Siong","Symbol":"OV8.SI"  
                }]  
           }  
      }  
 }  

Well, if you find it useful, feel free to use it.

No comments: