/ Published in: PHP
URL: 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/
Expand |
Embed | Plain Text
<?php /* 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/ */ class CompCalc { // 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, $reinvest_percentage=100, $addition_per_period=0) { // validate 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"); // convert interest and reinvest_percentage to decimal numbers $roi=$interest/100; $cp=$reinvest_percentage/100; // 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) $total_withdrawn=0; 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_withdrawn+=$withdraw; // total ROI $total_roi=($total_withdrawn/$investment)*100; $new_principal=$new_principal+$addition; // period adddition $investment+=$addition_per_period; $new_principal+=$addition_per_period; "return_for_the_period"=>$withdraw, "total_return"=>$total_withdrawn, "total_roi"=>$total_roi); $results[]=$result; } return $results; } } ?>
You need to login to post a comment.
