How to calculate NPL (NPV) and IRR (IRR) using Javascript?

Asked

Viewed 1,846 times

2

I am with a TCC project of economic viability using PHP + Javascript, because well, I can calculate all the indicators I need, except the VPL (NPV) and the TIR (IRR), I saw a library called finance.js, but I couldn’t integrate it into my script someone can help me in this?

here is part of the code:

<script type="text/javascript">
String.prototype.formatMoney = function() {
    var v = this;
    if(v.indexOf('.') === -1) {
        v = v.replace(/([\d]+)/, "$1,00");
    }
    v = v.replace(/([\d]+)\.([\d]{1})$/, "$1,$20");
    v = v.replace(/([\d]+)\.([\d]{2})$/, "$1,$2");
    return v;
};
function id( el ){
    return document.getElementById( el );
}
function getMoney( el ){
    var money = id( el ).value.replace( ',', '.' );
    return parseFloat( money );
}
function soma()
{
    var total = getMoney('total_gaiolas')*getMoney('produtividade');
    id('producao_total').value =  String(total).formatMoney2();
}
</script>

and here, what I found to calculate what I need: https://gist.github.com/ghalimi/4597900

  • You could post along with your question what you’ve got so far?

  • ready friend, but the formatting was not good.

  • To format code, just select the code and click the button {} above the editor.

  • Thanks Chun, well the code is this, where it prints the result automatically using the input onkeyup.

1 answer

1

VPL

According to the Wikipedia formula:

Net present value

[...] is the mathematical-financial formula capable of determining the present value of future discounted payments at an appropriate interest rate, less the investment cost.

Therefore, the calculation consists of summing the values of future payments (calculated at present) and subtracting the value of the initial investment.

A possible VPL implementation in Javascript:

/*
 * Calcula o Valor Presente Líquido para
 * uma variação de período constante
 *
 * @taxa => taxa de desconto
 * @montantes => vetor com os valores com os recebimentos ou pagamentos
 * 
 */
function vpl(taxa, montantes)
{
    var ret = montantes[0];

    for (var i=1; i<montantes.length; i++)
        ret += montantes[i] / Math.pow( (1.0 + taxa), i);
    return ret;
}

TIR

According to Wikipedia:

Internal rate of return

[...] is a hypothetical discount rate that, when applied to a cash flow, makes the values of expenses, brought to present value, equal to the values of returns on investments, also brought to present value.

The IRR is the interest rate that "Zera" the NPV, ie, vpl(TIR, montantes) = 0.

For the calculation of the IRR, it is necessary to find the root of the above equation.

There are several methods to find this root:

Algorithm to find root

Below is an example that uses the Bisection (which is one of the simplest to implement):

/*
 * Calcula a Taxa Interna de Retorno (Método da Bisseção)
 *
 * @montantes => vetor com os valores
 */
function tir(montantes)
{   
    var ret = -1000000000.0;
    var juros_inicial = -1.0;
    var juros_medio = 0.0;
    var juros_final = 1.0;
    var vpl_inicial = 0.0;
    var vpl_final = 0.0;
    var vf = 0.0;
    var erro = 1e-5; // Valor mínimo que determina que a raiz foi encontrada

    // Procura um possível intervalo para a raiz
    // O looping deve terminar antes de i chegar a 100!

    for (var i=0; i<100; i++) {
        vpl_inicial = vpl(juros_inicial, montantes);
        vpl_final = vpl(juros_final, montantes);
        if (sinal(vpl_inicial) != sinal(vpl_final))
            break;
        juros_inicial -= 1.0;
        juros_final += 1.0;
    };

    // Contador que evita um looping infinito
    var count = 0;

    // Busca por Bisseção
    for (;;) {          
      var juros_medio = (juros_inicial + juros_final) / 2.0;        
      var vpl_medio = vpl(juros_medio, montantes)

      if (Math.abs(vpl_medio) <= erro) {
          // Resultado foi encontrado
          return juros_medio*100.0;
      };

      if (sinal(vpl_inicial) == sinal(vpl_medio)) {
            juros_inicial = juros_medio;
          vpl_inicial = vpl(juros_medio, montantes);          
      } else {
            juros_final = juros_medio;
          vpl_final = vpl(juros_medio, montantes);          
      };

      // Evita um possível looping infinito
      if (++count > 10000)
        throw "looping inválido";
    };

    // O algoritmo nunca deve chegar aqui.
    return ret;
};



See working on jsfiddle


Below is a link to a page that makes these (and other) calculations interactively (more didactic):

Do the Count

Browser other questions tagged

You are not signed in. Login or sign up in order to post.