-
Notifications
You must be signed in to change notification settings - Fork 0
/
Monthly Savings Calculator.R
258 lines (188 loc) · 8.74 KB
/
Monthly Savings Calculator.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
#
# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
#
# Find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com/
#
# define the user interface
library(shiny)
library(shinythemes)
library(shinyMatrix)
library(ggplot2)
library(quantmod)
library(mice)
library(plotly)
ui <- fluidPage(
theme = shinytheme("darkly"),
titlePanel("Monthly Savings Calculator"),
sidebarLayout(
sidebarPanel(
numericInput("initial_amount",
"Initial Amount",
value = 10000,
min = 0,
step = 1000),
numericInput("final_amount",
"Desired Final Amount",
value = 100000,
min = 0,
step = 10000),
numericInput("years",
"Years",
value = 5,
min = 1,
step = 1), # Changed step to 1
numericInput("probability",
"Probability of Success",
value = 0.8,
min = 0,
max = 1,
step = 0.05),
selectInput("emprical_distribution",
"Distribution from which to sample monthly Returns",
choices = c(
"Normal Distribution" = "ND",
"Portfolio Distribution" = "PD",
"Empirical Distribution" = "ED"
)),
conditionalPanel(
condition = "input.emprical_distribution == 'ED'",
fileInput("file", "Choose CSV File",
multiple = FALSE,
accept = c("text/csv",
"text/comma-separated-values,text/plain",
".csv")),
checkboxInput("header", "Header", TRUE),
radioButtons("sep", "Separator",
choices = c(Comma = ",",
Semicolon = ";",
Tab = "\t"),
selected = ","),
),
conditionalPanel(
condition = "input.emprical_distribution == 'ND'",
numericInput("mean", "Arithmetic mean monthly Return", value = 0.0071, min = 0, step = 0.0001),
numericInput("volatility", "Monthly Volatility", value = 0.0558, min = 0, step = 0.0001)
),
conditionalPanel(
condition = "input.emprical_distribution == 'PD'",
matrixInput("input_matrix", "Portfolio",
value = matrix(data = c("SPYI.F", "BTC-EUR", 0.95, 0.05), nrow = 2, ncol = 2, dimnames = list(NULL, c("Ticker", "Weight"))),
rows = list(
extend = TRUE,
names = FALSE
),
cols = list(
names = TRUE
)),
checkboxInput("imputation", "Align periods by Imputation?", FALSE)
),
numericInput("simulations", "Simulations", value = 10000, min = 1),
numericInput("seed", "Seed", value = 12345), # Provided a non-zero seed
actionButton("submit", "Calculate")
),
mainPanel(
fluidRow(wellPanel(plotOutput("histogram"))),
fluidRow(wellPanel(plotOutput("cdf"))),
fluidRow(wellPanel(textOutput("text")))
)
)
)
server <- function(input, output) {
observeEvent(input$submit, {
set.seed(input$seed)
# Number of months
months <- input$years * 12
# Matrix to store the returns
gross_returns <- matrix(nrow = months, ncol = input$simulations)
# Matrix to hold the amount of savings at each time step
amount <- matrix(nrow = months + 1, ncol = input$simulations)
amount[1, ] <- input$initial_amount
if (input$emprical_distribution == "ED") {
inFile <- input$file
if (is.null(inFile)) # Added error handling for file input
stop("Please upload a file.")
data <- read.csv(inFile$datapath,
header = input$header,
sep = input$sep)
names(data)[1] <- "Header"
gross_returns <- replicate(n = input$simulations, expr = {
sample(1 + data$Header, size = months, replace = TRUE)
})
} else if (input$emprical_distribution == "ND") {
gross_returns <- replicate(n = input$simulations, expr = {
1 + rnorm(n = months, mean = input$mean, sd = input$volatility)
})
} else {
m <- input$input_matrix[!apply(input$input_matrix == "", 1, all),]
if (is.null(dim(input$input_matrix[!apply(input$input_matrix == "", 1, all),]))) {
m <- t(as.matrix(input$input_matrix[!apply(input$input_matrix == "", 1, all),]))
} else {
}
getSymbols(m[, 1], src = "yahoo", from = "1900-01-01")
assets <- c()
for (i in 1:length(m[, 1])) {
assets[[i]] <- monthlyReturn(get(m[i, 1])[, 6], leading = FALSE)
}
return_matrix <- do.call("merge.xts", assets)
if (input$imputation == TRUE) {
return_matrix <- mice(return_matrix,
m = max(round(sum(!complete.cases(return_matrix)) / nrow(return_matrix) * 100), 1),
maxit = length(m[, 1]))
return_matrix <- complete(return_matrix)
} else {
return_matrix <- na.omit(return_matrix)
}
gross_returns <- replicate(n = input$simulations, expr = {
sample(1 + (as.matrix(return_matrix) %*% as.matrix(as.numeric(m[, 2]))), size = months, replace = TRUE)
})
}
min_savings <- 0
max_savings <- input$final_amount %/% input$years
while (min_savings < max_savings) {
savings <- (min_savings + max_savings) %/% 2
for (x in 1:months) {
amount[x+1, ] <- (savings + amount[x, ]) * gross_returns[x, ]
}
if (sum(amount[(months + 1), ] > input$final_amount) / input$simulations >= input$probability) {
max_savings <- savings
} else {
min_savings <- savings + 1
}
}
output$histogram <- renderPlot({
options(scipen = 999)
ggplot(data = data.frame(amount[(months + 1), ]), aes(x = amount[(months + 1), ])) +
geom_histogram(aes(y = after_stat(density)), bins = min(100, input$simulations), color = "black", fill = "black", alpha = 1) +
geom_density(color = "red", alpha = 1, linewidth = 1) +
geom_vline(xintercept = input$final_amount, color = "darkred", linewidth = 2) +
ggtitle("Scenario Distribution") +
labs(y = "Density", x = "Final Amount") +
theme(text = element_text(size = 18, color = "black"),
axis.text = element_text(size = 15, color = "black"),
plot.title = element_text(hjust = 0.5))
})
output$cdf <- renderPlot({
data <- data.frame(amount = amount[(months + 1), ])
ggplot(data, aes(x = amount)) +
stat_ecdf(geom = "step", color = "black", linewidth = 2) +
geom_vline(xintercept = input$final_amount, color = "darkred", linewidth = 2) +
geom_hline(yintercept = 1 - input$probability, color = "darkred", linewidth = 2) +
ggtitle("Scenario CDF") +
labs(x = "Final Amount", y = "Probability") +
theme(text = element_text(size = 18, color = "black"),
axis.text = element_text(size = 15, color = "black"),
plot.title = element_text(hjust = 0.5))
})
output$text <- renderText({
if (input$initial_amount + months * min_savings >= input$final_amount) {
return(paste("You would have to invest as least ", min_savings, " each month in your risky securities portfolio, but it would be both safer and more capital efficient to simply save ", max(round((input$final_amount-input$initial_amount) / months, 0), 1), " each month without risk."))
} else {
return(paste("You have to invest at least ", min_savings, " each month in your risky securities portfolio. If you did not invest, but simply saved without risk, you would have to save ", as.integer((input$final_amount-input$initial_amount) / months), " each month. Accordingly, investing would be more capital efficient considering the given probability."))
}
})
})
}
shinyApp(ui = ui, server = server)