marksweston / finance

A library for financial calculations in Ruby
https://rubygems.org/gems/finance
Other
221 stars 91 forks source link

Doesn't give proper IRR for very negative returns #33

Open akayvanfar opened 10 years ago

akayvanfar commented 10 years ago

So the gem appears to incorrectly calculate IRR (using xirr) for highly negative returns. For example, using this set of cashflows / transactions

2014-04-15 00:00:00 -0700 : -10000.0 2014-04-16 00:00:00 -0700 : -10000.0 2014-05-16 14:59:00 -0700 : 305.6 2014-06-15 23:59:59 -0700 : 9800.07 2014-06-15 23:59:59 -0700 : 5052.645

the gem gave an IRR of -107% while other tools gave an IRR of -80%. Can you guys look into this please?

Thank you.

AK

tubedude commented 10 years ago

@akayvanfar, out of curiosity, do you really have a cashflow that depends on the hour of the flow? I was thinking of replacing Time in favor of a Date. Answering your question, in my branch of Finance you indeed get a IRR of -107% with the default guess. When you add a guess of -80.0 you end up with the expected result.

      @x=[]
      @x << Transaction.new(-10000.0, :date => Time.new(2014,4,15,0,0,0))
      @x << Transaction.new(-10000.0, :date => Time.new(2014,04,16,0,0,0))
      @x << Transaction.new(305.6, :date => Time.new(2014,05,16, 14,59,0))
      @x << Transaction.new(9800.07, :date => Time.new(2014,06,15, 23, 59,59))
      @x << Transaction.new(5052.645, :date => Time.new(2014,06,15, 23, 59,59))
      @x.xirr.effective.round(6) # => -1.078485
      @x.xirr(-80.0).effective.round(6) # => -0.809965

I've made a gem called XIRR that was based on finance that runs xirr calculations in two different methods. But it accepts only dates, so the result I get there is a bit different from yours:

  @x = Cashflow.new
  @x << Transaction.new(-10000.0, :date => Date.new(2014,4,15))
  @x << Transaction.new(-10000.0, :date => Date.new(2014,04,16))
  @x << Transaction.new(305.6, :date => Date.new(2014,05,16))
  @x << Transaction.new(9800.07, :date => Date.new(2014,06,15))
  @x << Transaction.new(5052.645, :date => Date.new(2014,06,15))
  @x.xirr # => -0.815121

Let me know if that is helpful.

akayvanfar commented 10 years ago

Thanks for the response. Weird that it is so dependent on the guess. Is there reason for that?

Using 'Date' would be fine by me. I only used 'Time' since it is what the Transaction object took. Thanks you for pointing out 'XIRR' . Our data scientist, @vnavkal , will be happy to hear that.