Published Feb 07, 2012
Updated Feb 07, 2012
This class calculates compounded interest on investment, saving or loan.
It allows variable compounding (reinvesting) percentage. Here's a page where you can see the class used: http://sharkinvestor.com/investment-calculator/
/* This class calculates compounded interest on investment, saving or loan.
It allows variable compounding (reinvesting) percentage
To do: add different types of loan calculations.
Will be useful for all kind of financial calculators and apps.
Here's a page where you can see the class used: http://sharkinvestor.com/investment-calculator/ */
// calculates compounded investment
// $num_periods - required, number of compounding periods (usually years or months)
// $investment - required, the initial investment amount
// $interest - required, interest in % for each period
// $reinvest_percentage - optional, now much from the return is reinvested
// $addition_per_period - optional, additional investment made in each period
// @returns array of arrays - one array for each period:
// [period, principal value, amount withdrawn so far, total return so far, total ROI]
// the results should be read as "at the end of period X"
function inv_calculate($num_periods, $investment, $interest,
if($num_periods<=0) throw new Exception("Periods should be at least 1");
if($investment<=0) throw new Exception("Investment amount should be bigger than 0");
if(!is_numeric($interest)) throw new Exception("Interest should be a number");
if(!is_numeric($reinvest_percentage)) throw new Exception("Reinvest % should be a number");
if(!is_numeric($addition_per_period)) throw new Exception("Addition should be a number");
// convert interest and reinvest_percentage to decimal numbers
// Start the calculations
// STEP 1 & 2:
// 1. When the user input specific number of periods, you just go thru them
// 2. for each period calculate: Profit = Principal (Invested amount) X (ROI / 100)
for($i = 1 ; $i < ($num_periods+1) ; $i++ )
$profit = $new_principal * $roi;
// STEP 3:
// 3. Then substract the withdrawn amount.
// This amount is: Withdrawn = Profit X (compounding percentage / 100)
$addition = $profit * $cp;
// totoal return
// total ROI
// period adddition