/* Copyright 2008 by Stefan Hollos and Richard Hollos
*/

/*
bond_ytm calculates the bond yield to maturity.
This function calls the 3 functions below, to solve for the bond yield to maturity
using Newton's root finding method.
  price = market price of the bond
  face = face value of the bond
  interest = interest (coupon) rate
  m = number of payments per year
  n = number of payments until maturity
*/
function bond_ytm(price, face, interest, m, n)
{
    var a = face/price;
    var i = interest/m;
    var ytm; /* yield to maturity */
    var x0;  /* initial guess for ytm/m */
    if (price == face)
	ytm = interest;
    else{
        x0 = a*i + (a - 1)/n;
        ytm = m*newt_root(x0, bond_ytm_f(n,a,i), bond_ytm_fp(n,a,i), 0.0001);
    }
    return ytm;
}

/*
The root of this equation gives you the bond yield to maturity.
*/
function bond_ytm_f(n, a, i)
{
    var f = function(x){ return n*Math.log(x+1) + Math.log((x-a*i)/(x-i)) - Math.log(a); };
    return f;
}

/*
This is the derivative of the bond_ytm_f equation above.
*/
function bond_ytm_fp(n, a, i)
{
    var f = function(x){ return n/(x+1) + i*(a-1)/((x-a*i)*(x-i)); };
    return f;
}

/*
newt_root implements Newton's method for finding roots.
;   x = initial guess
;   f = function whose root is to be found
;   fp = derivative of function
;   tol = tolerance desired
*/
function newt_root(x, f, fp, tol)
{
    var x0;
    for (x0=x; Math.abs(f(x0))>tol; x0-=f(x0)/fp(x0)) /*Empty for*/ ;
    return x0;
}
