Skip to content

Instantly share code, notes, and snippets.

@cdarringer
Created May 8, 2016 01:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cdarringer/18b1a25b844478524736ed5e091d8e37 to your computer and use it in GitHub Desktop.
Save cdarringer/18b1a25b844478524736ed5e091d8e37 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
"""
Simple compunding interest calculator.
Created on Sat May 7 12:48:37 2016
@author: Chris Darringer
"""
def main():
# read inputs
principal = readPrincipal()
rate = readInterestRate()
years = readYears()
compounding = readCompounding()
# map compounding type to a denominator
periodsPerYear = getPeriodsPerYear(compounding)
# print the schedule
balance = principal
for year in range(years):
for period in range(periodsPerYear):
interest = balance * ((rate / 100) / periodsPerYear)
newBalance = balance + interest
print "Year: ", year, "Period: ", period, "Beginning balance: ", \
balance, "Interest: ", interest, "New balance: ", newBalance
balance = newBalance
# print the final balance using the comppounding formula
balance = principal * ((1 + ((rate / 100) / periodsPerYear)) ** (years * periodsPerYear))
print "Balance calculated from compounding formula: ", round(balance, 2)
def getPeriodsPerYear(compounding) :
compoundingTypeMap = {
'a':1,
's':2,
'q':4,
'm':12,
'd':360
}
return compoundingTypeMap[compounding]
def readPrincipal():
principal = 0
while principal <= 0.0:
try:
answer = raw_input("What is the principal amount in dollars (i.e. 100.00)? ")
principal = float(answer)
except ValueError:
print "That's not a valid principal, please try again."
return principal
def readInterestRate():
rate = 0.0
while rate == 0.0:
try:
answer = raw_input("What is the interest rate percent (i.e. 5.2)? ")
rate = float(answer)
except ValueError:
print "That's not a valid percentage, please try again."
return rate
def readYears():
years = 0
while years <= 0:
try:
answer = raw_input("How many years is the principal invested? ")
years = int(answer)
except ValueError:
print "That's not a valid number of years, please try again."
return years
def readCompounding():
compounding = 'X'
while compounding not in ['a', 's', 'q', 'm', 'd']:
try:
question = "What type of Compounding?\n";
question = question + "(A=Annual, S=Semiannual, Q=Quarterly, M=Monthly, D=Daily) "
answer = raw_input(question)
compounding = answer.lower()
except ValueError:
print "That's not a valid compounding type, please try again."
return compounding
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment