Importing stock price from Yahoo Finance in Google sheets - google-sheets

I'm trying to import some Singapore stock prices from Yahoo finance in my Google sheets. I am using the code
=IMPORTXML("https://finance.yahoo.com/quote/" & A2,"//*[#id='quote-header-info']/div[3]/div[1]/div/span[1]")
and put the ticker in A2. It works for some SGX stocks but not the others. Applying to STI constituents, I got something like
Ticker
Price
D05.SI
28.4
O39.SI
11.61
U11.SI
#N/A
Z74.SI
2.41
J36.SI
#N/A
A17U.SI
3.05
C38U.SI
#N/A
Y92.SI
#N/A
S68.SI
#N/A
C31.SI
3.75
...
...
I have checked that for U11.SI and J36.SI, the XPATH of the price element is the same as for D05.SI. Below is the link to the Google sheet
https://docs.google.com/spreadsheets/d/1Tp9leC43J1W3Jun3Z23K51zmbkZRhPOcM60ffBPOs90/edit?usp=sharing
Could anyone shed some light on what's going wrong here? Thanks!

You can pull in data from Yahoo Finance quite easily using Google Apps Script. In the Apps script, you can define a function to retrieve data from any web page and then parse the HTML output.
function yahooF() {
const ticker = 'AAPL';
const url = `https://finance.yahoo.com/quote/${ticker}?p=${ticker}`;
const res = UrlFetchApp.fetch(url, {muteHttpExceptions: true});
const contentText = res.getContentText();
const price = contentText.match(/<fin-streamer(?:.*?)data-test="qsp-price"(?:.*)>(\d+\.\d+)<\/fin-streamer>/);
console.log(price[1]);
return price[1];
}
In the above snippet, Yahoo Finance's page on Apple's stock is retrieved using UrlFetchApp. The price of the ticker is then extracted using regex and one can get Apple's stock price in a Google sheet by using the defined =yahooF() function.
I explained this more in-depth in an article on Medium.

Related

dividend error on Google Sheets with the function IMPORTXML

I want to get the dividend of companies like ENG.MC or other stock like GSY.TO, but Sheets did not find the dividend.
i put on my Google Sheet:
=IMPORTXML($D$25;D24)
I want the "Forward Dividend & Yield" from Yahoo but i recieved a #N/A
example of the error

importxml & xpath in google sheets

I am trying to get stock info from Yahoo Finance with the function importxml in google sheets. How can I get to the revenue row?
https://finance.yahoo.com/quote/AMZN/financials?p=AMZN
From this page I would like to go down to income statement and get total revenue for the last 3 years.
First I click inspect the page and copy the full xpath. Then I add it to the formula importxml in google sheets:
=IMPORTXML(
"https://finance.yahoo.com/quote/AMZN/financials?p=AMZN";
"/html/body/div[1]/div/div/div[1]/div/div[3]/div[1]/div/div[2]/section/div[3]/div[1]/div/div[2]/div[1]/div[1]/div[2]")
but it says:
#N/A Error - Resource at url not found

Returning value of an item price in google sheets

I'm trying add easy updating prices into a google sheet.
I need the market price from
//*[#id="app"]/div/section[2]/section/div[1]/section[3]/div/section[1]/ul/li[1]/span[2]
https://www.tcgplayer.com/product/242811/pokemon-celebrations-celebrations-elite-trainer-box?Language=English
I need it to display just the one number from the XPath to a cell, and I can't seem to figure out where I am going wrong. I've been using the IMPORTXML function and it won't return a value.
=IMPORTXML(A2,"//*[#id='app']/div/section[2]/section/div[1]/section[3]/div/section[1]/ul/li[1]/span[2]")
where A2 is the URL.
In your situation, it seems that the value of the market price cannot be directly retrieved from the URL of https://www.tcgplayer.com/product/242811/pokemon-celebrations-celebrations-elite-trainer-box?Language=English. But, fortunately, it seems that that value can be directly retrieved from the endpoint of API. So, how about the following sample formula?
Sample formula:
=REGEXEXTRACT(JOIN(",",IMPORTDATA(A1)),"marketPrice:(.+?),")*1
or
=REGEXEXTRACT(QUERY(TRANSPOSE(IMPORTDATA(A1)),"WHERE Col1 matches 'marketPrice.+'"),"marketPrice:(.+)")*1
The cell "A1" has the URL of https://mpapi.tcgplayer.com/v2/product/242811/details.
In the case of https://www.tcgplayer.com/product/242811/pokemon-celebrations-celebrations-elite-trainer-box?Language=English, please use 242811 from the URL to the endpoint of API like https://mpapi.tcgplayer.com/v2/product/242811/details.
Result:
Note:
The value from the URL is JSON data. In this case, the following custom function can be also used. In this case, please copy and paste the following script to the script editor of Spreadsheet and save the script. And please put a custom function of =SAMPLE("url") to a cell.
const SAMPLE = url => JSON.parse(UrlFetchApp.fetch(url).getContentText()).marketPrice;
References:
IMPORTDATA
REGEXEXTRACT
Custom Functions in Google Sheets
it's not possible to scrape JS content into google sheets:

Google Finance Tesco

I am using GoogleFinance() function in Google Sheet for some stocks statistics, but I have problem with some tickers like Tesco (London). If I try GoogleFinance("TSCO", something), I get values of Tractor Supply Company (NASDAQ), because both are TSCO. Is there any possibility, to get Tesco (and other stocks with duplicate tickers)?
Thanks
try:
=IMPORTXML("https://www.marketwatch.com/investing/stock/tsco?countrycode=uk",
"//span[#class='value']")

Import data from yahoo finance to Google sheets [duplicate]

This question already has answers here:
Scraping data to Google Sheets from a website that uses JavaScript
(2 answers)
Closed last month.
I want to import the data from options tab in yahoo finance to my google sheet. It is this tables:
Picture with the table I want to import
First of all, you can see a box with different dates that when you change the date the URL change. The difference between the URLS is that you need to sum to the previous number 604800 and then you get the correct URL.
Well if you use Excel, you can download the data (is in the table 3 the ones I want) without any issue, but you need to be changing the website manually every time that the date change.
So I was thinking to use the ImportXML or ImportHTML of google sheet. For example if you use in the main page: https://finance.yahoo.com/quote/VZ?p=VZ
This formula: =importXML("https://finance.yahoo.com/quote/VZ?p=VZ";"//*[#id='quote-header-info']/div[3]/div[1]/div/span[1]")
You will get the value of the stock in that moment but if you change the website url for the one of the options: =importXML("https://finance.yahoo.com/quote/VZ/options?date=1618531200&p=VZ";"//*[#id='quote-header-info']/div[3]/div[1]/div/span[1]")
You got a NA value... even if the value is there and the HTML code of the website is the same... and this for me does no make sense.
So I do not know how I should do to can download the data from the tab "options", and is frustrating cause it must be possible as it is really "simple" to get it in Excel.
Some suggestion?
I am not sure about that function but I have downloaded historical stock pricing on Yahoo using a script.
function importCSVFromWeb() {
// Provide the full URL of the CSV file.
var csvUrl = "https://query1.finance.yahoo.com/v7/finance/download/MSFT?period1=1577806579&period2=1609428979&interval=1d&events=history&includeAdjustedClose=true";
var csvContent = UrlFetchApp.fetch(csvUrl).getContentText();
var csvData = Utilities.parseCsv(csvContent);
var sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);
}
Here is my sheet after running the script
Many thanks, it worked well. I slightly adapted code to work as a formula:
function importCSVFromWeb( url ) {
// Provide the full URL of the CSV file.
var csvUrl = url; // url example = "https://query1.finance.yahoo.com/v7/finance/download/%5EGSPC?period1=1495670400&period2=1653436800&interval=1wk&events=history&includeAdjustedClose=true"
var csvContent = UrlFetchApp.fetch(csvUrl).getContentText();
var csvData = Utilities.parseCsv(csvContent);
var sheet = SpreadsheetApp.getActiveSheet();
// sheet.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);
return csvData;
}

Resources