0

I have been tasked with migrating some specific Financial functions written in F# to C# The F# library I am using is excellent (http://archive.msdn.microsoft.com/FinancialFunctions) but environmental considerations prevent the deployment of a CLR assembly to our SQL Server with Unrestricted permissions that it requires to be deployed

The specific function I am having a problem with is the MacAuley Duration formula. I am an absolute novice with F# and would appreciate if an F# expert would explain the code snippet below:

    let aggrFunction acc index =
        let x5 = float index - 1. + x1
        let x6 = pow x3 x5
        ( x6 <> 0.) |> elseThrow "x6 must be different from 0)"
        let x7 = (100. * coupon / frequency) / x6
        let a, b = acc
        a + x7 * x5, b + x7
    let term2, term4 = aggrBetween 1 (int n) aggrFunction (0., 0.)

My best C# attempt looks thus and returns the wrong result (I am running the two side by side). btw frequency is an Enum hence the cast

    double term2 = 0;
    double term4 = 0;
    for (int i = 0; i <= n ; i++)
    {
        var x5 = i - 1 + x1;
        var x6 = Math.Pow(x3, x5);
        if (x6 == 0)
        {
            throw new Exception("x6 must be different from 0)");
        }
        var x7 = (100D * coupon/(int) frequency) / x6;
        term2 += (x7*x5);
        term4 += x7;
    }
  • 1
    Did you notice your for loop starts with 0, but the aggregate in F# starts with 1? Frequency should be a float. – Gus Feb 12 '14 at 10:10
  • To be honest, if you wouldn't have said it is the Macaulay Duration you are calculating, I would have not guessed it; and still the code looks fairly unreadable. – NoIdeaHowToFixThis Feb 12 '14 at 16:48
  • From your code it seems that you are interested in the case when coupon payments are constant over time. In this situation there's an explicit formula for the Macaulay duration, no need to loop. See for example, David Luemberger, "Investment Science". – NoIdeaHowToFixThis Feb 12 '14 at 17:00
  • For the record, the best place to get the Excel Financial Functions is now here rather than MSDN: http://fsprojects.github.io/ExcelFinancialFunctions/ – Kit Feb 13 '14 at 11:49

0 Answers0