How to Calculate Combinations and Permutations in Excel

Combinations and permutations are fundamental deal with the arrangement and selection of objects or elements from a set. While both combinations and permutations involve counting possibilities, they differ in terms of the order and repetition of elements. In this post, I’ll show you how to calculate both permutations and combinations in Excel, both with and without replacement and repetition.

What is a permutation?

A permutation refers to an arrangement of objects from a set, where the order matters. In other words, permutations consider the different ways in which objects can be arranged. For example, let’s take the set {A, B, C}. The permutations of this set would be ABC, ACB, BAC, BCA, CAB, and CBA. The number of permutations can be calculated using the formula:

nPr = n! / (n – r)!

Where n represents the total number of objects in the set and r denotes the number of objects being selected for each arrangement. The exclamation mark denotes factorial, which means multiplying a number by all the positive integers less than it down to 1.

Suppose you want to consider all 26 letters of the alphabet — this would be the n value. Now, if you want to know all the different permutations when selecting 3 characters, that would be your r value. To calculate the number of different permutations, your formula would be as follows:

nPr = 26! / (26 – 3)!

This gets simplified to:

nPr = 26! / 23!

Rather than doing this complex calculation, you can first cancel out the numbers going up until 23 on each side. Then you’re left with the following:

26*25*24 = 15,600

This tells us that there are 15,600 different permutations when selecting the three letters from the alphabet. The preceding formula assumes that you are not replacing objects. If, however, you are replacing them then that means you can select the same item multiple times. In this situation, the formula for calculation permutations with replacement is as follows:

=n^r

When choosing 3 letters from the alphabet, the result would be:

26^3 = 17,576

In this situation, you have will have more possible permutations since the objects can repeat.

What is a combination?

If you’re talking about combinations, then the difference here is that you don’t consider the order as you would with permutations. In the earlier example where the set was {A,B,C} and you needed to select three characters, there would only be 1 combination. That’s because whether it’s ABC, BAC, CAB, or any other order of the characters, that’s irrelevant since combinations don’t care about order. The letters are all the same, and thus, there would only be 1 possible combination.

The number of combinations can be determined using the formula:

nCr = n! / (r!(n – r)!)

Let’s do this again, when selecting 3 letters from the alphabet:

nCr = 26! / (23! (26-23)!)

That formula simplifies to this:

nCr = 26! / 23! (3)!

And again, up until 23, everything gets canceled out, leaving the following:

nCr = (26*25*24)/(3*2*1)

This is the same as the result from the permutation calculation but the difference is that the denominator is now larger; it is calculated as the r factorial. Upon completing this formula, the result is:

15,600/6 = 2,600

This is the number of permutations divided by the factorial of 3, the number of selections. If there are replacements and you select the same item multiple times, this is the formula:

(n + r -1)! / (r!(n-1)!)

This results in the following calculation:

(26 + 3 -1)! / (3!(26-1)!)

This simplifies to:

(28)!/(3!(25)!)

Which further simplifies to:

(28*27*26)/(3*2*1) = 3,276

How to calculate permutations and combinations in Excel

In the above examples, I showed you how you can calculate permutations and calculations manually. But with Excel, there are formulas that can do the work for you.

To calculate permutations, we use the PERMUT function when there are no replacements. In the first example where there were 3 items chosen from a set of 26, this is the PERMUT formula:

=PERMUT(26,3) => 15,600

It returns the same result. If there are replacements, then the PERMUTATIONA formula is used:

=PERMUTATIONA(26,3) => 17,576

For combinations, the default function is COMBIN:

=COMBIN(26,3) => 2,600

And when there are replacements, COMBINA is used:

=COMBINA(26,3) => 3,276

These results all match up with the calculations from the previous examples, where they were done manually.

How to calculate the Powerball odds

For the Powerball, there are two draws that happen. The first is where 5 numbers are chosen from 69 possible items. Then, in the second draw, there is 1 number that selected from 26 possibilities. When dealing with probabilities, when we want both events to happen, we need to multiply the odds. The first step will be to calculate the individual combinations. Since there is no replacement, the formula for the first draw is as follows:

=COMBIN(69,5) => 11,238,513

For the second draw, the calculations straightforward since there is only 1 item selected from 26 possible options, so there can only be 26 combinations. Thus, to calculate the Powerball odds where you win both the first draw and the second draw, you need to multiple the odds of winning the first draw by the odds of winning the second draw:

=11,238,513 x 26 = 292,201,338

This tells us that the odds of winning both draws are 1 in 292 million.


If you liked this post on How to Calculate Combinations and Permutations 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 me on Twitter and YouTube. Also, please consider buying me a coffee if you find my website helpful and would like to support it.

ExcelDatabase1

Can You Use Excel as a Database?

Microsoft Excel is a powerful spreadsheet software that people use for data analysis, calculations, and reporting. While Excel is primarily designed for managing and manipulating tabular data, many users have explored using it as a database. In this article, I will go over the pros and cons of using Excel as a database, highlighting its limitations and advantages compared to SQL and other alternatives.

Benefits of using Excel as a database

1. Familiarity and Accessibility

Excel enjoys widespread usage, and millions of users are already familiar with its interface and basic functionalities. It is easily accessible and requires no additional software or technical expertise to get started. This means no costly support bills as there are many users all over the world who can provide expertise on spreadsheets. And it’s already included in Microsoft 365, which many businesses already pay for.

2. Quick and Easy Data Entry

Excel provides a user-friendly environment for entering and editing data. Its intuitive grid layout allows for easy data input, and its familiar formula syntax enables simple calculations and data manipulation. You can also create templates for data entry so that it is customized to your company’s needs. Through userforms and visual basic, you can even create wizards that walk users through personalized data entry screens.

3. Simple Sorting and Filtering

Excel offers basic sorting and filtering capabilities that can be helpful for simple data analysis and organization. Users can sort and filter data based on specific criteria to extract relevant information quickly. This can make it easy to review and analyze data on-the-fly. Slicers also add convenience and can make filtering options even easier, giving users the ability to quickly apply filters with just a few clicks of a mouse.

4. Flexible Data Visualization

Excel provides various charting and graphing tools to visualize data effectively. Users can create professional-looking charts and graphs without the need for complex coding or external software. Pivot tables and pivot charts can be created within a few seconds and Excel has many chart templates available that can quickly summarize and display data. You can even create complex 3D bubble charts for more advanced models.

5. Low Learning Curve

Excel’s user-friendly interface and widespread familiarity make it more approachable for non-technical users. In addition to Microsoft’s tutorials, you can find help on message boards, and other websites, like this one, that can help you learn how to use Excel. There are also many YouTube videos covering tutorials as well. Oftentimes, you’ll find users with similar or even the exact problems you are experiencing, making it easy to find a solution with a simple search. In contrast, SQL and other database systems often require specialized knowledge and training.

6. Cost-Effectiveness

Excel is usually included in the Microsoft Office suite, which is commonly available in many organizations. Dedicated database systems may require additional licensing costs and infrastructure investments. With Excel, you just pay a recurring fee for Microsoft 365. And if you have an older off-the-shelf Excel product, you can use it indefinitely without having to pay a subscription fee.

7. Quick Prototyping and Ad Hoc Analysis

Excel’s ease of use allows for rapid prototyping and ad hoc analysis. Users can quickly create and modify data structures, perform calculations, and experiment with different scenarios without complex setup or formal data modeling.

Disadvantages of using Excel as a database

1. Limited Scalability

Excel is not designed to handle large datasets or complex data relationships. It has a practical limit on the number of rows (1,048,576 in Excel 2019) and can become sluggish when dealing with vast amounts of data. Additionally, as the file size grows, it can lead to performance issues and increased chances of data corruption.

2. Lack of Data Integrity and Security

Excel lacks built-in mechanisms for ensuring data integrity and enforcing strict security measures. It offers limited data validation features and minimal control over user access and permissions. This makes it prone to human errors, accidental data modifications, and unauthorized access. While macros, locked cells, and additional controls can be added to make a file more sure, they’re by no means ironclad; if you need to keep information confidential, then it’s best not to hold the data in Excel.

3. Lack of Concurrent Access and Collaboration

Excel files are typically stored on local machines, making it challenging for multiple users to collaborate simultaneously. Sharing and managing Excel files across different users can lead to version control issues and data inconsistencies. And if you’re using macros, then multiple users cannot be in the same file at once. This is one of the biggest drawbacks of trying to use Excel as a database and it’s one of the first questions I ask people who want to create a file that multiple people are using — do they need to be in it at the same time? If so, then Excel isn’t the right solution.

4. Limited Data Analysis and Reporting Capabilities

Excel’s analytical capabilities are limited compared to dedicated database systems like SQL. It lacks advanced querying capabilities, complex aggregations, and data mining functionalities, which can hinder advanced data analysis and reporting needs. While advanced users can create complex and custom reports, for those who aren’t comfortable doing it themselves, they may prefer using a different system.

Should you use Excel as a database?

Excel has lots of great functionality and by now it should be clear that you can use it as a database. However, the more important question is whether you should do so. There are three questions you can ask yourself to help make that decision:

  • Do multiple people need to be in the file at the same time?
  • Do you have a large database that may require more than 1 million rows in a single table?
  • Are you holding sensitive information (e.g. credit cards, social security numbers) in your database?

If you answer yes to any of those questions, then Excel probably isn’t going to work for you. But if you answered ‘no’ to all of them, then you may benefit from storing your data in Excel and using it as a database.

Regardless of what IT experts may tell you, there are situations where Excel can be used as a database and where it makes sense to do so, especially when the alternative is a costly system which requires ongoing maintenance and where support can be expensive.


If you liked this post on Whether You Can Use Excel as a Database, 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.

ChartWithinaChart

How to Create a Column Chart Within Another Column Chart

A column chart can be useful in data analysis to show growth, compare values, and display values by period. One of the drawbacks of a column chart is that as you add more data series and values to compare against, it starts to stretch out your chart. And when that happens, the data becomes more difficult to read. One way to conserve some space and to create a nice visual is by embedding one column chart within another. By doing this, you can show relative values. For example, one column chart might show total sales, while the embedded chart can show how much a particular product or geographical area accounted for.

Creating the column chart

In this example, I’m going to use the data set from the following webpage, which shows brewpub openings and closings by year (https://www.brewersassociation.org/statistics-and-data/national-beer-stats/).

I’ve created a table of the data by year:

Table showing brewpub openings and closings by year.

In this example, I’m going to use the openings as my outer column chart and the brewpub closing values as my inner column chart. This is because I know the closing values will be less than the opening values. When I first create the chart, I get both series showing up side by side:

Column chart showing brewpub closing and opening values.

This is how you might normally look at these values when using column charts. But this time, I want the orange columns to be within the blue ones. Before I merge them together, I’m going to put the other chart on a secondary axis by right-clicking the chart and selecting Change Chart Type. At the bottom, I select Combo and make sure that they are both set to Clustered Column with the Closing series set to the Secondary Axis:

Setting a secondary axis for a column chart.

You can see that there is already a bit of an overlap in the charts. But the problem is that the axis have different ranges. To fix this, I’ll click on the secondary axis and select Format Axis. I will adjust it so the maximum value is set to the same as the maximum for the initial axis — 500. After doing that, my chart now looks like this:

Two column charts overlapping one another.

This is already getting close what I wanted initially. However, I still want to have more of an embedded effect, for the closing series to be within the opening series. Now, if I right-click on the blue column chart and select Format Data, I’ll have an option to modify the Gap Width. What the gap width does is shrink the amount of white space between the columns. After setting it to 25, it looks like this:

Column charts after changing the gap width.

Next, I’ll set the orange columns to a gap width of 80:

One column chart embedded within another one.

The only thing left is possibly changing the color. To show that the two items are related, I prefer to use colors that are similar, with one being a darker shade than the other. I’ll also change the secondary axis font to white so that it is not visible, and add some vertical gridlines. That leaves me with this end result:

Two blue column charts, one within the other.

If you liked this post on How to Create a Column Chart Within Another Column Chart, 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.

TrendingStocks

Get Trending Stocks Into Excel Using Power Query

In the fast-paced world of investing, identifying trending stocks in Excel can provide a valuable edge for investors seeking profitable opportunities. Fortunately, with the power of Excel’s Power Query and the ability to connect to a website’s API, accessing real-time data and uncovering trending stocks has become more accessible than ever. In this article, I will go through the process of using Power Query to connect to a website’s API and importing in trending stock information.

Why should investors try to identify trending stocks?

As an investor, it is crucial to identify trending and popular stocks for several reasons:

  1. Profit Potential: Trending and popular stocks often have significant profit potential. When a stock is gaining popularity, it usually attracts more investors, leading to increased demand and potentially driving up the stock price. By identifying these stocks early, you can position yourself to benefit from the price appreciation and generate higher returns on your investment.
  2. Liquidity: Popular stocks tend to have higher liquidity, meaning there is a larger pool of buyers and sellers in the market. This liquidity allows you to enter and exit positions more easily, ensuring that you can buy or sell shares without significantly impacting the stock’s price. Investing in liquid stocks provides flexibility and reduces the risk of being unable to execute trades at desired prices.
  3. Market Validation: The popularity of a stock often reflects positive market sentiment and investor confidence. When a company is trending and gaining attention, it may indicate that the market believes in its growth prospects and overall performance. By identifying such stocks, you can align your investment choices with market sentiment and increase the likelihood of investing in companies with strong fundamentals and future growth potential.
  4. Information Availability: Popular stocks generally attract more media coverage, research reports, and analyst attention. This increased coverage provides you with a wealth of information and analysis to make more informed investment decisions. You can leverage these resources to understand the company’s financial health, competitive position, industry trends, and other relevant factors that can impact the stock’s performance.

How to get trending stocks in Excel

To get trending stock data into Excel, you should start with finding a good source that you can rely on for trending data. For this example, I’m going to use apewidsom.io, which provides free access to its API using the following url: https://apewisdom.io/api/. Here’s how I’m going to use that to pull in trending data:

Extract the data using Power Query. To get started, I’ll select the Data tab in Excel and click on the From Web option.

    Select the From Web option in Get & Transform Data to set up Power Query so that it connects to a certain web page.

    Next, there will be a field to enter the URL, this is where I will paste the link that the API references:

    https://apewisdom.io/api/v1.0/filter/all-stocks/page/4
    

    Entering a URL in the From Web field for creating a Power Query connection.

    After clicking OK, Power Query will launch. When the screen opens up, the following table appears. I click on List to open up another table.

    Power Query results stored in a list.

    After clicking that, there’s another list of records.

    A list of records in Power Query.

    Here, I’ll select the option to convert to table and leave the default settings and click OK. Then, there is another list of records. Clicking on the button with the arrows going in opposite directions will expand them:

    Expanding a list of records in Power Query.

    After expanding out those records, the table will now looks like a list of stocks and metrics relating to mentions, upvotes, and overall rank popularity:

    Power Query table showing a stock's populating by mentions and upvotes.

    Now that this has been setup, I will convert this into a Power Query function. To do that, I’ll click on the Advanced Editor button:

    Selecting the advanced editor option in Power Query.

    In the editor, I will add a line at the top to specify the name of the function. And at the bottom, I will add a line to circle back to it. Lastly, I’ll add a variable for the URL as well, and put that where the link used to be:

    Power Query code for a custom function.

    Next, with the custom function created, I’m going to go back into Excel and create a list of all the URLs I want to use this function on. In this situation, I’m going to adjust the page number at the end of the URL so that I have pages 1 through 5:

    A table of URLs.

    I’ll load this table, called URLtable, into Power Query using the From Table/Range button when selecting data. Next, I’ll select the Add Column tab and select Invoke Custom Function:

    Selecting the option to Invoke a Custom Function.

    Then, I reference the query as well as the URL variable that is to be used:

    Selecting which custom function to invoke.

    Then, there will be a field with the results, in table format. Again, this needs to be expanded out:

    A list of results in Power Query after invoking the custom function.

    That will leave a list of stocks starting from page 1 all the way through page 5. You can remove the URL field, which is no longer needed:

    A Power Query table showing the list of popular stocks.

    If you don’t want to follow through all those steps yourself, you can download the template I’ve created here.


    If you liked this post on Get Trending Stocks 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 me on Twitter and YouTube. Also, please consider buying me a coffee if you find my website helpful and would like to support it.

    CustomPQFunction

    How to Create a Custom Function in Power Query

    Excel’s Power Query is a powerful data transformation and analysis tool that allows users to retrieve, clean, and shape data from various sources. While Power Query provides an extensive set of built-in functions, there may be scenarios where you need to perform custom operations on your data. This is where custom functions in Power Query come into play. In this article, I will go over how to create a custom function in Power Query that you can invoke and re-use.

    Steps to creating a custom function in Power Query

    Creating custom functions in Power Query involves using the M language, which is the scripting language underlying Power Query. It can be complicated to create but I’ll show you two ways you can create a function. The first method is directly through coding, the other is after converting a query into a function.

    In this example, I’m going to pull all the stocks that are contained from a list of exchange-traded funds (ETFs). I’ve created the following table for this purpose, called tblETF:

    A table of different exchange-traded funds listed.

    Creating a custom function from scratch

    If you’re creating a function in Power Query directly from code, here’s how to do that:

    1. Go to load the data into Power Query by selecting a cell in your table, then click on the Data tab and click From Table/Range.

    Launching Power Query from the From Table/Range button.

    2. That will open up Power Query. Once there, on the Home Tab, click on the Advanced Editor button:

    Selecting the Advanced Editor option in Power Query.

    3. Create a name for the function using the let variable. In this example, I’m going to call it getholdings and it will pull all the holdings from the etf field. The opening line of the code is as follows:

    let getholdings = (etf) =>

    4. Next, list the commands that the function should execute. I’m going to pull the data from the stockanalysis.com page relating to the etf. This requires using the Web.Contents function and modifying the URL so that it includes the etf symbol:

    let

    Source = Web.Page(Web.Contents("https://stockanalysis.com/etf/"&etf&"/holdings/")),

    Then, reference the data as follows:

    Data0 = Source{0}[Data],

    The full code looks like this:

    Custom macro in Power Query that gets the ETF holdings.

    5. Now that the function is created, go into the query for the list of ETFs. Create an additional column from the Add Column tab, and select the button to Invoke Custom Function.

    Selecting the Invoke Custom Function option in Power Query.

    6. Set a column name for the new column. Then, specify the function query to reference. And you’ll also need to specify where the ETF value is coming from, which involves selecting the column:

    Invoking a custom function in Power Query.

    7. Next, you’ll expand the table that has been created within the column. This is done by pressing on the icon that shows arrows going in opposite directions. Then, select all the available columns.

    Expanding a table in Power Query.

    You should end up with something that looks like this:

    Fully expanded Power Query table showing holdings by ETF.

    You can now click Close & Load and this data will load in your Excel spreadsheet. Now you can add to your ETF list and refresh the data, and the table of all the holdings will populate.

    List of ETFs and their related holdings in two separate excel tables.

    Converting a query into a function

    If you’re not comfortable coding with Power Query, you can first create the steps, and then convert the query to a function.

    First, it’s necessary to create the query. In the previous example, I loaded the URL from a dynamic web page. To do that, I’ll start with selecting the From Web button on the Get & Transform Data section:

    Using the From Web button on the Get & Transform Data section in Excel.

    Next, populate the entire link, without the ETF variable — this will be added later:

    Setting the URL that you want to pull data from into Power Query.

    Then, select the table that contains the data and click the Load To button and select connection only:

    Selecting the table in Power Query that contains the ETF holdings.

    Then, right-click on the query to edit it so that you’re back in Power Query. From there, click on the Advanced Editor and you should see this:

    Power Query advanced editor showing the code to extract data from a web page.

    This is similar to the code in the first approach. To convert this into a function, we need to add another let variable and specify the function name, and any variables that will be used in the function. For the first line, I’ll add the following

    let getholdings = (etf) =>

    and for the URL, I’ll put the etf variable into there:

    Source = Web.Page(Web.Contents("https://stockanalysis.com/etf/"&etf&"/holdings/")),

    For the last line, I’ll add another in variable:

    in getholdings

    Here’s the updated code, with the changes highlighted in yellow:

    Now I’ve converted my query into a function that can be invoked.


    If you liked this post on How to Create a Custom Function 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 me on Twitter and YouTube. Also, please consider buying me a coffee if you find my website helpful and would like to support it.

    HstackVstack

    Use VSTACK and HSTACK in Excel and Google Sheets to Consolidate Lists

    Do you have multiple lists in Excel or Google Sheets that you want to combine together? With new functions such as VSTACK and HSTACK, you can do just that. In this post, I’ll show you how you can also filter out duplicates and apply sorting so that your data is organized after consolidating all of your lists.

    Combining multiple stock lists into a large one

    In this example, I’ll use various stock lists that I want to combine into one large list. On Yahoo Finance, you can find an assortment of different lists to help filter stocks. Below, I’ve pulled the lists of stocks that recently hit new 52-week highs, smart money stocks, medical device and research stocks, and e-commerce stocks:

    Lists of stocks from Yahoo Finance posted in an Excel spreadsheet.

    The advantage of keeping the lists separate is that you can more easily update them. And by using VSTACK, you can combine these lists into a larger one so there’s no worry about having to consolidate them later on.

    Based on the lists above, this is the formula that I use to combine them all together, using VSTACK:

    =VSTACK(A2:A31,B2:B10,C2:C31,D2:D20)

    Since I don’t want to include the headers, I start from row 2. You’ll notice that I’ve hardcoded the ranges here. One way to make this more dynamic would be to use a COUNTIF or COUNTA function for the individual lists, and then use the INDIRECT function to limit the scope of the list. Another option involves converting the lists into tables. That way, you only have to list the table column and you don’t have to worry about the ranges. The one caveat here is that if you have lists that have different lengths, you’ll want to make each list its own table. Otherwise, Excel will automatically fill in the gaps with blank values:

    List of stocks in a table.

    While the data looks correct, if I were to use the VSTACK formula for these different table columns, I would get a consolidated list that involves many zero values. To keep it cleaner, it’s easier to just separate them into their own tables, and then reference them afterwards.

    List of stocks broken down into multiple tables.

    To reference these columns, my formula becomes much simpler:

    =VSTACK(Table1[Recent 52-Week High],Table2[Smart Money Stocks],Table3[Medical Device and Research Stocks],Table4[E-commerce])

    The advantage of doing it this way is that now I don’t have to worry about hardcoding the ranges, and thus, it’s easier to update.

    Whichever method you prefer, the end result should look like a consolidated list:

    Consolidated list of stocks in Excel.

    Removing duplicates and sorting the list

    In some of these lists, there is some overlap. AMZN and META are two stocks that show up twice. This means that my consolidated list will include those values multiple times. To get around this, I can embed the formula within the UNIQUE function:

    =UNIQUE(VSTACK(A2:A31,B2:B10,C2:C31,D2:D20))

    If you also want to sort your list, then you can add the SORT function as well:

    =SORT(UNIQUE(VSTACK(A2:A31,B2:B10,C2:C31,D2:D20)))

    Use HSTACK for horizontal arrays

    If you have the same lists but instead have them going horizontally, then you can use the HSTACK function. It works the same way as the VSTACK but as the H suggests, it will require horizontal arrays. Here are the same list of stocks as in the first example, this time transposed so that they go horizontally:

    In this case, the formula for HSTACK would be as follows:

    =HSTACK(B1:AE1,B2:J2,B3:AE3,B4:T4)

    You can apply the same steps as for the VSTACK to eliminate duplicates and to sort the results.

    These formulas work the same in Google Sheets as in Excel

    Whether you’re working in Google Sheets or Excel, these formulas will be the same. The VSTACK, HSTACK, SORT, and UNIQUE functions are all available on the latest version of Excel and on Google Sheets. There is no need to change any of the formulas besides just adjusting for any difference in ranges. The formulas themselves work in the same ways, making it easy to transfer data between Google Sheets and Excel and to replicate these formulas wherever makes sense for you.


    If you liked this post on How to Use VSTACK and HSTACK in Excel and Google Sheets to Consolidate Lists, 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.

    FuzzyLookup

    How to Do a Fuzzy Lookup in Power Query

    Power Query is a powerful data transformation tool in Excel that allows you to effortlessly connect to various data sources, cleanse and manipulate data, and unlock advanced functionalities such as fuzzy matching. By leveraging the inherent “Fuzzy Lookup” feature within Power Query, you can seamlessly compare and match similar values across columns or tables using intelligent fuzzy logic algorithms. This article will highlight how you can use this functionality to help consolidate data, improve accuracy, and correct mistakes.

    What is the purpose of a fuzzy lookup in Power Query?

    A fuzzy lookup in Power Query refers to a powerful feature that allows you to match similar or related records within your dataset, even if they contain variations or discrepancies. Unlike an exact match that demands identical values, a fuzzy lookup takes into account the degree of similarity between values using intelligent fuzzy logic algorithms.

    Imagine you have a dataset containing customer names, and you want to compare it with another dataset to identify potential matches. However, due to typos, misspellings, or differences in formatting, the exact matches may not yield the desired results. This is where a fuzzy lookup comes to the rescue.

    By using a fuzzy lookup, you can overcome these obstacles. Power Query evaluates the similarity between values based on factors such as spelling variations, phonetic similarities, transpositions, and even differences in word order. This flexible approach allows you to find connections between records that might have otherwise been missed and unmatched.

    There are many benefits of fuzzy lookups. They enhance data accuracy and integrity by enabling you to identify related records that might have been entered inconsistently. They can consolidate information from different sources, harmonize data formats, and facilitate a comprehensive analysis of your datasets.

    Fuzzy lookups are particularly valuable when dealing with large datasets, data integration, data cleansing, or any scenario where data inconsistencies are prevalent. They provide a robust mechanism to uncover hidden associations that might have otherwise resulted in incomplete data. Leveraging the power of fuzzy lookups in Power Query can significantly improve the quality of your data analysis.

    What is the difference between an exact match and a fuzzy match?

    An exact match refers to a comparison between values that must be identical in every aspect, including spelling, punctuation, and formatting. It requires an exact one-to-one correspondence between the compared values.

    A fuzzy lookup, however, takes a more flexible approach by considering variations, similarities, and patterns within the values being compared. It utilizes fuzzy logic algorithms to calculate the degree of similarity between the values, allowing for differences in spelling, formatting, and other factors. Here’s an example:

    Dataset 1: “Robert Johnson” Dataset 2: “Robert Johhnson”

    In this example, an exact match would fail to identify a match due to the slight difference in spelling (“Johhnson” instead of “Johnson”). However, a fuzzy lookup would recognize the similarity between the values based on the fuzzy logic algorithms, identifying them as a potential match.

    While an exact match demands complete identity, a fuzzy lookup offers a more lenient approach by accommodating variations, spelling differences, abbreviations, and even phonetic similarities. It enables the discovery of relationships and connections that might otherwise be missed, allowing for more comprehensive data analysis and data integration.

    The limitations of a fuzzy lookup

    While fuzzy lookups in Power Query offer a powerful mechanism for matching similar records, it is important to be aware of their limitations. Understanding these limitations can help you effectively address challenges and make informed decisions when utilizing fuzzy lookups in Power Query.

    1. Performance Impact: Performing fuzzy lookups on large datasets can have an impact on performance. Fuzzy matching involves complex algorithms that analyze the similarity between values, which requires additional computational resources. When working with extensive datasets, it is advisable to consider the potential performance implications and evaluate whether optimization techniques, such as limiting the scope of matching or using more specific matching criteria, are necessary.
    2. Configuring Fuzzy Matching Parameters: The success of a fuzzy lookup heavily relies on properly configuring the fuzzy matching parameters. Selecting the appropriate similarity threshold and adjusting other options, such as case sensitivity or accents, is crucial. However, finding the right balance can be challenging, as overly strict or lenient parameters may result in missed matches or false positives. It often requires experimentation and fine-tuning to achieve the desired level of matching accuracy.
    3. Data Quality and Variations: Fuzzy lookups are highly dependent on the quality and consistency of the data being matched. Inaccurate or inconsistent data, such as misspellings, abbreviations, or incomplete information, can impact the effectiveness of fuzzy matching. While fuzzy lookups can handle some degree of variation, extreme discrepancies or inconsistent patterns in the data may hinder accurate matching.
    4. Ambiguity and Multiple Matches: In certain cases, fuzzy lookups may encounter situations where multiple records match a single value, leading to ambiguity. This can occur when there are similar records or when the matching criteria are not precise enough. Dealing with such scenarios requires additional consideration and possibly manual intervention to determine the correct matches.
    5. Sensitivity to Dataset Size and Complexity: The effectiveness of fuzzy lookups can vary depending on the size and complexity of the dataset. Extremely large datasets or datasets with high variability in the values being matched can pose challenges. It is important to assess the scale and complexity of the data and consider alternative approaches, such as data preprocessing or dividing the task into smaller subsets, to manage the impact on performance and improve matching accuracy.

    While fuzzy lookups provide valuable capabilities for identifying similar records, it is essential to be mindful of these limitations. There can be a risk of relying too heavily on fuzzy matches which results in erroneous results. By understanding and addressing these limitations appropriately, you can maximize the benefits of fuzzy lookups in Power Query and make informed decisions when incorporating them into your data analysis workflow.

    Steps to do a fuzzy lookup in Power Query

    Here’s a detailed overview of how to perform a fuzzy lookup in Excel:

    Step 1: Load your datasets into Power Query. Open Excel and go to the Data tab. Click on “Get Data” and select the appropriate option to load your datasets into Power Query. This could be from a file, a database, or any other supported data source. In this example, I have a couple of tables. One for the data entry, that contains misspellings. And another for the available values that users should have entered:

    Two tables in Excel.

    Step 2: On the data-entry table, select the Home tab and click on Merge Queries.

    The merge queries window in Power Query.

    Step 3: Select the other table and highlight the fields to merge. Leave the default join as a Left Outer and below it, select the option to Use fuzzy matching to perform the merge. Upon doing this, you should see Power Query indicate that it has found more matches.

    Merging tables in Power Query.

    You can also open up the fuzzy matching options to select whether you want the matches to be case-sensitive, and if you want to allow it to match by combining different text parts together. You can also limit the number of matches and set the similarity threshold.

    Specifying the fuzzy matching options in Power Query.

    Once you’re okay with the selections, you can click on OK.

    Step 4: Now, open up the and expand the table that has been merged. This will retrieve the matched values.

    A Power Query table after merging queries.

    If everything is matched correctly, you can go ahead and click Close & Load to get the data back into Excel. If there are issues, you may want to go the previous steps to check your fuzzy matching rules, and perhaps adjust the sensitivity of the matches.

    A Power Query table after merging and expanding the values.

    Using a Transformational Table to help fuzzy matching

    Fuzzy matches don’t always work. In some cases, you’ll need to create a transformational table to help guide Power Query. Here’s an example of when a fuzzy lookup won’t work:

    Two tables in Excel with similar values.

    These names are similar looking and there is a big opportunity for overlap. Even when using a low sensitivity threshold, it only matches 3 of the 6 names:

    Power Query's fuzzy matching only finds three out of six possible values.

    The one way to definitively fix this is to create a Transformational Table for Power Query. What this does is create mapping rules. The table needs to include a ‘From’ column and a ‘To’ column such as this:

    A transformational table in Power Query.

    Now, when you go back to the Merge Queries dialog and adjust the Fuzzy matching options, you can specify that this is the table you want to use:

    Using a transformational table in Power Query when specifying the fuzzy matching rules.

    Having this table will help Power Query understand which values are related to one another. It eliminates the guesswork and can ensure everything is mapping properly. It requires a bit of extra work but it can save time in the long run. Now when using this transformational table, it matches all of the values correctly:

    Power Query matches all the values after using a transformational table.

    If you liked this post on How to Do a Fuzzy Lookup 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 me on Twitter and YouTube. Also, please consider buying me a coffee if you find my website helpful and would like to support it.

    RSI

    How to Calculate RSI in Excel

    What is RSI?

    The Relative Strength Index (RSI) is a popular trading indcator that investors use for trading purposes. In this article, I’ll go over details as to what RSI is, why it’s useful, and how to calculate it in Excel.

    RSI is a bounded oscillator that fluctuates between 0 and 100, providing insights to investors as to whether a stock is overbought or oversold. It compares the magnitude of recent price gains relative to recent price losses over a specified period of time, typically 14 days, and generates a value that indicates the potential for a price reversal or continuation.

    The higher the losses are relative to the gains, the lower the RSI value becomes. And the opposite is also true, with the RSI value rising when a stock has been accumulating more gains than losses. Generally, an RSI value above 70 indicates an overbought condition, suggesting a potential price correction or reversal to the downside. Conversely, an RSI value below 30 indicates an oversold condition, implying a potential price bounce or reversal to the upside. Traders often use these overbought and oversold levels to identify possible entry or exit points in the market.

    Why RSI Is a Useful Indicator for Traders

    It’s important to note that the RSI is just one tool among many in technical analysis, and it should be used in conjunction with other indicators and analysis methods to make well-informed trading decisions. However, here are 4 reasons traders might find it useful:

    1. Finding overbought and oversold levels

    RSI can help investors identify buying and selling opportunities. When a stock is deeply oversold and the business is still in good shape but perhaps is down due to a bad quarter, it could be a sign to buy the beaten-down stock. In essence, it can help find market overreactions. At the same time, it can spot a stock that perhaps has become too hot when its RSI level is over 70 or 80, and that perhaps it has risen too much and too quickly.

    It’s useful to also look at a stock’s historical RSI levels to gauge what kind of an opportunity it is. If it frequently dips in and out of oversold/overbought territory, it could simply be that the stock is volatile. But if it is rare for the stock to become oversold/overbought, then it could make for a good opportunity to buy or sell the stock depending on what the indicator says.

    2. Measuring momentum and confirming a trend

    The RSI provides insights into the strength and momentum of a price trend. When the RSI is rising and stays above 50, it indicates that buying pressure is dominant and the price trend may continue. Conversely, when the RSI is falling and stays below 50, it suggests that selling pressure is dominant and the price trend may continue downward. This information can help investors confirm the strength of a trend and make informed decisions about entering or exiting positions.

    3. Identifying divergence patterns

    Another valuable aspect of the RSI is its ability to identify divergence patterns. Divergence occurs when the direction of the RSI differs from the direction of the price. Bullish divergence happens when the price makes lower lows while the RSI makes higher lows, indicating a potential trend reversal to the upside. On the other hand, bearish divergence occurs when the price makes higher highs while the RSI makes lower highs, suggesting a potential trend reversal to the downside. Investors can use these divergence patterns as early warning signals of potential trend shifts and adjust their investment strategies accordingly.

    4. Confirmation with other indicators

    The RSI can be used in conjunction with other technical indicators to confirm signals and strengthen investment decisions. For example, if a stock shows overbought conditions based on the RSI, investors may look for additional indicators such as bearish candlestick patterns or negative volume divergences to support their decision to sell or take profits.

    Other technical indicators investors can use alongside RSI

    Investors often use many different indicators to make investment decisions. Here are a few commonly used indicators that can be used in conjunction with the RSI:

    1. Moving Averages

    Moving averages are trend-following indicators that smooth out price fluctuations over a specific period. The most commonly used moving averages are the simple moving average (SMA) and the exponential moving average (EMA). Investors often use moving averages in combination with the RSI to identify trend direction and potential support or resistance levels.

    2. MACD (Moving Average Convergence Divergence)

    The MACD is another trend-following momentum indicator that consists of two lines, the MACD line and the signal line. It helps identify potential buy and sell signals by measuring the relationship between two moving averages. Traders often look for convergence or divergence between the MACD and the RSI to confirm potential trend reversals or continuations.

    3. Bollinger Bands

    Bollinger Bands consist of a centerline (typically a moving average) and two bands that are plotted above and below it. These bands represent volatility levels. When the price reaches the upper band, it suggests that the asset is overbought, while reaching the lower band suggests oversold conditions. Combining Bollinger Bands with the RSI can provide additional insights into potential price reversals or breakouts.

    4. Stochastic Oscillator

    The Stochastic Oscillator is a momentum indicator that compares the closing price of an asset to its price range over a specific period. It consists of two lines, %K and %D, which oscillate between 0 and 100. Traders often look for oversold or overbought conditions on the Stochastic Oscillator in conjunction with the RSI to confirm potential trading signals.

    5. Volume indicators

    Volume indicators, such as On-Balance Volume (OBV) or Volume Weighted Average Price (VWAP), provide insights into the buying and selling pressure behind price movements. By analyzing volume alongside the RSI, investors can assess the strength and validity of potential price trends or reversals.

    6. Fibonacci retracements

    Fibonacci retracements are based on the mathematical relationships found in the Fibonacci sequence. They are used to identify potential support and resistance levels. Combining Fibonacci retracements with the RSI can help investors identify areas where a price correction or reversal may occur.

    These are just a few examples of indicators that investors can use alongside the RSI. The choice of indicators depends on the investor’s trading strategy, timeframes, and personal preferences. It’s important to test and evaluate different combinations of indicators to find a system that works well for individual investment goals and risk tolerance.

    Why you shouldn’t buy a stock just because the RSI is low

    Buying a stock solely based on a low RSI level is not a recommended approach for several reasons:

    1. It lacks context

    The RSI is just one indicator and provides a snapshot of the stock’s recent price performance relative to its own historical price movements. It doesn’t take into account other fundamental factors or external market conditions that may impact the stock’s future prospects. For example, a stock may have a very low RSI because investors are selling it off due to liquidity issues or problems that may significantly impact the investing thesis behind a stock. Therefore, solely relying on the RSI without considering other relevant information may lead to an incomplete assessment of the stock’s potential.

    2. False signals

    The RSI is a bounded oscillator that fluctuates between 0 and 100. While an RSI below 30 may indicate an oversold condition, it doesn’t guarantee an immediate rebound or a profitable buying opportunity. Stocks can remain oversold for extended periods, and the RSI alone may not accurately predict the timing or magnitude of a price reversal. It’s essential to consider other technical and fundamental indicators to validate the potential opportunity.

    3. Downtrends and value traps

    A low RSI reading can sometimes be an indication of a stock in a prolonged downtrend. Just because a stock is oversold does not mean it will necessarily recover or provide substantial returns. There may be fundamental reasons behind the stock’s decline, such as poor financial performance, unfavorable industry conditions, or negative news. Investing solely based on a low RSI without understanding the underlying reasons for the low reading can lead to falling into a “value trap” not unlike how investors may buy a stock simply because its price-to-earnings multiple is low.

    4. Confirmation bias

    Relying solely on the RSI to make investment decisions may lead to confirmation bias, where investors seek information that supports their preconceived notions. It’s crucial to consider a broader range of indicators, conduct thorough research, and evaluate multiple factors to make well-informed investment decisions.

    5. False oversold signals in strong downtrends

    In strong downtrends, a stock can remain oversold for an extended period as selling pressure continues. Attempting to catch a falling knife solely based on a low RSI reading can result in further losses if the stock continues its downward trajectory. It’s important to assess the overall trend, market conditions, and other technical and fundamental factors to increase the probability of making successful investment decisions.

    While the RSI can be a useful tool to identify potential opportunities, it should be considered as part of a comprehensive analysis that incorporates other indicators, fundamental analysis, and market conditions. By taking a holistic approach to investment decision-making, investors can make more well-rounded and informed choices.

    How do you calculate RSI?

    Here are the steps to take when determining how to calculate RSI:

    1. Determine the timeframe

    Traders usually use a 14-day timeframe for calculating the RSI, but it can be adjusted to suit different trading strategies and timeframes.

    2. Calculate the average gain and average loss

    The RSI compares the average gains and average losses over the chosen timeframe. To calculate the average gain, sum up all the positive price changes (gains) over the period and divide them by the number of periods. Similarly, calculate the average loss by summing up all the negative price changes (losses) and divide that by the number of periods.

    3. Calculate the relative strength (RS)

    The relative strength is the ratio of the average gain to the average loss. RS = Average Gain / Average Loss.

    4. Calculate the RSI

    The RSI is derived from the relative strength and is calculated using the formula: RSI = 100 – (100 / (1 + RS)).

    Calculating RSI in Excel

    Using the STOCKHISTORY function in Excel, you can easily download a stock’s historical prices. In this example, I’ve downloaded Amazon’s stock price between the period Jan 1, 2021 and Dec 25, 2022.

    Amazon's historical stock prices pulled into Excel using the stockhistory function.

    The next step is to calculate the gains and losses for each day. This just involves looking at the current closing price and the previous. If the price went down, the difference goes into the loss column. If it’s a gain, it goes into the gain column. Here’s an example of the formula for the gain column:

    =IF(B7>B6,B7-B6,0)

    Here’s a look at what the sheet looks like with the formulas filled in for the gain and loss columns:

    Excel sheet showing the gain and loss columns for Amazon's stock history.

    Next up, I need to calculate the average gains and average losses. I’ll do this for the past 14 trading days. For the first value, I just need to calculate a simple average:

    =AVERAGE(C7:C20)

    For subsequent cells, however, I’ll use an exponential average. That way, I’ll apply more weighting to the the most recent calculation:

    =((E20*13)+C21)/14

    Next, I will calculate the RS Value. To do this, I take the average gain and divide it by the average loss:

    =E20/F20

    Lastly, that leaves the RSI calculation, which contains the following formula:

    =100-(100/(1+G20))

    With all the fields filled in, this is what the spreadsheet looks like:

    If you want to follow along with the file that I’ve created, you can download it from here. You can also watch the corresponding YouTube video that goes along with this tutorial:


    If you liked this post on How to Calculate the Relative Strength Index (RSI) 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 me on Twitter and YouTube. Also, please consider buying me a coffee if you find my website helpful and would like to support it.

    CountWords

    How to Count Words in Excel

    Excel has many different functions that can help you parse out text from cells. This includes the LEN, MID, LEFT, and RIGHT functions. By utilizing these and other functions, you can get just the values you want. And by determining the number of blank spaces within a cell, you can also determine the number of words that a cell contains. There are multiple ways you can count cells in Excel, I’ll start with using the easier, and newer TEXTSPLIT function.

    Method 1: Counting words using the TEXTSPLIT function

    The TEXTSPLIT function is available for users who have Microsoft 365 and so if you do not see that function available as you type it in, you’ll need to move to the second approach. Using the TEXTSPLIT function, you can turn a single text value in a cell into multiple cells or columns. And you can specify how you want to split a cell; which delimiter you want to use.

    In the example of counting words, the delimiter you would use is a blank space, as specified with ” ” in the delimiter argument. Here’s a list of article titles that I am going to use for this example:

    List of article titles in an Excel spreadsheet.

    The article titles are in column A. The formula to split the text every time there is a blank space would be as follows, assuming the first value is in cell A2:

    =TEXTSPLIT(A2,” “)

    This formula, however, would simply put all the words in different columns. Thus, it is incomplete when your goal is to count the number of words. To fix this, the formula needs to be embedded within the COUNTA function. How COUNTA works is that it simply counts the number of nonblank values.

    =COUNTA(TEXTSPLIT(A2,” “))

    Copying this formula down, these are the resulting values and the number of words found in each cell:

    List of article names in Excel with a corresponding number of words found.

    Here’s a closer look at how the formula in B2 works, using the Evaluate Formula feature in Excel:

    Using the evaluate formula feature in Excel to determine the number of words within a cell.

    The TEXTSPLIT function is breaking out each word as its own separate value. And the COUNTA function is then counting each one of those values. When combined, these functions allow you to count the number of words in a cell.

    If you’re using Google Sheets, you can use the exact same formula as shown above, with the only difference being that instead of TEXTSPLIT, you’ll use the SPLIT function. It works in the exact same way.

    Method 2: Using the LEN and SUBSTITUTE functions to count words

    If you are on an older version of Excel where TEXTSPLIT isn’t available, there’s still a way that you can count the number of words within a cell. It will be a slightly more complex formula that will use the LEN and SUBSTITUTE functions.

    The first part of the formula will involve counting the number of characters in a cell, which is what the LEN function does. This is accomplished through the LEN(A2) formula — assuming that A2 is where the article name is.

    Next, you’ll need to use the SUBSTITUTE function to replace the blank values ” ” with an empty string that just contains two quotes: “”. To do that, the formula for that portion would be: SUBSTITUTE(A2,” “,””). This formula will need to be enclosed within a LEN function. What this accomplishes is it counts the number of characters in the cell after you’ve replaced all the blank values. If you take the total cell length and subtract this second piece, you’ll be left with the number of blank values in the text.

    =LEN(A2)-LEN(SUBSTITUTE(A2,” “,””)

    However, this isn’t entirely correct as you will be off by 1 word. This is because since the formula is counting the number of blanks, it won’t include the first word, which doesn’t come with a space before it. That also means if you only have one word, you’ll have a value of 0 instead of 1. To fix this, you’ll simply need to add a +1 to the end of your formula.

    =LEN(A2)-LEN(SUBSTITUTE(A2,” “,””)+1

    This would mean, however, that even blank cells would return a value of 1. And this would technically be the same problem when using the TEXTSPLIT function as well, since it doesn’t check for blanks, either. To correct this, you can simply add an IF function to check if the value is indeed blank. Here’s how the full formula looks:

    =IF(A2=””,””,LEN(A2)-LEN(SUBSTITUTE(A2,” “,””))+1)

    This will return nothing if the cell is blank. If the cell isn’t blank, then it will go ahead and perform the rest of the calculation. As mentioned, this IF function can also be added to the start of the TEXTSPLIT function as well.


    If you liked this post on How to Count Words 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 me on Twitter and YouTube. Also, please consider buying me a coffee if you find my website helpful and would like to support it.

    NPVIRR

    How to Calculate Net Present Value (NPV) and Internal Rate of Return (IRR) in Excel

    What is Net Present Value (NPV)?

    Net Present Value (NPV) is a financial metric used to determine the current value of a series of cash inflows and outflows. It takes into account the time value of money, which means that a dollar received in the future is worth less than a dollar received today due to factors like inflation and the opportunity cost of not having that money available to invest in other projects.

    The calculation of NPV involves discounting the expected future cash flows of a project or investment back to their present value using a specified discount rate. The result is the difference between the present value of the expected cash inflows and outflows.

    NPV is an important calculation because it helps you evaluate the profitability and feasibility of an investment. It can also allow you to compare the expected returns of different investment opportunities, and to make informed decisions about which projects to pursue.

    If the NPV is positive, it means that the project is expected to generate more cash inflows than outflows, and thus, it’s a profitable investment opportunity. However, if the NPV is negative, the project is expected to result in a net loss and is therefore not considered a viable option.

    The NPV calculation is an important tool in finance as it can help decision makers determine whether to move forward on a project.

    What is the Internal Rate of Return (IRR)?

    The Internal Rate of Return (IRR) is used to measure the profitability of an investment project or opportunity, often in conjunction with calculating NPV. It is the discount rate where the present value of expected cash inflows equals the present value of expected cash outflows, or when NPV is equal to 0.

    IRR represents the rate of return at which an investment will break even over its lifetime. It is shown as a percentage. And if you use the IRR percentage as your discount rate in the NPV calculation, the result will be an NPV of 0.

    With Excel, you can quickly calculate the IRR through a simple formula, rather than having to go through a time-consuming process that might otherwise involve trial and error.

    Calculating NPV and IRR in Excel

    To illustrate how to calculate NPV and IRR, I’ll use the following example. Suppose that you are investing $1,000 into a project that will generate the following cost savings:

    • Year 1: $50
    • Year 2: $100
    • Year 3: $250
    • Year 4: $300
    • Year 5: $600

    In total, that is $1,300 in cost savings. Although that’s more than the original $1,000 investment, those savings are spread out over a period of five years. To get a true picture of whether the project is worthwhile, you need to adjust for the time value of money and adjust those amounts and calculate their present values — what their values are today. This is where the NPV function comes into play.

    However, before using the NPV function, you need to determine the discount rate that you are going to use. The discount rate is important as it tells you the interest rate that you will be using when adjusting the cost savings back to today, and to calculate the present value. If the discount rate is high, then it’ll be more difficult for the NPV calculation to be positive (and hence, suggest that the investment should be taken on). And if the discount rate is too low, then it could be too easy to clear the bar and for the NPV formula to suggest the project is worthwhile.

    The discount rate should be higher than the risk-free rate since you are taking on some risk, and thus, you should be compensated for doing so. If you were to use the same rate as what you could earn on a treasury bill or a bank deposit, there would be little incentive to go ahead with the project even with a positive NPV. After all, what’s the point of taking on the risk if you’re not getting a better return?

    In this example, I’m using a discount rate of 5%. This is what the NPV formula will look like with all of the inputs:

    =NPV(0.05,50,100,250,300,600)-1000

    As you can see, the order of the values is important as that will determine how many periods each value will be discounted by. The result of this formula is a value of $71.21. It’s a positive amount, indicating that the project should be undertaken as the present value of the future cost savings offset the current investment.

    To prove that calculation out, I’ll show you how this calculation could be done manually. Here, for example, is how the present value would be calculated for the $50 in cost savings that is achieved in year 1:

    =50*(1+0.05)^-1

    One plus the discount rate is raised to a power of negative one to bring the value back one period, using the discount rate. That returns a value of $47.619. Here are the other present value calculations:

    • Year 2 ($100) : $90.703
    • Year 3 ($250) : $215.959
    • Year 4 ($300) : $246.811
    • Year 5 ($600): $471.116

    If you add all of these present values up, they total $1,071.21. And that is $71.21 more than the $1,000 initial investment, which is the same result as the NPV formula.

    One thing you may be wondering is at what point does the value equal 0 — where is the breakeven? This can be calculated using the IRR formula. In Excel, this is a simple formula that just takes all the inflows and outflows. For example, if you had the negative investment amount of $1,000 in cell A1 followed by the cost savings in the the adjacent columns (until column F), then the formula for IRR would be as follows:

    =IRR(A1:F1)

    The end result is a value of 6.8576%. If you use this as the discount rate in the NPV calculation, you will get an NPV value of 0. This tells you that if you use a discount rate higher than this percentage, your NPV value will be negative as the level of discounting will be too high for the project to have a positive NPV value. On the other hand, anything below the IRR rate will result in a positive NPV value and thus indicate that the project should move forward.


    If you liked this post on How to Calculate Net Present Value and Internal Rate of Return 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 me on Twitter and YouTube. Also, please consider buying me a coffee if you find my website helpful and would like to support it.