Created
April 10, 2023 14:37
-
-
Save sgb-io/56b94de4422096cd9e3b79987bd945d6 to your computer and use it in GitHub Desktop.
Compound Interest
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| interface InvestmentPeriod { | |
| periodNumber: number; | |
| startingBalance: number; | |
| additionalInvestment: number; | |
| periodInterest: number; | |
| endingBalance: number; | |
| } | |
| interface CompoundResult { | |
| startingBalance: number; | |
| endingBalance: number; | |
| periods: InvestmentPeriod[]; | |
| } | |
| interface CompoundingInvestment { | |
| startingBalance: number; | |
| numPeriods: number; | |
| interestRate: number; | |
| additionalInvestment?: number; | |
| } | |
| // Uses plain "periods" and assumes compounding every period. | |
| // Custom compounding cadence is currently unsupported. | |
| function calculateCompoundInterest({ | |
| startingBalance, | |
| numPeriods, | |
| interestRate, | |
| additionalInvestment | |
| }: CompoundingInvestment): CompoundResult { | |
| const periods: InvestmentPeriod[] = []; | |
| let totalBalance = startingBalance; | |
| for (let i = 0; i < numPeriods; i += 1) { | |
| // 1. Calculate interest on existing balance | |
| const periodStartingBalance = totalBalance; | |
| const periodInterest = totalBalance * interestRate; | |
| const withInterest = (totalBalance += periodInterest); | |
| // 2. Calculate the new total balance | |
| if (additionalInvestment) { | |
| // If additional investment should happen at each period, add that, too | |
| totalBalance = withInterest + additionalInvestment; | |
| } else { | |
| totalBalance = withInterest; | |
| } | |
| periods.push({ | |
| periodNumber: i, | |
| periodInterest, | |
| startingBalance: periodStartingBalance, | |
| additionalInvestment: additionalInvestment || 0, | |
| endingBalance: totalBalance | |
| }); | |
| } | |
| return { | |
| startingBalance, | |
| endingBalance: totalBalance, | |
| periods | |
| }; | |
| } | |
| const result = calculateCompoundInterest({ | |
| startingBalance: 1800, | |
| interestRate: 0.01, // Daily (%) | |
| numPeriods: 30, // Days | |
| }) | |
| console.log('Investment result', result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment