-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServer.R
More file actions
632 lines (590 loc) · 18.9 KB
/
Server.R
File metadata and controls
632 lines (590 loc) · 18.9 KB
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
## Notes on Shiny:
## 1.) ui.R is the UI for the app.
## 2.) server.R is the logic for the app
## 3.) Any time you see "input$..." it is referencing a variable inputted by the user on in the UI
## 4.) Likewise, "output$..." is preparing an output to be displayed in the UI. However, in the UI,
## it will be reffered to by a "renderSomething" function, with "outputVariableName" as an argument.
## 5.) Reactive expressions, which are used heavily in this app, automatically update when a relevant input
## variable is changed.
## Load the required packages:
library("openxlsx")
library("stats")
library("fpp")
library("portes")
library(scales)
shinyServer(function(input, output) {
##### Section 1: Data Preperation #####
##### Section 1.0: Data Intake #####
## Status report for first page
output$statusReport <- reactive({
x <- "Status: Waiting..."
if((input$doArima | input$doHolt | input$doHW | input$doCAGR) && !is.null(input$inputFile)){
x <- "Status: Analyzing... Check the \"Outputs\" tab (top of page)!"
}
x
})
## Reads in the historical data from the uploaded file
readData <- reactive({
inFile <- input$inputFile
if (is.null(inFile))
return(NULL)
data <- read.csv(inFile$datapath, header=TRUE)
data
})
## Returns the historical values to be used in forecasting
historical <- reactive({
data <- readData()
## Remove any commas and dollar signs, and convert to a number
data[,2] <- as.numeric(sub("\\,","",
sub("\\$","",data[,2])
)
)
data
})
## Creates a data frame with labels for each of the historical periods
historicalLabels <- reactive({
historical <- historical()
freq <- strtoi(input$frequency)
year <- strtoi(input$startYear)
period <- strtoi(input$startTime)
if(input$frequency == 1){
labels <- c(toString(year))
for(i in 1:(nrow(historical)-1)){
year <- year + 1
labels <- c(labels, toString(year))
}
}
else{
labels <- c(paste(toString(year), toString(period), sep="-"))
for(i in 1:(nrow(historical)-1)){
p <- (period + i) %% freq
if(p == 0){
p <- freq
label <- paste(toString(year), toString(p), sep="-")
labels <- c(labels, label)
year <- year + 1
}
else{
label <- paste(toString(year), toString(p), sep="-")
labels <- c(labels, label)
}
}
}
labels
})
## Creates a data frame with labels for each of the periods to be forecasted
forecastLabels <- reactive({
start <- historicalLabels()
start <- start[length(start)]
start <- unlist(strsplit(toString(start), "[-]"))
year <- strtoi(start[1])
freq <- strtoi(input$frequency)
labels <- c()
if(freq == 1){
for(i in 1:input$forecast_periods){
labels <- c(labels, toString(year))
year <- year + 1
}
}
else{
period <- strtoi(start[2])
if((period %% freq) == 0){
year <- year + 1
}
for(i in 1:input$forecast_periods){
p <- (period + i) %% freq
if(p == 0){
p <- freq
label <- paste(toString(year), toString(p), sep="-")
labels <- c(labels, label)
year <- year + 1
}
else{
label <- paste(toString(year), toString(p), sep="-")
labels <- c(labels, label)
}
}
}
labels
})
## Converts the historical data to a time series
tsData <- reactive({
data <- historical()
data <- data[,2]
ts <- ts(data,
start=c(input$startYear, input$startTime),
end=c(input$endYear, input$endTime),
frequency = strtoi(input$frequency)
)
ts
})
tsArima <- reactive({
data <- historical()
data <- data[,2]
ts <- ts(data, frequency=strtoi(input$frequency))
ts
})
##### Section 1.1: ARIMA #####
## Create an ARIMA model for forecasting
arimaModel <- reactive({
ts <- tsData()
if(input$arimaAuto){
fit <- auto.arima(ts)
}
else{
order <- c(strtoi(input$arimap),
strtoi(input$arimad),
strtoi(input$arimaq))
seasonal <- c(strtoi(input$arimaP),
strtoi(input$arimaD),
strtoi(input$arimaQ))
fit <- Arima(ts, order=order, seasonal=seasonal)
}
fit
})
## Get an AIC value to judge the quality of the model
output$arimaAIC <- renderText({
if(is.null(input$inputFile)){
aic <- "No file found..."
}
else if(input$doArima ){
model <- arimaModel()
aic <- AIC(model)
aic <- round(aic, 3)
}
else{
aic <- ""
}
aic
})
## Creates an ARIMA model and returns a forecast based on that model.
arimaData <- reactive({
fit <- arimaModel()
f <- forecast(fit,
h = input$forecast_periods,
level=c(strtoi(input$confidence1), strtoi(input$confidence2))
)
f
})
##### Section 1.2: Holt #####
## Use Holt's Exponential Smoothing for a forecast of the given
## number of periods
holtData <- reactive({
ts <- tsData()
## If the user wants R to estimate the smoothing parameters
if(input$holtAuto){
h <- holt(ts,
h = input$forecast_periods,
damped=input$holtDamp,
exponential= input$holtExp,
level=c(strtoi(input$confidence1), strtoi(input$confidence2))
)
}
## If the user wants custom smoothing parameters
else{
h <- holt(ts,
h = input$forecast_periods,
damped = input$holtDamp,
exponential= input$holtExp,
alpha = input$holtAlpha,
beta = input$holtBeta,
level=c(strtoi(input$confidence1), strtoi(input$confidence2))
)
}
h
})
## Get an AIC value to judge the quality of the model
output$holtAIC <- renderText({
## If no file has been uploaded:
if(is.null(input$inputFile)){
aic <- "No file found..."
}
## Display the AIC if the user selected Holt
else if(input$doHolt){
holt <- holtData()
model <- holt$model
aic <- AIC(model)
aic <- round(aic,3)
}
## Otherwise, display blank text
else{
aic <- ""
}
aic
})
##### Section 1.3: Holt-Winters #####
## Use Holt-Winters seasonal method of Exponential Smoothing
## for a forecast of the given number of periods
hwData <- reactive({
ts <- tsData()
if(input$hwseasonal == 1){
hws <- "additive"
}
else{
hws <- "multiplicative"
}
## If the user wants R to estimate the smoothing parameters
if(input$hwAuto){
hw <- hw(ts,
h = input$forecast_periods,
damped=input$hwDamp,
level=c(strtoi(input$confidence1), strtoi(input$confidence2)),
seasonal=hws,
)
}
## If the user wants custom smoothing parameters
else{
hw <- hw(ts,
h = input$forecast_periods,
damped = input$hwDamp,
alpha = input$hwAlpha,
beta = input$hwBeta,
gamma = input$hwGamma,
level=c(strtoi(input$confidence1), strtoi(input$confidence2)),
seasonal=hws,
)
}
hw
})
## Get an AIC value to judge the quality of the model
output$hwAIC <- renderText({
## If no file has been uploaded:
if(is.null(input$inputFile)){
aic <- "No file found..."
}
## Display the AIC if the user selected Holt
else if(input$doHW){
hw <- hwData()
model <- hw$model
aic <- AIC(model)
aic <- round(aic,3)
}
## Otherwise, display blank text
else{
aic <- ""
}
aic
})
##### Section 1.4: CAGR #####
## Calc the actual CAGR rate
calcCAGR <- reactive({
if(!is.null(input$inputFile)){
## Get the time series data
ts <- tsData()
## Take the first known non-zero value:
for(i in 1:length(ts)){
x <- ts[i]
if(x > 0){
first <- x
offset <- i-1
break
}
}
## This should never need to be called:
if(first <= 0){
warning("The first value in the time series may lead to an inaccurate
CAGR forecast because the first value is less than or equal to 0.")
}
## Take the last known value
last <- ts[length(ts)]
## Make sure it's not zero
if(last == 0){
warning("The last value in the time series is zero, and therefore will not yield an accurate CAGR calculation.")
}
## Calculate the CAGR:
## Compute the actual growth rate:
CAGR <- ((last/first))^(1/(length(ts)-offset))
CAGR
}
})
## Prepare the text output do display the cagr rate in the UI
output$CAGR <- renderText({
if(is.null(input$inputFile)){
cagr <- "No file found"
}
else if(input$doCAGR){
cagr <- as.numeric(calcCAGR()-1)
cagr <- paste(round(cagr*100,2), "%", sep="")
}
else{
cagr <- ""
}
cagr
})
## Project out using the CAGR
cagrData <- reactive({
if(!is.null(input$inputFile)){
## Get the time series data
ts <- tsData()
## Take the first known non-zero value:
for(i in 1:length(ts)){
x <- ts[i]
if(x > 0){
first <- x
offset <- i-1
break
}
}
## This should never need to be called:
if(first <= 0){
warning("The first value in the time series may lead to an inaccurate
CAGR forecast because the first value is less than or equal to 0.")
}
## Take the last known value
last <- ts[length(ts)]
## Make sure it's not zero
if(last == 0){
warning("The last value in the time series is zero, and therefore will not yield an accurate CAGR calculation.")
}
CAGR <- calcCAGR()
cagrData <- last
## For each period of forecasting, take the last calculated value, and grow it by the CAGR
for (p in 1:input$forecast_periods) {
n <- round(as.numeric(cagrData[length(cagrData)]*(CAGR)), 2)
cagrData <- c(cagrData, n)
cagrData
}
## Remove the first value in the list, because it was the last value of historical data
cagrData <- cagrData[2:length(cagrData)]
}
})
################# Section 2: Plots #######################
##### Section 2.1: ARIMA #####
## Prepares the plot for the Arima forecast
output$arimaPlot <- renderPlot({
## Check to see if the user want's an ARIMA plot
if(input$doArima && !is.null(input$inputFile)){
data <- arimaData()
plot(data,
xlab="Years",
ylab="Quantity"
)
}
## If they don't, return a blank plot
else{
## Returns a blank plot
plot(1, type="n", axes=F, xlab="", ylab="")
}
})
##### Section 2.2: Holt #####
## Prepares the plot for the Holt Forecast
output$holtPlot <- renderPlot({
## Check to see if the use wants a Holt plot
if(input$doHolt && !is.null(input$inputFile)){
data <- holtData()
plot(data,
xlab="Years",
ylab="Quantity"
)
}
## If they don't, return a blank plot
else{
## Returns a blank plot
plot(1, type="n", axes=F, xlab="", ylab="")
}
})
##### Section 2.3: Holt-Winters #####
## Prepares the plot for the Holt-Winters Forecast
output$hwPlot <- renderPlot({
## Check to see if the user wants a Holt-Winters plot
if(input$doHW && !is.null(input$inputFile)){
data <- hwData()
plot(data,
xlab="Years",
ylab="Quantity"
)
}
## If they don't, return a blank plot
else{
## Plots a blank plot
plot(1, type="n", axes=F, xlab="", ylab="")
}
})
#### Section 2.4: CAGR #####
## Prepares the plot for the CAGR Projections
output$cagrPlot <- renderPlot({
## Check to see if the user wants a CAGR plot
if(input$doCAGR && !is.null(input$inputFile)){
data <- cagrData()
plot(data,
## type b = both, meaning both points and lines on the plot
type='b',
## plot labels
main="Forecast From Compound Annual Growth Rate (CAGR)",
xlab="Periods",
ylab="Quantity")
}
## If they don't, return a blank plot
else{
## Plots a blank plot
plot(1, type="n", axes=F, xlab="", ylab="")
}
})
##### Section 3: Download Handler #####
##### Section 3.1: Summary Sheet #####
## Creates a summary sheet with the historical data and the expected value from
## each chosen forecasting method.
createSummarySheet <- reactive({
## Make the first column the labels for the periods
historicalLabels <- data.frame(historicalLabels())
forecastLabels <- data.frame(forecastLabels())
names(forecastLabels) <- names(historicalLabels)
col1 <- rbind(historicalLabels, forecastLabels)
## Get the historical data, and store it in a well-formatted dataframe
data <- historical()
historical <- data.frame(data[,2])
empty <- data.frame(matrix(nrow=input$forecast_periods, ncol=1))
names(empty) <- names(historical)
resultDF <- rbind(historical,empty)
## Merge with the period labels
names(col1) <- names(resultDF)
resultDF <- cbind(col1, resultDF)
colnames(resultDF) <- c("Period", "Historical")
## Get the ARIMA data, convert it to a dataframe, take the first column (the expected value),
## make sure it's not in scientific format, and round it to 2 decimal places. Append it to the
## historical data, and add the column to the accumulating dataframe.
## Then give the column an appropriate name.
if(input$doArima){
arima <- round(
as.numeric(
format(
data.frame(arimaData())[,1],
scientific=FALSE
)
),
2)
arima <- data.frame(arima)
names(arima) <- names(historical)
newCol <- rbind(historical, arima)
resultDF <- cbind(resultDF, newCol)
colnames(resultDF)[ncol(resultDF)] <- "ARIMA"
}
## Get the Holt data, convert it to a dataframe, take the first column (the expected value),
## make sure it's not in scientific format, and round it to 2 decimal places. Append it to the
## historical data, and add the column to the accumulating dataframe.
## Then give the column an appropriate name.
if(input$doHolt){
holt <- round(
as.numeric(
format(
data.frame(holtData())[,1],
scientific=FALSE
)
),
2)
holt <- data.frame(holt)
names(holt) <- names(historical)
newCol <- rbind(historical, holt)
resultDF <- cbind(resultDF, newCol)
colnames(resultDF)[ncol(resultDF)] <- "Holt"
}
## Get the Holt-Winters data, convert it to a dataframe, take the first column (the expected value),
## make sure it's not in scientific format, and round it to 2 decimal places. Append it to the
## historical data, and add the column to the accumulating dataframe.
## Then give the column an appropriate name.
if(input$doHW){
hw <- round(
as.numeric(
format(
data.frame(hwData())[,1],
scientific=FALSE
)
),
2)
hw <- data.frame(hw)
names(hw) <- names(historical)
newCol <- rbind(historical, hw)
resultDF <- cbind(resultDF, newCol)
colnames(resultDF)[ncol(resultDF)] <- "Holt-Winters"
}
## Get the CAGR data, convert it to a dataframe, take the first column (the expected value),
## make sure it's not in scientific format, and round it to 2 decimal places. Then give the column
## an appropriate name.
if(input$doCAGR){
cagr <- cagrData()
cagr <- data.frame(cagr)
names(cagr) <- names(historical)
newCol <- rbind(historical, cagr)
resultDF <- cbind(resultDF, newCol)
colnames(resultDF)[ncol(resultDF)] <- "CAGR"
}
## Create a workbook (using openxlsx) to store the data in
wb <- createWorkbook(creator="Endeavour Partners")
## Add a sheet to save the summary to
addWorksheet(wb, sheetName="Summary")
## Save the data to the sheet
writeData(wb, "Summary", resultDF)
wb
})
##### Section 3.2: Details #####
## Prepares the desired detailed data for the user to download
## For more info on how this works, look at the openxlsx package
prepareOutput <- reactive({
## Creates a new workbook with a summary table as the first sheet
wb <- createSummarySheet()
## Get the labels to bind to each dataframe
labels <- forecastLabels()
## If the user wants the ARIMA forecast,
## write that to a new sheet in the workbook
if(input$doArima){
data <- data.frame(arimaData())
data <- cbind(labels, data)
colnames(data)[1] <- "Period"
addWorksheet(wb, "ARIMA Forecast")
writeData(wb, "ARIMA Forecast", data)
}
## If the user wants the Holt forecast,
## write that to a new sheet in the workboook
if(input$doHolt){
data <- data.frame(holtData())
data <- cbind(labels, data)
colnames(data)[1] <- "Period"
addWorksheet(wb, "Holt Forecast")
writeData(wb, "Holt Forecast", data)
}
## If the user wants the Holt-Winters forecast,
## write that to a new sheet in the workbook
if(input$doHW){
data <- data.frame(hwData())
data <- cbind(labels, data)
colnames(data)[1] <- "Period"
addWorksheet(wb, "Holt-Winters Forecast")
writeData(wb, "Holt-Winters Forecast", data)
}
## If the user wants the CAGR forecast,
## write that to a new sheet in the workbook
if(input$doCAGR){
data <- data.frame(cagrData())
data <- cbind(labels, data)
colnames(data) <- c("Period", "CAGR")
addWorksheet(wb, "CAGR Projection")
writeData(wb, "CAGR Projection", data)
}
## Finally, write the historical data to a new
## sheet, for easy reference
addWorksheet(wb, "Historical Data")
writeData(wb, "Historical Data", historical())
## return the workbook
wb
})
##### Section 3.3: Download #####
## Handles downloading the data for the user when they click the
## "Download" button on the "Outputs" page
output$downloadData <- downloadHandler(
## Create the filename
filename = function() { paste(input$outputName, '.xlsx', sep='') },
## Get the content and write it to a temporary file ("file")
content = function(file){
## A temporary name
fname <- paste(input$outputName, '.xlsx', sep='')
## Get the workbook with the requested data from the function above
wb <- prepareOutput()
## Save the workbook with the temporary file name
## This saves it as an Excel workbook, which is important as the
## temporary file used in the download does not have a filetype
saveWorkbook(wb, fname)
## Essentially saves the Excel workbook to the temporary file for downloading
file.rename(fname,file)
}
)
})