Interest and principal payments python
import numpy as np
import pandas as pd
import numpy_financial as npf
import matplotlib.pyplot as plt
loan = float(input("Please enter the value of the loan: "))
ir = float(input("Please enter the annual rate on that loan: "))
length = int(input("Please enter how long the mortgage loan is in years: "))
periods = length *12
monthly = (1+(ir/100))**(1/12) -1
payments = -npf.pmt(rate = monthly, nper= periods, pv=loan, fv=0)
initial_interest = loan * monthly
initial_principal = payments - initial_interest
principal_remaining = np.repeat(0, periods)
interest_paid = np.repeat(0, periods)
principal_paid = np.repeat(0, periods)
for i in range(0, periods):
# Handle the case for the first iteration
if(i==0):
previous_principal_remaining = loan
else:
previous_principal_remaining = principal_remaining[i-1]
#Calculate principal and interest payments
interest_payment = previous_principal_remaining * monthly
principal_payment = payments - interest_payment
# Catch the case where all principal is paid off in the final period
if(previous_principal_remaining - principal_payment <0):
principal_payment = previous_principal_remaining
# Collect the historical values
interest_paid[i] = interest_payment
principal_paid[i] = principal_payment
principal_remaining[i] = previous_principal_remaining - principal_payment
plt.plot(interest_paid, color="red")
plt.plot(principal_paid, color = "blue")
plt.xlabel("Months")
plt.ylabel("Payments")
plt.title("Interest and Principal Payment")
plt.show()