Monday, January 5, 2015

An Implementation in Javascript of the Interest Rate Algorithm

This is a follow on from Binary Search Algorithm for Calculating Interest Rate.
<html>
<body>
<pre>
<script>
function log(arg) {
    document.body.innerHTML = document.body.innerHTML + arg + '\n<br>';
}
function clear() {
    document.body.innerHTML = '';
}

function parseDate(dateString) {
    var mdy = dateString.split('/')
    return new Date(mdy[2], mdy[0]-1, mdy[1]);
}

function yearsInBetweenDates(date1, date2) {
    return (date2-date1)/(1000*60*60*24*365);
}

function assignYearsInBetween(paymentArray, currentNetWorth) {
    for (var i = 0; i<paymentArray.length; i++) {
        paymentArray[i].years = yearsInBetweenDates(paymentArray[i].date, currentNetWorth.date);
    }
}

function findRateOfReturn(paymentArray, currentNetWorth, lowRate, highRate){
    assignYearsInBetween(paymentArray, currentNetWorth);
    
    while(highRate-lowRate > .0001) {
        var testRate = (lowRate + highRate)/2;
        var calculatedNetWorth = calculateNetWorth(paymentArray, testRate);
        if(calculatedNetWorth < currentNetWorth.amount) {
            lowRate = testRate;
        } else {
            highRate = testRate;
        }
    }
    return lowRate;
}

function calculateNetWorth(paymentArray, interestRate) {
    var total = 0;
    for (var i=0; i<paymentArray.length; i++) {
        var P = paymentArray[i].amount;
        var r = interestRate;
        var y = paymentArray[i].years;
        total = total + P*Math.pow((1+r), y);
    }
    return total;
}

function createTransaction(date, amount) {
    var object = new Object();
    object.date = parseDate(date);
    object.amount = amount;
    return object;
}

var currentNetWorth = createTransaction("05/30/2014", 3170.14);
var paymentArray = [];
paymentArray[0] = createTransaction("04/02/2013", 300.00);
paymentArray[1] = createTransaction("05/03/2013", 300.00);
paymentArray[2] = createTransaction("09/03/2013", 300.00);
paymentArray[3] = createTransaction("10/01/2013", 300.00);
paymentArray[4] = createTransaction("11/01/2013", 300.00);
paymentArray[5] = createTransaction("12/01/2013", 300.00);
paymentArray[6] = createTransaction("01/02/2014", 250.00);
paymentArray[7] = createTransaction("02/04/2014", 250.00);
paymentArray[8] = createTransaction("03/04/2014", 250.00);
paymentArray[9] = createTransaction("04/02/2014", 300.00);
paymentArray[10] = createTransaction("05/02/2014", 300.00);
log('Rate:'+findRateOfReturn(paymentArray, currentNetWorth, -1, 1));

</script>
</pre>
</body>
</html>
The nice thing about Javascript is that these types of functions can be calculated anywhere without the need for the whole support.

This program outputs 1.17 as the interest rate.

This post was reposted from http://scottizu.wordpress.com/2014/06/12/an-implementation-in-javascript-of-the-interest-rate-algorithm/, originally written on June 12th, 2014.

No comments:

Post a Comment