Skip to content

Instantly share code, notes, and snippets.

@mcolyer
Created May 31, 2014 14:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcolyer/5c1dc750472d5f1659df to your computer and use it in GitHub Desktop.
Save mcolyer/5c1dc750472d5f1659df to your computer and use it in GitHub Desktop.
My function for Google App Script to grab tickers
function updateClosingPrice() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var positions = spreadsheet.getRangeByName('positions')
var values = positions.getValues();
var numRows = positions.getNumRows();
// Collect all of the symbols
var symbols = [];
for (var i = 0; i <= numRows - 1; i++) {
var row = values[i];
if (row[1] != 'Stock') continue;
var stockSymbol = row[2];
symbols.push('"'+stockSymbol+'"');
}
// Fetch the data
var params = [
'format=json',
'q='+encodeURIComponent('select symbol,Change,LastTradePriceOnly from yahoo.finance.quotes where symbol in ('+symbols.join(',')+')'),
'env='+encodeURIComponent('store://datatables.org/alltableswithkeys'),
]
var url = "http://query.yahooapis.com/v1/public/yql?"+params.join('&');
var response = JSON.parse(UrlFetchApp.fetch(url).getContentText()).query.results.quote;
// Turn it into a map
symbols = {};
for (var i = 0; i < response.length; i++) {
var data = response[i];
data.Change = data.Change.replace('+','');
symbols[data.symbol] = data;
}
// Update the spreadsheet
for (var i = 0; i <= numRows - 1; i++) {
var row = values[i];
if (row[1] != 'Stock') continue;
var stockSymbol = row[2];
var stockInfo = symbols[stockSymbol];
Logger.log('Updating price of ('+stockSymbol+') from ' + row[7] + ' to '+stockInfo.LastTradePriceOnly);
spreadsheet.getRange('positions').getCell(i+1, 8).setValue(stockInfo.LastTradePriceOnly);
Logger.log('Updating change of ('+stockSymbol+') from ' + row[9] + ' to '+stockInfo.Change);
spreadsheet.getRange('positions').getCell(i+1, 10).setValue(stockInfo.Change);
}
}
@seancolyer
Copy link

if github only let me leave inline gist comments, I could nitpick about missing a ; on L3 :) nice work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment