Last active
May 28, 2018 17:43
-
-
Save Torvaney/4394e99cb185ed58ccefe57a5afdbbe7 to your computer and use it in GitHub Desktop.
Notebook exploring compound interest
This file contains 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
--- | |
title: "Compound interest calculator" | |
--- | |
Terms are defined as: | |
* Principal - Initial amount invested | |
* Contribution - How much is contributed in each period | |
* Interest - Interest rate | |
* Period - How frequently interest is compounded | |
```{r} | |
suppressPackageStartupMessages(library(tidyverse)) | |
suppressPackageStartupMessages(library(lubridate)) | |
input <- list( | |
principal = 0.00, | |
contribution = 250.00, | |
interest = 0.02, | |
period = "month", | |
from = as_date("2019-01-01"), | |
until = as_date("2019-01-01") + years(10) | |
) | |
``` | |
# Do the calculation | |
See www.thecalculatorsite.com/articles/finance/compound-interest-formula.php?page=2 | |
```{r} | |
compound_principal <- function(principal, rate, p, time) { | |
t <- time_length(time, "years") | |
n <- years(1) / period(p) | |
principal * (1 + rate/n)^(n*t) | |
} | |
future_value <- function(contribution, rate, p, time) { | |
t <- time_length(time, "years") | |
n <- years(1) / period(p) | |
contribution * (((1 + rate/n)^(n * t) - 1) / (rate/n)) * (1 + rate/n) | |
} | |
calc_balance <- function(principal, contribution, rate, p, time) { | |
principal_value <- compound_principal(principal, rate, p, time) | |
contrbution_value <- future_value(contribution, rate, p, time) | |
principal_value + contrbution_value | |
} | |
project_balance <- function(input) { | |
compounded_balance <- | |
tibble(!!!input, | |
date = seq(input$from, input$until, by = "1 month")) %>% | |
mutate(amount = calc_balance( | |
input$principal, | |
input$contribution, | |
input$interest, | |
input$period, | |
date - input$from | |
)) | |
compounded_balance | |
} | |
``` | |
What about for various different scenarios... | |
```{r} | |
parameter <- "interest" | |
values <- c(0.0125, 0.02, 0.05) | |
values %>% | |
map(~ magrittr::inset(input, parameter, .x)) %>% | |
map_dfr(project_balance) %>% | |
mutate(parameter := pull(., !!parameter)) %>% | |
ggplot(aes(x = date, y = amount)) + | |
geom_path() + | |
geom_hline(yintercept = 0, colour = "dimgray") + | |
scale_y_continuous(labels = scales::dollar_format(prefix = "£")) + | |
expand_limits(y = 0) + | |
theme_minimal() + | |
labs(title = "Savings balance", | |
subtitle = str_glue("Starting with £{input$principal}, ", | |
"contributing £{input$contribution} per ", | |
"{input$period}"), | |
x = NULL, | |
y = NULL) + | |
facet_wrap(~ parameter) | |
``` | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment