简体   繁体   中英

Using Python for Compounding Interest

I'm writing a test that returns the interest total by year. How can I append the values of interest as it compounds on each step inside of the array interest = [] in my Investor class? For some reason this has been difficult to wrap my head around.

Code:

class Test(unittest.TestCase):

'''Represents my test case(s) for the dojo.'''

def setUp(self):
    '''Defines the initial state of an investor.'''
    self.investor = Investor(10000, 7.2, 5)

def test_solve_for_interest(self):
    self.assertEqual(self.investor.get_interest(), 720.0)

def test_get_interest_by_year(self):
    '''Returns a value of interest associated by the year.'''
    self.assertEqual(self.investor.interest_by_year(1), 10720.0)


class Investor(object):

    def __init__(self, amount, rate, time):
        self.amount = amount
        self.rate = rate
        self.time = time

    def get_interest(self):
        return (self.amount * self.rate) / 100.0

    def interest_by_year(self, year):
        interest = []
        for i in xrange(1, (self.time+1)):
            # collect compounding interest each year
        return interest[year]

Expected Results:

year 1 = 10,720.00 (interest[1])

year 2 = 11491.84  (interest[2])

year 3 = 12319.25  (interest[3])

year 4 = 13206.24  (interest[4])

year 5 = 14157.09  (interest[5])

This could be solved more elegantly with Pandas:

years = range(1,6)
rate = 0.072
rates = pandas.Series(index = years, data = rate)

Note that the rate may differ over the years

initialValue*((rates + 1).cumprod())
def interest_by_year(self, year):
    interest = [self.amount]
    for i in xrange(self.time):
        interest.append(interest[i]*self.rate)
    return interest[year]

Test:

ivt = Investor(10000, 1.072, 10)
for i in range(1, 6):
    print "year", i, "=", ivt.interest_by_year(i) 

Output:

year 1 = 10720.0
year 2 = 11491.84
year 3 = 12319.25248
year 4 = 13206.2386586
year 5 = 14157.087842    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM