XIRR Calculation

匿名 (未验证) 提交于 2019-12-03 01:29:01

问题:

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

回答1:

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:

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->

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  0.0;              for (int i = 0; i  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!



回答2:

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, Double> NewthonsMethod = cf => NewtonsMethodImplementation(cf, Xnpv, XnpvPrime); private static readonly Func, 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 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 cashFlow, Func, 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 cashFlow, Func, Double, Double> f, Func, 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) tolerance && ++i cashFlow, Func, 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) 0) throw new ArgumentException("Could not calculate: bracket failed for x1, x2"); result = (x1 + x2)/2; f3 = f(cashFlow, result); if (f3*f1 tolerance && Math.Abs(f3) > Double.Epsilon && ++i cashFlow, Double rate) { if (rate 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 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, Double, Double> f, IEnumerable 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 ? 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; } } }

}



回答3:

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 values, IList dates)     {         var xlApp = new Application();          var datesAsDoubles = new List();         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);     } 


文章来源: XIRR Calculation
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!