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()

Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source