@gooddata/react-components
Version:
GoodData.UI - A powerful JavaScript library for building analytical applications
82 lines (78 loc) • 2.83 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
// (C) 2019 GoodData Corporation
var isFunction = require("lodash/isFunction");
var sumBy = require("lodash/sumBy");
var differenceInDaysModule = require("date-fns/differenceInDays");
// jest is being difficult with normal imports for some reason
// enabling esModuleInterop would probably solve this issue, but it is not feasible now
var differenceInDays = isFunction(differenceInDaysModule)
? differenceInDaysModule
: differenceInDaysModule.default;
var newtonRaphson = function (fun, derivative, guess) {
var precision = 4;
var errorLimit = Math.pow(10, -1 * precision);
var iterationLimit = 100;
var previousValue = 0;
var iteration = 0;
var result = guess;
do {
previousValue = result;
result = previousValue - fun(result) / derivative(result);
if (++iteration >= iterationLimit) {
return NaN;
}
} while (Math.abs(result - previousValue) > errorLimit);
return result;
};
/**
* Calculates the XIRR value for the (amount, when) pairs.
* @see https://en.wikipedia.org/wiki/Internal_rate_of_return#Exact_dates_of_cash_flows for mathematical background.
* @param transactions
* @param guess
*/
exports.calculateXirr = function (transactions, guess) {
if (guess === void 0) { guess = 0.1; }
// convert any date to a fractional year difference to allow non-uniform cash-flow distribution (the X in XIRR)
var startDate = transactions[0].when;
var data = transactions.map(function (t) { return ({
C_n: t.amount,
t_n: differenceInDays(t.when, startDate) / 365,
}); });
/*
NPV is defined as
N
====
\ C_n
NPV = \ ----------
/ t_n
/ (1 + r)
====
n = 0
where n is a period and C_n is a cash-flow for the corresponding period.
IRR is defined as a real solution for r in NPV = 0
*/
var npv = function (r) { return sumBy(data, function (_a) {
var t_n = _a.t_n, C_n = _a.C_n;
return C_n / Math.pow(1 + r, t_n);
}); };
/*
We use Newton Raphson method to find the real root of NPV = 0, so we need its derivative:
N
====
dNPV \ C_n . t_n
---- = - \ ----------------
dn / (t_n + 1)
/ (1 + r)
====
n = 0
*/
var npvDerivative = function (r) {
return -1 * sumBy(data, function (_a) {
var t_n = _a.t_n, C_n = _a.C_n;
return (t_n * C_n) / Math.pow(1 + r, t_n + 1);
});
};
return newtonRaphson(npv, npvDerivative, guess);
};
//# sourceMappingURL=calculateXirr.js.map