0
$\begingroup$

I leveraged the github code (https://gist.github.com/ghalimi/4591338) to compute IRR using Newton method. When I replicated the codes step by step in excel, I'm able to find the optimized resultRate around -0.006. However when I ran the code directly, it generated a resultRate that doesn't accomplish a 0 NPV at all. Can someone please have a look and let me know what went wrong here?

FUNCTION IRRCalc(cash_flow ARRAY<FLOAT64>, date_delta ARRAY<INT64>){
    
      var positive = false;
      var negative = false;
      for (var i = 0; i < cash_flow.length; i++) {
        //dates[i] = (i === 0) ? 0 : dates[i - 1] + 365;
        if (cash_flow[i] > 0) {positive = true};
        if (cash_flow[i] < 0) {negative = true};
      }

      if (!positive || !negative) {return null;}
    
      var guess = (typeof guess === 'undefined') ? 0.1 : guess;
      var resultRate = guess;
      
      var epsMax = 1e-4;
      var iterMax = 100000;
    
      var newRate, epsRate;
      var resultValue = 0;
      var irrResultDeriv = 0;
      var iteration = 0;
      var contLoop = true;
      do {
        
        for (var i=0; i < cash_flow.length; i++){
          resultValue  += cash_flow[i]/Math.pow((1+resultRate),date_delta[i]/365);
        }
        
        for (var j=1; j < cash_flow.length; j++){
          var frac = date_delta[j] / 365;
          irrResultDeriv -= frac * cash_flow[j]/Math.pow((1+resultRate),(frac + 1));
        }
        
        newRate = resultRate - resultValue / irrResultDeriv;
        epsRate = Math.abs(newRate - resultRate);
        resultRate = newRate;
        contLoop = (epsRate > epsMax) && (Math.abs(resultValue) > epsMax);
      } while(contLoop && (++iteration < iterMax));
    
      if(contLoop) {return null};
    
      return resultRate;
}

Raw data:

cash_flow_date date_delta cash_flow

2017-07-18 0 -32984.35400000001
2017-11-23 128 744.2457850912499
2018-04-02 258 32093.94362265

$\endgroup$
0

1 Answer 1

1
$\begingroup$

The issue comes from below two variables are defined outside of do...while...

  var resultValue = 0;
  var irrResultDeriv = 0;

These statements need to be moved to immediately after the "do {" as they provide initialization for the two "for" statements immediately following.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.