Class: Finance::Calculations

Inherits:
Object
  • Object
show all
Defined in:
lib/finance/calculations.rb

Defined Under Namespace

Classes: Function

Class Method Summary collapse

Class Method Details

.irr(values) ⇒ Float Also known as: internal_return_rate

IRR computes the Rate of Interest per period.

Examples:

require 'finance_rb'
Finance::Calculations.irr([-100, 0, 0, 74]) #=> 0.14299344106053188

Parameters:

  • :values (Array<Numeric>)

    Input cash flows per time period. At least, must contain one positive and one negative value. Otherwise, irr equals zero.

Returns:

  • (Float)

    Internal Rate of Return for periodic input values.

See Also:



48
49
50
51
52
53
54
55
56
# File 'lib/finance/calculations.rb', line 48

def irr(values)
  return 0.0 unless correct_cashflows?(values)

  func = BigDecimal.limit(100)
  func = Function.new(values)
  rate = [ func.one ]
  nlsolve(func, rate)
  rate[0].to_f
end

.mirr(values, rate, reinvest_rate) ⇒ Float

MIRR computes the modified Rate of Interest.

Examples:

require 'finance_rb'
Finance::Calculations.mirr([100, 200, -50, 300, -200], 0.05, 0.06) => 0.2979256979689131

Parameters:

  • :values (Array<Numeric>)

    At least, must contain one positive and one negative value. Otherwise, mirr equals zero.

  • :rate (Numeric)

    Interest rate paid on the cash flows

  • :reinvest_rate (Numeric)

    Interest rate received on the cash flows upon reinvestment

Returns:

  • (Float)

    Modified Internal Rate of Return.

See Also:



73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/finance/calculations.rb', line 73

def mirr(values, rate, reinvest_rate)
  inflows = [];
  outflows = [];
  # We prefer manual enumeration over the partition
  #   because of the need to replace outflows with zeros.
  values.each do |val|
    if val >= 0
      inflows << val
      outflows << 0.0
    else
      outflows << val
      inflows << 0.0
    end
  end
  if outflows.all?(0.0) || inflows.all?(0.0)
    return 0.0
  end
  fv = npv(reinvest_rate, inflows).abs
  pv = npv(rate, outflows).abs

  return (fv/pv) ** (1.0/(values.size - 1)) * (1 + reinvest_rate) - 1
end

.npv(rate, values) ⇒ Numeric Also known as: net_present_value

Npv computes the Net Present Value of a cash flow series.

Examples:

require 'finance_rb'
Finance::Calculations.npv(0.1, [-1000, 100, 100, 100]) #=> -789.3518518518517

Parameters:

  • :rate (Numeric)

    A discount rate applied once per period.

  • :values (Array<Numeric>)

    The values of the time series of cash flows.

Returns:

  • (Numeric)

    The NPV of the input cash flow series ‘values` at the discount `rate`.

See Also:



25
26
27
28
29
30
31
# File 'lib/finance/calculations.rb', line 25

def npv(rate, values)
  npv_value = 0.0
  values.each_with_index do |current_value, pow_index|
    npv_value += current_value / (1.0 + rate) ** pow_index
  end
  npv_value
end