25

How do I calculate Excel's XIRR function using C#?

AakashM
  • 59,217
  • 16
  • 147
  • 181
Hitusam
  • 255
  • 1
  • 3
  • 6
  • 1
    Maybe [this KB article from Microsoft](http://support.microsoft.com/kb/214105/en-us) does help? – Uwe Keim Mar 03 '11 at 13:34
  • see my edit - i've added complete C# example... – Agnius Vasiliauskas Mar 04 '11 at 11:27
  • and do not forget to mark answer as accepted if you feel that it solves your problem. – Agnius Vasiliauskas Mar 04 '11 at 11:34
  • For anyone that wants to see the Excel link: http://msdn.microsoft.com/en-us/library/office/bb224771(v=office.12).aspx – dyslexicanaboko Oct 14 '12 at 20:47
  • 1
    Okay so a friend of mine just showed this to me, I haven't used it yet - but it might be a partial answer as it doesn't include the dates in the calculation http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.financial.irr.aspx – dyslexicanaboko Jun 20 '13 at 19:12
  • Exactly the link is for [IRR](http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.financial.irr.aspx) not for XIRR. [IRR vs XIRR](http://www.financialwebring.org/gummy-stuff/Return-on-Investments.htm) – Gonzalo Contento Sep 06 '13 at 15:59

5 Answers5

42

According to XIRR function openoffice documentation (formula is same as in excel) you need to solve for XIRR variable in the following f(xirr) equation:
enter image description here
You can calculate xirr value by:

  1. calculating derivative of above function -> f '(xirr)
  2. after having f(xirr) and f'(xirr) you can solve for xirr value by using iterative Newton's method - famous formula->
    enter image description here

EDIT
I've got a bit of time so, here it is - complete C# code for XIRR calculation:

class xirr
    {
        public const double tol = 0.001;
        public delegate double fx(double x);

        public static fx composeFunctions(fx f1, fx f2) {
            return (double x) => f1(x) + f2(x);
        }

        public static fx f_xirr(double p, double dt, double dt0) {
            return (double x) => p*Math.Pow((1.0+x),((dt0-dt)/365.0));
        }

        public static fx df_xirr(double p, double dt, double dt0) {
            return (double x) => (1.0/365.0)*(dt0-dt)*p*Math.Pow((x+1.0),(((dt0-dt)/365.0)-1.0));
        }

        public static fx total_f_xirr(double[] payments, double[] days) {
            fx resf = (double x) => 0.0;

            for (int i = 0; i < payments.Length; i++) {
                resf = composeFunctions(resf,f_xirr(payments[i],days[i],days[0]));
            }

            return resf;
        }

        public static fx total_df_xirr(double[] payments, double[] days) {
            fx resf = (double x) => 0.0;

            for (int i = 0; i < payments.Length; i++) {
                resf = composeFunctions(resf,df_xirr(payments[i],days[i],days[0]));
            }

            return resf;
        }

        public static double Newtons_method(double guess, fx f, fx df) {
            double x0 = guess;
            double x1 = 0.0;
            double err = 1e+100;

            while (err > tol) {
                x1 = x0 - f(x0)/df(x0);
                err = Math.Abs(x1-x0);
                x0 = x1;
            }

            return x0;
        }

        public static void Main (string[] args)
        {
            double[] payments = {-6800,1000,2000,4000}; // payments
            double[] days = {01,08,16,25}; // days of payment (as day of year)
            double xirr = Newtons_method(0.1,
                                         total_f_xirr(payments,days),
                                         total_df_xirr(payments,days));

            Console.WriteLine("XIRR value is {0}", xirr);
        }
    }

BTW, keep in mind that not all payments will result in valid XIRR because of restrictions of formula and/or Newton method!

cheers!

Agnius Vasiliauskas
  • 10,413
  • 5
  • 46
  • 66
  • 3
    Note if you are trying to match Excel's results you need to set the tolerance to 0.00000001 instead, and as mentioned below you may want to add code to max out the iterations at 100 (or make that configurable). – Luther Feb 07 '13 at 00:52
  • Pretty clean code. Thanks. As I need to use XIRR in my Java & Android app, I do the porting to Java. You may refer to https://github.com/yccheok/xirr if you need. Not using closure as the code need to be compatible with Java 6 & 7. – Cheok Yan Cheng Jul 10 '14 at 15:57
28

I started with 0x69's solution but eventually some new scenarios caused Newton's Method to fail. I created a "smart" version, which uses Bisection Method (slower) when Newton's fails.

Please notice the inline references to multiple sources I used for this solution.

Finally, you are not going to be able to reproduce some of these scenarios in Excel, for Excel itself uses Newton's method. Refer to XIRR, eh? for an interesting discussion about this.

using System;
using System.Collections.Generic;
using System.Linq;

// See the following articles: // http://blogs.msdn.com/b/lucabol/archive/2007/12/17/bisection-based-xirr-implementation-in-c.aspx // http://www.codeproject.com/Articles/79541/Three-Methods-for-Root-finding-in-C // http://www.financialwebring.org/forum/viewtopic.php?t=105243&highlight=xirr // Default values based on Excel doc // http://office.microsoft.com/en-us/excel-help/xirr-function-HP010062387.aspx

namespace Xirr { public class Program { private const Double DaysPerYear = 365.0; private const int MaxIterations = 100; private const double DefaultTolerance = 1E-6; private const double DefaultGuess = 0.1;

private static readonly Func<IEnumerable<CashItem>, Double> NewthonsMethod = cf => NewtonsMethodImplementation(cf, Xnpv, XnpvPrime); private static readonly Func<IEnumerable<CashItem>, Double> BisectionMethod = cf => BisectionMethodImplementation(cf, Xnpv); public static void Main(string[] args) { RunScenario(new[] { // this scenario fails with Newton's but succeeds with slower Bisection new CashItem(new DateTime(2012, 6, 1), 0.01), new CashItem(new DateTime(2012, 7, 23), 3042626.18), new CashItem(new DateTime(2012, 11, 7), -491356.62), new CashItem(new DateTime(2012, 11, 30), 631579.92), new CashItem(new DateTime(2012, 12, 1), 19769.5), new CashItem(new DateTime(2013, 1, 16), 1551771.47), new CashItem(new DateTime(2013, 2, 8), -304595), new CashItem(new DateTime(2013, 3, 26), 3880609.64), new CashItem(new DateTime(2013, 3, 31), -4331949.61) }); RunScenario(new[] { new CashItem(new DateTime(2001, 5, 1), 10000), new CashItem(new DateTime(2002, 3, 1), 2000), new CashItem(new DateTime(2002, 5, 1), -5500), new CashItem(new DateTime(2002, 9, 1), 3000), new CashItem(new DateTime(2003, 2, 1), 3500), new CashItem(new DateTime(2003, 5, 1), -15000) }); } private static void RunScenario(IEnumerable<CashItem> cashFlow) { try { try { var result = CalcXirr(cashFlow, NewthonsMethod); Console.WriteLine("XIRR [Newton's] value is {0}", result); } catch (InvalidOperationException) { // Failed: try another algorithm var result = CalcXirr(cashFlow, BisectionMethod); Console.WriteLine("XIRR [Bisection] (Newton's failed) value is {0}", result); } } catch (ArgumentException e) { Console.WriteLine(e.Message); } catch (InvalidOperationException exception) { Console.WriteLine(exception.Message); } } private static double CalcXirr(IEnumerable<CashItem> cashFlow, Func<IEnumerable<CashItem>, double> method) { if (cashFlow.Count(cf => cf.Amount > 0) == 0) throw new ArgumentException("Add at least one positive item"); if (cashFlow.Count(c => c.Amount < 0) == 0) throw new ArgumentException("Add at least one negative item"); var result = method(cashFlow); if (Double.IsInfinity(result)) throw new InvalidOperationException("Could not calculate: Infinity"); if (Double.IsNaN(result)) throw new InvalidOperationException("Could not calculate: Not a number"); return result; } private static Double NewtonsMethodImplementation(IEnumerable<CashItem> cashFlow, Func<IEnumerable<CashItem>, Double, Double> f, Func<IEnumerable<CashItem>, Double, Double> df, Double guess = DefaultGuess, Double tolerance = DefaultTolerance, int maxIterations = MaxIterations) { var x0 = guess; var i = 0; Double error; do { var dfx0 = df(cashFlow, x0); if (Math.Abs(dfx0 - 0) < Double.Epsilon) throw new InvalidOperationException("Could not calculate: No solution found. df(x) = 0"); var fx0 = f(cashFlow, x0); var x1 = x0 - fx0/dfx0; error = Math.Abs(x1 - x0); x0 = x1; } while (error > tolerance && ++i < maxIterations); if (i == maxIterations) throw new InvalidOperationException("Could not calculate: No solution found. Max iterations reached."); return x0; } internal static Double BisectionMethodImplementation(IEnumerable<CashItem> cashFlow, Func<IEnumerable<CashItem>, Double, Double> f, Double tolerance = DefaultTolerance, int maxIterations = MaxIterations) { // From "Applied Numerical Analysis" by Gerald var brackets = Brackets.Find(Xnpv, cashFlow); if (Math.Abs(brackets.First - brackets.Second) < Double.Epsilon) throw new ArgumentException("Could not calculate: bracket failed"); Double f3; Double result; var x1 = brackets.First; var x2 = brackets.Second; var i = 0; do { var f1 = f(cashFlow, x1); var f2 = f(cashFlow, x2); if (Math.Abs(f1) < Double.Epsilon && Math.Abs(f2) < Double.Epsilon) throw new InvalidOperationException("Could not calculate: No solution found"); if (f1*f2 > 0) throw new ArgumentException("Could not calculate: bracket failed for x1, x2"); result = (x1 + x2)/2; f3 = f(cashFlow, result); if (f3*f1 < 0) x2 = result; else x1 = result; } while (Math.Abs(x1 - x2)/2 > tolerance && Math.Abs(f3) > Double.Epsilon && ++i < maxIterations); if (i == maxIterations) throw new InvalidOperationException("Could not calculate: No solution found"); return result; } private static Double Xnpv(IEnumerable<CashItem> cashFlow, Double rate) { if (rate <= -1) rate = -1 + 1E-10; // Very funky ... Better check what an IRR <= -100% means var startDate = cashFlow.OrderBy(i => i.Date).First().Date; return (from item in cashFlow let days = -(item.Date - startDate).Days select item.Amount*Math.Pow(1 + rate, days/DaysPerYear)).Sum(); } private static Double XnpvPrime(IEnumerable<CashItem> cashFlow, Double rate) { var startDate = cashFlow.OrderBy(i => i.Date).First().Date; return (from item in cashFlow let daysRatio = -(item.Date - startDate).Days/DaysPerYear select item.Amount*daysRatio*Math.Pow(1.0 + rate, daysRatio - 1)).Sum(); } public struct Brackets { public readonly Double First; public readonly Double Second; public Brackets(Double first, Double second) { First = first; Second = second; } internal static Brackets Find(Func<IEnumerable<CashItem>, Double, Double> f, IEnumerable<CashItem> cashFlow, Double guess = DefaultGuess, int maxIterations = MaxIterations) { const Double bracketStep = 0.5; var leftBracket = guess - bracketStep; var rightBracket = guess + bracketStep; var i = 0; while (f(cashFlow, leftBracket)*f(cashFlow, rightBracket) > 0 && i++ < maxIterations) { leftBracket -= bracketStep; rightBracket += bracketStep; } return i >= maxIterations ? new Brackets(0, 0) : new Brackets(leftBracket, rightBracket); } } public struct CashItem { public DateTime Date; public Double Amount; public CashItem(DateTime date, Double amount) { Date = date; Amount = amount; } } }

}

Gustav Bertram
  • 13,450
  • 3
  • 38
  • 64
Gonzalo Contento
  • 817
  • 9
  • 21
  • 3
    Just to state that I'm using your code and it works as expected. – BrunoSalvino Dec 14 '11 at 18:35
  • 1
    Just a word of caution to the adopters of this code, it works great, however you may encounter a strange edge case where you enter a never ending loop, essentially a deadlock. To prevent this from happening I strongly suggest adding a max iteration of 100 or whatever number you are comfortable with in the NewtonsMethod method. Like so: while (err > TOLERANCE && i < 100), increment i on every iteration. The values I got were still spot on to what Excel was giving me. This only happens (from what I saw) in cases where you are converging to infinity, but can't quite get there quickly. – dyslexicanaboko Oct 16 '12 at 15:41
  • 1
    I found another edge case, this one matters because the results are different in Excel. Inside of the NewtonsMethod method - During computation if x0 and x1 are Infinity, the result that is returned from the method is Infinity. The reason being that Infinity - Infinity = NaN, but x0 gets the value of x1 after setting err, therefore the last value out is Infinity. In excel, the result is zero! For reference here is my data set: Values {-10000, 10100, 10000}, Dates {12/26/2010, 12/26/2010, 10/16/2012}. Maybe include an if statement looking for err == double.NaN, then x0 = 0; I am undecided. – dyslexicanaboko Oct 17 '12 at 18:58
  • dyslexicanaboko: I'm running into a situation where Excel can calculate XIRR but at some point in this code err ends up as NaN so I get no result here. 95% of my other test cases are fine. Let me know if you have any ideas on this :-) – Luther Feb 08 '13 at 00:48
  • @dyslexicanaboko take a look at the latest revision of this post. Not sure if it solves your issues. – Gonzalo Contento Feb 12 '13 at 20:37
  • @Luther - hey sorry I didn't see your comment until I was notified of the comment below yours. To notify people use the @ symbol before their handle. I can try to look at your problem later but I need some data to work with. Plus the code changed so I am not sure if it is a problem anymore. Try working with Gonzalo's changes maybe it solves your problem? – dyslexicanaboko Feb 14 '13 at 15:43
  • @GonzaloContento very nice improvements, I will play around with it and get back to you. I want your opinion on something: If you get NaN back, what is the best way to describe that to the user if they were expecting a percentage? I return positive infinity at times and I think they can grasp that, but NaN - not sure. – dyslexicanaboko Feb 14 '13 at 15:53
  • @dyslexicanaboko By looking at [Wikipedia](http://en.wikipedia.org/wiki/NaN) a better message could be something like "Invalid data..." – Gonzalo Contento Feb 14 '13 at 20:40
  • 1
    I was using this to calculate annualized returns on a stock portfolio and discovered that if you don't use a negative guess when trying to calculate negative returns the "Could not calculate: No solution found. df(x) = 0" exception gets thrown in cases where excel was able to calculate it. I got around the problem by throwing and catching a custom exception and repeating the calculation with a negative guess in the catch block. – MadMax1138 Sep 05 '13 at 22:25
  • @MadMax1138 would you please post the scenario "RunScenario(new[] ..."? I am going to add the fix... – Gonzalo Contento Oct 07 '13 at 19:07
  • 1
    i'm currently working with this and I happen to encounter a Math.pow returning a NaN. while this is understandable, i don't know how excel is able to get a value. Anyone else experience this? – Milo Cabs Mar 04 '16 at 06:48
  • I found an edge case as follows : For reference here is my data set: Values {-5383992.43, -0.03, 10066469.21,5053369.26,0.00999999999999999}, Dates {2013-02-27, 2013-02-28, 2013-03-06,2013-03-15,2013-03-31} I see that XL seems to come back with the highest of the multi result set. How do we emulate the same with our code? – Jersey_Guy Sep 11 '17 at 21:34
  • 1
    This answer got some really interesting comments. I'm most interested if @dyslexicanaboko or GonzaloContento got any new insights in the last 3 years using this code. – CularBytes Mar 21 '20 at 11:04
  • @CularBytes sorry no, I actually moved out of the investment industry and into health care instead. I don't have anything to report because I haven't used this code in a long time. Real life saver at the time that's for sure. – dyslexicanaboko Mar 28 '20 at 23:48
6

Thanks to contributors of the nuget package located at Excel Financial Functions. It supports many financial methods - AccrInt, Irr, Npv, Pv, XIrr, XNpv, etc.,

  1. Install and import the package.
  2. As all the methods are static in Financial class, directly call specific method as Financial.<method_name> with required parameters.

Example:

using Excel.FinancialFunctions;

namespace ExcelXirr
{
    class Program
    {
        static void Main(string[] args)
        {
            List<double> valList =new List<double>();
            valList.Add(4166.67);
            valList.Add(-4166.67);
            valList.Add(-4166.67);
            valList.Add(-4166.67);
            List<DateTime> dtList = new List<DateTime>();
            dtList.Add(new DateTime(2014, 9, 1));
            dtList.Add(new DateTime(2014, 10, 1));
            dtList.Add(new DateTime(2014, 11, 1));
            dtList.Add(new DateTime(2014, 12, 1));
            double result = Financial.XIrr(valList, dtList);
            Console.WriteLine(result);
            Console.ReadLine();
        }
    }
}

Result is same as Excel.

enter image description here

Saravanan Sachi
  • 2,532
  • 5
  • 29
  • 37
5

The other answers show how to implement XIRR in C#, but if only the calculation result is needed you can call Excel's XIRR function directly in the following way:

First add reference to Microsoft.Office.Interop.Excel and then use the following method:

    public static double Xirr(IList<double> values, IList<DateTime> dates)
    {
        var xlApp = new Application();

        var datesAsDoubles = new List<double>();
        foreach (var date in dates)
        {
            var totalDays = (date - DateTime.MinValue).TotalDays;
            datesAsDoubles.Add(totalDays);
        }

        var valuesArray = values.ToArray();
        var datesArray = datesAsDoubles.ToArray();

        return xlApp.WorksheetFunction.Xirr(valuesArray, datesArray);
    }
galbarm
  • 2,251
  • 2
  • 25
  • 50
  • This is likely to be considerably slower compared with the C# code implementations in the other answers (but it's a good demonstration if performance is not a concern!). – user700390 Jun 01 '16 at 15:01
0

This repo from GitHub - klearlending/XIRR has sample code on how to calculate XIRR.

The author also provided a blogpost XIRR-demystified, that explains the logic and reasoning.

So far that lib is giving close to accurate results for me. (Still exploring it and forked it for personal use)

Shubhan
  • 544
  • 4
  • 13