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.

Saturday, January 3, 2015

A Javascript Example to Calculate Net Worth Based on Monthly Contributions

Suppose you want to calculate how much your money would grow if you started out with a large lump sum and contributed monthly.

The formula here would be:

P*(1+r)^y + sum_{n=0}^{y*12-1} M*(1+r)^(y-n/12)

where P is the original amount, r is the rate, y is the number of years and M is the monthly contribution.

<html>
<head>
<script type="text/javascript">
function calculate(original, monthly, rate, years) {
   var multiplier1 = Math.pow((1+rate),years);
   var value1 = original*multiplier1;
   var multiplier2 = 0;
   for(var i=0; i<(years*12); i++) {
      multiplier2 = multiplier2 + Math.pow((1+rate), years-i/12);
   }
   var value2 = monthly*multiplier2;
   var total = value1 + value2;
   var o = '<b>Total:</b> '+total;
   o = o + '<br>';
   o = o + '<br><b>Original:</b> '+original;
   o = o + '<br><b>Multiplier1:</b> '+multiplier1;
   o = o + '<br><b>Value1:</b> '+value1;
   o = o + '<br>';
   o = o + '<br><b>Monthly:</b> '+monthly;
   o = o + '<br><b>Multiplier2:</b> '+multiplier2;
   o = o + '<br><b>Value2:</b> '+value2;
   output(o);
   return total;
}
function output(outputVal) { // Output Function
   document.getElementById('myoutput').innerHTML = outputVal;
}
function documentReady() { // Document Ready Function
   calculate(100000, 120, .05, 5);
}
</script>
</head>
<body onload="documentReady();">
   <div id="myoutput"></div>
</body>
</html>


Output:
Total: 135798.95858737087

Original: 100000
Multiplier1: 1.2762815625000001
Value1: 127628.15625000001

Monthly: 120
Multiplier2: 68.09001947809055
Value2: 8170.802337370867

This post was reposted from http://scottizu.wordpress.com/2014/07/30/a-javascript-example-to-calculate-net-worth-based-on-monthly-contributions/, originally written on July 30th, 2014.

Binary Search Algorithm for Calculating Interest Rate

This java code gives a snippet of how to calculate the interest rate based on 11 deposits in about a year's time frame.

The rate calculated was 1.17%.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

public class SolverExample {
    static SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
    public static void main(String[] args) {
        try {
            Double currentNetWorth = 3170.14;
            Date currentDate = sdf.parse("05/30/2014");
            Map<Double, Double> yearsToPaymentsMap = new LinkedHashMap<Double, Double>();
            yearsToPaymentsMap.put(yearsBetween(sdf.parse("04/02/2013"), currentDate), 300.00);
            yearsToPaymentsMap.put(yearsBetween(sdf.parse("05/03/2013"), currentDate), 300.00);
            yearsToPaymentsMap.put(yearsBetween(sdf.parse("09/03/2013"), currentDate), 300.00);
            yearsToPaymentsMap.put(yearsBetween(sdf.parse("10/01/2013"), currentDate), 300.00);
            yearsToPaymentsMap.put(yearsBetween(sdf.parse("11/01/2013"), currentDate), 300.00);
            yearsToPaymentsMap.put(yearsBetween(sdf.parse("12/01/2013"), currentDate), 300.00);
            yearsToPaymentsMap.put(yearsBetween(sdf.parse("01/02/2014"), currentDate), 250.00);
            yearsToPaymentsMap.put(yearsBetween(sdf.parse("02/04/2014"), currentDate), 250.00);
            yearsToPaymentsMap.put(yearsBetween(sdf.parse("03/04/2014"), currentDate), 250.00);
            yearsToPaymentsMap.put(yearsBetween(sdf.parse("04/02/2014"), currentDate), 300.00);
            yearsToPaymentsMap.put(yearsBetween(sdf.parse("05/02/2014"), currentDate), 300.00);
            
            Double rate = findRateOfReturn(-1.00, 1.00, yearsToPaymentsMap, currentDate, currentNetWorth);
            
            System.out.println("Rate:"+rate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    /**
     * Uses a binary search to converge on an interest rate between two guesses: lowRate and highRate
     * @param lowRate
     * @param highRate
     * @param yearsToPaymentsMap
     * @param currentDate
     * @param currentNetWorth
     * @return
     */

    private static Double findRateOfReturn(double lowRate, double highRate, Map<Double, Double> yearsToPaymentsMap, Date currentDate, Double currentNetWorth) {
        
        while(highRate-lowRate > .0001) {
            double testRate = (lowRate + highRate)/2;
            Double calculatedNetWorth = calculateNetWorth(testRate, yearsToPaymentsMap);

            if(calculatedNetWorth < currentNetWorth) {
                lowRate = testRate;
            } else {
                highRate = testRate;
            }
        }
        
        return lowRate;
    }
    
    /**
     * Returns P1(1+r)^Y1 + P2(1+r)^Y2 + ...
     * @param interestRate - r
     * @param yearsToPaymentsMap - give Y1->P1, Y2->P2, etc
     * @return
     */

    private static double calculateNetWorth(double interestRate, Map<Double, Double> yearsToPaymentsMap) {
        double sum = 0.0;
        for(double years: yearsToPaymentsMap.keySet()) {
            double payment = yearsToPaymentsMap.get(years);
            sum = sum + payment*Math.pow((1 + interestRate), years); // P(1+r)^y
        }
        return sum;
    }

    /**
     * 1000 millisec/sec * 60 sec/min * 60 min/hr * 24 hr/day * 365 day/year = 31536000000 millisec/year 
     * @param d1
     * @param d2
     * @return
     */

    public static double yearsBetween(Date d1, Date d2){
        return (double) (d2.getTime() - d1.getTime()) / 31536000000.0;
    }
}


This post was reposted from http://scottizu.wordpress.com/2014/05/30/binary-search-algorithm-for-calculating-interest-rate/, originally written on May 30th, 2014.