Search code examples
financial

XNPV calculation in C# or VB without using excel


Has anyone developed a financial function XNPV? I am looking for code that will calculate this value. I am not looking to call excel to calculate the value.

Any help would be great, thanks


Solution

  • I believe this is the correct implementation in c#:

    public double XNPV(decimal[] receipts,DateTime[] dates, double dRate, DateTime issueDate, decimal cf, int x)
    {
        double sum;
    
        for(int i =0;i<dates.Length;i++)
        {
            TimeSpan ts =  dates[i].Subtract(issuedate);
            sum +=receipts[i] / ((1 + dRate / cf) ^ ((ts.TotalDays / 360) * cf));
        }
        return sum;
    }
    

    and this is the equivalent in VB:

    Public Function XNPV(ByVal Receipts() As Decimal, ByVal Dates() As Date, ByVal dRate As Double, ByVal IssueDate As Date, ByVal CF As Decimal, ByVal x As Integer) As Double
    
    Dim i As Integer
    Dim sum As Double
    
    For i = 0 To UBound(Dates)
        sum = sum + Receipts(i) / ((1 + dRate / CF) ^ ((DateDiff / 360) * CF))
    
    XNPV = sum
    End Function