-
-
Save daverich204/a9351caa678a96dd5eaccf048942890a to your computer and use it in GitHub Desktop.
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); | |
// Check if the result exists and has data | |
if (data && data.chart && data.chart.result && data.chart.result.length > 0) { | |
const regularMarketPrice = data.chart.result[0].meta.regularMarketPrice; | |
console.log(regularMarketPrice); | |
return regularMarketPrice; | |
} else { | |
console.log("Error: Unable to retrieve market price."); | |
return null; | |
} | |
} |
Thanks for this updated function. It used to run great, but lately it gives this error many many times:
SyntaxError: Unexpected token 'E', "Edge: Not Found" is not valid JSON
in this line:
const data = JSON.parse(contentText);
It seems like yahoo are fighting against this script.
Thanks for this updated function. It used to run great, but lately it gives this error many many times: SyntaxError: Unexpected token 'E', "Edge: Not Found" is not valid JSON in this line: const data = JSON.parse(contentText);
It seems like yahoo are fighting against this script.
Same problem here. As a workaround I replaced the line
const data = JSON.parse(contentText);
by this block of code:
data = null;
try {
data = JSON.parse(contentText);
} catch (error) {
return yahooF(ticker)
}
So basically that makes the function recursive until the JSON.parse succeeds.
Thanks for getting back. That's a bummer that this field is not available via the API. Previously I and many others were using a regex pattern to grab various fields and it suddenly broke. I think going forward the API implementation is much more reliable, here's hoping they'll add more fields if enough people request.