In this activity, you will define a function to calculate compound annual growth rate (CAGR) for an investment portfolio. You are encouraged to work with a partner on this activity.
You have been working with Harold and Sam after hours to further develop your FinTech skills and automate your day jobs.
While fine-tuning your algorithms, you realize that you've written the logic to calculate compound annual growth rate three times: once for 2016, once for 2017, and once for 2018. You're annoyed that you've reinvented the wheel each time, and you're growing concerned that if you make any changes to the algorithm, you'll have to make changes in three different places.
This cannot be maintained. You decide to refactor all of your code to make it as modular and reusable as possible.
In this activity, define a function named calculate_compound_growth_rate
that will accept three arguments:
-
beginning_balance
-
ending_balance
-
years
The function should output a float as growth_rate
.
Modularize this code so that you can dynamically calculate compound annual growth rate (CAGR) by simply calling a function with the required inputs. The results will indicate how you've been functioning as a trader.
CAGR is valuable, as it calculates and predicts growth rate earnings and percent increase or decrease of a stock, portfolio, or bank account. This will be useful when trying to evaluate portfolio/stock performance or when choosing which savings account might produce the most return.
Compound annual growth rate formula:
-
Define a function
calculate_compound_growth_rate
that takes inbeginning_balance
,ending_balance
, andyears
as input. Outputgrowth_rate
. -
Initialize
beginning_balance
to 29000.00. -
Initialize
ending_balance
to 45000.00. -
Initialize
years
to 1.0. -
Call
calculate_compound_growth_rate()
and use the above values (found in Steps 3-5) to calculate and capture the result asyear_one_growth
. -
Update
beginning_balance
to 45000.00. -
Update
ending_balance
to 47000.00. -
Call
calculate_compound_growth_rate()
and capture results asyear_two_growth
. -
Update
beginning_balance
to 47000.00. -
Update
ending_balance
to 48930.00. -
Call
calculate_compound_growth_rate()
and capture results asyear_three_growth
. -
Use the Python
round()
function to roundyear_one_growth
,year_two_growth
, andyear_three_growth
. Capture these new values as new variables. -
Use string formatting to print
year_one_growth
,year_two_growth
, andyear_three_growth
as percents. -
Quickly review the values printed on the screen, and identify the year with the highest rate of return.
Instead of saving the year_one_growth
, year_two_growth
, and year_three_growth
values in variables, add growth_rate
to a global list named growth_rates
.
Then, write this logic in a new function calculate_compound_growth_rate_list
.
-
Instead of returning the local
growth_rate
variable, store it in thegrowth_rates
global list object. -
Refer to the W3Schools documentation for the Python round function.