Keith Schacht Keith Schacht - 2 years ago 161
Ruby Question

Calculating IRR in ruby

Can anyone help me with a method that calculates the IRR of a series of stock trades?

Let's say the scenario is:

$10,000 of stock #1 purchased 1/1 and sold 1/7 for $11,000 (+10%)
$20,000 of stock #2 purchased 1/1 and sold 1/20 for $21,000 (+5%)
$15,000 of stock #3 purchased on 1/5 and sold 1/18 for $14,000 (-6.7%)

This should be helpful:

But I couldn't figure out how to adapt any of the solutions since they assume the period of each return is over a consistent period (1 year).

Answer Source

I finally found exactly what I was looking for:

gem install finance

To solve the scenario I posted originally:

include Finance
trans = []
trans << -10000, date:,1,1) )
trans << 11000, date:,1,7) )
trans << -20000, date:,1,1) )
trans << 21000, date:,1,20) )
trans << -15000, date:,1,5) )
trans << 14000, date:,1,18) )


I also found this simple method:

However, it gave me some trouble. I tried a half dozen different test cases and one of them would raise an exception that I was never able to debug. But the xirr() method in this Finance gem worked for every test case I could throw at it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download