Last active
January 23, 2025 19:35
-
-
Save dwightmulcahy/7c18ea00e6f6dc8da52afd7100030a51 to your computer and use it in GitHub Desktop.
Google Sheets appscript to retrieve a stock quote from Yahoo Finance Api V8 with a lot of error recovery and checking
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
| // | |
| // Helper function that retrieves the JSON data from google finance | |
| // and handles all the error processing involved. | |
| // | |
| function getYahooF(symbol, range="1d") { | |
| const baseUrl = "https://query1.finance.yahoo.com/v8/finance/chart/"; | |
| const maxRetries = 5; // Maximum number of retry attempts | |
| let attempt = 0; | |
| while (attempt < maxRetries) { | |
| try { | |
| // Construct the URL for the Yahoo Finance API | |
| const url = `${baseUrl}${encodeURIComponent(symbol)}?interval=1d&range=${range}`; | |
| // Fetch the data from Yahoo Finance | |
| const response = UrlFetchApp.fetch(url, { muteHttpExceptions: true }); | |
| const responseCode = response.getResponseCode(); | |
| // Check if the response code is 200 (OK) | |
| if (responseCode === 200) { | |
| // Parse the JSON response | |
| const json = JSON.parse(response.getContentText()); | |
| const chartData = json.chart; | |
| // Check if the response contains valid chart data | |
| if (!chartData || chartData.error) { | |
| throw new Error("Error in fetching chart data: " + (chartData.error?.description || "Unknown error")); | |
| } | |
| const result = chartData.result; | |
| if (!result || result.length === 0) { | |
| throw new Error("No valid data found for the symbol."); | |
| } | |
| // return the full JSON | |
| return json | |
| } else if (responseCode === 404) { | |
| // Increment the attempt counter and retry | |
| attempt++; | |
| Utilities.sleep(500); // Wait for 1 second before retrying | |
| } else { | |
| // For other HTTP errors, throw an error | |
| throw new Error(`Yahoo Finance API returned status code ${responseCode}`); | |
| } | |
| } catch (error) { | |
| // If we've reached the maximum number of retries, return an error | |
| if (attempt >= maxRetries - 1) { | |
| return `Error: ${error.message}`; | |
| } | |
| attempt++; | |
| Utilities.sleep(500); // Wait for 1/2 second before retrying | |
| } | |
| } | |
| throw new Error(`Max attempts retrieving Yahoo Finance API`) | |
| } | |
| // | |
| // Returns the latest/current stock price | |
| // | |
| function yahooF(ticker) { | |
| data = getYahooF(ticker) | |
| result = data.chart.result[0] | |
| // Extract the closing price from the latest trading day | |
| const closePrices = result.indicators.quote[0].close; | |
| let latestPrice = closePrices ? closePrices[closePrices.length - 1] : null; | |
| // If no closing price is available, try to get the current price | |
| if (latestPrice === null || latestPrice === undefined) { | |
| const meta = result.meta; | |
| latestPrice = meta.regularMarketPrice; | |
| } | |
| // Return the latest price if available, otherwise show an error | |
| return latestPrice !== null ? latestPrice : "No price available"; | |
| } | |
| // | |
| // Returns an array of Hi/Lo for the 52 weeks | |
| // | |
| function getStockHighLow(ticker) { | |
| data = getYahooF(ticker, "52w") | |
| result = data.chart.result[0] | |
| const maxHigh = result.meta.fiftyTwoWeekHigh; | |
| const minLow = result.meta.fiftyTwoWeekLow; | |
| return [maxHigh, minLow]; | |
| } | |
| // TEST FOR THE FUNCTIONS | |
| function test() { | |
| const latestPrice = yahooF("T"); | |
| console.log('Last price = '+latestPrice.toFixed(2)) | |
| const { maxHigh, minLow } = getStockHighLow("T"); | |
| console.log('Max = '+maxHigh+' Low = '+minLow) | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How to Use the Script
=yahooF("AAPL")Replace "AAPL" with the symbol for the stock you want to check.
You can actually use
GOOGLEFINANCE()as a backup if theyahooF()errors for some reason like this: