Module: CashFlowAnalysis::Calculator::Xirr

Extended by:
Newton
Defined in:
lib/cash_flow_analysis/calculator/xirr.rb

Class Method Summary collapse

Class Method Details

.calculate(cash_flow_items) ⇒ Numeric

Calculates the XIRR, assuming irregularly timed cash flows.

Parameters:

  • cash_flow_items (Array)

    items which have `#date` ([Date]) and `#amount` ([Numeric]) properties

Returns:

  • (Numeric)

    the XIRR for the cash flow


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/cash_flow_analysis/calculator/xirr.rb', line 12

def self.calculate(cash_flow_items)
  return nil if cash_flow_items.map(&:amount).none? { |amount| amount >= 0 }
  return nil if cash_flow_items.map(&:amount).none? { |amount| amount < 0 }

  objective_function = Util::ObjectiveFunction.new(Xnpv, cash_flow_items)
  discount_rate_vector = [objective_function.one]

  begin
    nlsolve(objective_function, discount_rate_vector)
  rescue RuntimeError => ex
    raise CalculationError.new(ex)
  end

  discount_rate_vector.first
end