Calculating mortgage interest in Python
Asked Answered
P

6

11

I am currently learning python through a video tutorial on youtube, and have come up against a formula I cannot seem to grasp, as nothing looks right to me. The basic concept of the excersise is to make a mortgage calculator that asks the user to input 3 pieces of information, Loan Amount, Interest Rate, and Loan Term (years)

then it calculates the monthly payments to the user. here is my code:

__author__ = 'Rick'
# This program calculates monthly repayments on an interest rate loan/mortgage.

loanAmount = input("How much do you want to borrow? \n")
interestRate = input("What is the interest rate on your loan? \n")
repaymentLength = input("How many years to repay your loan? \n")

#converting the string input variables to float
loanAmount = float(loanAmount)
interestRate = float(interestRate)
repaymentLength = float(repaymentLength)

#working out the interest rate to a decimal number
interestCalculation = interestRate / 100

print(interestRate)
print(interestCalculation)

#working out the number of payments over the course of the loan period.
numberOfPayments = repaymentLength*12

#Formula
#M = L[i(1+i)n] / [(1+i)n-1]

#   * M = Monthly Payment (what were trying to find out)
#   * L = Loan Amount (loanAmount)
#   * I = Interest Rate (for an interest rate of 5%, i = 0.05 (interestCalculation)
#   * N = Number of Payments (repaymentLength)

monthlyRepaymentCost = loanAmount * interestCalculation * (1+interestCalculation) * numberOfPayments / ((1+interestCalculation) * numberOfPayments - 1)
#THIS IS FROM ANOTHER BIT OF CODE THAT IS SUPPOSE TO BE RIGHT BUT ISNT---
# repaymentCost = loanAmount * interestRate * (1+ interestRate) * numberOfPayments  / ((1 + interestRate) * numberOfPayments -1)

#working out the total cost of the repayment over the full term of the loan
totalCharge = (monthlyRepaymentCost * numberOfPayments) - loanAmount


print("You want to borrow £" + str(loanAmount) + " over " + str(repaymentLength) + " years, with an interest rate of " + str(interestRate) + "%!")

print("Your monthly repayment will be £" + str(monthlyRepaymentCost))

print("Your monthly repayment will be £%.2f " % monthlyRepaymentCost)

print("The total charge on this loan will be £%.2f !" % totalCharge)

Everything works, but the value it throws out at the end is completely wrong... a £100 loan with an interest rate of 10% over 1 year shouldn't be making me pay £0.83 per month. Any help in getting my head around this equation to help me understand would be greatly appreciated.

Pliner answered 22/4, 2015 at 17:26 Comment(9)
Somewhere you are just paying the interest and not adding the loan amount... 0.83 x 12 = ~10Resuscitator
How often is interest accumulated? Every month?Ponzo
I am not sure, this is the instruction i was given following the module. Create a mortgage/loan calculator. * Have the user enter the cost of the loan, the interest rate, and the number of years for the loan * Calculate the monthly payments with the following formula * * M = L[i(1+i)n] / [(1+i)n-1] * M = Monthly Payment * L = Loan Amount * I = Interest Rate (for an interest rate of 5%, i = 0.05 * N = Number of PaymentsPliner
This program doesn't calculate either compound or simple interest. It also doesn't provide a compounding period, It also incorrectly displays what your total charge will be, don't subtract the loan amount. It's also simply dividing your interest rate by your number of payments to get a monthly payment amount, and doesn't actually use a formula for either compound or simple interest. You really didn't implement the commented out formula correctly, you may want to take another look at that.Graecize
Ah I have just seen what you mean. Yes that equation was my attempt at actually making my own to see if i can get the correct outcome...I forgot to change it back to the original. I will edit the post now.Pliner
There are some exponentiations missing in the rendering of the commented formula. A better rendition (using Pythonish syntax) would be something like: M = L*i*(i+1)**n / ((1+i)**n - 1). Note that i here represents the interest rate for each period, not the annual interest rate.Ponzo
That seems to be better, The end value now being; You want to borrow £100.0 over 1.0 years, with an interest rate of 10.0%! Your monthly repayment will be £14.676331510028723 Your monthly repayment will be £14.68 The total charge on this loan will be £76.12 ! @MarkDickinson how would i go about adjusting that to reflect an anual interest rate and not a rate for each period? sorry I am really bad at maths so this is completely over my head lolPliner
That depends on the mortgage vendor's small print where they say exactly what they mean by "annual interest rate" :-) A crude (but not really correct) way to handle it would be to divide the annual interest rate by 12. Slightly better would be to use something like monthly_rate = (1 + annual_rate)**(1/12.) - 1.Ponzo
Compare your monthlyRepaymentCost line to what is described in en.wikipedia.org/wiki/…Purgation
W
6

With the help of examples, this is what I did.

# Formula for mortgage calculator
# M = L(I(1 + I)**N) / ((1 + I)**N - 1)
# M = Monthly Payment, L = Loan, I = Interest, N = Number of payments, ** = exponent

# Declares and asks for user to input loan amount. Then converts to float
loanAmount = input('Enter loan amount \n')
loanAmount = float(loanAmount)

# Declares and asks user to input number of payments in years. Then converts to float. Years * 12 to get
#  total number of months
years = input('How many years will you have the loan? \n')
years = float(years) * 12

# Declares and asks user to input interest rate. Then converts to float and input interest rate is /100/12
interestRate = input('Enter Interest Rate \n')
interestRate = float(interestRate) / 100 / 12

# Formula to calculate monthly payments
mortgagePayment = loanAmount * (interestRate * (1 + interestRate)
                                ** years) / ((1 + interestRate) ** years - 1)

# Prints monthly payment on next line and reformat the string to a float using 2 decimal places
print("The monthly mortgage payment is\n (%.2f) " % mortgagePayment)
Warp answered 20/9, 2017 at 5:10 Comment(0)
D
5

This mortgage package does it nicely:

>>> import mortgage
>>> m=mortgage.Mortgage(interest=0.0375, amount=350000, months=360)
>>> mortgage.print_summary(m)
                     Rate:      0.037500
             Month Growth:      1.003125
                      APY:      0.038151
             Payoff Years:            30
            Payoff Months:           360
                   Amount:     350000.00
          Monthly Payment:       1620.91
           Annual Payment:      19450.92
             Total Payout:     583527.60
Denticle answered 14/12, 2018 at 17:13 Comment(0)
A
0

Apparently you copied the formula wrong.

wrong:   * numberOfPayments 

correct: ** numberOfPayments 

note: it appears twice in the formula note: in python, ** is "to the power of" operator.

Ambala answered 30/7, 2015 at 15:52 Comment(0)
P
0

I also watched this youtube video and had the same problem. I'm a python newbie so bear with me. The instructors in the video were using python3 and I am using python2 so I am not sure if all the syntax are the same. But using some information found in this thread and info from this link: (http://www.wikihow.com/Calculate-Mortgage-Payments) I was able to get the answer. (My calculations matched an online mortgage calculator)

#!/usr/bin/env python
# The formula I used:
M = L * ((I * ((1+I) ** n)) / ((1+I) ** n - 1))

# My code (probably not very eloquent but it worked)

# monthly payment
M = None
# loan_amount
L = None
# interest rate
I = None
# number of payments
n = None

L = raw_input("Enter loan amount: ")
L = float(L)
print(L)

I = raw_input("Enter interest rate: ")
I = float(I)/100/12
print(I)

n = raw_input("Enter number of payments: ")
n = float(n)
print(n)

M = L * ((I * ((1+I) ** n)) / ((1+I) ** n - 1))

M = str(M)
print("\n")
print("Monthly payment is " + M)
Pietro answered 26/3, 2016 at 5:39 Comment(2)
Why are you using Python 2 instead of Python 3? Seems like it would be better to use Python 3 if you don't have to support a legacy codebase.Felsite
Dividing the interest rate by 12 may be wrong depending on whether the user types in APR or APY. reference.com/business-finance/…Unearthly
G
0

This worked pretty well for me. Not exact, as loan calculators usually go by days, and I'm lazy so I go by months but here's a simple one I wrote that is accurate enough to be practical.

L = input("How much will you be borrowing? ")
L = float(L)
print(L)


N = input("How many years will you be paying this loan off? ")
N = float(N) *12
print(N)

I = input("What is the interest in percents that you will be paying? Ex, 10% = 10, 5% = 5, etc. ")
I = float(I)/100
print(I)

M = (L/N) + I*(L/N)

float(M) 
print("Your monthly payment will be: ")
print(M)
Gormley answered 12/1, 2018 at 2:38 Comment(0)
B
-2

I also came accross this problem and this is my solution

loan = input('Enter Loan Amount: ')
loan = float(loan)

numberOfPayments = input('Enter Loan payments in years: ')
numberOfPayments = float(numberOfPayments) * 12

interest = input('Annuel interest Rate: ')
interest = float(interest)/100/12

monthlyPayments = loan * (interest * (1 + interest) ** numberOfPayments) / ((1 + interest) ** numberOfPayments - 1)

print (round(monthlyPayments))
Bug answered 6/8, 2015 at 13:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.