views:

54

answers:

1

I'm making an application that gives clients and approximate loan offer (they are later calculated by other back-office systems). I have received some code from the financial firm that we are making the calculator for. My problem is that I do not understand the part of the code that calculates the annual percentage rate (including startup and monthly fees).

It might be this method they are using, but I can't really tell: http://www.efunda.com/math/num_rootfinding/num_rootfinding.cfm#Newton_Raphson

The code works correctly, but I really hate building an application on code that I don't fully understand and/or trust. The ultimate reply would be source-code which does the same thing, but with comments and understandable variable names (I'm not really excepting that :-) All ideas are welcome - maybe someone has a link to an article that explains it.

(please note that I'm by no means a math or financial wiz)

[snip]
int n = numberOfPayments;
double a = (amount / (monthlyPayment * Math.Pow(n, 2)) - (monthlyPayment / amount));
double d = 0;
if (a == 0)
{
    d = 0;
}
else
{
    for (int qq = 0; qq < 20; qq++)
    {
        double b = amount + (monthlyPayment / a) * (1 - (Math.Pow((1 + a), -n)));
        double c = amount + (monthlyPayment / a) * ((n * (Math.Pow((1 + a), (-n - 1)))) - ((1 - (Math.Pow((1 + a), -n))) / a));
        d = a - (b / c);
        double aa = a;
        double dd = d;
        a = d;
        if (Math.Abs(aa - dd) < Math.Pow(10, -5)) { break; }
    }
}
double apr = ((Math.Pow((1 + d), 12)) - 1) * 100;
apr = Math.Round(apr * 100) / 100;
[/snip]
+2  A: 

The code is indeed using the Newton-Raphson method although I have no idea what exactly it is calculating; you may have copied from the wrong section. If, indeed, you want to calculate the annual percentage rate given the loan amount, the monthly payment and the number of months then you have nearly completely solved this except that you probably don't know what the function is whose roots are being searched for and this is, understandably, a stumbling block.

The value that is being searched is called the internal rate of return (IRR) for which there is no closed form; you have to calculate it the hard way or use numerical methods. Calculating the annual percentage rate is a special case of the IRR where all the payments are equal and the loan runs to term. That means that the equation is the following:

P is the principal/loan amount, m is monthly payment, i is the interest rate, N is number of months

0 = P - Sum[k=1..N](m*(1+i)^(-k))

And we have to solve for i. The above equation is equivalent to:

P = Sum[k=1..N](m*(1+i)^(-k))
P = m * Sum[k=1..N]((1+i)^(-k))  // monthly payments all the same
P/m = Sum[k=1..N]((1+i)^(-k))

There are some formulas to get the closed form for the sum on the right hand side which result in the following equation which relates all the quantities that we know already (term, loan, and monthly payment amount) and which is far more tractable:

monthlyPayment = loanAmount * interestRate * ((1 + interestRate)^numberOfPayments)/(((1 + interestRate)^numberOfPayments) - 1)

To reduce typing let:

  • P is the principal/loan amount
  • m is recurring payment amount
  • N is total number of payments

So the equation whose roots we have to find is:

F(x) = P * x * ((1 + x)^N)/(((1 + x)^N) - 1) - m 

To use the Newton-Rhapson method we need the first derivative of F with respect to x:

F_1(x) = P * ( (1 + x)^N/(-1 + (1 + x)^N) - ((N * x * (1 + x)^(-1 + 2*N))/(-1 + (1 + x)^N)^2) + (N * x * (1 + x)^(-1 + N))/(-1 + (1 + x)^N) )

The following code in Groovy does the proper calculation:

numPay = 360
payment = 1153.7
amount = 165000
double error = Math.pow(10,-5)
double approx = 0.05/12 // let's start with a guess that the APR is 5% 
double prev_approx

def F(x) {
  return amount * x * Math.pow(1 + x,numPay)/(Math.pow(1 + x,numPay) - 1) - payment
}

def F_1(x) {
  return amount * ( Math.pow(1 + x,numPay)/(-1 + Math.pow(1 + x,numPay)) - numPay * x * Math.pow(1 + x,-1 + 2*numPay)/Math.pow(-1 + Math.pow(1 + x,numPay),2) + numPay * x * Math.pow(1 + x,-1 + numPay)/(-1 + Math.pow(1 + x,numPay))) 
}


println "initial guess $approx"
for (k=0;k<20;++k) {
       prev_approx = approx
       approx = prev_approx - F(prev_approx)/F_1(prev_approx)
       diff = Math.abs(approx-prev_approx)
       println "new guess $approx diff is $diff"
       if (diff < error) break
}

apr = Math.round(approx * 12 * 10000)/100 // this way we get APRs like 7.5% or 6.55%
println "APR is ${apr}% final approx $approx "

I did not use the provided code since it was a bit murky (plus it did not work for me). I derived this from the definitions of Newton-Rhapson and monthly mortage payments equation. The approximation converges very quickly (10^-5 within 2 or 3 iterations)

NOTE: I am not able to get this link to be properly inserted for the text where the first derivative is first mentioned: http://www.wolframalpha.com/input/?i=d/dx(+x+*+((1+%2B+x)^n)/(((1+%2B+x)^n)+-+1)+-m+)

Allen
The above poster is correct in that the original code is attempting to calculate "apr" iteratively, stopping either at 20 steps or where the next step would produce a change of at most 10^-5. I'm uncertain as to whether the original code is accurate; it's opaque at best.
Borealid
It can't be accurate. I've tried it and it did not work for me. I may have made an error in transcribing, true, but I did derive what is supposedly the equivalent code from definitions which looks nothing like the question's code. The first derivative in particular does not look correct *at all*.
Allen
Impressive Allen - thanks a lot!I have to admit some of the math-heavy bits of your post is lost on me, but the Groovy code in particular made a number of things clearer to me. In the snippet I posted "monthlyPayment" is calculated exactly as you post (but I only posted the part of the code that I had trouble understanding).The snippet I posted does work, I've verified against a number of other similar calculators in Excel and javascript (but I appreciate that I might be murky since it is taken a bit out of context)
Torben Warberg Rohde
@Borealid: Judging from the scenarious I have tested it is fairly accurate (at least to one or two decimals). I have no idea whether it would suffice for a core financial system - but we are only using it to supply the customer with an indicative offer, which is further processed by other systems before a binding offer is given.
Torben Warberg Rohde