DynamicConditionalFormatting

Dynamic Conditional Formatting: How to Link Rules to Specific Cells

If you want to create conditional formatting rules but want to easily change the cutoff values for them, you can link your rules to specific cells, to make that process easy. Below, I’ll show you how to make your conditional formatting rules dynamic. Rather than going into the settings each time, you can just update specific cells, which will change your cutoff points.

Creating conditional formatting rules for changes in stock prices

A common example where you might want to adjust the cutoff values for conditional formatting rules is when dealing with stock prices. Suppose you want to highlight stocks when they have risen by more than 5%. But in other cases, such as when you’re looking at a long time frame, you may want the threshold to be much higher than that. This is where linking conditional formatting rules can be advantageous, by making the update process easier.

In the spreadsheet below, I have a list of stocks and their respective returns between December 31, 2024 and January 31, 2025. I have pulled in their performances using Excel’s STOCKHISTORY function.

Stock returns for the magnificent seven, between Dec. 31, 2024 and Jan. 31, 2025.

In this scenario, I may want to highlight stocks which have returns of more than 5% as green, and those which are down by 5% in red. I’ll create two conditional formatting rules to highlight both the return and the stock. Here’s how one of the rules looks:

Conditional formatting rule highlighting a value if it is greater than 5%.

The downside of this rule is that the 0.05 value is hardcoded. If I want to change the threshold, I would need to go back into the conditional formatting rules and modify it. There is an easier way around this, and that’s by just linking to a specific cell.

Custom conditional formatting thresholds setup in Excel.

In the above example, I’ve entered the values that I want to link my conditional formatting rules to. In the case of a green highlight, I’m going to link to cell E2. And when I’m formatting the cells red, I’ll link to cell E3. Here’s how my updated conditional formatting rule will look:

Conditional formatting rule which links to a specific cell.

Now, I’ve removed the hardcoded value and my conditional formatting rule now points to a specific cell, which is frozen and doesn’t change. To do the same thing for my red highlight rule, when the values are down 5%, I do the same thing, except flip the sign and refer to cell $E$3:

Conditional formatting rules for negative returns.

My conditional formatting rules are correctly applied to my data set, highlighting returns of more than 5% in green, and returns of less than negative 5% in red:

Conditional formatting rules applied using cells in Excel.

The advantage here is I can easily update my thresholds by just modifying the values in column E. If I change them to 10% for green and -10% for red, I simply make the changes in those cells and my conditional formatting updates immediately:

Updated conditional formatting rules for returns of greater than 10% and less than negative 10%.

By setting up my conditional formatting rules this way, it’s easy to update the process in seconds and at the same time, I can see what my threshold are.


If you like this post on How to Apply Dynamic Conditional Formatting and Link Rules to Specific Cells, 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.

ExcelChartGaps1

How to Create Excel Charts to Visualize Variances in Stock Performance

If you want to compare and contrast between two sets of values, a chart can help you accomplish that. In this post, I’m going to show you how you can compare multiple investment returns, and using a chart to not only map them but to also display the variances. For this example, I’m going to compare the historical returns of the S&P 500 against the S&P TSX 60.

Step 1: Setting up the table

The first thing to do is to plot the values into a table format, making it easy to compare the differences. Below, I have multiple columns for the year, S&P 500 returns, and the S&P TSX 60 returns.

Table in Excel comparing investment returns.

Step 2: Calculating the differences and starting point values

The goal of this chart is going to be to not just plot the values of these returns but to also show the gap between them. This can be a little tricky since the value scan be both positive and negative. It’s important to determine where the starting point for the column chart needs to be, and where it finishes.

The first calculated column I’m going to create is for the starting point. If the two returns are both negative, then it will take the largest value (i.e. smallest negative number). Otherwise, it will take the smallest positive value. The formula for the first set of values in row 2 looks as follows:

=IF(AND(B2<0,C2<0),MAX(B2:C2),MIN(B2:C2))

Next, it’s necessary to calculate the gap for when there are both positive and negative returns, and when a crossover needs to happen to get to 0. This column, called crossover, will check to see if the returns are both positive or both negative. And if they are, then it will remain 0 since no crossover is needed. Otherwise, it will return the starting value. The formula for this column is as follows:

=IF((B2*C2)>0,0,D2)

By multiplying the values for both returns, it checks to see if there is a mix of positive values. If there is, then the value will be negative. If they aren’t, then it will return a 0 value.

Lastly, there is a column for the final difference field. First, it checks whether there is a value in the crossover field. If there is, it takes the maximum value in column B or C, which will be the other part of the gap to be filled in . If there isn’t a crossover value, then it looks at the starting value. If the starting value is positive, then it takes the largest value and subtracts the positive one. Otherwise, if the starting value is negative, then it takes the lowest value and subtracts the largest. This is what the formula looks like:

=IF(E2<>0,MAX(B2:C2),IF(D2>0,MAX(B2:C2)-MIN(B2:C2),MIN(B2:C2)-MAX(B2:C2)))

And here is the table, with the values calculated:

Table comparing investment returns in Excel.

Step 3: Creating the chart

Now that the data is setup, the next step is to plot the values on a chart. This requires the use of a combination chart. To create it, make sure a cell on the data set is selected, click on the Insert tab and select the button to pop out more Charts. Go to the All Charts tab and select Combo. The S&P 500 and S&P TSX 60 fields, select the option for Line with Markers and for the others, choose Stacked Column.

Initially, the chart is likely going to look incorrect and may include the date field. To fix this, right-click on the chart and click on Select Data. Remove the Year field if it is there. For the other fields, adjust the Horizontal Axis labels to ensure they are reflecting the year:

Modifying the data source for a chart in Excel.

The chart still has a lot to fix in terms of formatting:

Chart in Excel showing a range of values and variances.

For the line charts, right-click on them and select Format Data Series. Since only the data point is necessary, I will go under the fill bucket tab and under the Line category, select No Line.

Next, the the starting value column, format the data series and for the fill bucket, set the Fill option to No Fill. Then, change the fill color for the difference and crossover columns so that they are the same color. I’ll use grey in this example.

To ensure the column charts stack properly, you’ll also want to modify the order of the series. Right-click to select the data, and ensure that Crossover field comes before the Starting field, followed by the Difference field. Here’s how the chart looks at this stage:

Excel chart showing a range of values.

To clean up the chart a bit, I will move the labels to the bottom. This can be done by right-clicking on the years and selecting Format Axis. Under the Labels section, set the Label Position to Low. I’ll also delete the legend labels for the Crossover, Starting, and Difference fields. The last change is to set a chart title. This is what the final result looks like:

Excel chart comparing the returns of the S&P 500 versus the S&P TSX 60.

If you like this post on How to Create a Chart to Show a Range of Differences, 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.

GoogleSheetsHeatMap

How to Create a Stock Heat Map in Google Sheets

Heat maps can help you easily identify high and low values. You’ll often find them to display stock prices to show which stocks did well, and which ones didn’t. They can also make it easy to see whether it was a good or bad day on the markets when looking at a list of stocks. In this post, I’ll show you how to create a heat map in Google Sheets to do this.

Step 1: Populating your list of stocks

To start with, I’m going to need a list of stocks to track. I’m going to use the top 20 most valuable stocks as of today’s date and put them into a list:

List of the 20 most valuable stocks in Google Sheets.

Step 2: Calculate the percentage change

Next, I’ll need to setup the percentage change. This can be either the percent change from the previous day, or I could calculate how a stock has done over a specific timeframe, such as a 12-month period. In Google Sheets, you can use the GOOGLEFINANACE function to track the percent change from the previous day. Here’s what that formula would look like, assuming I want to calculate this for the ticker symbol in cell A2:

=GOOGLEFINANCE(A2,”changepct”)

This will return a value to display the percent change.

I’m going to use a more complicated example, however, to show how the stock has performed over the past year. First, I’ll pull in the current stock price, using the following formula:

=GOOGLEFINANCE(A2,”price”)

The trickier part is to pull in the price from a year ago. To go back 365 days, I can set the start date equal to today’s date minus 365 days:

=GOOGLEFINANCE(A2,”price”,TODAY()-365)

The problem is that this returns a table, occupying two rows and columns:

Apple's stock price a year ago.

To ensure I’m just pulling in the closing price, I’ll use the INDEX function to grab the value from the second row and second column:

=INDEX(GOOGLEFINANCE(A2,”price”,TODAY()-365),2,2)

Now, to calculate the percent change, I will take the current price and divide it by the historical price:

=GOOGLEFINANCE(A2,”price”)/INDEX(GOOGLEFINANCE(A2,”price”,TODAY()-365),2,2)-1

I add the -1 at the end to get just the percent change. Now, if I format my values in percentages, I can see how the stocks have performed over the past 12 months:

Google sheets chart showing stock performance.

Step 3: Ranking the values

Using the RANK function in Google Sheets, I can easily determine which stocks were the best and worst performers in the range. The following formula just takes the percentage value in column B and compares it against all the values in that column:

=RANK(B2,B:B)

By copying this formula down, I can now see a ranking of all the values:

Google sheets showing stock performance and ranking.

Step 4: Populate the stocks in order of their performances

Now that the data is setup, I can start arranging the values in order of largest to smallest. To do this, I’m going to use the INDEX function along with the MATCH function to extract the stocks based on their performances. Here is what the first formula will be:

=INDEX($A:$A,MATCH(COLUMN(A1),$C:$C,FALSE),1)

I use the COLUMN function because what I am going to do is drag this formula to the right, so that my largest values go from left to right. And as I copy the formula, A1 will become B1, then C1, and so on. The purpose of this is to increment the function to get the next value. Here is what my table looks like for the first five values:

Top-performing stocks listed in Google Sheets.

These were the five best-performing stocks that were in my list. Below these values, I’m going to also pull in the percentages. This is accomplished through the following formula:

=INDEX($B:$B,MATCH(COLUMN(A1),$C:$C,FALSE),1)

Now I have a list of the top ticker symbols and their percentage gains:

Top-performing stocks listed in Google Sheets along with their changes in value from a year ago.

Step 5: Creating conditional formatting rules

I have the values setup and next I’ll need to create conditional formatting rules to display different colors based on their relative performances. I’ll use a bright green for the best performance, and gradually show a white color when the values are close to zero, and red when they are negative.

I’m going to setup a table which shows the different thresholds I want to track, so it’s easy to change these conditional formatting rules right on the spreadsheet:

Table of conditional formatting thresholds in Google Sheets.

This is my table of values in column K. To setup the rules, I’m going to select the ticker symbols which I ranked in step 4, and create the following conditional formatting rule to start with:

Setting up a conditional formatting rule in Google Sheets.

I’m going to repeat these steps for the values in K2, K3, K4, and K5. I’ll adjust the colors to differentiate between the colors ranges I specified earlier. I use the same formula but simply adjust the cell I’m comparing to:

One thing to note here is that the value I’m using as my comparison is in row two, which is where my percentages are. This means for the conditional formatting rules in the first row, Google Sheets is looking the row below, which contains the percentages.

I’ll need to create another set of conditional formatting rules for the actual percentages themselves in row two. In order to avoid disrupting the formulas and the logic for the first row, I’ll need to create these rules from scratch again. It’s important not to just copy the formatting rules as Google Sheets will end up misinterpreting what I want it to do.

After selecting the values in E2:I2, I create the same conditional formatting rules. The one key difference is that this time I’m referencing the values in row two, not the row below. Once that’s setup, you should now see the same conditional formatting rules applied to both rows:

