Last active
September 3, 2023 12:48
-
-
Save sickmz/04fc2950ea9d4ce0a9efaea941e8bae3 to your computer and use it in GitHub Desktop.
Fetch the price (EU format) of an asset from Yahoo Finance and saved to Google Sheet
This file contains 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
/** | |
* Fetches the price of a financial instrument from Yahoo Finance. | |
* | |
* @param {string} ticker The symbol/ticker of the financial instrument (e.g. "BTC-EUR" or "VWCE.MI"). | |
* @return {string} The price of the financial instrument. | |
* @customfunction | |
*/ | |
function YAHOOFINANCE(ticker) { | |
const url = `https://finance.yahoo.com/quote/${ticker}?p=${ticker}`; | |
const res = UrlFetchApp.fetch(url, { muteHttpExceptions: true }); | |
const contentText = res.getContentText(); | |
const priceMatch = contentText.match(/<fin-streamer(?:.*?)active="">(\d+[,]?[\d\.]+?)<\/fin-streamer>/); | |
if (priceMatch && priceMatch[1]) { | |
const rawPrice = priceMatch[1]; | |
const priceWithPoint = rawPrice.replace(',', '.'); | |
const lastIndex = priceWithPoint.lastIndexOf('.'); | |
const price = priceWithPoint.substring(0, lastIndex) + ',' + priceWithPoint.substring(lastIndex + 1); | |
return price; | |
} else return "Price not found"; | |
} | |
function refreshPrice() { | |
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet(); | |
var sheet = spreadsheet.getSheetByName("Investments"); | |
var cells = [ | |
sheet.getRange("W3"), | |
sheet.getRange("W4"), | |
sheet.getRange("W5") | |
]; | |
var originalFormulas = cells.map(function(cell) { | |
return cell.getFormula(); | |
}); | |
cells.forEach(function(cell) { | |
cell.setFormula(""); | |
}); | |
SpreadsheetApp.flush(); | |
Utilities.sleep(1000); | |
cells.forEach(function(cell, index) { | |
cell.setFormula(originalFormulas[index]); | |
}); | |
} | |
function createTrigger() { | |
ScriptApp.newTrigger("refreshPrice") | |
.timeBased() | |
.everyMinutes(1) | |
.create(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment