Skip to content

Instantly share code, notes, and snippets.

@andcl
Last active May 3, 2025 22:52
Show Gist options
  • Save andcl/11c71cc34d2ce3484c805f1a42b6ef58 to your computer and use it in GitHub Desktop.
Save andcl/11c71cc34d2ce3484c805f1a42b6ef58 to your computer and use it in GitHub Desktop.
Google Sheets Apps Script for getting the Net Asset Value (NAV) of any instrument by (ISIN, date) using the Yahoo Finance API
function getFundNAV(isin, date) {
// 0. Initial date validation
const targetDate = new Date(date);
if (isNaN(targetDate.getTime())) return 'Invalid date';
if (targetDate > new Date()) return 'Date is in the future';
// 1. Get Yahoo Finance symbol from ISIN
const searchUrl = `https://query2.finance.yahoo.com/v1/finance/search?q=${isin}`;
const searchResp = UrlFetchApp.fetch(searchUrl);
const searchData = JSON.parse(searchResp.getContentText());
const symbol = searchData.quotes?.[0]?.symbol;
if (!symbol) return 'No Yahoo Finance symbol found for the provided ISIN';
// 2. Convert target date to timestamps (get until 30 days before requested date)
const to_date = Math.floor(targetDate.getTime() / 1000) + 86400;
const from_date = to_date - 86400 * 30;
// 3. Retrieve historical NAV data from Yahoo Finance
const chartUrl = `https://query2.finance.yahoo.com/v8/finance/chart/${symbol}?period1=${from_date}&period2=${to_date}&interval=1d`;
const chartResp = UrlFetchApp.fetch(chartUrl);
const chartData = JSON.parse(chartResp.getContentText());
if (chartData.chart.error) return 'Yahoo Finance error: ' + chartData.chart.error.description;
// 4. Data extraction (timestamps and corresponding NAVs)
const timestamps = chartData.chart.result?.[0]?.timestamp;
const navs = chartData.chart.result?.[0]?.indicators?.quote?.[0]?.close;
if (!timestamps || !navs) return 'Historical NAV data is not available';
// 4. Find most recent NAV on or before the requested date
for (let i = timestamps.length - 1; i >= 0; i--) {
if (timestamps[i] * 1000 <= targetDate.getTime() && navs[i] !== null)
return navs[i];
}
return 'Net Asset Value not found for the requested or previous dates';
}
/* Example API calls (for, e.g., Vanguard S&P 500 ETF):
* https://query2.finance.yahoo.com/v1/finance/search?q=IE00BFMXXD54
* https://query2.finance.yahoo.com/v8/finance/chart/VOO?period1=1745193600&period2=1745280000&interval=1d
*/
/* Example of use in any Google Sheets spreadsheet:
* 1. Extensions > Apps script
* 2. "Add new file" and copy-paste the function
* 3. Back to the spreadsheet, use the function in any cell like '=getFundNAV("IE00BFMXXD54", "2025-04-22")', e.g.,
* to pull the NAV on close time for the Vanguard S&P 500 ETF (ISIN "IE00BFMXXD54") on 2025 Apr 22nd.
* 4. Enjoy ;)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment