Future Value of yearly investments - python

Suppose you have an investment plan where you invest a certain fixed amount at the beginning of every year. Compute the total value of the investment at the end of the last year. The inputs will be the amount to invest each year, the interest rate, and the number of years of the investment.
This program calculates the future value
of a constant yearly investment.
Enter the yearly investment: 200
Enter the annual interest rate: .06
Enter the number of years: 12
The value in 12 years is: 3576.427533818945
I've tried a few different things, like below, but it doesn't give me that 3576.42, it gives me only $400. Any ideas?
principal = eval(input("Enter the yearly investment: "))
apr = eval(input("Enter the annual interest rate: "))
years = eval(input("Enter the number of years: "))
for i in range(years):
principal = principal * (1+apr)
print("The value in 12 years is: ", principal)

If it's a yearly investment, you should add it every year:
yearly = float(input("Enter the yearly investment: "))
apr = float(input("Enter the annual interest rate: "))
years = int(input("Enter the number of years: "))
total = 0
for i in range(years):
total += yearly
total *= 1 + apr
print("The value in 12 years is: ", total)
With your inputs, this outputs
('The value in 12 years is: ', 3576.427533818945)
Update: Responding to your questions from the comments, to clarify what's going on:
1) You can use int() for yearly and get the same answer, which is fine if you always invest a whole number of currency. Using a float works just as well but also allows the amount to be 199.99, for example.
2) += and *= are convenient shorthand: total += yearly means total = total + yearly. It's a little easier to type, but more important, it more clearly expresses the meaning. I read it like this
for i in range(years): # For each year
total += yearly # Grow the total by adding the yearly investment to it
total *= 1 + apr # Grow the total by multiplying it by (1 + apr)
The longer form just isn't as clear:
for i in range(years): # For each year
total = total + yearly # Add total and yearly and assign that to total
total = total * (1 + apr) # Multiply total by (1 + apr) and assign that to total

It can be done analytically:
"""
pmt = investment per period
r = interest rate per period
n = number of periods
v0 = initial value
"""
fv = lambda pmt, r, n, v0=0: pmt * ((1.0+r)**n-1)/r + v0*(1+r)**n
fv(200, 0.09, 10, 2000)
Similarly, if you are trying to figure out the amount you need to invest so you get to a certain number, you can do:
pmt = lambda fv, r, n, v0=0: (fv - v0*(1+r)**n) * r/((1.0+r)**n-1)
pmt(1000000, 0.09, 20, 0)

As suggested in the comments, you shouldn't use eval() here. (More info on eval can be found in the Python Docs). -- Instead, change your code to use float() or int() where applicable, as shown below.
Also, your print() statement printed out the parenthesis and comma, which I expect you didn't want. I cleaned it up in the code below, but if what you wanted is what you had feel free to put it back.
principal = float(input("Enter the yearly investment: "))
apr = float(input("Enter the annual interest rate: "))
# Note that years has to be int() because of range()
years = int(input("Enter the number of years: "))
for i in range(years):
principal = principal * (1+apr)
print "The value in 12 years is: %f" % principal

Related

Why doesn't the break statement work in this program?

My program is supposed to tell users how many months it will take to double the money in their investment account. I am able to do the calculations correctly, but I'm unable to break out of the loop and print the statement that tells the user the final sentence "It will take x months to double your investment with a y% return".
balance = int(input("Enter an initial Roth IRA deposit amount:"))
apr = int(input("Enter an annual percent rate of return:"))
month = 0
while balance != 2*balance:
added_interest = balance * (apr / 100) / 12
balance = balance + added_interest
month +=1
formatted_balance = "${:.2f}".format(balance)
print("Value after month", month,":", formatted_balance)
if balance == 2*balance:
break
print("It will take", month, "months to double your investment with a", apr, "% return")
Your problem is that testing balance against 2*balance is always testing the current balance, not double the initial balance. Just store off the computed doubled balance initially, and test if the current balance is still less than that (no need for separate if/break, your while condition will handle it):
balance = int(input("Enter an initial Roth IRA deposit amount:"))
apr = int(input("Enter an annual percent rate of return:"))
month = 0
doubled_balance = 2 * balance # Store off doubled initial balance
while balance < doubled_balance: # Check current balance against doubled initial,
# and use <, not !=, so you stop when you exceed it,
# not just when you're exactly equal
added_interest = balance * (apr / 100) / 12
balance = balance + added_interest
month +=1
formatted_balance = "${:.2f}".format(balance)
print("Value after month", month,":", formatted_balance)
# No need for if/break
print("It will take", month, "months to double your investment with a", apr, "% return")
All that said, this doesn't need a loop at all. The initial balance doesn't matter (it takes just as long to double $1 as to double $1000 with a fixed rate of return, ignoring rounding errors), so this reduces to a simple conversion for APR to APY to account for monthly compounding, followed by a logarithm computation to figure out what power of the APY is necessary to reach 2 (a doubling), then convert from months to years and round up (since you won't double until the end of that month):
import math
apr = int(input("Enter an annual percent rate of return:"))
apr_decimal = apr / 100
apy = (1 + (apr_decimal / 12)) ** 12 # Standard APR to APY computation for monthly compounding
months = math.ceil(math.log(2, apy) * 12) # Compute the power (years) of APY to double the investment
# then multiply by 12 and round up to a full month
print("It will take", months, "months to double your investment with a", apr, "% return")
In your comparison you compared balance with 2*balance. Obviously balance == 2*balance will always be false, if balance > 0. So your code is stuck there forever if someone plans to invest anything more than $0.
You need a new variable to store the updated balance with rate of return:
# assuming you have balance and apr set
newBalance = balance # balance + returned amount
month = 0
while newBalance < 2*balance:
# replace ! with <, so that loop breaks when newBalance >= 2*balance
added_interest = newBalance * (apr / 100) / 12
newBalance = newBalance + added_interest
month +=1
formatted_balance = "${:.2f}".format(newBalance)
print("Value after month", month,":", formatted_balance)
The code above assumes that the added interest is calculated based on newBalance value. Please tell me if this does not work for you. I will debug it later.
Perhaps a little bit simpler solution.
from math import log, ceil
apr = int(input("Enter an annual percent rate of return: "))
rate = apr/12/100 # monthly rate
months = ceil(log(2)/rate)
print("It will take", months, "months to double your investment with a", apr, "% return")
prints:
Enter an annual percent rate of return: 10
It will take 84 months to double your investment with a 10 % return
This was calculated using the formula for continuous compounding. With a FV (future value) = PV (present value) * e**(rate * periods).
FV = PV * e**(rate*periods)
FV/PV = e**(rate*periods)
log(FV/PV) = log(e**(rate*periods))
log(FV/PV) = (rate*periods) * log(e)
log(FV/PV) = (rate*periods) * 1
log(FV/PV)/rate = periods
Since you want to find the months to double your initial investment, FV/PV will equal 2, so:
log(2)/rate = periods. (The log(e) == 1 above)
e and compound interest is defined here.

How to start table with correct output in python

I'm currently new to coding Python and am struggling with a small piece of code that I can't seem to figure out. My code essentially takes in a starting salary and outputs the salary increase over the course of how ever many years the user enters and makes a table out of the output. Everything in my code is correct except for one problem. I need to start the table with the starting salary that the user enters instead it starts the table with what you would make in year 2.
percent = float(input("Enter the annual percent increase: "))
years = int(input("Enter the number of years: "))
percent = percent / 100
print("%-7s%10s" % ("Year","Salary"))
for i in range(1,years):
starting += (starting * percent)
print("%2d%17.2f" % (i, starting))
Try swapping the order of the prints and the addition:
for i in range(1,years):
print("%2d%17.2f" % (i, starting))
starting += (starting * percent)
Try this
starting = 1000 # sample starting
percent = float(input("Enter the annual percent increase: "))
years = int(input("Enter the number of years: "))
percent /= 100
print("%-7s%10s" % ("Year", "Salary"))
for i in range(years):
print("%2d%17.2f" % (i, starting))
starting += (starting * percent)
Will give
Year Salary
0 1000.00
1 1030.00
2 1060.90

How to iterate until a condition is met in python for loop

I have been working on this simple interest calculator and I was trying to make the for loop iterate until the amount inputted by the user is reached. But I am stuck at the range part, if I assign a range value like range(1 ,11) it will iterate it correctly and print the year in in contrast to the amount but I want the program to iterate until the year in which principal is greater than the amount is reached. My current code is bellow and the final product I want to reach is also attached bellow the current code. I'm new to python so please bare with me if I'm of track. Thanks in advance.
Current code:
principal = float(input("How much money to start? :"))
apr = float(input("What is the apr? :"))
amount = float(input("What is the amount you want to get to? :"))
def interestCalculator():
global principal
year = 1
for i in range(1, year + 1):
if principal < amount:
principal = principal + principal*apr
print("After year " + str (i)+" the account is at " + str(principal))
if principal > amount:
print("It would take" + str(year) + " years to reach your goal!")
else:
print("Can't calculate interest. Error: Amount is less than principal")
interestCalculator();
Final expected result:
Instead, you can use a while loop. What I mean here is you can simply:
principal = float(input("How much money to start? :"))
apr = float(input("What is the apr? :"))
amount = float(input("What is the amount you want to get to? :"))
def interestCalculator():
global principal
i = 1
if principal > amount:
print("Can't calculate interest. Error: Amount is less than principal")
while principal < amount:
principal = principal + principal*apr
print("After year " + str (i)+" the account is at " + str(principal))
if principal > amount:
print("It would take" + str(year) + " years to reach your goal!")
i += 1
interestCalculator()
A suggestion for a more pythonic solution
PRINCIPAL = float(input("How much money to start? :"))
APR = float(input("What is the apr? :"))
AMOUNT = float(input("What is the amount you want to get to? :"))
def interestCalculator(principal, apr, amount):
year = 0
yield year, principal
while principal < amount:
year += 1
principal += principal*apr
yield year, principal
for year, amount in interestCalculator(PRINCIPAL, APR, AMOUNT):
print(f"After year {year} the account is at {amount:.2f}")
if year == 0:
print("Can't calculate interest. Error: Amount is less than principal")
print(f"It would take {year} years to reach your goal!")

How do I get this formula to work and put the return function into the print statement so that it just outputs a money value?

def compound_interest(P, r, n, Y):
'''
Computes the future value of investment after Y years
P: initial investment principal
r: the annual interest rate
n: the number of times per year interest will be compounded
Y: the number of years over which to invest
P = float(input("Enter your starting principal ($): "))
r = float(input("Enter the annual interest rate (value between 0 and 1): "))
n = float(input("Enter the number of times per year to compound interest: "))
Y = float(input("Enter the number of years over which to invest: "))
returns: the future value of investment
'''
compound_interest = ((P)((1+(r/n))**(ny)))
print("After 10 year (s), you will have", "$" + str(compound_interest))
return compound_interest
Here is a solution to your problem:
import math
def compound_interest():
P = float(input("Enter your starting principal ($): "))
r = float(input("Enter the annual interest rate (value between 0 and 1): "))
n = float(input("Enter the number of times per year to compound interest: "))
Y = float(input("Enter the number of years over which to invest: "))
cpd_interest = P * math.pow(r+1, n * Y)
print("After {} year (s), you will have {} $".format(Y, cpd_interest))
return cpd_interest
compound_interest()
I've removed the parameters you give in your function, because you don't need them if you ask for them as input() from the user.
I also improved your calculation: When you want to calculate the interest it should be the starting principal * (the interest percentage +1 to the power (number of years times number of times per year)). I used the math.pow() function for this, and you can see here how it works exactly.
I renamed the variable name from compound_interest to cpd_interest, as it's a bad idea to have variable names the same name as your function.
I also rewrote your print statement, and used a replacement field to correctly format the invested years & interest. You cannot return inside a print statement, returning is always the last thing the function does (unless it returns nothing).

For loop only increasing one of two variables

I wanted the result to show the total amount of money after adding interest every year but it only increases the year but not the amount. Why?
while True:
try:
investment = float(input('How much to invest : '))
interest = float(input('Interest rate : '))
break
except ValueError:
"Please enter a valid number"
for year in range(10):
money = investment + (investment * interest)
print("Total money in year {} : {}".format((year+1), money))
It sounds like you need to accrue the interest:
for year in range(10):
investment += (investment * interest)
print("Total money in year {} : {}".format((year + 1), investment))
Logical error. Your investment variable does not be assigned each round in the loop.

Categories

Resources