Skip to content

Instantly share code, notes, and snippets.

@daverich204
Created April 16, 2024 01:58
Show Gist options
  • Save daverich204/a9351caa678a96dd5eaccf048942890a to your computer and use it in GitHub Desktop.
Save daverich204/a9351caa678a96dd5eaccf048942890a to your computer and use it in GitHub Desktop.
Yahoo Finance Api V8 Example Google App Script
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;
}
}
@Optimolachi
Copy link

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.

@orior1
Copy link

orior1 commented Oct 9, 2024

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.

@LucDeBatselier
Copy link

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.

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