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.

WeeklySalesReports2

Compare Weekly Sales in Excel Using a Pivot Table

Do you need to create weekly sales reports that compare the same days of the week? This kind of analysis can be tricky to ensure that you are comparing the same day of the week against the same week in the previous year. Simply comparing dates may not be sufficient, as you could end up comparing a Sunday’s revenue numbers against a Friday’s, and depending on the industry you are in, the results could look drastically different. In this post, I’ll show you how you can make reliable comparisons which look at the same weeks and the same days of the week.

Preparing the data

Let’s start with a pretty simple data set which just has the date and the sales amount, as such:

A table in Excel showing daily sales data.

The data set contains sales for January and February of 2024 and 2023. To facilitate the comparisons, I’m going to add fields for the week # and the day of the week. For the week, I can use the WEEKNUM function, which just takes the date as a single argument. And for the day of the week, I’ll use the TEXT function, which can use the “dddd” format type to specify the day. Here’s how the data looks after I’ve added those fields:

A table in Excel showing daily sales data with week and day of the week information.

Loading the data into a Pivot Table

Now that my data is ready to analyze, I can create a pivot table. While any cell on the data set is selected, I’ll click on the Insert tab and select Pivot Table. Next, I’m going to set up the pivot table as follows:

  • Columns: Year
  • Rows: Week , Day
  • Values: Sales Amount

To get the year to show, I’ll select the Date field and put the Years (Date) value under columns. You could also create a formula in the previous step to calculate the year value based on the date. Here is what my pivot table looks like thus far:

Pivot table showing sales by week and day.

There are a few things I will do improve the appearance and usefulness of the pivot table, including:

  • Removing the grand total, since I’m comparing and not adding the values.
  • Changing the report layout to a tabular format so that the Week values will now create subtotals.
  • Change the value field settings for the Sales Amount so that it resembles a currency format.
Pivot table showing sales by week and day after applying formatting.

Now, I’m ready to do the analysis in the pivot table.

Comparing values in a Pivot Table

If I want to compare values from one year to the next, I need to pull in another field for the values section. I’m going to pull in the Sales Amount into the section again. While at first, this looks like I’m just duplicating the values, I’m going to change the appearance of the second field. If I click ok the Sum of Sales Amount2 field and select Value Field Settings, I can change how the values are shown. Instead of a sum, when selecting the Show Values As tab, I have the ability to select % Difference From:

Selecting the percent difference from in a pivot table.

I then select my base field. I need to select the Years (Date) field, since I’m comparing years. As for the base item, I’m going to select (previous). If you’re always going to be comparing against a certain year, you can select the specific year. But if you always want to be comparing against the previous year, choose previous.

Selecting the percent difference from a previous year in a pivot table.

I have also renamed the field to ‘Revenue Growth %’ to signify that the value in the field represents the growth (or decline) compared to the previous year. Here’s how my data looks with the new field:

Pivot table showing percent change from the previous year.

There are a few things I need to fix there. The first is that I have a #NULL! error in the first row. This is because in the previous year, there was no sales, presumably as this would have been a holiday. To fix this, I can go into the Pivot Table options and check off the option For error values show and just leave it blank.

Setting the for error values show in a pivot table to be blank.

That gets rid of the error. Another thing I need to do is get rid of the unnecessary revenue growth field for 2023. As there is no comparable, it will always be blank for the first year. The simple solution here is to just hide the column entirely. Now I’m left with a pivot table that shows my sales data by week, day, and year, and the year-over-year change in percent:

Pivot table showing year-over-year change in revenue by week and day.

One last thing you may want to do is add some conditional formatting, to help highlight the good and bad weeks and days. Using a directional icon set could help make the results stand out:

Creating conditional formatting rules with icon sets in Excel.

By using this formatting, any values where the growth rate is more than 5%, will have a green triangle. Anything less than 0 will be red, while anything in-between will show a yellow horizontal line.

Pivot table showing year-over-year change in revenue by week and day with conditional formatting applied to highlight good and bad days.

If you liked this post on How to Compare Weekly Sales in Excel Using a Pivot Table, 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.

RunningTotalsinPQ

How to Calculate Running Totals in Power Query

Do you have year-to-date values and need to calculate running totals? What about if you have criteria you want to track running totals for? In this post, I’ll show you how to accomplish both and how you can create a custom function in Power Query that you can re-use in other queries. Here is a simple table I am going to use for this example:

Table in Excel showing sales by day, rep, and location.

In this table we have date, sales, salesperson, and location. Initially, I am just going to calculate the running total, regardless of the salesperson. I just want to know how much everyone has generated up to a certain point in time. The one step that I need to do is sort the dates in order, so they are going from smallest to largest. You can do this in either Excel or within Power Query.

Creating a running total for everything in Power Query

Step 1: Load your data into Power Query

To load your existing table into Power Query, click on your table and select the Data tab and click on From Table/Range.

Selecting the From Table/Range button in the Data tab.

Step 2: Sort your data

If your data is not already sorted in Power Query, then select the Date column and click the button to sot in ascending order.

Sorting data in Power Query.

Step 3: Create an Index column

On the Add Column tab, select the option to insert an Index Column, and select to the option to start From 1:

Creating an index column in Power Query.

This now creates a simple column that starts from 1.

A Power Query table with an index column.

Step 4: Create a column for the Running Total calculation

Select the Custom Column button from the Add Column tab, which will let you create a column based on a formula.

Selecting the Custom Column button from the Add Column tab.

There are two functions will be used in the formula. The first is the List.Sum function, which as the name describes, will sum up the values in a list. Within that will be the List.FirstN function which will grab all the index values up until that point. The custom column formula to enter, is as follows:

=List.Sum(List.FirstN(#"Added Index"[Sales],[Index]))

This is how it appears within the Power Query screen:

Creating a formula for a custom column in Power Query.

This now creates a Running Total column which calculates the year-to-date sales values:

A Power Query table after adding a Running Total column.

Creating a running total for when criteria is met in Power Query

This time around, I’m going to show you how to create a running total which resets for each salesperson. By doing this, you can track their individual year-to-date totals. If you’re starting from scratch, you will need to repeat the steps from the previous section in order to arrive at your Running Total formula.

Step 1: Convert the Running Total formula into custom function

Once you have created the Running Total formula, you can convert it into a custom function. If you select the query and click on the Advanced Editor button on the home tab, you will see the code for all the steps which were previously created:

Power Query advanced editor showing multiple steps.

To reuse this code and use it as a function, I need to add a place to enter a variable at the beginning.

let runningtotal = (x) =>

In the above example, x is the input. It will refer to the table which the custom function will execute on. And at the end of the custom function, there should be another ‘in’ keyword to circle back to the function, such as follows:

in runningtotal

Here is how my custom function looks like after removing the Changed Type step and setting the source equal to the variable:

The advanced editor showing a formula to calculating a running total.

If you remove any steps, however, just remember to update the formulas. In the “Added Index” step, I updated the step I’m referencing to Source. Otherwise, it would reference a step that doesn’t exist and would result in an error.

After saving, you should notice an fx function next to your query, which you may want to now rename to your desired function name. This is what you will reference it to when invoking the function. In this example, I’m going to call it RunningTotal to keep everything consistent.

Now the function is ready to be used.

Step 2: Group the data

On the Home tab, select the Group By button. This will allow you to break your data into multiple tables.

Selecting the Group By button in Power Query.

In the Group By section, select the option to group by Salesperson and use All Rows as the operation, which ensures no data is lost. I’ll name the new column Data.

Grouping data by salesperson in Power Query.

This now creates a column that contains tables based on the salesperson:

Power Query data which has been grouped by salesperson.

Step 3: Invoke the custom function

On the Add Column tab, press the button to Invoke Custom Function

Invoking a custom function in Power Query.

Then, on the details, enter the column name, the function to invoke, and the data which contains the variable. Since the new ‘Data’ column contains the table, that will be the variable in this example. But if you named the column differently, you would use that name.

The invoke custom function dialog box.

This will now create an additional column, which also contains a table.

A Power Query table after invoking a custom function to create a new column.

If you click on any of the cells in the newly created field, you’ll see that the preview contains the running total field:

A preview in Power Query of a table nested within a field.

Step 4: Expanding the table

The last step involves expanding the tables in the newly created field. By pressing on the two arrows going in opposite directions, you will be able to expand all of the columns.

Expanding a table in Power Query.

You can omit including the Index column as that is not necessary, and the Salesperson field is already there. The only other column you may want to remove in addition to this is the Data column, but that has to be removed with an additional step. Here is how my final table looks:

A Power Query table after adding a field for the running total.

You can see that as the name changes to a different salesperson, the running total doesn’t continue adding; it starts from the first date for that salesperson.


If you liked this post on How to Calculate Running Totals in Power Query, 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.

sumgroupPQ

How to Sum and Group Values in Power Query

Have data in Power Query that you want to sum up and group by category? In this post, I’ll show you how you can sum up values in Power Query to help you analyze your information. In this example, I’m going to use daily sales values by different sales reps.

Sales data in Power Query.

Getting a simple sum

If you just want to calculate a sum in Power Query, select the column you want to sum, and then on the Transform tab, select Statistics, and select Sum.

Summing up a column.

This will create a new step, where it will calculate the sum.

The calculated sum step in Power Query.

You could reference this step in other calculations. However, if you want to tally up sales by categories, there’s a better way to do this.

Summing values using Group By

One way to both group and summarize your totals is by using the Group By method. To do this, select the column you want to group by. In this case, it’s going to be by the sales rep, since I want to see the total sales by rep. Then, on the Transform tab, I’ll click on the Group By button:

Selecting the group by method in Power Query.

Then, I’ll enter a column name of Total Sales and for the operation, select Sum and select Sales Amount ($) as the column I want to sum.

Setting the group by parameters in Power Query.

After pressing OK, I have a breakdown of sales by the different reps.

Grouping sales by sales rep in Power Query.

There are, however, more splits that you could do. Suppose you wanted to group sales rep sales by the type of product that was sold and the region. To split into more categories, select the Advanced option in the Group By dialog box. From there, you’ll have the ability to specify more levels to break sales down by.

Using advanced rules for the group by method in Power Query.

I can click on Add grouping to add more layers, such as Product Category and Region.

Adding more groupings in Power Query.

Now I have summations based on those different splits.

A summary in Power Query which shows totals by the different categories.

One thing you may still want to do at this point is to organize the data so that it is in some sort of order. To apply a sort, select the column you want to sort by and on the Home tab, indicate whether you want it to be in ascending or descending order. In the below example, I have arranged the data by sales rep, then product category, and then by region.

Data that has been summarized, grouped, and sorted in Power Query.

If you liked this post on How to Sum and Group Values in Power Query, 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.

ReplaceNullValueswithAveragesinPQ

Replace Missing Values in Power Query With an Average

A common problem you might come across with data is that it may sometimes contain missing values. You can remove the data entirely or you can replace the values with something else. If you remove it, you might throw away other useful data related to that record in the process. If you replace it, you don’t want to just replace missing values with a zero, as that can impact your calculations. The optimal choice may be to replace it with the average of the other values. In this post, I’ll show you how you can easily do that in Power Query.

Calculating an average in Power Query

Here is the data set I’m starting with in Power Query, where you’ll see numerous null values in the Price field:

A data table in Power Query which is missing values.

To calculate an average in Power Query, follow these steps:

Select the column you want to calculate the average for. On the Transform tab, select Statistics and select Average.

Select the average function in Power Query.

Power Query now creates a separate step for me which has calculated the average:

Power Query calculating the average of the Price field.

To easily reference this value later on, I’m going to rename this step as AveragePrice.

Replacing the values

Now that you have calculated the average, you can use it to replace the null values in your data set. To do this, you’ll again need to highlight the column which contains null values. Right-click and select Replace Values:

Replacing values in Power Query.

Enter ‘null’ as the value you want to replace and just enter ‘1’ as the value to replace it with. This will just be a temporary placeholder.

Replacing null values with a 1 in Power Query.

In the formula bar, replace the ‘1’ with the name of the step — AveragePrice:

Adjusting a formula in Power Query so that it references the average price.

You’ll get an error saying there is a circular reference:

A cyclic reference in Power Query.

To fix this, drag the new step you just created so that it comes after the AveragePrice calculation step.

Moving the replaced value step in below the AveragePrice step in Power Query.

This still results in an error, and that’s because the formula is now referencing the AveragePrice step. This needs to be adjusted so that it references the Source step — or the one which contains the data immediately before the average price calculation.

Adjusting the Power Query formula so that it references the Source step.

Now the field is correctly updated and the null values have been replaced with the average for the column:

Power Query table after the null values have been replaced with an average.

In this situation, we now have eliminated the null values while being able to keep the other fields and simply replaced the empty values with averages.


If you liked this post on how to Replace Missing Values in Power Query With an 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.

CryptoUsingPowerQuery

Get Crypto Prices for Multiple Coins Into Excel Using Power Query

Do you want an easy way to pull in crypto prices for multiple coins? Using Power Query in Excel, you can accomplish this by connecting to a website such a coingecko.com and downloading the historical values. Below, I’ll show you how you can pull in historical prices for multiple coins at once, and how you can easily update the values in the future.

Here are the steps to download crypto prices and import them into Power Query from coingecko.com:

  1. Connect to the data source using Power Query.
  2. Download the files into a folder.
  3. Combine and Transform the files in Power Query.
  4. Modify the data to make it consistent.
  5. Update the data.

Step 1: Connect to the data source using Power Query

In this example, I’m using coingecko.com as my source but the process may be similar for other sources. As long as the data as in a table format, there may not be a big difference in the process, however, there could be subtle changes in how you get data from one site versus another.

First, navigate to the coingecko.com website to the cryptocurrency’s price history that you want to download. On the historical data tab, there is a link to download the data:

Historical price data for bitcoin.

Step 2: Download the files into a folder

Download this file and save it into a folder. Repeat the process for any other cryptocurrencies that you want to track historical price information for. In this example, I’ve downloaded the price history for Bitcoin, Ethereum, Shiba Inu, and Dogecoin, and saved it within a folder called ‘Crypto’ on my computer:

Crypto excel files in a folder.

Step 3: Combine and transform the files in Power Query

Now that all the files have been downloaded, I can use Power Query to consolidate them. With all the files in a folder, I can go and select to get data From Folder:

Selecting to get data from a folder.

Then navigate to the folder which contains your downloads:

Folder which contains downloaded files to consolidate in power query.

Since you are selecting a folder, you won’t see the individual Excel files that you have saved — this is fine. Only if you were selecting files would you see the actual files. Once you’ve selected the correct folder, click on the Open button.

Next, select the option to Combine &Transform the files. If you get an error saying that it is an unexpected format, you may need to click on Edit on the next screen. This is because in this example, the data is in a comma-separated value format. After clicking edit, make sure you select the option for a CSV document:

Selecting the option to open the files as a CSV document.

Then, at the next screen, you’ll see that the data has correctly been broken out into columns.

CSV data in Power Query broken out into separate columns.

This is how the data looks loaded in Power Query:

Combined crypto data loaded into Power Query.

Step 4: Modify the data to make it consistent

There are multiple changes that need to be made to the file. The first is to adjust the source.name field so that it reflects the coin and doesn’t include the full filename. To do this, click on the Transform tab and select the option to Extract Text Before Delimiter and use – as the delimiter.

Extracting text before delimiter in power query.

Then, I’ll rename the first two headers to ‘symbol’ and ‘date’

Power Query table after renaming columns.

Next, to correctly parse out the date, I’m going to grab the first 10 characters in the field. To do this, select the date column, and on the Transform tab, select Extract and select First Characters:

Extracting the first characters in a Power Query field.

Specify 10 for the number of characters, and Power Query will remove the rest:

Power Query table after the date field has kept only the first 10 characters.

I’ll remove the market_cap and total_volume columns since they aren’t needed. The last step involves pivoting the data so that the crypto symbols are going across. To do that, select the symbol column, and on the Transform tab, click on the Pivot Column button:

Pivoting a column in Power Query.

Select ‘price’ as the values column. Then, the end result should show the crypto prices going across:

Power Query table with crypto prices going horizontally and dates going vertically.

Step 5: Update the data

Now that the data is all entered in Power Query format, the process of updating it at a later date is fairly straightforward. Simply download the Excel files again, save them into the same folder (overwriting the previous files), and then click on the Refresh Data button on the Data tab:

Refreshing data in Power Query.

Clicking the button will refresh all the queries and do all the transformations and adjustments that were made earlier. By setting this all up in Power Query, you can easily repeat the process. Just download the latest data, and then click Refresh All.


If you liked this post on Get Crypto Prices for Multiple Coins Into Excel Using Power Query, 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.

CryptoCoinDominance

How to Calculate Crypto Coin Dominance Using Power Query in Excel

Crypto coin dominance is a vital metric in the cryptocurrency market, providing insights into the relative market strength of a particular cryptocurrency, compared to the overall market. It reflects the proportion of a specific cryptocurrency’s market capitalization in relation to the total market cap of all cryptocurrencies. This metric is particularly significant for investors as it indicates the level of risk, market sentiment, and the dominance of major players like Bitcoin and Ethereum.

Formula for calculating crypto coin dominance

To calculate crypto coin dominance, you the formula itself is fairly straightforward: divide the market capitalization of the cryptocurrency in question by the total market capitalization of all cryptocurrencies. Market capitalization, in this context, is calculated by multiplying the current price of the crypto coin by its total circulating supply.

For instance, if Bitcoin has a market cap of $700 billion and the total market cap of all cryptocurrencies is $2 trillion, Bitcoin’s dominance would be 35%.

Why is this useful for investors?

Crypto coin dominance helps investors understand the weight of a particular cryptocurrency in the market, aiding in diversification and risk assessment strategies. A high dominance might suggest a more stable investment but with potentially lower growth prospects, while a lower dominance could indicate a more volatile but possibly high-growth opportunity. Additionally, shifts in dominance can signal broader market trends, helping investors to anticipate and react to market movements.

Calculating crypto coin dominance in Excel is a practical way for investors to actively monitor these shifts and make informed decisions. By regularly updating the market cap data for various cryptocurrencies, investors can use Excel to quickly calculate and track changes in dominance, enabling them to identify trends and adjust their portfolios accordingly.

Pulling in crypto market caps into Excel

To calculate coin dominance in Excel, you can use Power Query. Through Power Query, you can pull in the data, and do calculations to determine the dominance percentage.

You can find a list of the top cryptos by market cap from the following URL in Yahoo! Finance: https://finance.yahoo.com/u/yahoo-finance/watchlists/crypto-top-market-cap/

To get this data into Excel, take the following steps:

Go to the Data tab and select ‘From Web’

Selecting the From Web option in the Data section of Excel.

Paste the link the following prompt and click OK.

Using the From Web option in Power Query to import data.

Select the table in Power Query which contains data on the crypto market caps. Then Load the data.

Selecting a table to import from Power Query.

The data is now in Excel but there are no calculations happening just yet. To get this to work, we need the total crypto market cap. The table in Yahoo! Finance didn’t have this information readily available to pull into Power Query. Instead, I’ll leave a place in Excel where the data can easily be entered.

Currently, the crypto market cap is $1.8 trillion. Since the majority of crypto market caps are in billions, I’ll put this in the form of billions, as 1,810.

Exporting data into Power Query from a range in Excel.

Next, I’ll load this into Power Query. With one of the cells selected, click on the Data tab again, this time, select From Table/Range

Exporting data into Power Query using the From Table/Range option.

In Power Query, I’m going to rename this table MarketCap and the other one as YahooFinance.

Calculating coin dominance in Power Query

Before I start my calculations, I need to first convert the market caps from the YahooFinance in terms of billions, and remove the ‘B’ that comes after them. Currently, those values are reading as text, and they need to be numbers. In the YahooFinance table, highlight the column which contains the market cap. Then, on the Transform tab, click the Extract option and select Text Before Delimiter

Selecting a column in Power Query to parse out numbers from.

Just enter the letter ‘B’ for the delimiter and press OK on the next screen.

Parsing out the text before a delimiter in Power Query.

Then, it’s necessary to convert the text into numbers. For that, select the ABC indicator on the header for the market cap, and select Decimal Number for the type.

Converting a column into a decimal number format.

After doing so, the data in the column aligns to the right, indicating the field is a number.

The last part involves creating a new column to calculate the market dominance percentage. For this, go onto the Add Column tab in Power Query. Then, select the option for a Custom Column.

Adding a custom column in Power Query.

I’m going to name the column ‘Dominance’ and this is where I’ll need to enter my formula. The numerator will be market cap column, which in this case is Column9. I will divide this by the value in the MarketCap table. To reference that value, I need to use the following syntax: MarketCap[MarketCap](0}.

The table is called MarketCap, as is the field name, which is in parenthesis. Since I want the first value in the list, I use {0} since it is a 0-based index. That returns the total market cap I entered of 1,810. To put this all together, this is what the formula looks like in my Custom Column calculation:

Custom column calculation in Power Query which calculations coin dominance percentage.

After clicking OK, now my dominance column appears. Now I can load the data into Excel. All that’s left is to convert the column into a percentage.

Excel table showing crypto coin dominance.

Power Query will create another sheet for the MarketCap, but you can delete that as it isn’t necessary.

Updating the file

Moving forward, to update the calculations, all you need to do is update the MarketCap value. This is the only value that won’t pull in automatically from the Yahoo! Finance link. Then, click on the Refresh button on the Data tab and Power Query will pull in the updated market caps for the top cryptocurrencies, and then do the dominance percentage calculation.

Refreshing the data in Power Query.

Ideally, the total market cap could also be pulled in. However, given the vast number of cryptocurrencies, the list in Yahoo! Finance isn’t comprehensive enough; nor is there a table to pull just from market cap. If you do come across a better source for pulling in crypto market caps, let me know!


If you liked this post on How to Calculate Crypto Coin Dominance Using Power Query 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.

CoreInflation

How to Calculate Inflation, Core Inflation, and CPI in Excel

Inflation is a critical economic indicator, reflecting the rate at which the general level of prices for goods and services is rising, and subsequently, how that erodes the purchasing power of money. To gauge inflation accurately, economists and policymakers rely on various metrics, with the Consumer Price Index (CPI), the Personal Consumption Expenditures Price Index (PCE), and the Core PCE being the most prominent. Each of these measures has its unique methodology and scope, making them useful in different economic contexts.

Let’s start with breaking down how these different measures are calculated, and what their strengths and weaknesses are.

Consumer Price Index (CPI)

The CPI, published by the Bureau of Labor Statistics, is one of the most widely recognized measures of inflation. It calculates the average change over time in the prices paid by urban consumers for a basket of goods and services. This basket includes a wide range of items such as food, clothing, shelter, fuels, transportation fares, charges for doctors and dentists’ services, drugs, and the other goods and services that people buy for day-to-day living. Prices are collected monthly from about 75 urban areas across the country, from about 6,000 housing units and approximately 22,000 retail establishments.

The strength of the CPI lies in its detailed breakdown of expenditure categories, which makes it a useful tool for understanding the impact of inflation on consumers. However, it has its limitations. For instance, it does not account for changes in consumer behavior or substitutions they make in response to price changes. Also, the CPI focuses only on urban consumers and may not accurately represent the experience of people in rural areas.

Personal Consumption Expenditures Price Index (PCE)

The PCE, published by the Bureau of Economic Analysis, measures the prices that people living in the United States, or those buying on their behalf, pay for goods and services. Unlike the CPI, the PCE includes all goods and services consumed by households, including those paid for by third parties such as employer-provided healthcare. The PCE is calculated by using data on nearly all goods and services businesses sell to households and on the incomes that households receive from business and from government.

One key advantage of the PCE is its ability to reflect changes in consumer behavior and the substitutions they make, which the CPI does not fully capture. This makes the PCE a broader measure of inflation. However, its wide scope can sometimes dilute the impact of price changes in specific categories, which might be more apparent in the CPI.

Core PCE

The Core PCE Price Index is a version of the PCE index that excludes the more volatile and seasonal food and energy prices. By excluding these items, Core PCE provides a clearer picture of the underlying inflation trend and is less subject to short-term volatility. This makes Core PCE a preferred metric for policymakers, including the Federal Reserve, when making decisions about monetary policy. This metric is often referred to as ‘core inflation.’

The exclusion of food and energy prices can be both a strength and a weakness. While it offers a more stable view of inflation, it can sometimes underrepresent the actual burden on consumers, especially during periods when food and energy prices are rapidly changing.

Calculating CPI, PCE, and Core PCE

Now that we know what these metrics are, let’s grab that data and plot them in a chart, to see how they have been trending in recent periods.

CPI can be downloaded from www.bls.go/cpi. The link to get the historical data can be found at https://data.bls.gov/timeseries/CUUR0000SA0?years_option=all_years. You can follow along with this post on how to calculate the inflation rate based on this data set with Power Query.

PCE and Core PCE can be downloaded from the stlouisfed website. Below are the follow links you can use to access the data for each of them: https://fred.stlouisfed.org/series/PCEPI and https://fred.stlouisfed.org/series/PCEPILFE. This data can easily be downloaded from the Fred website and compared both metrics.

For the % change, take the current month value and divide it by the same value in the prior-year month and deduct 1. Here’s how all the data points and inflation rates look when compared against one another:

With that data set up, it’s now easy to plot the different inflation rates on a chart to see how they have varied and converged over the past year and a half:


If you liked this post on How to Calculate Inflation, Core Inflation, and CPI 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.