DEV Community


Posted on

Mortgage Calculator to help determining financial suitability with Python: an OOP approach


If one is willing to buy a home, land, or other type of real estate without paying the entire price upfront, may have considered borrowing some money from a bank or other institution.

Mortgage is a type of loan to raise funds to purchase real estate. Sometimes, property's owners may use a mortgage to raise funds as well. The borrower grants the real estate as collateral to ensure that the loan will be paid.

One of the consequences of defaulting on the mortgage for the borrower is losing the property. On the other hand, the lender must follow a procedure in order to seize and sell the property to recoup the debt.

That said, it's crucial for lenders and borrowers assessing the financial suitability of the mortgage program beforehand. A potential borrower can check which property's value he or she can afford and test different terms and interest rates. Lenders can check whether a plan is feasible.

Despite the fact there are several types of mortgage, a loan is satisfied by paying to zero balance over the course of the loan term. Regular payments are divided into principal and interest charged and may include others costs like taxes, fees, and insurance.

The program

One way to implement this calculator is by using classes, which allows splitting the program into 'zones' with some code and data in order to create several objects using the same template.

This is a basic terminal program written with Python that uses fixed-rate mortgage to estimate monthly payments and loan's term, the major variables in a mortgage calculation, along loan's principal and interest rate.

Off the bat, principal and yearly interest rate are provided by the user and stored as attributes of the class Mortgage, since they remain the same for both monthly amount calculus and term calculus.

class Mortgage:
    def __init__(self):
        self.principal = pyip.inputFloat("Type loan's principal: ")
        self.interest_rate = pyip.inputFloat("Type yearly interest rate: ")
        self.interest_rate = self.interest_rate / 100 / 12  # yearly percentage rate divided by 12

Enter fullscreen mode Exit fullscreen mode

The methods defined inside the class Mortgage are in charge of the calculus involved and will be run according to the user option: calculating monthly payment over a provided yearly term or estimating how long it would take to have the loan paid off in full for a given monthly payment.

 def monthly_amount(self):
        self.yearly_term = pyip.inputInt("Type yearly term: ")
        self.yearly_term *= 12 #number of monthly payments
        payment = ((self.interest_rate * self.principal) / ((1 - ((1 + (self.interest_rate)) ** (-self.yearly_term)))))
        return f'Monthly amount payment for ${self.principal:6.2f} in {self.yearly_term} months: ${payment:6.2f}'

    def term(self):
        self.payment = pyip.inputFloat("Type the monthly amount: $")
        term = 0
        balance = self.principal
        while balance > 0:
            balance = balance + (self.interest_rate * balance) - self.payment
            term += 1
        return f"The loan's principal ${self.principal} would take {term} months to be paid."
Enter fullscreen mode Exit fullscreen mode

At the end of the script, an instance of the class is created and a menu is prompted:

mortgage = Mortgage()
print("Choose '1' for monthly amount, '2' for loan's term(years), or '3' to exit.")
choice = pyip.inputMenu(choices=['monthly amount', "loan's term", "quit"], numbered=True)
print('Your choice:', choice)
if choice == 'monthly amount':
    print('=' * (len(mes) + 10))
    print('=' * (len(mes) + 10))
elif choice == "loan's term":
    print('=' * (len(mes) + 10))
    print('=' * (len(mes) + 10))
Enter fullscreen mode Exit fullscreen mode

The module pyinputplus, imported at the beginning of the script as pyip, was used for input validation.

When the script is run in the terminal, the result on the screen will be as such:

A terminal screen showing initial message "Welcome to the mortgage calculator" followed by "type loan's principal: 200000", "type yearly interest rate: 6.5", "Choose '1'for monthly amount, '2'for loan's term(years), or '3'to exit". So the menu is provided like so: "Please select one of the following: 1. monthly amount 2. loan's term 3. quit". Option 1 was selected and the program prints "1 Your choice: monthly amount". After a line separating the previous content, you can see "Type yearly term: 30", and the result "Monthly amount payment for $200000.00 in 360 months: $1264.14".

A link to the code on GitHub:

Top comments (2)

emwalesfs profile image

Fantastic bit of code, I have recently started trying to code something similar using Python, this help me get started, I have previously coded a calculator using HTML, CSS and Java that worked really well and have included it on my website Cardiff Mortgage Broker, take a look and let me know what you think, it has a flip function and then allows the user to input their details and send an email to me with their inputs and details.

taylorblake88 profile image
TaylorBlake88 • Edited

Seems kinda difficult to be honest