Skip to content

Instantly share code, notes, and snippets.

@faizzed
Created May 23, 2021 14:58
Show Gist options
  • Save faizzed/9bf69a49b26c0b39e6c60999cf47f17a to your computer and use it in GitHub Desktop.
Save faizzed/9bf69a49b26c0b39e6c60999cf47f17a to your computer and use it in GitHub Desktop.
Investment Calculator
/**
* S&P 500 from 2010 to 2019, the average stock market return for the last 10 years is 11.805%
* This can be different for other indexes. We can make a dictionary of returns and see how others compare to it.
*
* Given a static amount or added over the years we can see how it will look like after x years.
*
* */
class InvestmentCalculator(val initial: Double, val returnPercentage: Double, val years: Int) {
/*
* One time investment and if the return wasn't reinvested
*/
fun staticAmountNonRollingReturn(): Double {
return initial + (initial * returnPercentage/100) * years
}
/*
* If the returns were re-invested on a one time investment
*/
fun staticAmountRollingReturn(): Double {
var _initial = initial
for (year in 1..years) {
_initial += (_initial * (returnPercentage / 100))
}
return _initial
}
/*
* If the returns were re-invested as well as the same amount is added each month
*/
fun staticAmountAddedRollingReturn(): Int {
var _initial = initial
for (month in 1..(years * 12)) {
val returnThisMonth = (_initial * (returnPercentage / 100))
_initial += returnThisMonth
val profit = _initial - (initial * month) // this var isnt necessary
val beforeAddingInvestment = _initial // this var isnt necessary
_initial += initial
println("Month $month; " +
"return: ${returnThisMonth.toInt()}; " +
"afterReturn: ${beforeAddingInvestment.toInt()}; " +
"afterAddingExtra: ${_initial.toInt()}; " +
"Profit: ${profit.toInt()}")
}
println("End analysis:")
val totalStaticValueAdded = initial * (years * 12)
println("Total static value added: $totalStaticValueAdded")
println("Final value over $years years investment on $returnPercentage% return: ${_initial.toInt()}")
val profitMade = _initial - totalStaticValueAdded
println("Profit made: ${profitMade.toInt()}")
return _initial.toInt()
}
}
fun main() {
InvestmentCalculator(500.0, 10.0, 10).apply {
staticAmountNonRollingReturn().also(::println)
staticAmountRollingReturn().also(::println)
staticAmountAddedRollingReturn()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment