StockHighandLow2

Add Horizontal Lines to Stock Charts to Identify Min and Max Values in Excel and Google Sheets

If you’re pulling in stock prices into your spreadsheet, you can easily plot those values on a chart. And one way to help visualize the data is to add horizontal lines to help you identify where the maximum and minimum values are. I’ll go over how this can be done in both Excel and Google Sheets.

Pulling in the historical stock prices in Excel and Google Sheets

In Excel, you can use the STOCKHISTORY function to pull in historical stock prices. And in Google Sheets, there’s the GOOGLEFINANCE function. Both are fairly straightforward functions which can extract stock prices going back days, months, and even years.

Below, I’ve pulled Nvidia’s stock price history from Jan 1, 2024 through to Oct 31, 2024, in Excel:

NVDA stock price history in Excel.

And here is the price history in Google Sheets:

NVDA stock price history in Google Sheets.

Calculating the highs and lows

In Google Sheets, you can pull in a stock’s 52-week high and low from right within the GOOGLEFINANCE function. But in this example, I’m going to calculate the minimum and maximum values based on the range that has been downloaded. This will make the chart more dynamic, allowing you to have these values updated based on your range.

In both Excel and Google Sheets, I’ll setup columns for HIGH and LOW. I’ll use the MAX function to get the highest value and the MIN function to get the lowest value. The only argument needed is the column which contains the closing price. The same value needs to be repeated in both of these columns to ensure the line is horizontal.

The formula is exactly the same whether you’re using Excel or Google Sheets. What’s important, however, is to ensure the values are the same all the way down; you’ll want to copy it all the way to the bottom. Here’s how it looks in Excel:

NVDA stock price history in Excel showing highs and lows for a period.

Plotting the values on a chart

Next, with the highs and lows added, it’s just a matter of creating a line chart which shows these values. The default formatting in Excel already does this effectively for me, displaying the high and low ranges:

High and low values plotted on a chart in Excel.

At this stage, it’s just a matter of any additional formatting you may wish to do, such as changing the line colors. I also prefer to make these dotted lines, and this can be done by changing the dash type. Here’s what my finished chart looks like in Excel:

Excel stock chart showing maximum and minimum values.

To format the individual lines, right-click to Format Data Series, where you can then change the color and the dash type. The changes I made above are to change the color to black and the lines to a dash. I have also added vertical gridlines to the chart by going to the Chart Design tab and selecting Add Chart Element and Gridlines and then clicking Primary Major Vertical.

On Google Sheets, the process is largely the same. The main difference is that you need to access the edit chart menu and under the Customize tab, select your options for gridlines, color, and dash type for an individual data series.

Google Sheets stock chart showing maximum and minimum values.

If you like this post on Add Horizontal Lines to Stock Charts to Identify Min and Max Values in Excel and Google Sheets, please give this site a like on Facebook and also be sure to check out some of the many templates that we have available for download. You can also follow me on Twitter and YouTube. Also, please consider buying me a coffee if you find my website helpful and would like to support it.

sddefault (1)

How to Create a Secondary Axis in Google Sheets

If you want to create a chart in Google Sheets that displays different kinds of data, you may benefit from using a secondary axis. If you just use a single axis, that may not be ideal as depending on the scale, your data may not display correctly if the values are either too large or too small for a series.

In the chart below, I have data which shows actual sales numbers along with year-over-year growth rates. They are plotted with just a single axis being used. As you can see, it becomes difficult to see the growth rate because the values are so low.

Chart showing Netflix's sales data and growth rate.

The right line for the growth rate is barely visible at the bottom. Since the growth rate is in percentages, the values will be fairly small (less than one), hence they are only slightly visible. To fix this, I need to adjust the axis the growth rate shows on. Here’s how to put that series on a separate axis:

  • Select the chart, click on the three dots in the right-hand side, and select Edit
  • Click on the Customize tab and go under Series
  • Select the series you want to put onto another axis. In my example, it is the growth rate.
  • At the bottom, change the Axis selection from Left axis to Right axis
Changing a series axis in Google Sheets.

That’s it, now the growth rate shows more clearly and I can see the related axis on the right-hand side of the chart.

Chart showing Netflix's sales data and growth rate with a second axis.

You may also want to display the series differently, such as showing by dashes rather than a straight line, but that is an optional step. To make changes to an individual series, simply select the series as you did when changing the axis, and make changes in that same screen. In the chart below, I’ve simply changed the line so that is shows as a dash:

Chart showing Netflix's sales data and growth rate with a second axis and a dashed line.

For another example of how to add a secondary axis, check out the below video:


If you like this post on How to Create a Secondary Axis in Google Sheets, please give this site a like on Facebook and also be sure to check out some of the many templates that we have available for download. You can also follow me on Twitter and YouTube. Also, please consider buying me a coffee if you find my website helpful and would like to support it.

sddefault (1)

How to Use Compare Mode in Google Sheets

If you’re creating a chart on Google Sheets, there’s a really useful feature you can use which makes it easy to compare values, and that’s compare mode. In this post, I’ll go over how to use compare mode and how it can help you easily compare results in your charts. Here’s a sample data set I’ll use for this example, which shows excerpts from Nvidia’s annual earnings numbers:

Key earnings data from Nvidia.

These figures are all in billions and I’m going to plot them on a simple chart in Google Sheets to help display these values. This what a simple line chart showing these values looks like in Google Sheets:

Line chart in Google Sheets showing Nvidia's financial numbers from the past few years.

While the chart is easy to see, it can be challenging to see what those numbers are without the use of a data table. And using labels would be too cluttered. The best solution here is to use compare mode.

How to turn compare mode on in Google Sheets

To activate compare mode, select the chart in Google Sheets. Then, select Edit Chart and under Customize, select the option for Chart Style and then check off Compare Mode:

Enabling compare mode in Google Sheets.

Now, with compare mode enabled, you can easily see the values for each year. First, click away from the chart and then click back on it, to activate it again. Then, you when you hover over a data point, you will see all that data points which relate to that year:

A Google Sheets chart with compare mode activated.

This saves me the trouble of having to try and estimate what the values are and avoids having to use a data table or labels. And as I hover over different data points, I’ll get the updated values for each year.


If you like this post on How to Use Compare Mode in Google Sheets, please give this site a like on Facebook and also be sure to check out some of the many templates that we have available for download. You can also follow me on Twitter and YouTube. Also, please consider buying me a coffee if you find my website helpful and would like to support it.

sddefault

Quickly Add Rows and Columns in Google Sheets

Google Sheets is a powerful and versatile tool for managing data, whether you’re tracking expenses, analyzing survey results, or organizing information for a project. One of the fundamental skills you need to master is adding rows and columns to your spreadsheet. This guide will walk you through how you can quickly add either rows or columns to provide you with enough room for your data set.

How to Add Several Rows or Columns at Once in Google Sheets

You can add an extra row or column in Google Sheets by just right-clicking on any cell in your spreadsheet and selecting to either Insert 1 Row Above or Insert 1 Column Left:

Menu in Google Sheets to add rows and columns.

Since you’re adding an entire row or column, it doesn’t really matter which cell you select in your spreadsheet. But you might need to add more than just a single column or row. What if you wanted to add 20 columns, or 20 rows? In that case, simply select that many rows or columns and right-click to select whether you want to add columns or rows. In the below example, I’ve selected 20 rows and columns, and now I have the option to add that many as well:

Menu in Google Sheets to add 20 rows and columns.

If you want to add a lot of rows, there is an easier way to do this than selecting how many rows you want to add.

How to Input the Number of Rows You Want to Add

You can specify how many rows you want to add by just going to the bottom of your Google Sheets spreadsheet. By using the shortcut CTRL+DOWN two times, that will get you to the bottom of your sheet and you’ll see an option to enter in the number of rows you want to add:

Input to add more rows in Google Sheets.

Although the default is set to 1,000 you can add more or less than that. But if you specify a large number, it may take some time for those rows to get added.

How to Add Many Columns in Google Sheets

Unfortunately, going to the right-most column of the screen, you don’t get a similar option to specify how many columns to add. This is likely because adding a lot of rows is going to be more common for users than just adding columns; spreadsheets are more often going to be expanding vertically rather than horizontally.

The quickest way to add a lot of columns is to select all your cells using the CTRL+A shortcut and then adding as many columns as you have on your spreadsheet. This will effectively double the number of columns you have. You can repeat these steps to continue doubling until you have enough columns.

Important Note About Large Google Sheets Files

Before you try and create a Google Sheets spreadsheet with 100,000 rows, be careful because you may notice performance issues when your file gets too large. If you have an extremely large data set, you may still be better off using Excel for that purpose as opposed to Google Sheets. Handling large amounts of data isn’t ideal in a Google Sheets spreadsheet as it can take a while to make changes, and that can slow down your machine and the page may even crash.

While Google Sheets can be a great way to share information and data between users, I wouldn’t suggest trying to use it as a replacement for Excel, especially if you work with significantly large data sets (e.g. tens of thousands of rows long). It may work depending on the complexity of your file but you may want to test out the performance before relying on Google Sheets entirely.


If you like this post on How to Quickly Add Rows and Columns in Google Sheets, please give this site a like on Facebook and also be sure to check out some of the many templates that we have available for download. You can also follow me on Twitter and YouTube. Also, please consider buying me a coffee if you find my website helpful and would like to support it.

sddefault

Create an Automatically Updating Pivot Table in Google Sheets

Did you know you can create a pivot table in Google Sheets which automatically updates as you add data to it? Remarkably, it’s an easier process than in Excel where you would need a macro or where you might need to right-click on the pivot table and select to refresh the data. Here’s how we can go about creating a pivot table in Google Sheets, and having it automatically update.

Creating a pivot table in Google Sheets

For this example, I’m going to use the following data for my pivot table:

A table in Google Sheets.

To create a pivot table with this range, all I need to do is, with a cell selected, to go to the Insert menu and click on Pivot Table

Inserting a pivot table in Google Sheets.

As long as you have a cell selected on your data set, Google Sheets will automatically detect your range. If it looks correct, you can just select whether you want it to be placed in a new sheet or an existing sheet, and then click on Create.

Selecting where to create a pivot table.

The next part is to setup the pivot table and ensure that the value section contains values and you have something in either the rows, columns, or filters sections to summarize your data. In my example, I’m going to summarize my data by rep and store:

A pivot table in Google Sheets.

The pivot table is setup but the problem is it won’t automatically update. Here’s how we can fix that.

Setting up your pivot table so that it automatically updates in Google Sheets

The problem with this pivot table lies with the range. While Google Sheets correctly detected a range, it also set it to a specific number of rows. My data set went up to row 201 as it contained 200 rows of data. But if I add more data, my pivot table won’t automatically expand. To get around this, I need to adjust my pivot table range.

With my pivot table selected, I can see the range that it references in the Pivot table editor pane:

The pivot table editor pane in Google Sheets.

If I add another row of data, I can adjust this range so that it goes from A1:G202. But this would be a very tedious task if every time I added data I needed to remember to adjust the range. Instead, what I can do is adjust my range so that it references entire columns. By doing this, Google Sheets will automatically detect the size of my data set. In this example, I just need to set my range to A:G:

Changing the range in the pivot table editor.

Now my pivot table will include a blank value under the Salesperson field as well as a blank store value.

A pivot table in Google Sheets which includes entire columns.

To fix this, what I can do is hide row 3 and column B, since these ranges contain the blanks. And as long as the blank values always appear first, this can be an effective way to hide the data, even if the pivot table expands.

A pivot table with the empty rows and columns hidden.

If you like this post on How to Create an Automatically Updating Pivot Table in Google Sheets, please give this site a like on Facebook and also be sure to check out some of the many templates that we have available for download. You can also follow me on Twitter and YouTube. Also, please consider buying me a coffee if you find my website helpful and would like to support it.

heat map

Create a Heat Map in Google Sheets

Heat maps are visual representations of data where individual values are represented by colors. They are particularly useful for identifying patterns, trends, and outliers in large data sets at a glance. By using a spectrum of colors, typically ranging from cool (blue) to warm (red), heat maps make it easy to see which values are higher or lower, helping users quickly understand the data’s distribution and key insights.

Why heat maps are useful

  1. Visual Clarity: Heat maps turn complex data sets into easy-to-understand visual formats.
  2. Quick Analysis: They allow for the rapid identification of trends, patterns, and outliers.
  3. Enhanced Decision Making: By highlighting critical data points, heat maps aid in making informed business decisions.
  4. Comparative Insights: They facilitate the comparison of different data points within a set.

How to create heat maps in Google Sheets

Follow these steps to create a heat map in Google Sheets:

Step 1: Prepare Your Data

Ensure your data is organized in a clear and structured manner. Each column should represent a different variable, and each row should represent a different observation or data point. You should give Google Sheets enough data so that it can determine the location for your data points. In the example below, I have U.S. states listed in column A and values in column B. Since I’ve labeled column A as ‘State’ that gives Google Sheets sufficient information to map the data points. If I had a list of countries, then I would label the header as ‘Country.’

Table of values in Google Sheets.

Step 2: Insert the chart

Select any data point on your table and on the Insert menu, select Chart. Google Sheets will create a default chart but you can change it by selecting the Chart Type and then selecting Geo Chart from the Map section.

Selecting a geo chart in Google Sheets.

Step 3: Select the correct map

When the map chart is created, it may not automatically detect the correct area. In my example, it selects the entire world.

Map chart in Google Sheets showing the entire world.

The chart looks incorrect as nothing is filled in, but this is because I’m at too high of a level to see the values. I need to adjust my chart to focus just on the United States. To fix this, edit the chart and under the Customize tab, select the Geo settings and change the region to United States.

Selecting the region settings in Google Sheets.

You can adjust the range per your individual data set. But in this example, since my data has U.S. states only, then I need to select the United States. And once I do so, now my chart is filled in:

Map chart showing values for the United States.

Step 4: Adjust the color scales

By default, the chart shows green and red colors for high and low values, respectively. I can customize this in the Geo section as well. You can modify this so that blue colors are for the low values, green for the maximum values, and yellow for the mid-range values:

Modifying the colors on the heat map in Google Sheets.

Step 5: Modify other chart settings

The last step is, as with any other chart, modifying the font, background color, border color, and any other settings for the chart. These can also be changed in the Customize section of the chart settings.

Modifying the chart settings in Google Sheets.

Once you’re done, the heat map chart is ready to go:

A heat map chart in Google Sheets.

If you like this post on How to Create a Heat Map in Google Sheets, please give this site a like on Facebook and also be sure to check out some of the many templates that we have available for download. You can also follow me on Twitter and YouTube. Also, please consider buying me a coffee if you find my website helpful and would like to support it.

MensOlympicFootball

Free Men’s Olympic Football Prediction Template for Paris 2024

The Paris Olympics are taking place next month, and one of the more popular tournaments is likely to be the men’s football competition, which will include 2022 World Cup finalists France and Argentina. I have created a template in Google Sheets which will help track the tournament and allow you to make predictions with others.

Tracking matches in the template

On the main page of the template, there is a tab for Actuals where you can enter the actual results as they occur. And based on those results, the tables will automatically populate, to determine which teams will play one another in the knockout stages.

