import math
from ipywidgets import interact, interactive, IntSlider, FloatSlider
import numpy
from matplotlib import pyplot
def simple_interest(principal, rate, time):
rate = rate / 100
interest = principal * rate * time
return round(interest, 2)
def compound_interest(principal, rate, time):
rate = rate / 100
interest = principal * ((1 + rate)**time)
return round(interest, 2)
def continuously_compounding_interest(principal, rate, time):
rate = rate / 100
interest = principal * (math.e**(rate * time))
return round(interest, 2)
We'll start by comparing the three types of interest given the same principal, rate (% return), and time (in years).
You can change the rate and time using the sliders below to get an idea of how the interest changes.
PRINCIPAL = 100
%matplotlib inline
@interact(rate=IntSlider(min=0, max=20, step=1, value=10),
time=IntSlider(min=2, max=40, step=2, value=10))
def graph(rate, time):
x = range(0, time)
y = [simple_interest(PRINCIPAL, rate, i) for i in range(0, time)]
pyplot.plot(x, y, marker='o', label='simple')
x = range(0, time)
y = [compound_interest(PRINCIPAL, rate, i) for i in range(0, time)]
pyplot.plot(x, y, marker='o', label='compound')
x = range(0, time)
y = [continuously_compounding_interest(PRINCIPAL, rate, i) for i in range(0, time)]
pyplot.plot(x, y, marker='o', label='continously_compound')
pyplot.legend()
We'll take a closer look at compound interest as it is most common (it's used to calculate return of stock investments, bank accounts, and more).
%matplotlib inline
@interact(principal=IntSlider(min=100, max=10000, step=100, value=100),
rate=IntSlider(min=0, max=20, step=1, value=10),
time=IntSlider(min=2, max=40, step=2, value=10))
def graph(principal, rate, time):
x = range(0, time)
y = [compound_interest(principal, rate, i) for i in x]
pyplot.plot(x, y, color='orange', marker='o', label='compound')
for x, y in zip(x, y):
label = y
pyplot.annotate(str(label), (x, y),
xycoords='data',
textcoords='offset points',
xytext=(0, 5), ha='center')
pyplot.legend()
And just for fun, here's another way to look at how much an initial investment would be worth:
%matplotlib inline
@interact(principal=IntSlider(min=100, max=10000, step=100, value=100),
rate=IntSlider(min=0, max=20, step=1, value=10),
time=IntSlider(min=2, max=40, step=2, value=10))
def calculate(principal, rate, time):
value_with_interest = compound_interest(principal, rate, time)
print(f'Investing ${principal:,} for {time} years at {rate}% interest would return: ${value_with_interest:,}')