Created
April 16, 2024 01:58
-
-
Save daverich204/a9351caa678a96dd5eaccf048942890a to your computer and use it in GitHub Desktop.
Yahoo Finance Api V8 Example Google App Script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.
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
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.