Search code examples
pythoniterationsympysolver

Solve for unknown interest rate in accumulated amount


Hi I am looking for a way to iterate some value with an unknown. There are 18 cashflows (cf_1 to cf_18) and their corresponding accumulate periods (t1 to t18), stored in 2 lists. I wish to equate the sum of the accumulated amounts (in terms of the unknown interest rate i) to 500000, and solve for this i.

The formula is: 500000 = accumulated value = cf1 * (1+i)^t1 +...+ cf_18 * (1+i)^t18. I could think of using sympy solver:

solve(cf1 * (1+i)**t1 +...+ cf_18 * (1+i)**t18 - 500000, i) 

to solve for i. But apparently for loop can not take this unknown i. So what else can I do beside type out the whole 18 expressions?

This is the data and what I have tried:

from sympy.solvers import solve
from sympy import Symbol

i = Symbol('i')

cashflow = [13000,
12500,
12000,
11500,
11000,
10500,
10000,
9500,
9000,
8500,
8000,
7500,
7000,
6500,
6000,
5500,
5000,
4500,]

years_accum = [22.75,
22.5,
20.5,
20,
19.25,
19,
18.75,
12,
10.25,
10,
9.75,
9,
8.5,
8,
7.5,
5,
3.5,
3.25,]

for cf in cashflow:
    for yr in years_accum:
        S_t = sum(cf* (1+i)^yr)
        print(S_t)
solve(S_t - 500000, i)

Any help appreciated!


Solution

  • Your double loop is incorrect since for each cash flow it adds all the years. I would have done

    >>> eq = sum([cf*(1+i)**yr for cf,yr in zip(cashflow, years_accum)]) - 500000
    

    But to see this in a loop it could be

    >>> S_t = 0
    >>> for cf, yr in zip(cashflow, years_accum):
    ...    S_t = S_t + cf*(1+i)**yr
    
    >>> eq = S_t - 500000
    

    Now to solve...solve would be good if we expect a simple answer (from a relatively simple equation). Since this is highly non-linear nsolve (for numerical-solutions) is a better choice:

    >>> nsolve(eq, 0)  # assume i is close to 0
    0.0747836528616713