The Compound Annual Growth Rate (CAGR) is a useful measure for assessing the mean annual growth rate of an investment or business metric over a specified period longer than one year. Unlike other growth metrics, CAGR smooths out the volatility, providing a clearer picture of how investments grow over time.
In this guide, I’ll show you exactly how I calculate CAGR with code examples in Python and JavaScript.
How Is CAGR Calculated?
To calculate CAGR, you need three key pieces of information:
- The initial value
- The closing value
- The number of years
The formula is (end_value / begin_value) ** (1 / years) - 1
Let’s break it down with an example. Suppose you invested $1,000, and after 5 years, your investment grew to $1,200.
Using the formula, we get: CAGR = (1200 / 1000) ** (1 / 5) - 1 = 0.03713728933 or 3.71%
Python CAGR Function
Calculating CAGR in Python is straightforward. Here’s the function I use:
def calculate_cagr(begin_value, end_value, years):
return (end_value / begin_value) ** (1 / years) - 1
begin_value = 1000
end_value = 1500
years = 5
cagr = calculate_cagr(begin_value, end_value, years)
print(f"The CAGR is {cagr:.2%}")
Javascript CAGR Function
For those who prefer JavaScript, here’s how you can calculate CAGR:
const calculateCagr = (beginValue, endValue, years) => {
return Math.pow(endValue / beginValue, 1 / years) - 1;
}
let beginValue = 1000;
let endValue = 1500;
let years = 5;
let cagr = calculateCagr(beginValue, endValue, years);
console.log("The CAGR is " + (cagr * 100).toFixed(2) + "%");
This JavaScript function uses the Math.pow
to handle the exponentiation.
CAGR smooths out the volatility by averaging the annual growth rate over the investment period, thereby providing a consistent rate of return as if the investment had grown at a steady pace each year.
These simple functions can help measure and compare the growth rates of your investments over time. I hope this is useful for your analysis tools and scripts.
If you found this guide helpful and want to stay updated on blockchain development and emerging DeFi technology, subscribe to my newsletter at https://bachini.substack.com