jQuery + YQL で株価情報取得
株価をAndroidのホーム画面にウィジェットとして表示させたいなと思い、
GooglePlayをみてたのだけど、これというものが見つからない。
iSpeed
ないなら作ってしまえということで、株価表示アプリの作成に取り掛かる。
で、まずつくったのがこれ。
YQL(https://developer.yahoo.com/yql/) + jQuery(http://jquery.com/) でブラウザに表示するアプリ。
YQL,jQuery両方ともはじめてさわったけど、とっても使いやすくて便利。
これは今後、重宝させていただきます。
ちょっと、はまった点は以下の2点。
1.yahoo.finance.quotesにYQLで問い合わせる場合
env: "store://datatables.org/alltableswithkeys"が必要。これがないと、
Object {error: Object}
error: Object
description: "No definition found for Table yahoo.finance.quotes"
なjsonが返却される。
2.株価のAsk、Bid等、詳細情報が必要な場合は、yahoo.finance.quoteではなく、yahoo.finance.quotesにリクエストを投げる必要がある。
<html> <style> <!-- .ta1 { width: 560px; margin-top:20px; margin-left:50px; margin-bottom:10px; color:#555555; } .ta1 .status { text-align:center; } num { text-align:right; } td { padding:7px 22px; } th { padding:7px 22px; } tr { background-color:#c9eFFF; } tr.even { background-color:#edF9FF; } th { color:#333333; background-color:#5caadb; border-bottom:solid 1px #FFFFFF; } --> </style> <head> <script type="text/javascript" src="http://code.jquery.com/jquery.js"></script> <script type="text/javascript"> $(document).ready(function () { $.getJSON("http://query.yahooapis.com/v1/public/yql?callback=?", { q: "select * from yahoo.finance.quotes where symbol in ('IVV', 'VTI', 'VT', 'VWO')", env: "store://datatables.org/alltableswithkeys", format: "json" }, function (data) { console.log(data); $("#article").append("<table class='ta1' cellspacing='0'> <tr> <th>symbol</th> <th>Ask</th> <th>Bid</th> <th>Change</th> </tr>"); for(var i in data.query.results.quote){ $("#article").append("<tr>" + "<td>"+ data.query.results.quote[i].symbol + "</td>" + "<td class='num'>" + data.query.results.quote[i].Ask + "</td>" + "<td>" + data.query.results.quote[i].Bid + "</td>" + "<td>" + data.query.results.quote[i].Change + "</td>" + "</tr>"); } $("#article").append("</table>"); }); }); function add() { $.ajax({ url: "http://query.yahooapis.com/v1/public/yql", data: { format: "json", env: "store://datatables.org/alltableswithkeys", q: "select * from yahoo.finance.quotes where symbol in ('" + $("#symbol").val() + "')" } }) .then(function(data) { console.log(data); $("#article").append("<tr>" + "<td>"+ data.query.results.quote.symbol + "</td>" + "<td class='num'>" + data.query.results.quote.Ask + "</td>" + "<td>" + data.query.results.quote.Bid + "</td>" + "<td>" + data.query.results.quote.Change + "</td>" + "</tr>"); }); } </script> </head> <body> <div id="container"> <h1>Viva Index</h1> <div id="article"></div> </div> symbol <input id="symbol" type="text" value="GOOG" /> <input type="button" value="add" onClick="add()" /> </body> </html>
次回はAndroidアプリを作る予定。