Compound interest with adding money each year - python

I am trying to figure out this question in python, I found the compound interest rate formula however, for me the biggest problem is how to add 50 dollars after each year after my money increased by interest rate
Principal(Starting amount) is: 100 USD
Yearly Interest rate: 10 percent
after each year-end, we add 50 USD.
How much our money will be after 3 years?
def compound_interest(p,r,n,t):
a = p * (1 + r/n)**t
return a
Thank you so much for your help from now!

capital = 100
ir = 0.1
bonus = 50
def compound_interest(year, capital, ir, bonus):
if year == 0:
return capital
investment_return = (capital * ir) + bonus
return compound_interest(year - 1, capital + investment_return, ir, bonus)
print(compound_interest(0, capital, ir, bonus))
print(compound_interest(1, capital, ir, bonus))
print(compound_interest(2, capital, ir, bonus))

Related

This should calculate how long it takes for an investment to double. Return values are way too long. I am required to use a while loop

This program is meant to get input from the user, initial investment and apy and is meant to return the number of years it takes for the investment to double. I've been testing 100 for the principal and .05 for the apy but the result I'm getting is over 14,000 years. This value should calculate to a little over 15 years. I can seem to find the issue and could use some pointers.
def main():
print("This program calculates the amount of time it takes for an investment to double")
principal = eval(input("What is the initial investment amount? "))
apy = eval(input("What is the annual interest rate? "))
years = 0
while principal < (2 * principal):
principal = principal * (1 + apy)
years = years + 1
print("It will take", years, "years for your investment to double." )
main()
when you increase the pricipal in every loop you also increase 2 times principal
as x+1 < (x+1)* 2
And you have your infinite loop in at least theory
But python stops at ∞ < 2 * ∞ and that is correct as 2 * ∞ Is ∞ and makes the equation false and ends the loop
Add another variable.
def main():
print("This program calculates the amount of time it takes for an investment to double")
principal = eval(input("What is the initial investment amount? "))
apy = eval(input("What is the annual interest rate? "))
years = 0
resultinv = principal
while resultinv < (2 * principal):
resultinv = resultinv * (1 + apy)
years = years + 1
print("It will take", years, "years for your investment to double." )
main()

Calculating returns with trading costs

This perhaps is an over simplification of calculating trading returns while including trading costs. I've made some assumptions - the commission for investing and extracting an investment is 1% and 2% respectively. The commissions do not change over the trading period which in this case is 5 time steps. I've used Python code to perform the calculations.
Set of positive and negative percentage changes in price for a given asset over 5 time steps is {0.031% , 0.00121% , 0.0231% , -0.0213% , -0.0121%}.
The commission to enter an investment is 1% of the invested amount, the commission to exit an investment is 2% of the current value of the invested amount.
If I invest 1 euro in this asset, is the following correct?
1.
The final investment amount if I do not trade the investment until $t=5$ is:
the final percentage change amount at $t=5$ which is 'initial invested amount' + '% change' - 'commission to enter' - 'commission to exit', therefore:
initial_investment_amt = 1
comission_in_amt = 1
comission_out_amt = 2
price_change = -.0121
return_amt = (initial_investment_amt + (price_change / 100)) - (comission_in_amt / 100) - (comission_out_amt / 100) = 0.97 which represents a loss of 1 - .97 = .03
2.
The final investment amount if I trade the investment at each time step until $t=5$ is:
initial_investment_amt = 1
comission_in_amt = 1
comission_out_amt = 2
price_change = .031
return_amt_1 = (initial_investment_amt + (price_change / 100)) - (comission_in_amt / 100) - (comission_out_amt / 100)
price_change = .00121
return_amt_2 = (return_amt_1 + (price_change / 100)) - (comission_in_amt / 100) - (comission_out_amt / 100)
price_change = .0231
return_amt_3 = (return_amt_2 + (price_change / 100)) - (comission_in_amt / 100) - (comission_out_amt / 100)
price_change = -.0213
return_amt_4 = (return_amt_3 + (price_change / 100)) - (comission_in_amt / 100) - (comission_out_amt / 100)
price_change = -.0121
return_amt_5 = (return_amt_4 + (price_change / 100)) - (comission_in_amt / 100) - (comission_out_amt / 100)
print(return_amt_1)
print(return_amt_2)
print(return_amt_3)
print(return_amt_4)
print(return_amt_5)
prints :
0.97031
0.9403220999999999
0.9105530999999999
0.8803400999999998
0.8502190999999998
which represents a loss of $1 - 0.85 = 0.15$.
First, I have to respectfully disagree with your conclusion for case 1:
The final investment amount if I do not trade the investment until $t=5$ is: the final percentage change amount at $t=5$ which is 'initial invested amount' + '% change' - 'commission to enter' - 'commission to exit
The correct formula for the final value, I believe, is
((initial investment amount - commission to enter) * (1 + % change)) - commission-to-exit.
The main difference being the fact that the commission to enter/investment fee is taken out of circulation before the return on investment can be earned. This makes for a significant difference over time.
Assuming I'm correct, below is the code I propose. I took the liberty of changing some of the terminology for ease of reference, but you can obviously change it to whatever suits you:
p_changes = [0.03100, 0.00121, 0.02310, 0.02130, -0.01210]
initial_investment_amt = 100 #I used a larger initial investment; otherwise, the fees would have eaten you alive...
invest_fee = 1
sell_fee = 2
def periodic_ret(amount,change,reinv):
if reinv == 0:
if ind + 1 == 1: #for the initial period
forward = (amount-invest_fee)*(1+change)
if ind +1 == len(p_changes): #for the final period
forward = (amount*(1+change))-sell_fee
else:
forward = (amount*(1+change))
else:
forward = (amount-invest_fee)*(1+change)-sell_fee
print(forward)
return forward
for i in range(len(p_changes)):
reinv = 1 #1 if an invest and sell fee are paid each period, or 0, if an invest fee is paid once upfront and sell fee is paid once at the end
if i == 0: #for the initial period
cur = periodic_ret(initial_investment_amt, p_changes[0], reinv)
else:
cur = periodic_ret(cur,p_changes[i], reinv)
Output (w/ reinv = 1):
100.06899999999999
97.18887348999998
96.41083646761896
95.44308728437926
91.30032592823827
Both the commissions and price changes are given as percentages. This means that immediately after investment the amount in the account is:
initial_investment_amt*(1-commission_in_amt/100)
The _amt suffix is perhaps confusing but commission is stated as % in the question.
After the first investment period the account has the amount:
initial_investment_amt*(1-commission_in_amt/100)*(1-price_change/100)
And finally after exit the client receives:
initial_investment_amt*(1-commission_in_amt/100)(1-price_change/100)(1-commission_out_amt/100)
I think the pattern is clear so you just insert more price_changes for a lengthier investment and if you disinvest and reinvest you'll have a lot more commission to pay.
Hope this is OK - sorry no code - but it seems clearer like this and uses the question notation.

Yearly Interest on house and deposit

Suppose you currently have $50,000 deposited into a bank account and the account pays you a constant interest rate of 3.5% per year on your deposit. You are planning to buy a house with the current price of $300,000. The price will increase by 1.5% per year. It still requires a minimum down payment of 20% of the house price.
Write a while loop to calculate how many (integer) years you need to wait until you can afford the down payment to buy the house.
m = 50000 #money you have
i = 0.035 #interest rate
h = 300000 #house price
f = 0.015 #amount house will increase by per year
d= 0.2 #percent of down payment on house
y = 0 #number of years
x = 0 #money for the down payment
mn = h*d #amount of down payment
while m <= mn:
m = (m+(m*i)) #money you have plus money you have times interest
y = y + 1 #year plus one
mn = mn +(h*f*y)
print(int(y))
The answer you should get is 10.
I keep getting the wrong answer, but I am not sure what is incorrect.
You can simplify the code by using the compound interest formula.
def compound_interest(amount, rate, years):
return amount * (rate + 1) ** years
while compound_interest(m, i, y) < d * compound_interest(h, f, y):
y += 1
If you are allowed to do without the while loop, you can resolve the inequality after the years y.
So you get this code snippet:
import math
base = (i + 1) / (f + 1)
arg = (d * h) / m
y = math.ceil(math.log(arg, base))

I can't understand how this (function?) works

I'm pretty new to Python and I'm going through a starter book. The code isn't written in English so I tried my best to translate, hope you guys understand.
It has this exercise where we calculate the taxes from the user salary:
salary = float(input("Enter your salary to taxes calculation: "))
base = salary
taxes = 0
if base > 3000:
taxes = taxes + ((base - 3000) * 0.35)
base = 3000
if base > 1000:
taxes = taxes + ((base - 1000) * 0.20)
My problem is when the input is bigger than 3000, for example, if I run the code with the salary of 5000, the result will be 1100. But when I do the 'same' math on the calculator the result is 700, so I'm lost in here, could someone explain it please?
Please note that in case of salary 5000, the control will go to both the if statements. So it comes out as 700 from first, and 400 from second, therefore answer is 700+400. This also makes sense, as tax calculation is mostly partitioned in brackets, and is not a flat percentage on salary.
Alright, let's walk through it with your example of 5000
salary = float(input("Enter your salary to taxes calculation: "))
base = salary
# base = 5000
taxes = 0
if base > 3000: # base is larger than 3000, so we enter the if statement
taxes = taxes + ((base - 3000) * 0.35)
# taxes = 0 + ((5000 - 3000) * 0.35)
# taxes = 0 + 700
# taxes = 700
base = 3000 # base is set to 3000
if base > 1000: # base was set to 3000 in the line above, so we enter the if statement
taxes = taxes + ((base - 1000) * 0.20)
# taxes = 700 + ((3000 - 1000) * 0.20), remember taxes is already 700 from above
# taxes = 700 + 400
# taxes = 1100
since it is two if statements and not an if and an else we evaluate both statements when base is set larger than 3000. I hope that helps.
It flows on to the second function
so if I sub in the numbers:
Salary = 5000
base = 5000
taxes = 0
if 5000 > 3000:
taxes = 0 + ((5000- 3000) * 0.35) # = 700
base = 3000
if 3000 > 1000:
taxes = 700 + ((3000 - 1000) * 0.20) # = 1100
This is an economical equation which calculate tax for every part of salary.
the procedure would be this:
For amount greater than 3000 calculate 35% tax for this portion of salary.
For amount greater than 1000 (and less than 3000) calculate 20% tax for this portion of salary.
Tax over salary would be the summation of this taxes.

Python: smarter way to calculate loan payments

How to calculate the monthly fee on a loan?
Given is:
a: an amount to loan.
b: the loan period (number of months).
c: the interest rate p.a. (interests is calculated and added every month, 1/12 of the interest is added. So if the interest is on 12%, 1% interest is added every month).
d: the amount of money owed after the end of the period.
This problem is a bit different than the usual since, the goal is not to have the loan payed after the loan period has ended, but to still owe an amount that is given. I have been able to find an algorithm so solve the problem if I wanted to pay the entire amount, but it will of course not work for this problem where the goal is to end up owing a given amount rather than not owing anything.
I managed to make a solution to this problem by starting with an guess and then keep on improving that guess until it was close enough. I wondered however, if there is a better way to simply calculate this, rather than just guessing.
Edit: Here's how I'm doing it now.
def find_payment(start, end, months, interest):
difference = start
guess = int(start / months * interest)
while True:
total = start
for month in range(1, months + 1):
ascribe = total * interest / 12
total = total + ascribe - guess
difference = total - end
# See if the guess was good enough.
if abs(difference) > start * 0.001:
if difference < 0:
if abs(difference) < guess:
print "payment is %s" % guess
return evolution(start, guess, interest, months)
else:
mod = int(abs(difference) / start * guess)
if mod == 0:
mod = 1
guess -= mod
else:
mod = int(difference / start * guess)
if mod == 0:
mod = 1
guess += mod
else:
print "payment is %s" % guess
return evolution(start, guess, interest, months)
evolution is just a function that displays how the loan would look like payment for payment and interest for interest, summing up total amount of interest paid etc.
An example would be if I wanted to find out the monthly payments for a loan starting with $100k and ending at $50k with an interest of 8% and a duration of 70 months, calling
>>> find_payment(100000, 50000, 70, 0.08)
payment is 1363
In the above case I would end up owing 49935, and I went through the loop 5 times. The amount of times needed to go through the loop depends on how close I want to get to the amount and it varies a bit.
This is a basically a mortgage repayment calculation.
Assuming that start is greater than end, and that interest is between 0 and 1 (i.e. 0.1 for 10% interest)
First consider the part of the payment you want to pay off.
Principal = start - end
The monthly payment is given by:
pay_a = (interest / 12) / (1 - (1+interest/12) ^ (-months))) * Principal
You then need to consider the extra interest. Which is just equal to the remaining principal times the monthly interest
pay_b = interest / 12 * end
So the total payment is
payment = (interest / 12) * (1 / (1 - (1+interest/12) ^ (-months))) * Principal + end)
On the example you gave of
Start: 100000
End: 50000
Months: 70
Interest: 8%
pay_a = 896.20
pay_b = 333.33
Payment = 1229.54
When I tested these values in Excel, after 70 payments the remaing loan was 50,000. This is assuming you pay the interest on the notional before the payment is made each month.
Perhaps the easiest way to think about this is to split the loan in two parts, one part which is to be repaid in full and another part where you don't pay off anything. You have already computed the monthly fee for the first part.
You can keep paying the interest of every month; then, you will alway owe the same amont.
Owe_1 = a
Int_2 = Owe_1*(InterestRate/12)
Pay_2 = Int_2
Owe_2 = Owe_1 + Int_2 - Pay_2 # ==> Owe_1 + Int_2 - Int_2 = Owe_1
Int_3 = Owe_2*(InterestRate/12)
Pay_3 = Int_3
Owe_3 = Owe_2 + Int_3 - Pay_3 # ==> Owe_2 + Int_3 - Int_3 = Owe_2 = Owe_1
python code to calculate emi
class EMI_CALCULATOR(object):
# Data attributes
# Helps to calculate EMI
Loan_amount = None # assigning none values
Month_Payment = None # assigning none values
Interest_rate = None #assigning none values
Payment_period = None #assigning none values
def get_loan_amount(self):
#get the value of loan amount
self.Loan_amount = input("Enter The Loan amount(in rupees) :")
pass
def get_interest_rate(self):
# get the value of interest rate
self.Interest_rate = input("Enter The Interest rate(in percentage(%)) : ")
pass
def get_payment_period(self):
# get the payment period"
self.Payment_period = input("Enter The Payment period (in month): ")
pass
def calc_interest_rate(self):
# To calculate the interest rate"
self.get_interest_rate()
if self.Interest_rate > 1:
self.Interest_rate = (self.Interest_rate /100.0)
else:
print "You have not entered The interest rate correctly ,please try again "
pass
def calc_emi(self):
# To calculate the EMI"
try:
self.get_loan_amount() #input loan amount
self.get_payment_period() #input payment period
self.calc_interest_rate() #input interest rate and calculate the interest rate
except NameError:
print "You have not entered Loan amount (OR) payment period (OR) interest rate correctly,Please enter and try again. "
try:
self.Month_Payment = (self.Loan_amount*pow((self.Interest_rate/12)+1,
(self.Payment_period))*self.Interest_rate/12)/(pow(self.Interest_rate/12+1,
(self.Payment_period)) - 1)
except ZeroDivisionError:
print "ERROR!! ZERO DIVISION ERROR , Please enter The Interest rate correctly and Try again."
else:
print "Monthly Payment is : %r"%self.Month_Payment
pass
if __name__ == '__main__':# main method
Init = EMI_CALCULATOR() # creating instances
Init.calc_emi() #to calculate EMI
for more info visit : https://emilgeorgejames.wordpress.com/2015/07/29/python-emi-equated-monthly-installment-calculator/
This rather a detailed way but will give the whole payment as well
# Mortgage Loan that gives the balance and total payment per year
# Function that gives the monthly payment
def f1 (principle,annual_interest_rate,duration):
r = annual_interest_rate/1200
n = duration*12
a=principle*r*((1+r)**n)
b= (((1+r)**n)- 1)
if r > 0 :
MonthlyPayment = (a/b)
else :
MonthlyPayment = principle/n
return MonthlyPayment
# Function that gives the balance
def f2 (principle,annual_interest_rate,duration,number_of_payments):
r = annual_interest_rate/1200
n = duration*12
a= ((1+r)**n)
b= ((1+r)**number_of_payments)
c= (((1+r)**n)-1)
if r > 0 :
RemainingLoanBalance = principle*((a-b)/c)
else :
RemainingLoanBalance = principle*(1-(number_of_payments/n))
return RemainingLoanBalance
# Entering the required values
principle=float(input("Enter loan amount: "))
annual_interest_rate=float(input("Enter annual interest rate (percent): "))
duration=int(input("Enter loan duration in years: "))
# Output that returns all useful data needed
print ("LOAN AMOUNT:",principle,"INTEREST RATE (PERCENT):",annual_interest_rate)
print ("DURATION (YEARS):",duration,"MONTHLY PAYMENT:",int(f1(principle,annual_interest_rate,duration)))
k=duration+1
BALANCE=principle
total=0
for i in range (1,k):
TOTALPAYMENT= f1(BALANCE,annual_interest_rate,k-i)*12
total+= TOTALPAYMENT
BALANCE= f2(principle,annual_interest_rate,duration,12*i)
print("YEAR:",i,"BALANCE:",int(BALANCE),"TOTAL PAYMENT",int(total))
How about this?
def EMI_calc(principle, rate, time, frequency):
return (principle / ((1-((1+(rate/frequency))**(-1*(time*frequency))))/(rate/frequency)))
print("""
----- Welcome to EMI programe for Python -----
""")
print("\n You have chosen to know the EMI for Loan.\n")
input('\nTo Continue Press ENTER --- to ABORT Press ctrl+c > \n')
print("\nPlease Enter amount of Loan to be taken: >\n")
principle = int(input())
print("\nEnter rate of interst (%): >\n")
rate = float(input())/100
print("\nEnter Term (Years): >\n")
time = float(input())
print("\nPlease enter the frequency of installments) : >\n")
frequency = int(input())
EMI = round(EMI_calc(principle, rate, time, frequency),0)
print("""
---------------------------------------------------------------------
""")
print(f"""
The EMI for Loan of Rs.{principle};
at interest rate of {rate*100} % for {time} years;
would be: Rs.""", EMI)
print("""
---------------------------------------------------------------------
""")
Here is a code snippet using numpy functions. This shows you the payment, principal, interest, instalment and total_amount each month. Run it and see the output. You can also check the syntax for Excel "IPMT()" and "PPMT()" functions for more explanation of the arguments.
https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.pmt.html#numpy.pmt
import math
import numpy as np
rate = 0.08
start_amount = 100000.0
end_amount = 50000.0
diff_amount = start_amount - end_amount
# nr_years = 4
payment_frequency = int (12)
nr_months = 70 # = nr_years * payment_frequency
per_np = np.arange (nr_months) + 1 # +1 because index starts with 1 here
pay_b = rate / payment_frequency * end_amount
ipmt_np = np.ipmt (rate / payment_frequency, per_np, nr_months, diff_amount) - pay_b
ppmt_np = np.ppmt (rate / payment_frequency, per_np, nr_months, diff_amount)
for payment in per_np:
idx = payment - 1
principal = math.fabs (ppmt_np [idx])
start_amount = start_amount - principal
interest = math.fabs (ipmt_np [idx])
instalment = principal + interest
print payment, "\t", principal, "\t", interest, "\t\t", instalment, "\t\t", start_amount
print np.sum (ipmt_np)

Categories

Resources