Heat map conditional formatting rules setup in Google Sheets for multiple stocks.

Step 6: Create borders and setup additional formatting

Before I copy over the formulas and conditional formatting to more rows, I’m going to setup additional formatting and borders. I’m going to make the ticker font larger and bold. And I’ll also outline a border for each stock and its percent change. Here’s what my tickers look like after making these changes:

Heat map conditional formatting rules setup in Google Sheets for multiple stocks.

Step 7: Copying the formatting rules and formulas to accommodate more stocks

I created a row of top 5 stocks but I’m going to expand this so that I have four rows of five stocks each, so that I’m capturing all 20 stocks in my list. To do this, I’m going to copy the cells in E1:I2 multiple times:

Heat map conditional formatting rules setup in Google Sheets for 20 stocks.

I’ve copied the formulas but I need to adjust them so that they aren’t all starting from the top-ranking stock all over again. Here’s how I’m going to adjust this. For the formulas in cells E3:E4, I’m going to add five so that they start at the sixth value. This is the updated formula in E3:

=INDEX($A:$A,MATCH(COLUMN(A3)+5,$C:$C,FALSE),1)

Now I’m going to do the same thing for cell E4. Once I’m done, I’ll copy the formulas across and now my second row is updated to show the stocks in the 6th, 7th, 8th, 9th, and 10th positions:

Heat map conditional formatting rules setup in Google Sheets for 10 stocks.

For the next row, I’ll add 10 to the formulas in column E. Then copy those across. Repeat the same process for the next set of rows and add 15, and do the same. Here’s what my updated table looks like:

Heat map conditional formatting rules setup in Google Sheets for 20 stocks.

Now my heat map is setup to show the percent changes. But as you can see, there’s not a lot of variability here. I’m going to change my values in column K as follows: 100%, 60%, 30%, 20%, -100%. I always leave the last one to -100% to ensure it captures everything else. With the updated rules, now my heat map looks as follows:

Heat map conditional formatting rules setup in Google Sheets for 20 stocks, showing red highlights for the poorest-performing stocks.

Although the values in red are not negative, based on the rules I’ve set out, it highlights the lowest-performing stocks in this list as red, and thus, the sheet follows the rules correctly. You can expand this to include more stocks or to track daily changes or other values.


If you like this post on How to Create a Stock 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.

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.

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.

GetFinancials2

How to Download Financial Statements Into Excel and Google Sheets

In a previous post, I went over how to download a company’s financial statements from the Wall Street Journal’s website. However, that connection appears to now be closed. One of the risks when using Power Query to download data from a website that the connection will always be there. But there is another way to get financial statement data, and it can allow you to download much more than what was available through the Wall Street Journal.

You’ll need to setup an account with Alpha Vantage

The website that you can use is Alpha Vantage. It provides API access which you can use to download financial data. There is a free account but there is a limit to the number of requests you can make every day — up to 25. But with the wealth of information you can get with just a single query, there’s a lot of data you can accumulate.

Once you sign up for an account with Alpha Vantage, you’ll have an API key that you can use to connect to its database. You’ll need to save that key to download the data.

Use the site’s custom Excel add-in

Once you have the API key, you can start downloading data. But rather than creating your own template or even using Power Query, what you can do is download the sample Excel files that are available on the site on the spreadsheets page. Here you can select to download the Office 365 add-on, which also includes sample Excel files that can get you started in seconds.

There is a template called FundamentalData.xlsx which contains a file that’s ready to go to import the financials. When you first open it, you’ll need to select the AlphaVantage(Web) tab and click on the Open Taskpane command.

The alphavantage tab in Excel.

From there, you’ll see an option to input your API Key.

The alphavantage API key section.

Then, on the filings tab, you’ll see an area where you can specify the ticker symbol you want, the type of filing (cash flow, income statement, or balance sheet) and the reporting frequency (quarterly versus annual). Then, as you make your selections, the data on your spreadsheet will update with various financial metrics.

Downloading financial statement data in Excel.

Using Alpha Vantage is one of the better options for investors today who want to download financial data into Excel.

Importing financial statement data in Google Sheets

The company also has a Google Sheets add-on available from the Google Workspace Marketplace, just go to Extensions ->Add-ons -> Get add-ons. Then search for ‘Alpha Vantage’ and download the add-on:

The Alpha Vantage add-on in Google Sheets.

Once installed, go back to the Extensions menu, select Alpha Vantage Market Data and select Enter API Key, where you can paste your API key into. Once that’s done, you can use formulas to pull in financials. The following pulls in the quarterly income statement data for MSFT stock:

=AVGetCompanyFilings(“MSFT”,”IncomeStatement”,”Quarterly”)

For a full breakdown of what you can download on Google Sheets, refer to the documentation on the Alpha Vantage website.

Download the data using Power Query

If you prefer not to install an add-in, then you can still download the data from Alpha Vantage using Power Query. You can refer to the documentation for the various links to pull financial data. For the income statement, for example, this is the following url:

https://www.alphavantage.co/query?function=INCOME_STATEMENT&symbol=TICKER&apikey=DEMO

Where Ticker is the stock symbol and Demo is your API Key. To generate the data in Power Query, use the Get Data option and select From Web and paste the URL into there:

Using Power Query to download financial statement data.

Then, once Power Query is loaded up you have the option to specify whether you want the list for the annual reports or the quarterly reports.

Selecting the type of financial report to download from Power Query.

If I select the quarterlyReports list, I’ll have another list of records. I can expand this by clicking on the Convert To Table button in Power Query:

Converting a list of records in Power Query into table.

This will put everything back into a single column. This time, however, I can expand all the fields out by clicking the two arrows going in opposing directions.

Expanding a column in Power Query to list all the fields.

Now my data looks complete:

Income statement data loaded in Power Query.

And this is what it looks like once it’s loaded back into Excel:

Income statement data loaded into Excel.

If you like this post on How to Import Financial Statements Into 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.

MovingAveragesinExcel

What Is the Difference Between a Moving Average and an Exponential Moving Average

Moving averages can be useful in data analysis, when looking at trends both in finance and in the stock market. You can look at 30, 60, 90 day trends, and even longer or shorter durations. There’s also a difference between whether you are looking at a simple moving average and an exponential moving average. In this article, I’ll go over the differences between the two, and show you how you can calculate them in Excel.

How to Calculate a Moving Average (MA) in Excel

A moving average is a simple tool used by investors and traders to smooth out price data over a specified period. It is called “moving” because it is continually recalculated based on the latest data, providing a dynamic view of an asset’s average price over time. The advantage of an MA is its simplicity as it can easily be calculated.

A moving average is calculated by simply taking the average of the trailing periods. In the case of a 60-day MA, you would look at the average over the past 60 days. If it’s a 90-day MA, then you average the past 90 days. In the following example, I have the price of Bitcoin over the past few years. Ideally, when setting up moving averages, you want your dates in ascending order, going from oldest to newest.

Price of Bitcoin in an Excel spreadsheet.

Here are the steps to calculate the moving average:

  1. Determine the number of periods you want to go back. For 5 days, it will be 5, for 10 days it will be 10, and so on.
  2. Calculate the average in the adjacent column. Make sure you do not freeze cells.
  3. Copy the formula down so that the average moves (hence why you do not want to freeze cells).

Here is what the values look like, along with the formula for each cell:

20-day moving average of Bitcoin in an Excel spreadsheet.

The average is continuously moving with each cell, but it always contains a range of 20 values since the 20-day MA contains 20 days. Oftentimes, people using multiple moving averages as a way to identify crossovers, such as when stocks cross 20-day MAs and 50-day MAs. Depending on the direction of the crossover, it can be a very bullish indicator (20-day MA crosses from underneath) or a very bearish indicator (20-day MA crosses from above). This is what those moving averages look like for Bitcoin and how they appear on a chart:

A bullish crossover involving Bitcoin's 20-day moving average and its 50-day moving average.

In this example, the 20-day MA made a bullish crossover recently, going higher than the 50-day MA. This is a very bullish trend. However, with simple moving averages, these trends can take a while to develop, and that is one of the drawbacks of using them — they are slower to react to recent price movements.

How to Calculate an Exponential Moving Average (EMA) in Excel

The exponential moving average (EMA) gives more weight to recent prices, making it more responsive to new information, and thus, there’s less of a lag effect; changes and crossovers can occur much more rapidly. This characteristic makes the EMA a preferred choice for many traders, especially those looking to capitalize on short-term trends.

Here’s how to calculate an exponential moving average in Excel:

  1. Determine the number of periods, as you did with the simple moving average.
  2. Calculate a multiplier, using the formula 2 / (period +1). In the case of a 20-day MA, the multiplier would be 0.095, which is 2/(20+1).
  3. Calculate the moving average for the first period. The very first period needs to be a simple moving average.
  4. For every value afterwards, you’ll use the following formula: =Multiplier x (Current Price – Previous EMA) + Previous EMA.

Here’s how this would be calculated with the price of Bitcoin, as in the previous example:

Calculating Bitcoin's exponential moving average in Excel.

After the initial moving average, the subsequent averages are calculated using the weighting. Here’s a side-by-side comparison of how the 50-day EMA compares with the 50-day MA. I’m using 50-day averages here since they are normally slower to see movements in. But by using an EMA, that can help expedite trends.

Comparing Bitcoin's 50-day exponential moving average against its 50-day simple moving average.

The 50-day EMA makes quicker, more rapid movements and is changing more frequently while the 50-day MA is smoother and more gradual in its changes. With Bitcoin’s price rising rapidly in recent weeks, that uptrend is observed more immediately with the EMA than with the simple MA.

Which Should You Use: MA or EMA?

While both MAs and EMAs provide valuable insights into market trends, the choice between them depends on the specific needs of the trader or analyst. MAs are best suited for identifying long-term trends, as they smooth out price fluctuations evenly. In contrast, EMAs are ideal for those looking to react quickly to recent price changes due to their emphasis on newer data.

By understanding the differences between these two types of averages and knowing how to calculate them in Excel, investors and analysts can better tailor their strategies to suit their goals. Whether it’s the simplicity and broad trend identification of the MA or the responsiveness of the EMA to new information, both tools can be useful.


If you liked this post on What Is the Difference Between a Moving Average and an Exponential Moving Average, 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 us on Twitter and YouTube.

StockTradingTemplate2024

2024 Stock Trading Template

Do you buy stocks? Help track your transactions and your returns with this stock trading template. This is an update over the previous stock trading template, offering more reports and analysis, and the ability to more easily track your portfolio’s performance. In this post, I’ll go over how the template works, and how to use it.

Using the stock trading template for the first time

When you first use the 2024 stock trading template, there are a few items you may wish to modify on the Settings tab. These are the end date (by default set to today) and the short-term trading days cutoff. The end date is used because the reporting tab looks at the trailing 12 months. So if you want a cutoff as of Dec. 31, 2023 and see the full year, you can modify the cutoff there. But if you want to look at your returns up until today, you can leave that as is, up to today’s date.

The short-term trading days cutoff is used for a report which pulls your gains and losses over this number of days. If you’re a very active trader, you my want to lessen this interval to 30 days or less. If, however, you don’t trade that often, you may prefer a longer cutoff. The default is set to 60.

Enter transactions in the file

To make the data-entry process simple, there is a userform which will allow you to enter your buy and sell transactions. You can also enter starting balances and dividend payments. You can access the form from the Trading Journal section on the Home tab, right within the Excel ribbon.

The trading journal buttons for the stock trading template.

By clicking the Enter Transaction button, you will see the following form pop up:

The userform to enter transactions in the stock trading template.

To start, you can use the Date Picker button to select the transaction date. With the date picker, you can use the button on the left and right side to move one month at a time. You can also select the month from the drop-down list. You can change the year by just typing in the year of the transaction. Once you have the right date and month, use the tab key so that the calendar updates. Then, click on the date the transaction relates to.

The date picker userform in the stock trading template.

Next, select the action type. This will determine which fields you need to enter. There are multiple options to choose from.

Selecting a transaction type for the stock trading template.
  • If you are buying a new stock you don’t already own, select Open New Position.
  • If you already own a stock and are adding more shares, select Add to Existing Position.
  • If you are selling shares of a stock you own, select Sell Shares.
  • If you are adding cash to your portfolio, select Enter Contribution.
  • If you are withdrawing cash from your portfolio, select Enter Withdrawal.
  • If you are recording dividend payments, please select Enter Dividends.
  • If you are already own stocks and need to enter in your initial positions, select Starting Balance. For starting cash positions, use the Enter Contribution option.

You will then see a different form based on your selection, showing you which fields you need to enter.

Using different investing strategies

By default, there are three investing strategies you can select from when buying a stock: Buy and Hold, Contrarian, and Speculative. This can be helpful if you want to track how your different strategies work. If you don’t use different strategies, you can just leave everything as Buy and Hold. If, however, you want to add or modify strategies, click on the Update Strategies button when entering a new position:

Selecting a strategy on the stock trading template.

That will then populate a new userform where you can manage the different strategies.

Modifying strategies on the stock trading template.

How the template tracks transactions

When you enter a transaction, it goes into two places. One is the Activity tab, and this acts as a log for everything you’ve entered. There is also the Transactions tab, which is designed for traders to track their opened and closed positions.

The data also flows through to the Summary tab, where you will be able to see your running portfolio balance, track gains and losses, and also see reports highlighting your overall trading performance. To make sure that all the charts update correctly, click on the Refresh button from the Trading Journal section on the Home tab.

Chart showing portfolio balance by month.

Download the template

Want to try out the template? You can download the trial version here. It is limited to 25 transactions. If you like it, please consider purchasing the full version.

If you run into any issues with the template or have feedback or suggestions for improvements, please feel free to contact me. Please include the name of the template when drafting your message.


If you like the 2024 Stock Trading Template, 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 us on Twitter and YouTube.

PEGRatio

How to Calculate the PEG Ratio in Excel

What is the PEG Ratio?

The Price/Earnings to Growth (PEG) Ratio is a metric that enhances the traditional price-to-earnings (P/E) ratio by incorporating the company’s earnings growth rate into the calculation. This ratio is calculated by dividing the P/E ratio by the annual earnings per share (EPS) growth rate.

This calculation provides a more nuanced view of a stock’s valuation by factoring in future earnings growth, offering a more comprehensive perspective compared to the P/E ratio alone, which only considers the current price relative to earnings.

Why Investors Find the PEG Ratio Useful

Investors use the PEG ratio for several reasons. It allows for a more balanced comparison between companies with differing growth rates. A high P/E ratio might suggest a stock is overvalued, but when accounting for strong anticipated growth (as the PEG ratio does), the stock might actually be undervalued. This makes the PEG ratio a favored tool for identifying stocks that might offer a better return on investment, particularly when looking for good growth stocks.

The PEG ratio also aids in evaluating the potential overvaluation or undervaluation of a stock in relation to its growth prospects. A PEG ratio below 1 is often interpreted as a stock being undervalued given its earnings growth, whereas a ratio above 1 might indicate overvaluation. This simple benchmark can guide investors in making more informed decisions.

What is the Formula to Calculate the PEG Ratio?

The PEG ratio includes two components: the stock’s P/E ratio and the annual EPS growth rate. This is what the formula looks like:

PEG ratio formula.

Creating a template in Excel to calculate the PEG Ratio

Calculating the PEG ratio in Excel is straightforward, allowing investors to efficiently assess multiple stocks’ growth prospects against their valuations. Here’s a step-by-step guide to setup a worksheet to help you do this:

  1. Input Data: Begin by entering the necessary data into Excel. You’ll need the current stock price, EPS, and the annual EPS growth rate. Ideally, you’ll want to setup the inputs first, followed by the formulas at the bottom. This will make it easier to enter the data in logical steps: first the ticker, the stock price, the EPS, and then the annual EPS growth.
  2. Calculate P/E Ratio: In the first calculation cell, I’ll calculate the P/E ratio by dividing the stock price by the EPS.
  3. Calculate PEG Ratio: The next calculation cell is the PEG ratio. This is calculated by taking the P/E ratio and dividing it by the annual EPS growth rate. If a stock is expected to grow at a 50% growth rate, the value should be 50, not 0.5 (i.e. don’t enter it as a percentage). Otherwise, this won’t calculate correctly.
  4. Conditional Formatting. This is an optional step, but one which can help with your analysis. Use conditional formatting rules to highlight the PEG ratio based on its value. If it is less than 1, I’ll apply a green highlighting, a red highlight if it is more than 3, and yellow for anything in-between. Here is how you might set that up with an icon set
Creating conditional formatting rules using icon sets.

Here is how the template looks based on their stock prices and data as of Feb. 1, 2024:

In the above example, we have a fast-growing stock in NVDA, a moderate-growing stock in AAPL, and a slower-growing one in KO. Essentially what we are doing here is looking if the EPS growth rate is higher than the P/E ratio. If it is, that suggests it is not an expensive buy. NVDA, for example, is expected to more than double each year for the next five years, as is evident by its 102% EPS growth rate. While that would make it look like a cheap buy, you’re also assuming that it really can achieve that kind of a growth rate, which would be no easy feat. That leads us to an important part section: the limitations of this calculation.

Limitations of the PEG Ratio

While the PEG ratio offers valuable insights into a stock’s potential value by incorporating growth into the valuation equation, it’s important to recognize its limitations. Understanding these constraints can help investors use the PEG ratio more effectively alongside other analysis tools.

  1. Growth Rate Estimations: The PEG ratio is heavily dependent on the accuracy of the earnings growth rate projections. These forecasts can be highly speculative and vary widely among analysts. Overly optimistic or pessimistic growth estimates can skew the PEG ratio, leading to potentially misleading conclusions about a stock’s valuation.
  2. Historical Growth vs. Future Potential: The PEG ratio typically uses historical data to predict future growth, but past performance is not always a reliable indicator of future results. Companies in rapidly changing industries or facing new competitors may not sustain their previous growth rates.
  3. One-Size-Fits-All Approach: The simplicity of the PEG ratio, while a strength, can also be a drawback. It does not account for the nuances of different industries or the specific risks and opportunities facing individual companies. A low PEG ratio does not guarantee success, nor does a high PEG ratio always indicate a bad investment.
  4. Dividend Exclusion: The PEG ratio does not consider dividend payments. For income-focused investors, a company’s dividend yield and the stability of its dividend payments can be as important as growth. Companies with high dividend yields might be undervalued by the PEG ratio, which only focuses on earnings growth.
  5. Market Conditions: The effectiveness of the PEG ratio can also be influenced by the overall market conditions. During bull markets, growth stocks tend to perform well, and their high PEG ratios may be justified by the market’s momentum. Conversely, in bear markets, value stocks with lower PEG ratios might be more favorable, regardless of growth projections.
  6. Quantitative Focus: The PEG ratio is a purely quantitative tool and does not take qualitative factors into account. Elements such as management quality, brand strength, market position, and industry trends can significantly impact a company’s future performance but are not reflected in the PEG ratio.

If you liked this post on How to Calculate the PEG Ratio in Excel, 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 us on Twitter and YouTube.

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.