Skip to content

Instantly share code, notes, and snippets.

@venkatd
Created November 23, 2012 01:57
Show Gist options
  • Save venkatd/4133679 to your computer and use it in GitHub Desktop.
Save venkatd/4133679 to your computer and use it in GitHub Desktop.
Easy way to fetch stock quotes from Yahoo Finance using YQL
AAPL: $<span class="stock-quote" data-value="AAPL"></span>
<br/>
MSFT: $<span class="stock-quote" data-value="MSFT"></span>
<br/>
GE: $<span class="stock-quote" data-value="GE"></span>
(function($) {
var getStockQuotesQuery = function(tickers) {
return "select * from yahoo.finance.quotes" + " where symbol IN ('" + tickers.join("', '") + "')";
};
var processStockQuotesResponse = function(response) {
var quotes = {};
if (!$.isArray(response.query.results.quote)) response.query.results.quote = [response.query.results.quote];
$.each(response.query.results.quote, function(index, quote) {
quotes[quote.symbol] = quote;
});
return quotes;
};
var getStockQuotes = function(tickers) {
var url = 'http://query.yahooapis.com/v1/public/yql';
var d = $.Deferred();
$.ajax({
dataType: 'jsonp',
type: 'GET',
url: url,
data: {
q: getStockQuotesQuery(tickers),
env: 'store://datatables.org/alltableswithkeys',
format: 'json'
},
success: function(response) {
var quotes = processStockQuotesResponse(response);
d.resolve(quotes);
},
failure: function(response) {
d.reject();
}
});
return d;
}
window.getStockQuotes = getStockQuotes;
})(jQuery);
(function($) {
var stockSymbolsOnPage = function() {
var symbols = [];
$('.stock-quote').each(function() {
var value = $(this).data('value');
var symbol = value.split('.')[0];
symbols.push(symbol);
});
return symbols;
};
var stockQuotesOnPage = function() {
return getStockQuotes(stockSymbolsOnPage());
};
var updateStockQuoteForElement = function(element, quotes) {
var value = $(element).data('value');
var symbol = value.split('.')[0];
var property = value.split('.')[1] || 'AskRealtime';
$(element).text(quotes[symbol][property]);
};
var updateStockQuotesOnPage = function(quotes) {
console.log(quotes);
$('.stock-quote').each(function() {
updateStockQuoteForElement(this, quotes);
});
};
var refreshStockQuotesOnPage = function() {
$.when(stockQuotesOnPage()).then(function(quotes) {
updateStockQuotesOnPage(quotes);
});
};
window.refreshStockQuotesOnPage = refreshStockQuotesOnPage;
})(jQuery);
jQuery(function($) {
var refreshTimeInSeconds = 60;
setInterval(refreshStockQuotesOnPage, refreshTimeInSeconds * 1000);
refreshStockQuotesOnPage();
});​
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment