SYSK 323: Financial Functions IPmt, Pmt, FV Implemented in C#

Microsoft.VisualBasic.dll exposes a number of very useful financial functions, but, as far as I can see, there are no such functions in C#.

 

Of course one can simply reference Microsoft.VisualBasic assembly, especially since it is relatively light and, while it is linked to a number of other libraries (i.e. mscorlib, System, System.Deployment, System.Windows.Forms, System.Runtime.Remoting, System.Management, System.Drawing, System.Web, user32.dll, kernel32.dll, shell32.dll, Advapi32.dll, oleaut32.dll), they are likely to be in loaded in your process space already anyway.

 

However, just for fun, I coded same functionality in C#. I have omitted the last two optional parameters (future value and due date) and use the default values (future value = 0 and due date = end of period).

 

Note: if you’re not familiar with these functions, check out Help in Excel or look for Microsoft.VisualBasic.Financial class in Visual Studio Documentation.

 

 

// Calculate the interest part of a payment for a given period.

// This implementation uses 'payment due at end of period' formula.

public double IPmt(double rate, int paymentPeriod, int numberOfPayments, double amount)

{

    if (paymentPeriod < 1 || paymentPeriod > numberOfPayments)

        throw new ArgumentException("paymentPeriod must be between 1 and numberOfPayments");

    if (rate == 0)

        throw new ArgumentException("This implementation doesn't handle zero interest rate");

    double payment = Pmt(rate, numberOfPayments, amount);

    double futureValue = FV(rate, (paymentPeriod - 1), payment, amount);

    return (futureValue * rate);

}

public double Pmt(double rate, int numberOfPayments, double amount)

{

    double temp = System.Math.Pow((rate+1), numberOfPayments);

    return ((-amount * temp) / ((temp - 1)) * rate);

}

public double FV(double rate, int numberOfPayments, double payment, double amount)

{

    double temp = System.Math.Pow(rate+1, numberOfPayments);

    return ((-amount) * temp) - ((payment/rate) * (temp - 1));

}