Google finance api to excel

Содержание

  1. Функция GOOGLEFINANCE для загрузки котировок акций и курсов валют
  2. Валюты
  3. Акции
  4. Excel: stock prices from Google Finance
  5. Share:
  6. Currency formatting
  7. Query Editor
  8. Finding Stock Codes
  9. GoogleFinance()
  10. How to Visualize Financial Data With Google Finance API, Google Sheets & Tableau
  11. Greg Rossi, Raul Garcia
  12. Analyzing Google Finance with Google Sheets
  13. Build the Tableau Visualization!
  14. Additional Resources
  15. What is Google Finance and Google Finance API?
  16. What is Google Finance API?
  17. How to use Google Sheets with Google Finance?
  18. Live Connect to Google Sheets with Tableau
  19. What’s Next? Embedded Analytics

Функция GOOGLEFINANCE для загрузки котировок акций и курсов валют

Обсудим функцию GOOGLEFINANCE, которая позволяет загружать в Таблицы котировки акций и курсы валют — как в динамике, так и на текущий момент.

Валюты

Для получения биржевого курса достаточно ввести два трехбуквенных кода валют внутри этой функции. Например, “USDRUB”:

USDRUB — текстовое значение, мы указываем его в кавычках внутри функции.

Более наглядно будет указывать коды валют в ячейках и объединять их в такую конструкцию с помощью амперсанда (символа, который соединяет несколько текстовых значений).

Такую функцию можно протянуть и сразу получить результат в нескольких валютных парах.

Объединение кодов валют из ячеек внутри функции GOOGLEFINANCE (BTC — это код биткоина)

Чтобы загрузить курс валюты за определенный период, нужно добавить аргументов — помимо кода валюты, указать второй аргумент “PRICE” и даты начала и окончания периода (третий и четвертый аргументы):

Или сослаться на ячейки с кодами валют и датами:

Получили информацию о курсе валюты за длительный период. Формат вывода результатов — два столбца, с датой и курсом.

Отметим, что график (спарклайн) в ячейке C2 сформирован с помощью функции SPARKLINE, которую мы будем обсуждать позднее в курсе. Здесь график добавлен для наглядности.

Акции

Для получения информации об акциях нужно использовать вместо двух кодов валют тикер, четырехбуквенный код — например, AAPL для акций компании Apple.

В случае с акциями функция может загрузить большое количество параметров — цену открытия, цену закрытия, самую низкую или высокую цену за день, объем торгов, капитализацию компании и много других — все они перечислены в справке.

Тикер указывается в первом аргументе функции. Параметр указывается во втором аргументе функции.

Соответственно, следующая функция

Будет возвращать объемы торгов акциями Apple с первого января 2017 по 1 февраля 2019 года.

Все аргументы — тикер, параметры и даты — можно указывать как в самой функции, так и в ячейках, на которые вы будете из функции ссылаться.

В следующем примере мы получаем максимальные цены дня по Apple за период с 1 января 2014 по 19 февраля 2019 года. Все параметры мы получаем из ячеек, на которые ссылаемся из функции:

Загружаем максимальные цены (high) по акциям с помощью GOOGLEFINANCE

Источник

Excel: stock prices from Google Finance

Here’s another method of getting stock prices into Excel. It’s part of a series: introduction and using MSN Money in Excel.

This time we’ll use the improved Query system in recent versions of Excel combined with data from Google Finance.

It’s a sad indictment of Microsoft Office that the best place to get stock data is Google.

Google’s version of Excel is Sheets and that has a nifty function that grabs stock prices right into the worksheet. Once you get the data into a Google Sheet, it can be automatically exported and grabbed by Excel.

It’s an indirect method but effective. Google’s GoogleFinance() function returns a lot of information about many global stocks and indexes. 18 different ‘attributes’ for each stock or index – too many to show in a single screen image (they’re listed later in this article).

To make this work, create a new Google Sheets from the online service (not the downloadable software). Go to Google Drive and make a new sheet.

Add to the sheet codes you want to look up, then a column with calls to GoogleFinance() to lookup those codes. For simplicity we’ll just lookup the price. We’ve added another column with the vital currency detail as well eg GoogleFinance(A3,’currency’)

Sheets works similarly to Excel for these operations. There’s an autocomplete in the function entry line and you can copy then paste to fill cells too.

Extra: you can view only the Sheet that Peter Deegan made for these examples at https://docs.google.com/spreadsheets/d/1ZPfVybR-8HNlo4qXjP14B5guXQiaFuw9iz3xOGgxdgY/edit?usp=sharing It’s a READ ONLY worksheet with editing not available, for obvious reasons. The usual 21 st century disclaimers, use at your own risk etc.

Get full details on stock price integration with Excel in Real-Time Excel – get live stock prices, currency rates and more – less than US$12 or even a measly US$7 for Office-Watch.com subscribers (which is free).

Each column has a standard heading with the GoogleFinance() attribute in the 2 nd row.

Once you have a simple sheet to start with, the next step is to publish it in a form that Excel can understand. Go to File | Publish to the Web

Choose the worksheet/tab you want to publish and select ‘Comma-separated values (.csv)’.

Make sure the ‘Automatically republish when changes are made’ option is on.

Copy the supplied link so you can use it in Excel. The link will download a .csv file with the data from the worksheet cells.

Switch to Excel (in this case Excel 2016 for Windows). Go to Data | New Query | From File | From CSV.

You’ll be presented with a standard File Open dialog but you don’t have to select a saved .csv file. Paste in the link from Google Sheets then click Open.

After a pause, Excel will show you what it’s downloaded and how it suggests dealing with the data. It should do an accurate job dealing with the incoming data.

Click Load and Excel will make a new worksheet for you.

Currency formatting

In the above example, you’ll see that the Sheets column was formatted with the correct symbols for each currency (Sterling and Euro).

Unfortunately, that doesn’t translate correctly. See the Sheets column on left and the Excel version on the right.

The solution is to change Sheets to Number format, with no currency symbols. Do any currency formatting in Excel.

Query Editor

The setup isn’t finished, right click on the query and choose Edit to fix a few things.

Make the first row of data into the column headings.

Change the sort order to put Symbols in alphabetical order. This makes them available for VLOOKUP() searches and a very welcome (ie overdue) inclusion in Excel.

Finally, go to Query | Properties and rename the query to something more helpful than the link text.

Click Close and Load to leave the Query Editor.

Now you have a ‘live’ data worksheet that you can use to lookup prices etc to insert into your own calculations.

Finding Stock Codes

Here’s how to find stock or index codes to use with the GoogleFinance() function.

Search Google Finance for companies across many different markets. The code will be in brackets after the company name.

For US companies, the market prefix (eg NYSE or NASDAQ) isn’t necessary. NYSE:WMT and WMT both work as do NASDAQ:MSFT and MSFT. But you might like to add it anyway, to distinguish the same company being listed on multiple exchanges.

International exchanges are also well represented. The exchange prefix is required.

London:

Frankfurt:

Hong Kong: number codes are used.

GoogleFinance()

If you just want the latest price, simply add the stock code eg GoogleFinance(“MSFT”) or GoogleFinance() function supports the following attributes to use with stock quotes. Use these in the second parameter of the function eg GoogleFinance(“MSFT”,”priceopen”):

  • “price” – Realtime price quote, delayed by up to 20 minutes.
  • “priceopen” – The price as of market open.
  • “high” – The current day’s high price.
  • “low” – The current day’s low price.
  • “volume” – The current day’s trading volume.
  • “marketcap” – The market capitalization of the stock.
  • “tradetime” – The time of the last trade.
  • “datadelay” – How far delayed the realtime data is.
  • “volumeavg” – The average daily trading volume.
  • “pe” – The price/earnings ratio.
  • “eps” – The earnings per share.
  • “high52” – The 52-week high price.
  • “low52” – The 52-week low price.
  • “change” – The price change since the previous trading day’s close.
  • “beta” – The beta value.
  • “changepct” – The percentage change in price since the previous trading day’s close.
  • “closeyest” – The previous day’s closing price.
  • “shares” – The number of outstanding shares.
  • “currency” – The currency in which the security is priced.

Google Finance should have a ‘Long Name’ attribute so you can confirm that the stock code is returning the data you intend. That’s especially true for codes such as the Hong Kong bourse which are numbers, not letters.

The function also supports Mutual Funds and historical data check out the GoogleFinance() help page for full info.

Источник

How to Visualize Financial Data With Google Finance API, Google Sheets & Tableau

Looking for an innovative solution to monitor financial data? Learn how to visualize the data with Google Finance API, Google Sheets, and Tableau 2020.2

Greg Rossi, Raul Garcia

Tableau 2020.2 was a substantial release with new features like Relationships, Metrics, and Set Controls. Personally, until I am presented the opportunity to apply my skills and use these features, it never fully sets in. The below video and corresponding dashboard are just that, a workshop to help learn the new features while also building something useful in the process!

Need help upgrading your Tableau Server to the latest version? Our certified Tableau Server experts can help!

Analyzing Google Finance with Google Sheets

