Compound interest is a fundamental concept in finance and mathematics that describes how interest accumulates on an initial investment over time. Unlike simple interest, which is calculated solely on the principal amount, compound interest grows exponentially because interest is periodically added to the principal. In this blog, we will explore the formula for compound interest and implement it in Python.
The formula for compound interest is:
\(
A = P \left(1 + \frac{r}{n}\right)^{nt}
\)
Where:
- A = Final amount
- P = Principal (initial investment)
- r = Annual interest rate (decimal form)
- n = Number of times interest is compounded per year
- t = Time in years
Python Code to Calculate Compound Interest
import argparse
def compound_interest(principal, rate, time, compounds_per_year=1):
"""
Calculate compound interest.
:param principal: Initial investment amount (P)
:param rate: Annual interest rate (in decimal, e.g., 15% -> 0.15)
:param time: Time in years (t)
:param compounds_per_year: Number of times interest is compounded per year (n)
:return: Final amount after interest is applied (A)
"""
amount = principal * (1 + rate / compounds_per_year) ** (compounds_per_year * time)
interest = amount - principal
return amount, interest
def main():
"""
This program computes compound interest earned on money and total amount earned after full term.
"""
# get data from the user from command line
parser = argparse.ArgumentParser(description="Calculate Compound Interest")
parser.add_argument("-p", type=float, required=True, help="Initial investment amount (P)")
parser.add_argument("-r", type=float, required=True, help="Annual interest rate)")
parser.add_argument("-t", type=float, required=True, help="Time in years (t)")
parser.add_argument("-n", type=int, required=True, help="Number of times interest is compounded per year")
args = parser.parse_args()
# Convert rate from percentage to decimal
rate_decimal = args.r / 100
# Calculate compound interest
final_amount, interest_earned = compound_interest(args.p, rate_decimal, args.t, args.n)
print(f"Final Amount: ${final_amount:.2f}")
print(f"Interest Earned: ${interest_earned:.2f}")
if __name__ == "__main__":
main()
To run this program, save it as compute_compound.py
(or whatever name you prefer) and execute it with values for the principal, annual interest rate, time in years, and the number of times interest is compounded per year as command-line arguments, as shown below:
python compute_compound.py -p 1000 -r 5 -t 5 -n 4
Please let me know in the comments if you find any issues with the code.