How can I get the same results of the Excel YearFrac function in my C# application?
Calculates the fraction of the year represented by the number of whole days between two dates (the start_date and the end_date). Use the YEARFRAC worksheet function to identify the proportion of a whole year's benefits or obligations to assign to a specific term.
You can use Excel's functionality directly to calculate
YearFrac
. Microsoft says you are not supposed to use it, but it works very well. If you need a 100% compatibility with Excel, this solution is hard to beat. You need to add to your project a reference toMicrosoft.Office.Interop.Excel
in order for this code to compile.Here is a good snippet.
The algorithm for the YearFrac function is in fact very complex. Maybe this article can provide you with more details.
May I suggest:
The signature of YEARFRAC is YEARFRAC(Date startDate, Date endDate, int convention). The method to calculate the YEARFRAC depends on the convention.
For convention = 2, YEARFRAC will calculate the YEARFRAC using ACT/360 method. An implementation of the ACT/360 can be found at svn.finmath.net, specifically DayCountConvention_ACT_360.java
For convention = 3, YEARFRAC will calculate the YEARFRAC using ACT/365 method. An implementation of the ACT/365 can be found at svn.finmath.net, specifically DayCountConvention_ACT_365.java
For convention = 4, YEARFRAC will calculate the YEARFRAC using 30E/360 method. An implementation of the 30E/360 can be found at svn.finmath.net, specifically DayCountConvention_30E_360.java
For convention = 1, the documentation claims that YEARFRAC is calculate using ACT/ACT convention. However, there are a multiple versions of ACT/ACT and I believe the standard for many financial products is ACT/ACT ISDA. I found that YEARFRAC differs by a small amount from the ACT/ACT IDSA convention! An implementation of the ACT/ACT IDSA can be found at DayCountConvention_ACT_ACT_ISDA.java
I haven't checked the other act/act versions yet, but I would not rely on an emulation of YEARFRAC ACT/ACT, when it is not clear what kind of method they implement...