In the following tutorial, you’ll be presented with a tutorial geared toward building a ‘Market Watch’ dashboard with Tableau 2020.2.

You will also learn things like:

  • How to build an automated data pipeline
  • How to use Google Finance API
  • How to build a live data stream with Google Finance API and Google Sheets
  • How to live connect to Google Sheets
  • Tableau 2020.2 features (Relationships, Metrics, Set Controls)
  • Tableau dashboarding tips and tricks

If you successfully complete this tutorial, you will produce something that resembles:

Leverage this tutorial to build your own Market Watch-style dashboard with companies that you care about, and embed it into a web page like above!

Build the Tableau Visualization!

Additional Resources

  • PPT presentation: https://drive.google.com/file/d/1T7BWCkQV2zsyng2OWn-Yy04iRfhkoY6B/view?usp=sharing
  • Google Finance Data: https://docs.google.com/spreadsheets/d/1hcso8qRQ7JWBcLBPPIosu1Y9iqqfF8HhrsrmogW2iug/edit?usp=sharing
  • Dashboard on Tableau Public: https://public.tableau.com/profile/greg.rossi#!/vizhome/ExampleWorkbook-MarketWatch/MarketWatch

What is Google Finance and Google Finance API?

Part of the Google family of websites, Google Finance debuted in 2006. It competes with many other financial websites, including Yahoo! Finance and MSN Money.

Google Finance is a tool that reflects up-to-date market information and news. It’s implemented with the Google Search engine, so if you look up information like AAPL or Walmart for Apple, you will see an up-to-date stock quote and security data from the past. When you check out one of these stocks, it takes you to the company’s Google Finance page, which provides an overview of the company’s news, finances, and allows you to make comparisons with other commodities.

Even though there are better tools to track security, Google Finance is unique because it is the only one to integrate with Google Sheets. This has become a significant game-changer for both novice and experienced stock traders because the integration is convenient to import and observe stock information in a spreadsheet. Keep in mind that Google Finance sheet integration is only offered in English and not in other languages, so it may not be a good option if you want to do any transaction on European or Asian exchanges.

In a nutshell, Google Finance helps individuals monitor their financial portfolios, provides up to date news, and provides information related to Wall Street.

What is Google Finance API?

An API (Application Programming Interface) is a set of programming code that sends instructions between one software platform to another, parses responses, and queries data. If you combine this with Google Finance, then you definitely got something special.

The Google Finance API allows you to leverage historical securities data from Google Finance so that you can build customized analysis. The Google Finance API exposes a variety of endpoints ranging from public company names/tickers to daily share prices, market capitalization, highs, lows, trading volume, and more! It can even make REST requests and return the desired data in JSON format.

How to use Google Sheets with Google Finance?

To fetch Google Finance Data from the exposed API endpoints and keep the data fresh, you will likely want to leverage Google Sheets. Google Sheets allow you to make direct calls to Google Finance and build a data table from a variety of attributes.

The standard syntax for fetching data will look something like:

GOOGLEFINANCE(«NASDAQ:GOOG», «price», DATE(2014,1,1), DATE(2014,12,31), «DAILY»)

Google does a nice job of explaining the syntax and attributes in this document. By following the above tutorial, you will be provided with some pre-built tables/examples and how to leverage the Google Finance API.

Live Connect to Google Sheets with Tableau

After you have built your finance data table, you can then use Tableau to live connect to the Google Sheets and begin your visual analysis. The live connection will maintain a relative level of freshness and also allow you to publish the dashboard to your Tableau Server or Tableau Public.

What’s Next? Embedded Analytics

Although it was not included in this tutorial, the next practical step after the dashboard has been published would be embedding it into another application or your own application! Don’t miss our tutorial on how to embed a dashboard into a web page!

Источник

Yes. The methods are XMLHTTPRequest, https://msdn.microsoft.com/en-us/library/ms759148%28v=vs.85%29.aspx for getting the response. And parsing JSON with VBA for parsing the response since it is JSON. Simplest method for parsing JSON with VBA is described here Parsing JSON in Excel VBA but there are much more comfortable libraries available with search keywords Excel VBA parse JSON.

Simple example for your use case:

Sub testGetJSON()

 sExchangeCode = "TPE"
 sStockCode = "2330"
 sURL = "https://finance.google.com/finance/info?client=ig&q=" & sExchangeCode & ":" & sStockCode

 Set oXMLHTTP = CreateObject("MSXML2.XMLHTTP")
 oXMLHTTP.Open "GET", sURL, False
 oXMLHTTP.send

 sJSONResp = oXMLHTTP.responseText

 sJSONResp = Mid(sJSONResp, 4, Len(sJSONResp))

 Set oScript = CreateObject("ScriptControl")
 oScript.Language = "jscript"
 oScript.AddCode "function getProperty(jsonObj, propertyName) { return jsonObj[propertyName]; } "

 Set oJSObj = oScript.eval("(" & sJSONResp & ")")

 Set oProp0 = oScript.Run("getProperty", oJSObj, "0")

 sLCur = oProp0.l_cur
 sLT = oProp0.lt

 MsgBox sLT & " : " & sLCur

End Sub

Fetches current or historical securities information from Google Finance.

Sample Usage

GOOGLEFINANCE("NASDAQ:GOOG", "price", DATE(2014,1,1), DATE(2014,12,31), "DAILY")

GOOGLEFINANCE("NASDAQ:GOOG","price",TODAY()-30,TODAY())

GOOGLEFINANCE(A2,A3)

Syntax

GOOGLEFINANCE(ticker, [attribute], [start_date], [end_date|num_days], [interval])

  • ticker — The ticker symbol for the security to consider. It’s mandatory to use both the exchange symbol and ticker symbol for accurate results and to avoid discrepancies. For example, use “NASDAQ:GOOG” instead of “GOOG.”

    • If the exchange symbol is not specified, GOOGLEFINANCE will use its best judgement to choose one for you.

    • Reuters Instrument Codes are no longer supported. Use TSE:123 or ASX:XYZ instead of ticker 123.TO or XYZ.AX.

    • Not all futures are supported at this time.

  • attribute[ OPTIONAL — "price" by default ] — The attribute to fetch about ticker from Google Finance and is required if a date is specified.

    • attribute is one of the following for real-time data:

      • "price" — Real-time price quote, delayed by up to 20 minutes.

      • "priceopen" — The price as of market open.

      • "high" — The current day’s high price.

      • "low" — The current day’s low price.

      • "volume" — The current day’s trading volume.

      • "marketcap" — The market capitalization of the stock.

      • "tradetime" — The time of the last trade.

      • "datadelay" — How far delayed the real-time data is.

      • "volumeavg" — The average daily trading volume.

      • "pe" — The price/earnings ratio.

      • "eps" — The earnings per share.

      • "high52" — The 52-week high price.

      • "low52" — The 52-week low price.

      • "change" — The price change since the previous trading day’s close.

      • "beta" — The beta value.

      • "changepct" — The percentage change in price since the previous trading day’s close.

      • "closeyest" — The previous day’s closing price.

      • "shares" — The number of outstanding shares.

      • "currency" — The currency in which the security is priced. Currencies don’t have trading windows, so open, low, high, and volume won’t return for this argument.

    • attribute is one of the following for historical data:

      • "open" — The opening price for the specified date(s).

      • "close" — The closing price for the specified date(s).

      • "high" — The high price for the specified date(s).

      • "low" — The low price for the specified date(s).

      • "volume" — The volume for the specified date(s).

      • "all" — All of the above.

    • attribute is one of the following for mutual fund data:

      • "closeyest" — The previous day’s closing price.

      • "date" — The date at which the net asset value was reported.

      • "returnytd" — The year-to-date return.

      • "netassets" — The net assets.

      • "change" — The change in the most recently reported net asset value and the one immediately prior.

      • "changepct" — The percentage change in the net asset value.

      • "yieldpct" — The distribution yield, the sum of the prior 12 months’ income distributions (stock dividends and fixed income interest payments) and net asset value gains divided by the previous month’s net asset value number.

      • "returnday" — One-day total return.

      • "return1" — One-week total return.

      • "return4" — Four-week total return.

      • "return13" — Thirteen-week total return.

      • "return52" — Fifty-two-week (annual) total return.

      • "return156" — 156-week (3-year) total return.

      • "return260" — 260-week (5-year) total return.

      • "incomedividend" — The amount of the most recent cash distribution.

      • "incomedividenddate" — The date of the most recent cash distribution.

      • "capitalgain" — The amount of the most recent capital gain distribution.

      • "morningstarrating" — The Morningstar «star» rating.

      • "expenseratio" — The fund’s expense ratio.

  • start_date[ OPTIONAL ] — The start date when fetching historical data.

    • If start_date is specified but end_date|num_days is not, only the single day’s data is returned.
  • end_date|num_days[ OPTIONAL ] — The end date when fetching historical data, or the number of days from start_date for which to return data.

  • interval[ OPTIONAL ] — The frequency of returned data; either «DAILY» or «WEEKLY».

    • interval can alternatively be specified as 1 or 7. Other numeric values are disallowed.

Notes

Usage restrictions: The data is not for financial industry professional use or use by other professionals at non-financial firms (including government entities). Professional use may be subject to additional licensing fees from a third-party data provider.

  • All parameters must be enclosed in quotation marks or be references to cells containing text. 
    Important: A possible exception is when interval is specified as a number and when end_date|num_days is specified as a number of days.

  • Real-time results will be returned as a value within a single cell. Historical data, even for a single day, will be returned as an expanded array with column headers.

  • Some attributes may not yield results for all symbols.

  • If any date parameters are specified, the request is considered historical and only the historical attributes are allowed.
  • GOOGLEFINANCE is only available in English and does not support most international exchanges.

  • Historical data cannot be downloaded or accessed via the Sheets API or Apps Script. If you attempt to do so, you’ll see a #N/A error in place of the values in the corresponding cells of your spreadsheet.

  • Quotes are not sourced from all markets and may be delayed up to 20 minutes. Information is provided ‘as is’ and solely for informational purposes, not for trading purposes or advice.

  • Google treats dates passed into GOOGLEFINANCE as as noon UTC time. Exchanges that close before that time may be shifted by a day.

Examples

Make a copy

Important: Each example is in its own tab.

General usage

Retrieves market information from Google Finance.

Common attributes

Historical market data

Retrieves historical market information based on the specified dates from Google Finance.

Mutual funds

Common attributes for mutual funds.

Currency exchange trends

Creates a chart inside a cell to display the currency exchange trend during the last 30 days, using the retrieving result returns by GoogleFinance.

Was this helpful?

How can we improve it?

Here’s another method of getting stock prices into Excel.  It’s part of a series: introduction and using MSN Money in Excel.

This time we’ll use the improved Query system in recent versions of Excel combined with data from Google Finance.

It’s a sad indictment of Microsoft Office that the best place to get stock data is Google.

Google’s version of Excel is Sheets and that has a nifty function that grabs stock prices right into the worksheet.  Once you get the data into a Google Sheet, it can be automatically exported and grabbed by Excel.

It’s an indirect method but effective.  Google’s GoogleFinance() function returns a lot of information about many global stocks and indexes.    18 different ‘attributes’ for each stock or index – too many to show in a single screen image (they’re listed later in this article).

To make this work, create a new Google Sheets from the online service (not the downloadable software).  Go to Google Drive and make a new sheet.

Add to the sheet codes you want to look up, then a column with calls to GoogleFinance() to lookup those codes.  For simplicity we’ll just lookup the price. We’ve added another column with the vital currency detail as well  eg GoogleFinance(A3,’currency’)

Sheets works similarly to Excel for these operations. There’s an autocomplete in the function entry line and you can copy then paste to fill cells too.

Extra:  you can view only the Sheet that Peter Deegan made for these examples at https://docs.google.com/spreadsheets/d/1ZPfVybR-8HNlo4qXjP14B5guXQiaFuw9iz3xOGgxdgY/edit?usp=sharing  It’s a READ ONLY worksheet with editing not available, for obvious reasons. The usual 21st century disclaimers, use at your own risk etc.

Get full details on stock price integration with Excel in Real-Time Excel – get live stock prices, currency rates and more – less than US$12 or even a measly US$7 for Office-Watch.com subscribers (which is free).

Each column has a standard heading with the GoogleFinance() attribute in the 2nd row.

Once you have a simple sheet to start with, the next step is to publish it in a form that Excel can understand.  Go to File | Publish to the Web

Choose the worksheet/tab you want to publish and select ‘Comma-separated values (.csv)’.

Make sure the ‘Automatically republish when changes are made’ option is on.

Copy the supplied link so you can use it in Excel.  The link will download a .csv file with the data from the worksheet cells.

Switch to Excel (in this case Excel 2016 for Windows).  Go to Data | New Query | From File | From CSV.

You’ll be presented with a standard File Open dialog but you don’t have to select a saved .csv file.  Paste in the link from Google Sheets then click Open.

After a pause, Excel will show you what it’s downloaded and how it suggests dealing with the data. It should do an accurate job dealing with the incoming data.

Click Load and Excel will make a new worksheet for you.

Currency formatting

In the above example, you’ll see that the Sheets column was formatted with the correct symbols for each currency (Sterling and Euro).

Unfortunately, that doesn’t translate correctly.  See the Sheets column on left and the Excel version on the right.

The solution is to change Sheets to Number format, with no currency symbols.  Do any currency formatting in Excel.

Query Editor

The setup isn’t finished, right click on the query and choose Edit to fix a few things.

Make the first row of data into the column headings.

Change the sort order to put Symbols in alphabetical order.  This makes them available for VLOOKUP() searches and a very welcome (ie overdue) inclusion in Excel.

Finally, go to Query | Properties and rename the query to something more helpful than the link text.

Click Close and Load to leave the Query Editor.

Now you have a ‘live’ data worksheet that you can use to lookup prices etc to insert into your own calculations.

Finding Stock Codes

Here’s how to find stock or index codes to use with the GoogleFinance() function.

Search Google Finance for companies across many different markets.  The code will be in brackets after the company name.

For US companies, the market prefix (eg NYSE or NASDAQ) isn’t necessary.  NYSE:WMT and WMT both work as do NASDAQ:MSFT and MSFT.  But you might like to add it anyway, to distinguish the same company being listed on multiple exchanges.

International exchanges are also well represented.  The exchange prefix is required.

London:

Frankfurt:

Hong Kong: number codes are used.

GoogleFinance()

If you just want the latest price, simply add the stock code eg  GoogleFinance(“MSFT”) or GoogleFinance() function supports the following attributes to use with stock quotes.  Use these in the second parameter of the function eg GoogleFinance(“MSFT”,”priceopen”):

  • “price” – Realtime price quote, delayed by up to 20 minutes.
  • “priceopen” – The price as of market open.
  • “high” – The current day’s high price.
  • “low” – The current day’s low price.
  • “volume” – The current day’s trading volume.
  • “marketcap” – The market capitalization of the stock.
  • “tradetime” – The time of the last trade.
  • “datadelay” – How far delayed the realtime data is.
  • “volumeavg” – The average daily trading volume.
  • “pe” – The price/earnings ratio.
  • “eps” – The earnings per share.
  • “high52” – The 52-week high price.
  • “low52” – The 52-week low price.
  • “change” – The price change since the previous trading day’s close.
  • “beta” – The beta value.
  • “changepct” – The percentage change in price since the previous trading day’s close.
  • “closeyest” – The previous day’s closing price.
  • “shares” – The number of outstanding shares.
  • “currency” – The currency in which the security is priced.

Google Finance should have a ‘Long Name’ attribute so you can confirm that the stock code is returning the data you intend.  That’s especially true for codes such as the Hong Kong bourse which are numbers, not letters.

The function also supports Mutual Funds and historical data check out the GoogleFinance() help page for full info.

The GOOGLEFINANCE function allows you to import real-time financial and currency market data straight into Google Sheets. As well as enabling you to track current stocks and shares information, it can also be used to retrieve historical securities data.

This function imports data from the Google Finance web application, which provides daily stock prices, news from the currency and financial markets, and other information on market trends. Google Finance can be accessed from the Google menu like all other Google applications, or simply by searching for a stock on Google, which will bring up the Google Finance information relating to that stock.

If an analyst wants to gather information on a stock, they would usually have to visit a financial market website or database to access a range of information. After carrying out research, the next step is to compile all that relevant stock information into a spreadsheet to prepare it for further number crunching or building financial models.

To do this, the analyst normally has to copy the stock information from the website and paste it into a spreadsheet or use customized scripts to pull in such information. The first approach is cumbersome, unreliable, and definitely not recommended. While the second method is faster, it also has drawbacks. Getting a coder to write a script is expensive and complex, and not very flexible if you need to make changes in the future.

A more reliable and economic alternative to both options is the GOOGLEFINANCE function. If you work with financial market data, this function can save you a serious amount of time, automating data retrieval for you.

Syntax

GOOGLEFINANCE(ticker, [attribute], [start_date], [num_days|end_date], [interval])

  • ticker – This is an abbreviation used to uniquely identify publicly traded securities. It may consist of letters, numbers, or a combination of both. For example, AAPL and MSFT represent the tickers for Apple Inc. and Microsoft Corporation respectively. The ticker will tell the function which stock to provide information on. The exchange that the stock trades on can also be specified, which will help avoid discrepancies. For example, you could type “NASDAQ:AAPL”. Be sure to put quotation marks around the ticker (including the exchange if used).
  • attribute – This is an optional parameter that specifies the type of information GOOGLEFINANCE function should fetch. There are a number of different outputs that are available such as price and earnings per share. Check out the full list below. The attribute input, like the ticker, is processed as text, so you’ll need to put quotation marks (“”) around the attribute you’re asking for. Please note, if you don’t enter any attribute, Google Sheets will retrieve Price information by default.
  • start_date – This is used when accessing historical data on a stock, and it indicates the date from which the historical data needs fetching. This is an optional parameter – if you leave it blank, the function will provide information from today. If you specify the start_date but not the num_days|end_date parameter, then you’ll only receive data for that day.
  • num_days|end_date – This optional parameter, along with the start_date, will indicate the time frame between which Google Sheets should fetch the stock information.
  • interval – This is an optional parameter that indicates the frequency. The two possible inputs are “WEEKLY” and “DAILY”.

Attributes for the GOOGLEFINANCE function

Attribute Description
“price” Stock price. In real-time but with a delay of up to 20 minutes.
“priceopen” Opening price (price at market open).
“high” High price of the current day.
“low” Low price of the current day.
“volume” The trading volume of the current day.
“marketcap” The market capitalization of the stock.
“tradetime” The time of the last trade of the stock.
“datadelay” The delay time for the real-time data.
“volumeavg” The average daily trading volume.
“pe” Price-to-earnings ratio
“eps” Earnings per share
“high52” The highest price in the last 52 weeks.
“low52” The lowest price in the last 52 weeks.
“change” The stock price change since the end of yesterday’s trading.
“beta” The beta value
“changepct” The percentage change in price since the end of yesterday’s trading.
“closeyest” Yesterday’s closing price.
“shares” The number of shares outstanding.
“currency” The currency that the stock is priced in.
Historical attribute Description
“open” Price at market open.
“close” Price at market close.
“high” The high price during the specified time period.
“low” The low price during the specified time period.
“volume” The volume during the specified time period.
“all” Returns all of the above.

For a complete list of all attributes including those for mutual fund data, head to Google’s GOOGLEFINANCE support page.

How to use the GOOGLEFINANCE function

1. Obtain stock information

Syntax: GOOGLEFINANCE(ticker, [attribute])

In the following examples, I have used “AAPL” (Apple Inc.) for the ticker.

Firstly, I visited the Google Finance website, and keyed in “AAPL” in the search box and hit the Enter key.

As a result, you can see all the current stock indicators for Apple Inc.

googlefinance-stock-1

Here’s how that information looks in Google Sheets using the basic version of the function: GOOGLEFINANCE(ticker, [attribute]).

The GOOGLEFINANCE function pulls the corresponding information into the spreadsheet:

googlefinance-ticker-plus-attribute-2

In the example above, I have listed the different attributes I want to look at in column A. I then reference these attributes in the formula, which allows me to quickly go down the list without having to change the formula every time.

Alternatively, I could also hardcode each attribute into the formula, for example by typing =GOOGLEFINANCE(“AAPL”,”Low”) to give me the low price of the day.

googlefinance-function-3

Note that I’ve fixed the location of the ticker reference cell B1 by putting the $ sign in front of the B and the 1 (using the F4 key on your keyboard is a shortcut).

By doing this, you can drag the formula down from cell D4 cell right down to D18, and the formula will keep this reference cell constant. I did not fix the location of the attribute cell, because I want this to change as I go down the list to get all the different attributes.

2. Obtain historical stock information for a single day

Syntax: GOOGLEFINANCE(ticker, [attribute], [start_date])

As listed in the table previously, Google Sheets provides a handful of historic data attributes like “open”, “close”, “high”, “low” etc.

While you could try them individually, I’ll explore the “all” attribute, which provides them all at once.

This will give the following result for the corresponding start_date:

googlefinance-example-4

Notice that the output of this historical attribute is more than one cell.

When calling up historical data, the formula will provide a Date column and an attribute column (in this case, because I used “all” to call up multiple attributes and I got 5 different attribute columns):

=GOOGLEFINANCE(“AAPL”,”all”,DATE(2017,2,27))

Please note: When calling up historical data you might see a #REF! error. This occurs when the GOOGLEFINANCE function encounters cells that already contain data. Here, the function would have to overwrite this data when it outputs its information over multiple cells.

To solve this error, just make sure there are enough empty cells below and beside the cell in which you’re entering the GOOGLEFINANCE formula, so that it has room to output its results over multiple cells.

googlefinance-ref-error-5

The fact that the GOOGLEFINANCE formula fills multiple cells when providing historical information is usually helpful because it adds clarity to the information provided.

Sometimes, however, you may want the formula to only give you a single number.

For example, you might want the highest price of a stock on a given day, without the formula outputting a matrix including the date and the price. In this case, you would combine the GOOGLEFINANCE formula with the INDEX formula:

=INDEX(GOOGLEFINANCE(“AAPL”,”High”,date(2017,2,27)),2,2)

googlefinance-function-6

In this example, I have used the GOOGLEFINANCE formula to give me the highest price of Apple stock on February 27, 2017.

In the above screenshot, you can see that the output of the formula is a 2×2 matrix which gives the date and the high price.

If you want the formula to only give you the high price, without the cells that indicate the date and the headers, you can use the INDEX function and specify that you only want the formula to provide the information in the second row of the second column of the matrix that the GOOGLEFINANCE formula provides.

As you can see, I do this by adding INDEX to the start of the formula and then specifying cell 2,2 as the output I want.

google-finance-7

3. Obtaining historical stock information over a period of time

Syntax: GOOGLEFINANCE(ticker, [attribute], [start_date], [end_date], [interval])

So far I’ve tried fetching the information corresponding to a single day. Can you do so for a period of time? Yes, you certainly can. Here’s an example.

googlefinance-8

The formula I use to do this is:

=GOOGLEFINANCE(“AAPL”,”Price”,date(2016,6,1),date(2016,12,31),”Weekly”)

From here, it’s easy to create a chart of the weekly closing price using the charting function in Google Sheets.

By using the GOOGLEFINANCE formula to call up different attributes over different time periods and intervals, you can create highly customizable data sets and charts that will help you analyze the stock data in many different ways.

googlefinance-example-9

4. Obtain YTD stock information

Another common need for users is to obtain the YTD (Year To Date) stock information. This allows you to see how the stock is performing from the beginning of the year until now. Unfortunately, the only attribute for YTD is returnytd, which can only be applied to mutual fund data. To find the YTD value for your real-time or historical data, we must find an alternative.

Luckily, we can find the YTD of stock by combining two specific formulas in one. Use the following syntax as your reference. Simply substitute the ticker with your own.

=(GOOGLEFINANCE(ticker,”price”)/INDEX(GOOGLEFINANCE(ticker,”close”,”01/01″, today()),2,2))-1

Here I’ve obtained the YTD price for Apple. My formula looks like this:

=(GOOGLEFINANCE(“AAPL”,”price”)/INDEX(GOOGLEFINANCE(“AAPL”,”close”,”01/01″, today()),2,2))-1

GOOGLEFINANCE function YTD

As you can see, by copying and pasting the formula above and substituting the ticker with my chosen stock, I have successfully returned the YTD value.

How to use the GOOGLEFINANCE function for Currency Conversion

Another helpful feature of the GOOGLEFINANCE function is the ability to get live currency conversion rates directly in your spreadsheets.

This can easily be done by replacing the stock ticker with “Currency:currency1currency2”, where currency1 and currency2 are the three-letter codes for the currencies you want to convert.

For example, to find the conversion rate between U.S dollars and Canadian dollars, I do the following:

=GOOGLEFINANCE(“CURRENCY:USDCAD”)

googlefinance-example-10

Googlefinance and Wisesheets

Two downsides of the GOOGLEFINANCE function are the lack of historical stock financials and real-time data. As you have learned, GOOGLEFINANCE is amazing but it does also have its limitations. If you are serious about stock investing and you want to save hours manually copy-pasting stock data the best way to do it is to use GOOGLEFINANCE and Wisesheets together.

With Wisesheets you can get the company’s financials including the income statement, balance sheet, cash flow, and key metrics for 14 different exchanges. It can bring a 20-year coverage quarterly or annually directly on your Excel or Google Sheets spreadsheet in one click.

All you need to do is enter the ticker in the add-on:

Googlefinance and Wisesheets 1

Another option to get the same information but filtered is by using the =WISE() function. All you need is the company ticker, parameter, and the period (year, quarter, or TTM).

You could for example get Apple’s revenue Q1 revenue for 2020 by using the function like this:

=WISE(“AAPL”,”Revenue”,”2020″,”Q1″)

When you use the GOOGLEFINANCE function and Wisesheets together, you can create dynamic stock analysis models and get all the financial data you need immediately.

Googlefinance and Wisesheets 2

Get the add-on here: Wisesheets

Stock reporting in Google Sheets

If you work with stock market and currency data, GOOGLEFINANCE function is a huge time-saver when working in Google Sheets. Experiment with the different attributes and find out what works for you!

Need to collate financial data from multiple Google Sheets into a central file for reporting or analysis? Discover how to merge multiple Google Sheets into one.

Editor’s note: This is a revised version of a previous post that has been updated for accuracy and comprehensiveness.

Понравилась статья? Поделить с друзьями:
  • Google excel что это такое
  • Google excel формула если
  • Google excel форматирование ячеек
  • Google excel формат ячейки
  • Google excel условное форматирование