blib/lib/Finance/Math/IRR.pm

filter: Statementstmt 90.5% 96 / 106 Branchbran 83.3% 35 / 42 Conditioncond 80.9% 17 / 21 MC/DCmcdc 69.2% 9 / 13 Subroutinesub 91.6% 11 / 12 Podpod 100% 1 / 1 totaltotal 86.6% 169 / 195 CC 30 SCAR 31.1
CC
30
Cov
88%
xirr
31.2
_debug
2.1
_crash
2.0
CRAP 22.5
↑ Summary
1 #################################################################
2 #
3 # Finance::Math::IRR - Calculate the internal rate of return of a cash flow
4 #
5 # $Id: IRR.pm,v 1.5 2007/07/12 12:35:46 erwan_lemonnier Exp $
6 #
7 # 061215 erwan Started implementation
8 # 061218 erwan Differentiate bugs from failures when calling secant() and brent()
9 # 061218 erwan Handle precision correctly
10 # 061218 erwan Support cashflows with only 0 amounts
11 # 070220 erwan Support when secant converges toward a non root value
12 # 070404 erwan Cleanup cashflow from transactions of amount 0
13 # 070404 erwan Error if last transaction is a positive amount. Added $DEBUG
14 # 070411 erwan Return undef when cashflow has only 1 non zero transaction
15 # 070418 erwan Update license
16 # 070711 erwan Removed the restriction requiring the last transaction to be negative
17 #
18  
19 package Finance::Math::IRR;
20  
21 5 ▶use 5.006;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 5 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
23 5 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 5 ▶use Carp qw(confess croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
25 5 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
26 5 ▶use Math::Polynom;
Subroutine BEGIN: called CC=1 SCAR=0.0
27 5 ▶use Date::Calc qw(Delta_Days);
Subroutine BEGIN: called CC=1 SCAR=0.0
28 5 ▶use Scalar::Util qw(looks_like_number);
Subroutine BEGIN: called CC=1 SCAR=0.0
29 5 ▶use base qw(Exporter);
Subroutine BEGIN: called CC=1 SCAR=0.0
30  
31 5 our @EXPORT = qw(xirr);
32 5 our $VERSION = '0.10';
33 5 our $DEBUG = 0;
34  
35 #----------------------------------------------------------------
36 #
37 # parameters for secant and brent methods
38 #
39  
40 5 my %ARGS_SECANT = ( p0 => 0.5,
41 p1 => 1,
42 max_depth => 100,
43 );
44  
45 5 my %ARGS_BRENT = ( max_depth => 50 );
46  
47 # how many couple of points to search for positive and negative values
48 5 my $MAX_POS_NEG_POINTS = 1024;
49  
50 #----------------------------------------------------------------
51 #
52 # _crash - die with a usable error description
53 #
54  
55 0 ▶sub _crash {
Subroutine _crash: not called CC=1 SCAR=6.9
56 0 my($method,$poly,$args,$err) = @_;
57  
58 0 croak "BUG: something went wrong while calling Math::Polynom::$method with the arguments:\n".
59 Dumper($args)."on the polynomial:\n".
60 Dumper($poly)."the error was: [$err]\n".
61 "Please email all this output to erwan\@cpan.org\n";
62 }
63  
64 #----------------------------------------------------------------
65 #
66 # _debug
67 #
68  
69 386 ▶sub _debug {
Subroutine _debug: called CC=2 SCAR=7.2
70 386 my $msg = shift;
71 386 ▶ print STDOUT "Finance::Math::IRR: $msg\n" if ($DEBUG);
Branch: 1 branch
BranchTrueFalseTotal
if $Finance::Math::IRR::DEBUG 0 386 386
72 }
73  
74 #----------------------------------------------------------------
75 #
76 # xirr - calculate the internal rate of return of a cash flow
77 #
78  
79 195 ▶sub xirr {
Subroutine xirr: called CC=29 SCAR=34.4
Pod documented
80 195 my $precision = 0.001; # default precision seeked on irr, ie 0.1%
81 195 my $guess = 0.1;
82 195 my %cashflow;
83 my $root;
84  
85 #
86 # Parse input arguments and build the cashflow's polynomial
87 #
88  
89 195 ▶ croak("ERROR: xirr() got an odd number of arguments. this can not be correct") if (!scalar(@_) || scalar(@_) % 2);
Branch: 1 branch
BranchTrueFalseTotal
if not scalar @_ or scalar(@_) % 2 2 193 195
Condition100%3/3
not scalar @_ or scalar(@_) % 2
l!l&&r!l&&!r
11193
MC/DC100%2/2
not scalar @_ or scalar(@_) % 2
not scalar @_ scalar(@_) % 2
Truth table100%3/3
not(A) or B
A= not scalar @_B= scalar(@_) % 2
ABresult
1X1
011
000
90  
91 193 %cashflow = @_;
92  
93 193 _debug("xirr() called with arguments:\n".Dumper(\%cashflow));
94  
95 # parse arguments
96 193 ▶ if (exists $cashflow{precision}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $cashflow{"precision"}) 192 1 193
97 192 $precision = $cashflow{precision};
98 192 delete $cashflow{precision};
99 }
100  
101 193 ▶ if (!defined $precision || !looks_like_number($precision)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $precision and &looks_like_number($precision)) 1 192 193
Condition66%2/3
defined $precision and &looks_like_number($precision)
!ll&&!rl&&r
10192
MC/DC50%1/2
defined $precision and &looks_like_number($precision)
defined $precision &looks_like_number($precision)
Truth table66%2/3
A and B
A= defined $precisionB= &looks_like_number($precision)
ABresult
0X0
100
111
102 1 croak "ERROR: precision is not a valid number";
103 }
104  
105 # remove intermediary transactions with 0 amount from cashflow
106 192 my @sorted_dates = sort keys %cashflow;
107 192 ▶ croak "ERROR: you provided an empty cash flow" if (scalar @sorted_dates == 0);
Branch: 1 branch
BranchTrueFalseTotal
if scalar @sorted_dates == 0 1 191 192
108  
109 191 my $date_end = $sorted_dates[-1];
110  
111 191 foreach my $date (@sorted_dates) {
112 11576 my $amount = $cashflow{$date};
113 11576 ▶ croak "ERROR: the provided cashflow contains undefined values" if (!defined $date || !defined $amount);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $date and defined $amount 1 11575 11576
Condition66%2/3
defined $date and defined $amount
!ll&&!rl&&r
0111575
MC/DC50%1/2
defined $date and defined $amount
defined $date defined $amount
Truth table66%2/3
A and B
A= defined $dateB= defined $amount
ABresult
0X0
100
111
114 11575 ▶ croak "ERROR: invalid date in the provided cashflow [$date]" if ($date !~ /^\d\d\d\d-\d\d-\d\d$/);
Branch: 1 branch
BranchTrueFalseTotal
unless $date =~ /^\d\d\d\d-\d\d-\d\d$/ 1 11574 11575
115 11574 ▶ croak "ERROR: invalid amount in the provided cashflow at date [$date]" if (!looks_like_number($amount));
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number($amount) 1 11573 11574
116  
117 # remove transaction from cashflow if it has a 0 amount
118 11573 ▶ if ($amount == 0 && $date ne $date_end) {
Branch: 1 branch
BranchTrueFalseTotal
if ($amount == 0 and $date ne $date_end) 19 11554 11573
Condition100%3/3
$amount == 0 and $date ne $date_end
!ll&&!rl&&r
11550419
MC/DC100%2/2
$amount == 0 and $date ne $date_end
$amount == 0 $date ne $date_end
Truth table100%3/3
A and B
A= $amount == 0B= $date ne $date_end
ABresult
0X0
100
111
119 19 delete $cashflow{$date};
120 }
121 }
122  
123 188 ▶ if ($cashflow{$date_end} == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cashflow{$date_end} == 0) 4 184 188
124 # the last value is 0: we may be able to handle it
125 # was the whole cashflow made of transactions with amount 0?
126 4 ▶ if (scalar keys %cashflow == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %cashflow == 1) 3 1 4
127 3 _debug("all transactions in the cashflow have 0 in amount. IRR=0.");
128 3 return 0;
129 }
130 }
131  
132 185 ▶ if (scalar keys %cashflow < 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %cashflow < 2) 1 184 185
133 # we got a cashflow with only 1 entry and can't calculate an irr on it
134 1 return undef;
135 }
136  
137 # TODO: what if all transactions have the same sign?
138  
139 # we want $precision on the irr, but can only steer the precision of 1/(1+irr), hence this ratio, that
140 # should insure us the given precision even on the irr for irrs up to 1000%
141 184 $precision = $precision / 1000;
142  
143 # build the polynomial whose solution is x=1/(1+IRR)
144 184 @sorted_dates = sort keys %cashflow;
145 184 my @date_start = split(/-/,$sorted_dates[0]);
146 184 ▶ croak "BUG: expected 3 arguments after splitting [".$sorted_dates[0]."]" if (scalar @date_start != 3);
Branch: 1 branch
BranchTrueFalseTotal
if scalar @date_start != 3 0 184 184
147  
148 184 my %coeffs;
149  
150 184 ▶ while (my($date,$amount) = each %cashflow) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %cashflow) 11550 184 11734
151 11550 my $ddays = Delta_Days(@date_start, split(/-/,$date));
152 11550 $coeffs{$ddays/365} = $amount;
153 }
154  
155 184 my $poly = Math::Polynom->new(%coeffs);
156  
157 #
158 # Find a real root of the polynomial
159 #
160  
161 184 $ARGS_SECANT{precision} = $precision;
162  
163 _debug("trying secant method on interval [".$ARGS_SECANT{p0}."-".$ARGS_SECANT{p1}."] with precision ".
164 184 $ARGS_SECANT{precision}." and max ".$ARGS_SECANT{max_depth}." iterations");
165  
166 # try finding the IRR with the secant metho
167 184 eval {
168 184 $root = $poly->secant(%ARGS_SECANT);
169 };
170  
171 184 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 3 181 184
172 # secant failed. let's make sure it was not a bug
173 3 my $error = $poly->error;
174 3 ▶ if ( grep( /^$error$/,
Branch: 1 branch
BranchTrueFalseTotal
if (grep /^$error$/, 1, 4, 2, 6) { } 3 0 3
175 Math::Polynom::ERROR_NAN,
176 Math::Polynom::ERROR_DIVIDE_BY_ZERO,
177 Math::Polynom::ERROR_MAX_DEPTH,
178 Math::Polynom::ERROR_NOT_A_ROOT ) ) {
179 3 _debug("secant failed on with error code $error");
180 } else {
181 # ok, the method did not fail, something else did
182 0 _crash("secant", $poly, \%ARGS_SECANT, $@);
183 }
184  
185 # let's find two points where the polynomial is positive respectively negative
186 3 my $i = 1;
187 3 ▶ while ( (!defined $poly->xneg || !defined $poly->xpos) && $i <= $MAX_POS_NEG_POINTS ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $poly->xneg && defined $poly->xpos and $i <= $MAX_POS_NEG_POINTS) 1026 3 1029
Condition83%5/6
not defined $poly->xneg && defined $poly->xpos and $i <= $MAX_POS_NEG_POINTS
!ll&&!rl&&r
211026
defined $poly->xneg && defined $poly->xpos
!ll&&!rl&&r
102702
MC/DC66%2/3
not defined $poly->xneg && defined $poly->xpos and $i <= $MAX_POS_NEG_POINTS
defined $poly->xneg defined $poly->xpos $i <= $MAX_POS_NEG_POINTS
Truth table60%3/5
not(A && B) and C
A= defined $poly->xnegB= defined $poly->xposC= $i <= $MAX_POS_NEG_POINTS
ABCresult
11X0
0X00
1000
0X11
1011
188 1026 $poly->eval( $i );
189 1026 $poly->eval( -1+10/($i+9) );
190 1026 $i++;
191 }
192  
193 # if we did not find 2 points where the polynomial is >0 and <0, we can't use Brent's method (nor the bisection)
194 3 ▶ if ( !defined $poly->xneg || !defined $poly->xpos ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $poly->xneg and defined $poly->xpos) 1 2 3
Condition66%2/3
defined $poly->xneg and defined $poly->xpos
!ll&&!rl&&r
102
MC/DC50%1/2
defined $poly->xneg and defined $poly->xpos
defined $poly->xneg defined $poly->xpos
Truth table66%2/3
A and B
A= defined $poly->xnegB= defined $poly->xpos
ABresult
0X0
100
111
195 1 _debug("failed to find an interval on which polynomial is >0 and <0 at the boundaries");
196 1 return undef;
197 }
198  
199 # try finding the IRR with Brent's method
200 2 $ARGS_BRENT{precision} = $precision;
201 2 $ARGS_BRENT{a} = $poly->xneg;
202 2 $ARGS_BRENT{b} = $poly->xpos;
203  
204 _debug("trying Brent's method on interval [".$ARGS_BRENT{a}."-".$ARGS_BRENT{b}."] with precision ".
205 2 $ARGS_BRENT{precision}." and max ".$ARGS_BRENT{max_depth}." iterations");
206  
207 2 eval {
208 2 $root = $poly->brent(%ARGS_BRENT);
209 };
210  
211 2 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 2 2
212 # Brent's method failed
213 0 $error = $poly->error;
214 0 ▶ if ( grep( /^$error$/,
Branch: 1 branch
BranchTrueFalseTotal
if (grep /^$error$/, 1, 2, 6) { } 0 0 0
215 Math::Polynom::ERROR_NAN,
216 Math::Polynom::ERROR_MAX_DEPTH,
217 Math::Polynom::ERROR_NOT_A_ROOT )) {
218 # Brent's method was unable to approximate the root
219 0 _debug("brent failed with error code: $error");
220 0 return undef;
221 } else {
222 # looks like a bug, either in Math::Polynom's implementation of Brent of in the arguments we sent to it
223 0 _crash("brent", $poly, \%ARGS_BRENT, $@);
224 }
225 }
226 }
227  
228 183 ▶ if ($root == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($root == 0) 0 183 183
229 # that would mean IRR = infinity, which is kind of not plausible
230 0 _debug("got 0 as the root, meaning infinite IRR. impossible.");
231 0 return undef;
232 }
233  
234 # TODO: verify IRR against cashflow
235 # TODO: is the IRR impossibly large?
236 # TODO: try secant with other intervals
237 # TODO: calculate the number of real roots of the polynomial, find them all and choose the most relevant? or die if more than 1?
238  
239 183 return -1 + 1/$root;
240 }
241  
242 5 1;
243  
244 __END__
↑ Summary