Men's 2024 olympic football match schedule.

You can also highlight countries you want to track by specify the name of country under the watchlist section below. There is also a space to adjust the time based on your time zone. In the example below, the match times are adjusted based on GMT-4. I have also chosen to highlight all the matches where either France or Argentina play.

Men's 2024 olympic football match schedule adjusted to GMT-4 settings.

Making predictions in the template

In addition to tracking the matches and results, you can also make predictions with your friends. There are five predictions tabs in the file. The tabs are the same as the actual tab. The one difference is that there is column for prediction points earned. The prediction results will compare to the actuals to determine if a result was correct and if so, the number of points that someone should have earned from that prediction.

You can adjust the points someone will earn by making changes to the scoring rules tab. Here are the default rules that are in the sheet:

Scoring rules for the Men's 2024 olympic football match template.

Points can be earned for determining the correct number of goals, the right result, score, and even if the teams were correctly predicted to be in the correct elimination stage.

To track how all the players are doing, update the scoring results tab with the name of the players — this should match the individual tabs. If you rename Player1, Player2, etc, then be sure to adjust the names on the scoring results tab. If you need more players, you can copy one of the existing player tabs.

Player standings in the prediction tab.

Try the template!

This template is available for free and you can access it by clicking on this link. It will create a copy of the file which you can then use.


If you like this free template for the Men’s Olympic Football Tournament for Paris 2024, please give this site a like on Facebook and also be sure to check out some of the many templates that we have available for download. You can also follow me on Twitter and YouTube. Also, please consider buying me a coffee if you find my website helpful and would like to support it.

MapCharts2

Creating a Map Chart in Excel and Google Sheets

If you have sales data organized by country, you can create map charts in both Excel and Google sheets. These charts can make it easy to visualize sales and identify patterns and trends. Below, I will compare the different ways to create map charts in Excel and Google Sheets, and highlight any similarities and differences.

For this example, I’m going to use a data set which just includes two fields, one for the country and one for the sales data.

Sales data by country.

Creating a map chart in Excel

To create a map chart in Excel, all you need to do is click anywhere on your data set and insert a chart. Excel will likely automatically detect the data and recommend a Filled Map as an option. But if it doesn’t, you can select a Map option under the All Charts tab:

Selecting a filled map chart in Excel.

You’ll now have a chart that displays the values based on a color scale. In this example, the larger values are in a darker shade of blue whereas the smaller values are in light blue. And if there is no data, the countries are filled in grey.

A map chart in Excel.

As with other Excel charts, you can specify a different color scheme and chart layout. In the chart below, I’ve used a theme which has a black background.

A map chart in Excel with a black background.

By using the dark theme, it makes it easier to focus on areas where there is data, as those countries stand out more prominently. You can also manually adjust the color scheme for the chart by formatting the data series. To do so, right-click on the chart, select Format Data Series and under the option for Series Color, you can specify a 3-color range. And you can adjust what the minimum, midpoint, and maximum values should look like. This logic is similar to how you might set up conditional formatting rules in Excel.

Formatting a data series in a map chart in Excel.

With more colors, readers can now see more variation in visualization.

Map chart showing three different colors.

Creating a map chart in Google Sheets

To create a map chart in Google Sheets, the process is comparable to Excel’s. Simply select a cell on your data set and when you create a chart, select the option for Geo Chart under the Map section

Selecting a Geo chart in Google Sheets.

The result is similar to Excel, with the countries being shaded based on their values:

A map chart in Google Sheets.

Under the Customize section of the chart settings, you can specify what the max, min, mid values should look like. In addition, you can specify how countries without values should be displayed.

In Google Sheets, you also have a bit more flexibility in how to zoom in on data. In the region drop down, you can specify whether you want to look at the entire world, or narrow in on specific continents.

Customizing a map chart in Google Sheets.

If I select North America, then I will only get a view of that continent, even if there is data for other countries.

A map chart in Google Sheets focusing on North America.

Google Sheets also allows you to create a Geo chart with markers, which is a bit similar but the difference is the countries are not filled in. Instead, there are circles representing the values.

A geo chart in Google Sheets using markers.

With this type of chart, you can add another field to track the size of the circles. In the following data table, I also have a field for the average sale price.

Table showing sales and average sale price by country.

The average sale prices are highest in North America and smallest in Asia, and that is visually represented in the chart below. In addition to having the colors indicating the overall sales values, I can compare the average prices by looking at the size of the circles.

A geo chart in Google Sheets using markers.

Overall, creating map charts is easy whether you’re making them in Excel or Google Sheets. In Google Sheets, however, there is some added flexibility, and the ability to use markers allows you to utilize an additional field in map charts.


If you like this post on Creating Map Charts in Excel and Google Sheets, please give this site a like on Facebook and also be sure to check out some of the many templates that we have available for download. You can also follow me on Twitter and YouTube. Also, please consider buying me a coffee if you find my website helpful and would like to support it.

TrackStocksinGoogleSheets v1

How to Track Hundreds of Stocks in Google Sheets

Google Sheets makes it easy to pull in data from the internet, including stock prices. An advantage it has over Excel’s StockHistory function is that it can pull prices even before the trading day has finished. This gives users access to more up-to-date information. Plus, it’s easy to track not just one or two stock prices in Google Sheets but even hundreds.

How to pull in a stock price for a ticker symbol in Google Sheets

Using the GOOGLEFINANCE function, you can quickly pull in a stock price easily. Here are the main components of the function:

  • Ticker
  • Attribute. Below are the attributes you can use for stocks:
    • “price”: current price, up to 20 minutes delayed.
    • “priceopen”: the opening price.
    • “high”: the current day high.
    • “low”: the current day low.
    • “volume”: the current day’s volume.
    • “marketcap”: the stock’s current market cap.
    • “tradetime”: the time the last trade was made.
    • “datadelay”: how delayed the real-time data is.
    • “volumeavg”: the stock’s average trading volume.
    • “pe”: the price-to-earnings ratio.
    • “eps”: the most recent earnings per share.
    • “high52”: the stock’s 52-week high.
    • “low52′: the stock’s 52-week low.
    • “change”: the change in stock price from the previous day’s close.
    • “changepct”: the percentage change in price from the previous day’s close.
    • “beta”: the stock’s beta value.
    • “closeyest”: the previous day’s closing price.
    • “shares”: the number of shares outstanding.
    • “currency”: the stock’s currency
  • Start Date
  • End Date
  • Interval

You don’t, however, need to fill in all of the arguments. For example, the following formula only uses the ticker and the attribute field and it will pull in Amazon’s current stock price:

=GOOGLEFINANCE(“AMZN”,”price”)

If you want to pull in Amazon’s stock price for the first trading day of the year, you could use the following formula:

=GOOGLEFINANCE(“AMZN”,”price”,”1/1/2024″)

This will return the following table:

Amazon's stock price for Jan. 2, 2024.

Although January 1 was not a trading day, the formula automatically gets the data for the next trading day. If you just want to get the closing price and don’t want the rest of the table, you can nest this formula within the INDEX function as follows:

=INDEX(GOOGLEFINANCE(“AMZN”,”price”,”1/1/2024″),2,2)

Since we are getting the second column and the second row, it will only retrieve the closing price for that day. This method works when you are just pulling in the stock price for a single date.

Adding a prefix for exchanges

If you want to track a lot of stocks, the one thing you may inevitably run into is a situation where Google Sheets doesn’t correctly identify your stock ticker. If, for example, you want to pull in a stock from a different exchange, entering just the ticker symbol alone won’t be enough. If I wanted to pull in the price for Air Canada stock, which has a ticker symbol AC on the Toronto Stock Exchange (TSX), this formula won’t work:

=GOOGLEFINANCE(“AC”,”price”)

Instead, that formula will return the value for Associated Capital Group, which trades on the NYSE. Google Sheets effectively takes its best guess as to which ticker you want to pull in. But as you can imagine, it may get it wrong if you have a symbol which is active on multiple exchanges.

To get around this, you can incorporate an indicator for the exchange. For the TSX, it’s TSE. If you’re not sure which one to use, go to the Google Finance website and look for the stock you want, and take note of the code for the exchange:

Google Finance quote showing the stock ticker and the exchange code.

To ensure the GOOGLEFINANCE function is retrieving the correct stock, I can adjust my formula as follows:

=GOOGLEFINANCE(“TSE:AC”,”price”)

You can follow the same methodology for other stocks and exchanges.

Creating a template to track hundreds of stocks

To create a template to help you track stocks in Google Sheets, all you really need are a few fields. One for the ticker, one for the exchange, plus one for the stock price. I’ll also add one for the % change. This can help you build out a dashboard.

If I have my tickers in column A and the exchange code in column B, I can combine the values to create a dynamic formula which will update based on those combinations. This way, I can avoid having to hardcode the individual stock tickers. Here’s how that formula would look:

=GOOGLEFINANCE(B2&”:”&A2,”price”)

The key is to combine those values and separate them with a colon in-between, so that the format is exchange:ticker. Now, when I create my template, I can copy that formula down and it will pull in stock prices which aren’t based solely on just the stock ticker:

Stock prices in Google Sheets based on multiple tickers.

Let’s extend this a bit further and now also include the percent change from the previous day. If I want to format it as a percentage, I need to make sure I divide the value by 100:

=GOOGLEFINANCE(B2&”:”&A2,”changepct”)/100

And now I can display both the stock price and the percent change from the previous day:

Stock prices in Google Sheets based on multiple tickers showing the price and the percent change.

You can copy these formulas down hundreds of rows, making it possible to track as many stocks as you need in Google Sheets.


If you like this post on How to Track Hundreds of Stocks in Google Sheets, please give this site a like on Facebook and also be sure to check out some of the many templates that we have available for download. You can also follow me on Twitter and YouTube. Also, please consider buying me a coffee if you find my website helpful and would like to support it.

LoopStocksGoogleSheets

Loop Through Stocks in Google Sheets With a Macro

Google Sheets provides investors with a great way to pull in stock prices, ratios, and all sorts of information related to stocks. Pulling in a stock’s history, for example, can make it easy for you to calculate a stock’s relative strength index, or create a MACD chart. But doing any sort of analysis for multiple stocks at a time isn’t easy. One way around this is to create a macro using Google App script that can automate the process for you and cycle through multiple stocks. Don’t know how to do it? No problem, because below I’ll provide you with a setup and a code that you can use.

First, I’ll go through creating the file from scratch and how it works.

Setting up the template

In this example, I’m going to find the stock’s largest value for a specific period. To start, I’m going to use the GOOGLEFINANCE function to get the stock history going back to Jan. 1, 2020. In the below example, I’ve got the price history for Meta Platforms, aka Facebook:

Stock history in Google Sheets for Meta Platforms.

In cell B1 I’ve put a variable for the ticker symbol. This is to avoid hardcoding anything in the formula. This is important to make the process easy to update. In the macro, I’m going to cycle through ticker symbols. In Cell E2, I also have a formula that grabs the largest value in column B (the closing price):

=MAX(B:B)

However, this is where you can put your own formula or the results of your own calculation. Whether it’s a minimum, a maximum, or some other computation you want to do, you can put the results of that calculation here. This is the cell that will get copied during the macro.

Then, in column G, I have a list of the stocks that I want the macro to cycle through:

A list of stocks on Google Sheets.

