I have a Google Sheet in which I'm gathering some stock-related data. I'm using the googlefinance() function, among others:
Some formula's I use:
// current price
=if($D$1=true,googlefinance(_ticker(A3),"price"),D3)
// 5 year low
=if($D$1=true, min(index(googlefinance(_ticker(A3), "price", date(year(today()) - 5, month(today()), day(today())), today()), 0, 2)),E3)
// 5 year trend
=if($D$1=true, sparkline(googlefinance(_ticker(A3), "price", today()-1825, today(), "weekly"), {"charttype","line";"linewidth",1;"color","#5f88cc"}), J3)
Since the list is over 1'000 tickers, I used the checkbox in D1 to purposefully activate the formula's using googlefinance() to not get rate limited or have too many Internal Error: xx retuned no result-errors that googlefinance() just happend to randomly generate.
This measure is not enough though. I still get many errors when I'm checking D1, because the sheet is firing somewhat of 1'000 (tickers) x 5 (columns using googlefinance()) = 5'000 queries.
I was wondering if there is no better way. Ideally, I would:
- Call on
googlefinance()for only, say, 10 tickers at a time - This call would be, for instance, every 5 minutes. So the first 10 tickers at 1PM, the second 10 at 1:05PM, the next 1:10PM, etc.
- In an extra column
KI would note the date when for that ticker the data was retrieved - I would only want to retrieve data once per day. I am not interested in intraday changes
- So some script would work its way down the list, filling the next 10 tickers every 5 minutes. Once it's done, it starts from the top, but if the current date equals the "last retrieved" date from column
K, nothing is done.
The problem is that I have no clue on how to do this. In a test, I tried invoking googlefinance() from a Google Apps script underlaying the sheet, but you can only invoke the function from within a cell directly.
I am without ideas not. Does someone know how to do this?
Sample sheet: https://docs.google.com/spreadsheets/d/1_Tl0LK2hvc3GzBLXUtomI-cAuFdOQCj7HxfdnkrStJg/edit#gid=0

Unfortunately, you can not call sheets function inside apps script. You either have to get data from a web API or set formulas to the columns. However, Google's finance API no longer works. The only option is to scrap this site, https://www.google.com/finance/quote, which is difficult. Though you can also use another API like Alpha Vantage.
I will provide an example in the latter option. To counteract rate limitation, as you said, we will update only ten cells. To do that, we will store an index to a cell, I chose C1, don't forget to enter an initial value manually. I assume it is set to 1. When the last cell is updated, it starts from 1 again.
For the clock, set a time based trigger. You can choose the function to run and how frequent it runs. Here are some helpful resources,
You can customize the code as you like. I hope my answer is useful.
Edit:
Code: