Skip to content

Instantly share code, notes, and snippets.

@weihsiu weihsiu/tw-stock.js
Created Mar 25, 2009

Embed
What would you like to do?
CmdUtils.CreateCommand({
name: "tw-stock",
author: { name: "Walter Chang", email: "weihsiu@gmail.com" },
license: "Creative Commons 3.0 (by nc)",
description: "Quote a stock symbol from Taiwan Stock Exchange",
takes: {"stock symbol": noun_arb_text},
preview: function(pblock, what) {
var msg = 'Gets stock quote for "${stockSymbol}"';
var subs = { stockSymbol: what.text };
pblock.innerHTML = CmdUtils.renderTemplate(msg, subs);
},
execute: function(what) {
this._queryQuote(what.text);
},
_queryQuote: function(stockSymbol) {
function plus(n) { return n > 0 ? "+" : ""; }
jQuery.get("http://tw.stock.yahoo.com/q/q", { s: stockSymbol }, function(content) {
var regexps = [new RegExp('\s*<td align="center" bgcolor="#FFFfff" nowrap><b>(.+)</b></td>\s*'),
new RegExp('\s*<td align="center" bgcolor="#FFFfff" nowrap>([^:]+)</td>\s*')];
var items = [];
var lines = content.split("\n");
for (var i in lines) {
for (var j in regexps) {
var matches = regexps[j].exec(lines[i]);
if (matches != null) {
items.push(matches[1]);
break;
}
}
}
if (items.length == 0)
displayMessage("Invalid stock symbol: " + stockSymbol);
else {
var msg = "${stockSymbol}: ${quote} ${diff} ${percentage}%"
var quote = parseFloat(items[0]);
var oldQuote = parseFloat(items[4]);
var diff = quote - oldQuote;
var percentage = diff / oldQuote * 100;
var subs = { stockSymbol: stockSymbol, quote: quote.toFixed(2), diff: plus(diff) + diff.toFixed(2), percentage: plus(percentage) + percentage.toFixed(2) };
displayMessage(CmdUtils.renderTemplate(msg, subs));
}
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.