samedi 21 février 2015

Javascript Yield Calculator that emulates Excel


I am building a bond calculator and I need to get the Yield outputted as a percentage I have used Excel as a guide and the =YIELD() function that is in there.


In excel for these given values I return 5.181800



=YIELD(19-02-2015, 21-02-2019, 5.75/100, 102.031, 100, 2, 1)*100
=YIELD(SettlementDate, MaturityDate, CouponsRate, BondPrice, 100, Coupons PA, Basis) * 100


In Javascript I have written



function dayDiff(date1, date2) {

var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));

return diffDays;
}

var settlement = '2015-02-19',
maturity = '2019-02-21',

settlement = new Date(settlement);
maturity = new Date(maturity);

var timeToMaturity = dayDiff(settlement, maturity);
var coupon = 5.75 / 100;
var yield = 102.031;
var redemption = 100;
var frequency = 2;

var price = 0.0;
if(timeToMaturity > 0) {
price += redemption;
}
var paymentTime = timeToMaturity;
while(paymentTime > 0) {
price += coupon/frequency;

// Discount back
price = price / (1.0 + yield / frequency);
paymentTime -= 1.0 / frequency;
}
var accrualPeriod = 0.0-paymentTime;
price *= Math.pow(1.0 + yield / frequency, accrualPeriod*frequency);
price -= coupon/frequency * accrualPeriod*frequency;

console.log(price * 100 * 100);


This returns 5.635542139153786 can anyone tell me where I am going wrong?





Aucun commentaire:

Enregistrer un commentaire