Code Examples

Calculate compound interest

programming

In this code example, we will show you how to calculate compound interest, using Python.

# -*- coding: utf-8 -*-
"""
Created on Sun Dec 25 14:02:42 2022

@author: Konstantin
"""

# initial amount
p = 2000;

# monthly contribution
pmt = 200;

# interest rate %/100
# Ex: 1% = 1/100 = 0.01
r = 0.01

# number of contributions, during this period
# if monthly, then 12
# if bi-weekly, then 12*2 = 24
n = 12

# time in years
t = 1

# Formula
# Total = [ P(1+r/n)^(nt) ] + [ PMT × (((1 + r/n)^(nt) - 1) / (r/n)) ]
# *****

total = (p * pow(1+r/n,n*t)) + (pmt * ((pow(1+r/n,n*t) - 1)/(r/n)))
total_contribution = pmt * n
total_interest = total - (p + total_contribution)

print("Summary:")
print("========")
print("Your initial amount is: $" + "{:.2f}".format(p))
print("Your interest rate is: " + "{:.2f}".format(r*100) + "%")
print("Your initial amount is: $" + "{:.2f}".format(p))
print("You will deposit: $" + "{:.2f}".format(pmt) + ", " + str(n) + " times, during " + str(t) + " year(s)")

print("========")
print("Your net deposit will be: $" + "{:.2f}".format(total_contribution))
print("Total interest received will be: $" + "{:.2f}".format(total_interest))
print("Total cumulated amount will be: $" + "{:.2f}".format(total))