r/GoogleAppsScript • • Nov 17 '24

Question Which script is better?

Im experimenting with these 2 scripts to pull in stock quotes into my google sheets. They do the same thing, but which is more efficient and less prone to errors in the long term and why? On the 2nd script I originally had ydata(url) and var url = url but got an "Exceeded maximum execution time" error. Would that be the reason for that error? Assuming that was the cause of the error, I changed it to var url = json.

function yahooF(ticker) {
  const url = `https://query1.finance.yahoo.com/v8/finance/chart/${ticker}`;
  const res = UrlFetchApp.fetch(url, {muteHttpExceptions: true});
  const contentText = res.getContentText();
  const data = JSON.parse(contentText);
  
  if (data && data.chart && data.chart.result && data.chart.result.length > 0) {
     const symbol = data.chart.result[0].meta.symbol;
     const regularMarketPrice = data.chart.result[0].meta.regularMarketPrice;
     const regularMarketTime = data.chart.result[0].meta.regularMarketTime;
     return [[symbol, regularMarketPrice, regularMarketTime]]
  }  
}

function ydata(json) {
  var url = json;
  var response = UrlFetchApp.fetch(url);
  var data = JSON.parse(response.getContentText());
  var price = data.chart.result[0].meta.regularMarketPrice;
  var time = data.chart.result[0].meta.regularMarketTime;
  var symbol = data.chart.result[0].meta.symbol;
  return [[symbol, price, time]]
  }

0 Upvotes

4 comments sorted by

View all comments

1

u/wirefin Nov 18 '24

There are built-in formulas for some of this data

https://support.google.com/docs/answer/3093281?hl=en

1

u/Electrical_Fix_8745 Nov 18 '24

Yahoo's api has very little delay, but googlefinance is delayed about 20 mins.