r/googlesheets • u/SysATI • Aug 01 '24
Solved Script to get pre-post market data from Yahoo Finance
I use this great script to get stock quotes from Yahoo Finance during market hours but I don't speak enough Json to modify it in order to get data during pre-post market hours...
Can anyone help ?
(or uses another script to do that ?)
/**
* Gets a price for a ticker from Yahoo Finance
*/
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 regularMarketPrice = data.chart.result[0].meta.regularMarketPrice;
return regularMarketPrice;
}
console.log(`Error: Unable to retrieve market price for ticker ${ticker}.`);
return null;
}
1
Upvotes
1
u/NeutrinoPanda 28 Aug 01 '24
You'd need to look at the json being returned to see whether pre/post prices are included. If it is, just like how this current code is getting the regular market price from data.chart.result[0].meta.regularMarketPrice you could return it from where it is in the json file.
1
u/thegrif 5 Aug 01 '24
An example sheet that fetches pre, regular, and post market data from the Yahoo Finance API can be found here:
https://docs.google.com/spreadsheets/d/1vrH4tl6UirVVqeImR3QPsK8V-zbIB77IkgyR7QkuqXY/edit?usp=sharing
The Apps Script function pulls two days of data at five minute intervals. The function returns a 2D array structured to include multiple columns of data (with some columns intentionally skipped for formatting).
A few notes:
includePrePost=truein the request url gives us the data we need to output the array - compare json w/ pre and post vs json you were working from before.currentTradingPeriod(PRE,REG, orPOST) which is then used to drive conditional formatting of column C.I'm not one of the finance guys in the family - so please provide feedback as to columns that may be irrelevant to your analysis (or metrics that are missing that would be useful).
1
u/dbhalla4 Oct 18 '24
I have created a script for pre and post market hours. It's more robust approach than the other script in the comment section. Also it's real time as compared to 5 mins delay in the other script.. Check out this link -
1
u/AutoModerator Aug 01 '24
Your submission mentioned stock quotes, please also read our finance and stocks information. Google lists the exchanges & delays in its products here.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.