-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.R
394 lines (305 loc) · 17.8 KB
/
app.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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
#
# 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/
#
library(shiny)
library(DT)
library(plotly)
library(stringr)
source("stocks_new.R")
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("Portfolio Analysis Tool"),
h5("Created by Rockford Mankini and Nicolas Christou"),
a("Click for GitHub Repository", href="https://github.com/RockfordMankini/PortfolioAnalysis"),
sidebarLayout(
sidebarPanel(
tabsetPanel(type="tabs",
tabPanel("Setup",
helpText("Upload a .csv of your monthly returns. The format of the data needs
to be such that each column is a stock and each row is
a closing value, with the earliest dates being at the top of the .csv file. Sample data below:"),
downloadButton("sample_data", "Sample Data"),
br(),
br(),
fileInput("stock_data", "Upload Stock Data"),
helpText("If you want to analyze the portfolio using the single index model, upload a market index
such as the S&P 500 (in the same format as the previous data) below. Sample Index Data below:"),
downloadButton("sample_data_index", "Sample Data (S&P 500)"),
br(),
br(),
fileInput("index_data", "Upload Index Data (Optional)")),
tabPanel("Model Selection",
selectInput("method", label="Select a model",
choices=c("Historical Covariance"="historical",
"Single Index Model"="SIM",
"Constant Correlation Model" = "CC",
"Multi-Group Model" = "MGM")),
selectInput("short", "Short Sales Allowed? (Non Historical-Covariance Models Only, No Efficient Frontier Will Be Drawn)",
c("Yes" = TRUE,
"No" = FALSE))),
tabPanel("Multi-Group Model",
helpText("This requires that the uploaded stock data is formatted such that stocks
in the same industry are in adjacent columns. Breaks also must be input so that the model
can tell which stocks belong to which industry. For example, if you have 3 industries for 3 stocks
each, the breaks would be input as '3, 6, 9'."),
br(),
textInput("industry_breaks", "Breaks For Industries", "3, 6, 9")),
# tabPanel("Constant Correlation Model",
# helpText("This requires that the uploaded stock data is formatted such that stocks
# in the same industry are in adjacent columns. Breaks also must be input so that the model
# can tell which stocks belong to which industry. For example, if you have 3 industries for 3 stocks
# each, the breaks would be input as '3, 6, 9'."),
# br(),
# textInput("industry_breaks", "Breaks For Industries", "3, 6, 9")),
# tabPanel("Single Index Model",
# helpText("Upload the index in setup and decide if short sales should be allowed."),
# br(),
# selectInput("SIM_short", "Short Sales Allowed?",
# c("Yes" = TRUE,
# "No" = FALSE))),
tabPanel("Find Portfolios",
numericInput("rf", label = h3("Add Risk Free Asset"), value = .001, step=.001, min=.001),
textInput("rfName", "RF Name", "RF"),
numericInput("num", label = h3("Expected Value"), value = .01, step=.01),
actionButton("optimumPortfolio", label = "Find Optimum Portfolio"),
actionButton("portfolioFromReturn", label = "Get Portfolio From E"),
actionButton("minRiskPortfolio", label = "Get Minimum Risk Portfolio"),
br(),
br(),
actionButton("clearPortfolios", label="Clear Portfolios")),
tabPanel("Frontier Plot",
textInput("portfolioName", "Portfolio Name", "New Portfolio"),
actionButton("addPortfolio", label = "Add To Plot"),
checkboxInput("plotTopFrontier", label = "Print Frontier (Top Half)", value = TRUE),
checkboxInput("plotBottomFrontier", label = "Print Frontier (Bottom Half)", value = TRUE),
checkboxInput("plotCAL", label = "Print CAL Line", value = TRUE),
checkboxInput("plotRF", label = "Plot Risk Free Assets", value = TRUE),
checkboxInput("plotPortfolio", label = "Plot Portfolio", value = TRUE)),
tabPanel("Methodology and Notes",
helpText("This tool was made by Rockford Mankini with the help of his professor, Nicolas Christou.
The models used in this tool are covered in his course, Statistics C183/C283: Statistical Models in Finance,
at the University of California, Los Angeles."),
br(),
helpText("For drawing the efficient frontier with short sales allowed, the hyperbola method is used. For short sales not allowed,
the frontier is traced out using multiple values for the risk-free asset."),
br(),
helpText("All of the optimal portfolios are found by multiplying the inverse of the covariance matrix of the portfolio by
the average returns of each stock minus the risk-free asset.")))),
# Show a plot of the generated distribution
mainPanel(
tabsetPanel(type = "tabs",
tabPanel("Plot of Weights", plotlyOutput("portfolio_hist")),
tabPanel("Portfolio Summary", verbatimTextOutput("summary")),
tabPanel("Table of Weights", DT::dataTableOutput("portfolio_table")),
tabPanel("Stock Data", DT::dataTableOutput("stock_data")),
tabPanel("Misc. Mathematical Values:", verbatimTextOutput("portfolioVals"))
),
h2("Efficient Frontier"),
h6("(Plot Needs to be Added to Display)"),
plotlyOutput("frontier")
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
output$sample_data <- downloadHandler(
filename = function() {
paste0("sample.csv")
},
content = function(file) {
write.csv(read.csv("stonks_cut.csv"), file, fileEncoding = "UTF-8", row.names = FALSE)
}
)
output$sample_data_index <- downloadHandler(
filename = function() {
paste0("sample_index.csv")
},
content = function(file) {
write.csv(read.csv("index.csv"), file, fileEncoding = "UTF-8", row.names = FALSE)
}
)
data <- reactive({
req(input$stock_data)
read.csv(input$stock_data$datapath)
})
frontier <- reactive({
req(length(portfolio_list()) > 0)
#g <- plot_frontier(portfolio())
g <- plot_ly()
x <- list(
title = "Standard Deviation (Risk)"
)
y <- list(
title = "Expected Return"
)
g <- g %>% layout(xaxis = x, yaxis = y)
if(length(portfolio_list()) > 0) {
for(i in 1:length(portfolio_list())) {
portfolio <- portfolio_list()[[i]]
rf <- portfolio$rf
sd <- portfolio$port_var^.5
expected <- portfolio$port_return
name <- portfolio$name
# if shorts allowed, use hyperbola method
if(portfolio$shorts_allowed == TRUE) {
df <- plot_frontier(portfolio)
if(input$plotTopFrontier){
g <- g %>% add_trace(x = df$sdeff, y= df$y1, type='scatter', mode = 'lines', name=paste("Expected Returns From:", name))
}
if(input$plotBottomFrontier) {
g <- g %>% add_trace(x = df$sdeff, y= df$y2, type='scatter', mode = 'lines', name=paste("Expected Returns From:", name))
}
}
# if shorts not allowed, draw using multiple rfs
else {
df <- portfolio$df_no_shorts
g <- g %>% add_trace(x = df$risk_opt, y= df$rbar_opt, type='scatter', mode = 'lines', name=paste("Expected Returns From:", name))
}
if(input$plotPortfolio) {
g <- g %>% add_trace(x = sd, y = expected, name = name, mode = 'markers')
}
if(!is.na(rf) & rf > 0) {
name_rf <- portfolio$rf_name
if(input$plotRF) {
g <- g %>% add_trace(x = 0, y = rf, name = name_rf, mode='markers', type='scatter')
}
slope <- (rf - expected)/(0-sd)
new_x <- sd + .25
new_y <- new_x * slope + rf
if(input$plotCAL) {
g <- g %>% add_segments(x = new_x, y = new_y, xend = 0, yend = rf, name=paste("Capital Allocation Line:", name))
}
}
}
}
g %>% layout(xaxis = list(range = c(0, .2)), yaxis = list(range=c(-.2, .2)))
})
portfolio <- reactiveVal()
portfolio_list <- reactiveVal(list())
observeEvent(input$portfolioFromReturn, {
req(data())
rf <- input$rf
shorts_allowed <- as.logical(input$short)
if(input$method == "SIM" & rf > 0 & shorts_allowed) {
req(input$index_data)
index <- read.csv(input$index_data$datapath)
portfolio(build_portfolio(stocks=data(), rf=input$rf, rf_name=input$rfName, method=input$method,
name=input$portfolioName, index=index, shorts_allowed = shorts_allowed, E=input$num))
}
else if(input$method == "CC" & rf > 0 & shorts_allowed) {
portfolio(build_portfolio(stocks=data(), rf=input$rf, rf_name=input$rfName, method=input$method,
name=input$portfolioName, shorts_allowed = shorts_allowed, E=input$num))
}
else if(input$method == "historical" & rf >= 0 & shorts_allowed) {
portfolio(build_portfolio(stocks=data(), rf=input$rf, rf_name=input$rfName, method=input$method,
name=input$portfolioName, shorts_allowed = TRUE, E=input$num))
}
else if(input$method == "MGM" & rf > 0 & shorts_allowed) {
breaks <- str_split(input$industry_breaks, ",")[[1]] %>% str_trim() %>% as.numeric()
portfolio(build_portfolio(stocks=data(), rf=input$rf, rf_name=input$rfName, method=input$method,
name=input$portfolioName, shorts_allowed = TRUE, breaks=breaks, E=input$num))
}
})
observeEvent(input$minRiskPortfolio, {
req(data())
rf <- input$rf
shorts_allowed <- as.logical(input$short)
if(input$method == "SIM" & rf > 0) {
req(input$index_data)
index <- read.csv(input$index_data$datapath)
portfolio(build_portfolio(stocks=data(), rf=input$rf, rf_name=input$rfName, method=input$method,
name=input$portfolioName, index=index, shorts_allowed = shorts_allowed, min_risk = TRUE))
}
else if(input$method == "CC" & rf > 0) {
portfolio(build_portfolio(stocks=data(), rf=input$rf, rf_name=input$rfName, method=input$method,
name=input$portfolioName, shorts_allowed = shorts_allowed, min_risk = TRUE))
}
else if(input$method == "historical" & rf >= 0) {
portfolio(build_portfolio(stocks=data(), rf=input$rf, rf_name=input$rfName, method=input$method,
name=input$portfolioName, shorts_allowed = TRUE, min_risk = TRUE))
}
else if(input$method == "MGM" & rf > 0) {
breaks <- str_split(input$industry_breaks, ",")[[1]] %>% str_trim() %>% as.numeric()
portfolio(build_portfolio(stocks=data(), rf=input$rf, rf_name=input$rfName, method=input$method,
name=input$portfolioName, shorts_allowed = TRUE, breaks=breaks, min_risk = TRUE))
}
})
observeEvent(input$optimumPortfolio, {
req(data())
rf <- input$rf
shorts_allowed <- as.logical(input$short)
if(input$method == "SIM" & rf > 0) {
req(input$index_data)
index <- read.csv(input$index_data$datapath)
portfolio(build_portfolio(stocks=data(), rf=input$rf, rf_name=input$rfName, method=input$method,
name=input$portfolioName, index=index, shorts_allowed = shorts_allowed))
}
else if(input$method == "CC" & rf > 0) {
portfolio(build_portfolio(stocks=data(), rf=input$rf, rf_name=input$rfName, method=input$method,
name=input$portfolioName, shorts_allowed = shorts_allowed))
}
else if(input$method == "historical" & rf >= 0) {
portfolio(build_portfolio(stocks=data(), rf=input$rf, rf_name=input$rfName, method=input$method,
name=input$portfolioName, shorts_allowed = TRUE))
}
else if(input$method == "MGM" & rf > 0) {
breaks <- str_split(input$industry_breaks, ",")[[1]] %>% str_trim() %>% as.numeric()
portfolio(build_portfolio(stocks=data(), rf=input$rf, rf_name=input$rfName, method=input$method,
name=input$portfolioName, shorts_allowed = TRUE, breaks=breaks))
}
})
observeEvent(input$addPortfolio, {
req(portfolio())
portfolios <- length(portfolio_list())
new_portfolio_list <- portfolio_list()
new_portfolio_list[[portfolios + 1]] <- portfolio()
names(new_portfolio_list)[portfolios + 1] <- input$portfolioName
portfolio_list(new_portfolio_list)
#print(portfolio_list())
})
observeEvent(input$clearPortfolios, {
portfolio_list(list())
})
output$frontier <- renderPlotly({
frontier()
})
output$summary <- renderText({
req(portfolio())
sd <- portfolio()$port_var^.5
expected <- portfolio()$port_return
paste("Expected Return: ", expected, "\n", "Risk (Standard Deviation): ", sd, sep="")
})
output$portfolio_hist <- renderPlotly({
if(!is.null(portfolio())) {
plot_portfolio(portfolio())
}
})
output$portfolio_table <- renderDataTable({
portfolio()$weights
})
output$stock_data <- renderDataTable({
data()
})
output$portfolioVals <- renderText({
req(portfolio())
portfolio <- portfolio()
toPrint <- paste("A: ", portfolio$A, "\n",
"B: ", portfolio$B, "\n",
"C: ", portfolio$C, "\n",
"D: ", portfolio$D, "\n", sep="")
if(!is.null(portfolio$lambda_1)) {
toPrint <- paste(toPrint,
"Lambda 1: ", portfolio$lambda_1, "\n",
"Lambda 2: ", portfolio$lambda_2, "\n", sep="")
}
toPrint
})
}
# Run the application
shinyApp(ui = ui, server = server)