CAGR Calculator (Compound Annual Growth Rate) in Python
What is CAGR?
CAGR stands for Compound Annual Growth Rate, which measures an investment's mean annual growth rate over a specified period of more than one year.
The formula of CAGR is (Ending value/Beginning Value)^(1/Number of Years)-1.
To calculate the result, the user provides the initial value, the final value, and the number of years. Then, the CAGR displays the result as a percentage.
There should be the prompts as :
Prompt the user to input the initial value of investment.
- Next, it is prompt for the final value. Then, prompt the number of years or period.
- Now, validate that all inputs are positive numbers and the year is greater than zero
- Then calculate CAGR using the formula.
- Now, the result is displayed as percentage.
- And formatted to two decimal places.
To develop a Compound Annual Growth Rate (CAGR) calculator in Python. You have to follow these steps:-
Step 1 - Understand the concept of the CAGR Formula.
CAGR = Ending Value/Beginning Value ^ 1/Number of Years - 1
Step - 2 -Set up input functions with validation.
Make a function to collect data and validate user inputs for initial value, final value, and the number of years
Step 3—Implement the Main Calculation.
Use the CAGR formula to compute the growth rate and format the result as a percentage.
Step 4 - Assemble the Complete Code.
Assemble all components and finish the Python script.
CAGR Calculator (Compound Annual Growth Rate) in Python
Complete Python Code -
Python Code
def get_initial_value():
while True:
try:
value = float(input("Enter the initial value: "))
if value <= 0:
print("Initial value must be greater than 0.")
else:
return value
except ValueError:
print("Please enter a valid number.")
def get_final_value():
while True:
try:
value = float(input("Enter the final value: "))
if value < 0:
print("Final value cannot be negative.")
else:
return value
except ValueError:
print("Please enter a valid number.")
def get_years():
while True:
try:
years = float(input("Enter the number of years: "))
if years <= 0:
print("Years must be greater than 0.")
else:
return years
except ValueError:
print("Please enter a valid number.")
def main():
print("CAGR Calculator")
initial = get_initial_value()
final = get_final_value()
years = get_years()
cagr = (final / initial) ** (1 / years) - 1
print(f"The Compound Annual Growth Rate (CAGR) is: {cagr:.2%}")
if __name__ == "__main__":
main()
Code Out
CAGR Calculator
Enter the initial value: 1000
Enter the final value: 2000
Enter the number of years: 5
The Compound Annual Growth Rate (CAGR) is: 14.87%