As long as it’s a valid ticker symbol that the GOOGLEFINANCE function recognizes, you can enter it in this column. You can expand it as far as you like. However, if the macro goes on for too long then it will eventually time out and stop. If you want to cycle through every stock in the S&P 500, it is possible, but just be aware that you’ll likely have to do it in chunks. When testing it myself, I estimated I could do somewhere in the neighborhood of 200+ stocks in a single run. Once done, I copied the values onto another place on the spreadsheet with the values, and then replaced the stocks in column G with the next batch.

In Cell J1, I also have a variable called tickercount. This is a helper calculation to make the macro efficient. Instead of it having to count the number of stocks in my list, I provide it for the macro — anything to make it run quicker.

The Apps Script Code

Now it’s time for the code to make this all work. To add code to your Google Sheet, select the Extensions menu and select Apps Script

Selecting Apps Script from Google Sheets.

Once in Apps Script, you can setup a new function. You should see the following:

United project in Google Sheets Apps Script.

Here’s the entire code that you can use based on my setup:

function myFunction() {
  
var sht = SpreadsheetApp.getActiveSheet();
var lastrow = sht.getRange("tickercount").getValue();

for (i=1; i<=lastrow;i++) {

  //change ticker
  sht.getRange('B1').setValue(sht.getRange('G' + i).getValue());

  //copy maximum value
  var result = sht.getRange('result').getValue();

  sht.getRange('H' + i).setValue(result);
  

}
}

Here’s a brief explanation of how the code works:

  • It begins by selecting the active sheet.
  • It determines the last value based on the ‘tickercount’ named range.
  • It loops through the values in column G.
  • It takes the value in column G and pastes it into cell B1 (the ticker variable).
  • The macro then gets the value from cell E1 (it has a named range called ‘result’)
  • It pastes the value of the result into column H, to the same row that the stock ticker was on.

If you leave my setup the way it is, what you can do is do any of your desired calculations on another part of the worksheet. As long as it doesn’t interfere with the ticker list or any of the ranges used in the macro, then you’re fine. You can also adjust where the cells are if that makes it easier. For example, you could move the ‘result’ named range from E1 to somewhere else in the spreadsheet. With a named range, you don’t need to worry about updating the cell reference.

Running the macro

A final part of this macro is actually running it. You need a way to trigger it. In my example, I’m using a button. This makes it easy to see what you need to click on for the macro to run. Here’s how you can create a button in Google Sheets and assign a macro to it:

1. Go to Insert and select Drawing

2. Create a shape, add text to it, and whatever colors/formatting you want. Then click Save and Close.

3. Select the button and click on the three dots on the right-hand side, where you will see an option to Assign Script.

4. In the following dialog box, enter the name of your function (don’t include the parentheses). The default function in Apps Script is called myFunction() and if that’s the macro you want to use, then you would just enter myFunction and click on OK.

If everything works, now when you click on your button, the macro will run. Check for any error messages to see if you run into any issues. If you need to edit the button afterwards, right-click on it first so that you don’t accidentally trigger the macro.

One thing to note is that when you run a macro on a Google Sheets file for the first time, you’ll be given a warning about doing so:

Google Sheets warning message.

Click on Review permissions and select your Google account. You’ll get the next warning, saying that Google hasn’t verified this app and you’ll need to click on Advanced to continue despite the warnings. This is similar to the warnings you encounter in Microsoft Excel when enabling macros. Once you proceed and click on Allow, the macro will proceed to run.

Here’s how it looks in action:

Download my loop macro template

If you’ve gone through this post and run into issues or it is too complicated for you, feel free to download my loop macro template. Since it’ll create a copy for your use, you can modify it however you like to suit your needs.


If you like this post on Loop Through Stocks in Google Sheets With a Macro, please give this site a like on Facebook and also be sure to check out some of the many templates that we have available for download. You can also follow me on Twitter and YouTube. Also, please consider buying me a coffee if you find my website helpful and would like to support it.