Loan payment calculation - python

I am learning Python and am stuck. I am trying to find the loan payment amount. I currently have:
def myMonthlyPayment(Principal, annual_r, n):
years = n
r = ( annual_r / 100 ) / 12
MonthlyPayment = (Principal * (r * ( 1 + r ) ** years / (( 1 + r ) ** (years - 1))))
return MonthlyPayment
n=(input('Please enter number of years of loan'))
annual_r=(input('Please enter the interest rate'))
Principal=(input('Please enter the amount of loan'))
However, when I run, I am off by small amount. If anyone can point to my error, it would be great. I am using Python 3.4.

Payment calculation-wise, you don't appear to have translated the formula correctly. Besides that, since the built-in input() function returns strings, you'll need to convert whatever it returns to the proper type before passing the values on to the function which expects them to numeric values.
def myMonthlyPayment(Principal, annual_r, years):
n = years * 12 # number of monthly payments
r = (annual_r / 100) / 12 # decimal monthly interest rate from APR
MonthlyPayment = (r * Principal * ((1+r) ** n)) / (((1+r) ** n) - 1)
return MonthlyPayment
years = int(input('Please enter number of years of loan: '))
annual_r = float(input('Please enter the annual interest rate: '))
Principal = int(input('Please enter the amount of loan: '))
print('Monthly payment: {}'.format(myMonthlyPayment(Principal, annual_r, years)))

I think in the last bit of your calculation,
/ (( 1 + r ) ** (years - 1))
you have your bracketing wrong; it should be
/ ((( 1 + r ) ** years) - 1)

I think the correct formula is this,
MonthlyPayment = (Principal * r) / (1 - (1 + r) ** (12 * years))
I cleaned up your variables some,
def get_monthly_payment(principal, annual_rate, years):
monthly_rate = annual_rate / 100 / 12
monthly_payment = principal * (monthly_rate + monthly_rate / ((1 + monthly_rate) ** (12 * years) - 1))
return monthly_payment
years = float((input('Please enter number of years of loan')))
annual_rate = float((input('Please enter the interest rate')))
principal = float((input('Please enter the amount of loan')))
print ("Monthly Payment: " + str(get_monthly_payment(principal, annual_rate, years)))
It would also be prudent to add a try-except block around the inputs.

Related

How can I print in the main program the result of a function within another function in Python?

*****UPDATE: Thanks to everyone who contributed. The code is alright. I figured there was a problem with the website I was using as IDLE.
I have to write a program in Python that calculates then prints specific information about a loan. The program (code below) consists of 2 functions and I have written them correctly. The only problem I have is that I have to write the second function within the first one. When I run the code, I get this error: NameError: name 'vaam' is not defined
I've just started coding last week, I hope you guys help me out with this.
Here's my program:
# Your function for calculating payment goes here
def loan(principal,annual_interest_rate,duration):
r=(annual_interest_rate)/1200
n=duration*12
if annual_interest_rate==0:
monthly_payment=principal/n
else:
monthly_payment=(principal*(r*(1+r)**n))/((1+r)**n-1)
return monthly_payment
# Your function for calculating remaining balance goes here
def vaam(principal, annual_interest_rate, duration , number_of_payments):
n=duration*12
r=(annual_interest_rate)/1200
if annual_interest_rate==0:
remaining_loan_balance=principal-principal*(number_of_payments/n)
else:
remaining_loan_balance=(principal*((1+r)**n-(1+r)**number_of_payments))/((1+r)**n-1)
return remaining_loan_balance
# Your main program goes here
principal=float(input("Enter loan amount: "))
annual_interest_rate=float(input("Enter annual interest rate (percent): "))
duration=int(input("Enter loan duration in years: "))
print('LOAN AMOUNT:',int(principal),'INTEREST RATE (PERCENT):',int(annual_interest_rate))
print('DURATION (YEARS):',int(duration),'MONTHLY PAYMENT:',int(loan(principal,annual_interest_rate,duration)))
for i in range(1,duration+1):
print('YEAR:',i,'BALANCE:',int(vaam(principal, annual_interest_rate, duration , i*12)),'TOTAL PAYMENT:',int(loan(principal,annual_interest_rate,duration)*12*i))
Try this:
# Your function for calculating payment goes here
def loan(principal, annual_interest_rate, duration):
r = (annual_interest_rate) / 1200
n = duration * 12
if annual_interest_rate == 0:
monthly_payment = principal / n
else:
monthly_payment = (principal * (r * (1 + r) ** n)) / ((1 + r) ** n - 1)
return monthly_payment
# Your function for calculating remaining balance goes here
def vaam(principal, annual_interest_rate, duration, number_of_payments):
n = duration * 12
r = (annual_interest_rate) / 1200
if annual_interest_rate == 0:
remaining_loan_balance = principal - principal * (number_of_payments / n)
else:
remaining_loan_balance = (principal * ((1 + r) ** n - (1 + r) ** number_of_payments)) / ((1 + r) ** n - 1)
return remaining_loan_balance
# Your main program goes here
principal = float(input("Enter loan amount: "))
annual_interest_rate = float(input("Enter annual interest rate (percent): "))
duration = int(input("Enter loan duration in years: "))
print('LOAN AMOUNT:', int(principal), 'INTEREST RATE (PERCENT):', int(annual_interest_rate))
print('DURATION (YEARS):', int(duration), 'MONTHLY PAYMENT:', int(loan(principal, annual_interest_rate, duration)))
for i in range(1, duration + 1):
print('YEAR:', i, 'BALANCE:', int(vaam(principal, annual_interest_rate, duration, i * 12)), 'TOTAL PAYMENT:',
int(loan(principal, annual_interest_rate, duration) * 12 * i))
Output
Enter loan amount: 5000
Enter annual interest rate (percent): 8
Enter loan duration in years: 5
LOAN AMOUNT: 5000 INTEREST RATE (PERCENT): 8
DURATION (YEARS): 5 MONTHLY PAYMENT: 101
YEAR: 1 BALANCE: 4152 TOTAL PAYMENT: 1216
YEAR: 2 BALANCE: 3235 TOTAL PAYMENT: 2433
YEAR: 3 BALANCE: 2241 TOTAL PAYMENT: 3649
YEAR: 4 BALANCE: 1165 TOTAL PAYMENT: 4866
YEAR: 5 BALANCE: 0 TOTAL PAYMENT: 6082
The issue is with your indentation, you put vaam function under loan function.

Division by zero using // operator in python

Running the following code:
p = int(input("principal: "))
interest = int(input("annual interest rate: "))
years = int(input("# of years: "))
r = interest // 100
n = years * 12
top = r * (1 + r) ** n
bottom = (1+r) ** n - 1
fraction = top // bottom
A = fraction * p
print(A)
I get:
line 17, in <module>
fraction = top // bottom
ZeroDivisionError: integer division or modulo by zero
I am a beginner, please be kind!
The floor division // rounds the result down to the nearest whole number (data type = integer) and r as an integer will be 0 when interest is <100.
You can see what happens with top if r equals 0.
Same thing with fraction and the // operator. Use round to round the numbers.
p = int(input("principal: "))
interest = int(input("annual interest rate: "))
years = int(input("# of years: "))
r = interest / 100
n = years * 12
top = r * (1 + r) ** n
bottom = (1+r) ** n - 1
fraction = top / bottom
A = round(fraction * p, 2)
print(A)

How can I apply loops to shave off lines from this convoluted interest rate calculator?

How do I shave off lines from this code? I feel I could use loops to simplify this process.
I just started learning python to make my math studies more interesting. I barely know anything about coding so an example would be of great help.
The code must include an option to put down an initial capital.
Thank you!
capital = float(input("Enter initial capital: "))
interest_rate = float(input("Enter interest rate: "))
annual_saving = float(input("Enter annual savings: "))
year = float(input("Enter number of years of saving: "))
# Y stands for Year
Y0 = capital + annual_saving
Y1 = Y0 * (1 + interest_rate)
Y2 = (Y1 + annual_saving) * (1 + interest_rate)
Y3 = (Y2 + annual_saving) * (1 + interest_rate)
Y4 = (Y3 + annual_saving) * (1 + interest_rate)
Y5 = (Y4 + annual_saving) * (1 + interest_rate)
Y6 = (Y5 + annual_saving) * (1 + interest_rate)
Y7 = (Y6 + annual_saving) * (1 + interest_rate)
Y8 = (Y7 + annual_saving) * (1 + interest_rate)
Y9 = (Y8 + annual_saving) * (1 + interest_rate)
Y10 = (Y9 + annual_saving) * (1 + interest_rate)
Y11 = (Y10 + annual_saving) * (1 + interest_rate)
if year == 1:
print(Y1)
if year == 2:
print(Y2)
if year == 3:
print(Y3)
if year == 4:
print(Y4)
if year == 5:
print(Y5)
if year == 6:
print(Y6)
if year == 7:
print(Y7)
if year == 8:
print(Y8)
if year == 9:
print(Y9)
if year == 10:
print(Y10)
The formula for accrued interrest is K_interrest = K_start * (1 + (p/100))**n with p as your interrest rate and n as years. With that we can put your code in a handy function. Your initial fund and annual saving multiplied by interest rate get your new capital. This happens n times.
def calculate_savings(k, p, a, n):
for i in range(n):
k = (k+a) * (1 + (p/100))
print(f"{k:.2f}", "$") # will print your result with 2 decimal digits
capital = float(input("Enter initial capital: "))
interest_rate = float(input("Enter interest rate [%]: ")) # input in percent
annual_saving = float(input("Enter annual savings: "))
years_duration = int(input("Enter number of years of saving: ")) # years must be int here
calculate_savings(capital, interest_rate, annual_saving, years_duration)
The other possibility is using a recursive function (a function that calls itself):
def calculate_savings(k, p, a, n):
if n <= 0:
print(f"{k:.2f}", "$")
else:
k = (k+a) * (1 + (p/100))
calculate_savings(k, p, a, n-1) # calculates k with one year less
It is generally considered good practice to keep your code DRY (Don't repeat yourself). Also, when your script get's a little more substantial, you should consider catching faulty inputs.
You can create a function that will make all calculations and return proper result. Function get 4 variables from input.
def calculations(capital, interest_rate, annual_saving, year):
x = (capital + annual_saving) * (1 + interest_rate)
for i in range(1, year, 1):
x = (x + annual_saving) * (1 + interest_rate)
return x
capital = float(input("Enter initial capital: "))
interest_rate = float(input("Enter interest rate: "))
annual_saving = float(input("Enter annual savings: "))
year = float(input("Enter number of years of saving: "))
results = calculations(capital, interest_rate, annual_saving, year)
print(results)

Finding Future Investment Value in Python

I am a beginner programmer and have a question regarding the calculation of future investment values based on the following formula :
futureInvestmentValue = investmentAmount * (1 + monthlyInterestRate)numberOfMonths
... ofc the numberOfMonths value is an exponent.
I have created this so far but seem to receive incorrect answers when running the program
#Question 2
investmentAmount = float(input("Enter investment amount: "))
annualInterestRate = float(input("Enter annual interest rate: "))
monthlyInterestRate = ((annualInterestRate)/10)/12
numberOfYears = eval(input("Enter number of years: "))
numberOfMonths = numberOfYears * 12
futureInvestmentValue = investmentAmount * (1 + monthlyInterestRate) **\
numberOfMonths
print("Accumulated value is", futureInvestmentValue)
what do I need to fix in order to get this thing to work, any help would be appreciated thank you
annualInterestRate should be divided by 12 to get monthlyInterestRate.
The correct final formula should be
futureInvestmentValue = investmentAmount * (1 + (monthlyInterestRate/100) ** \
numberOfMonths
You can do it like this:
from __future__ import division # assuming python 2.7.xxxxx
investmentAmount = float(input("Enter investment amount: "))
annualInterestRate = float(input("Enter annual interest rate: "))
monthlyInterestRate = ((annualInterestRate)/10)/12
try:
numberOfYears = int(input("Enter number of years: "))
except Exception, R:
print "Year must be a number"
numberOfMonths = numberOfYears * 12
futureInvestmentValue = investmentAmount * (1 + monthlyInterestRate) **\
numberOfMonths
print("Accumulated value is", futureInvestmentValue)
The errors are in:
monthlyInterestRate = ((annualInterestRate)/10)/12
futureInvestmentValue = investmentAmount * (1 + monthlyInterestRate) **\
numberOfMonths
There are two errors i think. The first is that the interest rate is being divided by 10 when it should be divided by 100. Right now, if you enter 2, its treated as 20% interest because 2/10 = .2.
The second error is that monthlyInterestRate assumes a flat interest rate whereas futureInvestmentValue assumes a compound interest rate. It should be
monthlyInterestRate = (1 + (annualInterestRate/100))**(.1/1.2).
For example(Using /12):
print 0.05/12
print (1+0.05/12)**12
Output:
0.00416666666667
1.05116189788
The monthly interest rate compounded is not equal to the annual interest rate for a single year. Its because in one case you divide by 12, the next case you raise to the raise to the power of 12 which are not equivalent.
Example (Using **1/12)
from __future__ import division
print (1.05**(1/12))**12 #returns 1.05
investmentAmount = eval(input("Enter investment amount: "))
annualInterestRate = eval(input("Enter annual interest rate: "))
monthlyInterestRate = (annualInterestRate) / 10 / 12
numberOfYears = eval(input("Enter number of years: "))
numberOfMonths = numberOfYears * 12
futureInvestmentValue = investmentAmount * (1 + monthlyInterestRate) **\
numberOfMonths
print("Accumulated value is", futureInvestmentValue)
You just have one mistake which is "eval"

Calculating mortgage interest in Python

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

Categories