I have the following C# code for calculating the modified duration of fixed coupon bonds:
public Double duration(Bond bond, DateTime dtSettle)
{
double duration = 0.0;
double timeDiff1;
double timeDiff2;
double ytm = YTM(bond,bond.marketPrice,dtSettle);
double impPrice = ImpliedBPFfromYTM(bond,ytm,dtSettle);
timeDiff1 = getDayCount(dtSettle, bond.termdates[0], "ACT/365", false);
for (int i = 0; i < bond.termdates.Count; i++)
{
timeDiff2 = getDayCount(bond.termdates[0], bond.termdates[i],bond.dayCountConvention, false) + timeDiff1;
duration = duration + timeDiff2*(cpn/Math.Pow((1+ytm),timeDiff2));
}
timeDiff2 = getDayCount(bond.termdates[0], bond.termdates[bond.termdates.Count - 1], bond.dayCountConvention, false) + timeDiff1;
duration = duration + timeDiff2 * (bond.workoutPar / Math.Pow((1 + ytm), timeDiff2));
return (duration / (impPrice + bond.accrued_interest)) / (1 + ytm / bond.freq);
}
Could anyone give me any pointers as to how I can create a similiar function that calculates the modified duration for Floating Rate Notes?
Some explanation of the code: the YTM function returns yield to maturity given bond characteristics. ImpliedBPFromYTM returns the price of the bond given the yield to maturity, market price etc. getDayCount returns the days between two different dates given the day-count-convention of the bond. Please let me know if there is anything else you need clarified.