Module: Finance::Cashflow
- Included in:
- Array
- Defined in:
- lib/finance/cashflows.rb
Overview
Provides methods for working with cash flows (collections of transactions)
Defined Under Namespace
Classes: Function
Instance Method Summary collapse
-
#irr ⇒ DecNum
calculate the internal rate of return for a sequence of cash flows.
- #method_missing(name, *args, &block) ⇒ Object
-
#npv(rate) ⇒ DecNum
calculate the net present value of a sequence of cash flows.
-
#xirr(iterations = 100) ⇒ Rate
calculate the internal rate of return for a sequence of cash flows with dates.
-
#xnpv(rate) ⇒ DecNum
calculate the net present value of a sequence of cash flows.
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(name, *args, &block) ⇒ Object
53 54 55 56 |
# File 'lib/finance/cashflows.rb', line 53 def method_missing(name, *args, &block) return self.inject(:+) if name.to_s == "sum" super end |
Instance Method Details
#irr ⇒ DecNum
calculate the internal rate of return for a sequence of cash flows
46 47 48 49 50 51 |
# File 'lib/finance/cashflows.rb', line 46 def irr func = Function.new(self, :npv) rate = [ func.one ] n = nlsolve( func, rate ) rate[0] end |
#npv(rate) ⇒ DecNum
calculate the net present value of a sequence of cash flows
65 66 67 68 69 70 71 72 73 74 |
# File 'lib/finance/cashflows.rb', line 65 def npv(rate) self.collect! { |entry| entry.to_d } rate, total = rate.to_d, 0.to_d self.each_with_index do |cashflow, index| total += cashflow / (1 + rate) ** index end total end |
#xirr(iterations = 100) ⇒ Rate
calculate the internal rate of return for a sequence of cash flows with dates
85 86 87 88 89 90 |
# File 'lib/finance/cashflows.rb', line 85 def xirr(iterations=100) func = Function.new(self, :xnpv) rate = [ func.one ] n = nlsolve( func, rate ) Rate.new(rate[0], :apr, :compounds => :annually) end |
#xnpv(rate) ⇒ DecNum
calculate the net present value of a sequence of cash flows
101 102 103 104 105 106 107 108 109 |
# File 'lib/finance/cashflows.rb', line 101 def xnpv(rate) rate = rate.to_d start = self[0].date self.inject(0) do |sum, t| n = t.amount / ( (1 + rate) ** ((t.date-start) / 31536000.to_d)) # 365 * 86400 sum + n end end |