forked from mlombera94/forecast_R-shiny
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.R
7224 lines (6152 loc) · 376 KB
/
server.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
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
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# This is the server logic of a Shiny web application. You can run the
# application by clicking 'Run App' above.
#
# Find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com/
#
library(shiny)
# Define server logic required to draw a histogram
shinyServer(function(input, output, session) {
###################################################################
###################### TIME SERIES FORECASTING ####################
###################################################################
# Load any required functions
source("functions.R", local = TRUE)
######################################### READ IN CSV FILE BASED ON SELECTION #############################################################
mySeries_raw <- reactive({
inFile <- input$i_file
if (is.null(inFile)){return(NULL)}
df <- read.csv(inFile$datapath)
# Rename columns
# df %>% setnames(old = c("SDATE", "LEVEL0", "LEVEL3", "LEVEL5", "LEVEL6", "SDATA4"),
# new = c("Date", "SKU", "Product", "Country", "Region", "Actuals"))
# Convert Date variable from chr to Date
df$Date <- as.Date(df$Date, format = "%Y-%m-%d")
# Convert any remaining character variables to factors
df[sapply(df, is.character)] <- lapply(df[sapply(df, is.character)], as.factor)
# Drop observations containing observations from regions 177899, 234601, 236273, 250900, 29437 and filter observations that exceed current date
df <- df %>%
filter(Date < as.Date(Sys.Date() %m-% months(1)),
!is.na(Region),
!is.na(Country))
df$Region <- df$Region %>%
recode(N.A = "NA")
# Recode observations
# df$Region <- df$Region %>%
# recode(CLIN = "CLIN",
# `8851` = "NA",
# `8848` = "EU",
# `8847` = "AS",
# `8846` = "AF",
# `8850` = "ME",
# `8852` = "OC",
# `8849` = "LA")
#Remove "-" and replace with "_" as the "-" causes error
df$SKU <- gsub('-', '_', df$SKU)
return(df)
})
########################################################## BUILD DATAFRAME ################################################################
# Create Select option for all regions available in the data
output$region <- renderUI({
data <- mySeries_raw()
if(is.null(data)){return(NULL)}
selectInput(inputId = "region",
label = "Select Region",
choice = sort(unique(data$Region)),
multiple = TRUE)
})
# Filter the raw data based on regions selected
region_df <- reactive({
data <- mySeries_raw()
if(is.null(data)){return(NULL)}
data %>%
filter(Region %in% input$region)
})
# Create select option for all markets available in the regions selected in previous filter
output$market <- renderUI({
data <- region_df()
if(is.null(data)){return(NULL)}
selectInput(inputId = "market",
label = "Select Country",
choice = sort(unique(data$Country)),
multiple = TRUE)
})
# Create a checkbox option to include all markets in filter
observe({
data <- region_df()
updateSelectInput(
session,
"market",
choices = sort(unique(data$Country)),
selected = if(input$all) unique(data$Country)
)
})
# Filter the previous dataset of selected regions based on markets selected
market_df <- reactive({
data <- region_df()
if(is.null(data)){return(NULL)}
data %>%
filter(Country %in% input$market)
})
# Create select option for all products available in the markets selected in previous filter
output$product <- renderUI({
data <- market_df()
if(is.null(data)){return(NULL)}
selectInput(inputId = "product",
label = "Select Product",
choice = sort(unique(data$Product)),
multiple = TRUE)
})
# Create a checkbox option to include all products in filter
observe({
data <- market_df()
updateSelectInput(
session,
"product",
choices = sort(unique(data$Product)),
selected = if(input$all2) unique(data$Product)
)
})
# Filter the previous dataset of selected markets based on products selected
product_df <- reactive({
data <- market_df()
if(is.null(data)){return(NULL)}
data %>%
filter(Product %in% input$product)
})
# Create select options for all SKUs in the products selected in previous filter
output$sku <- renderUI({
data <- product_df()
if(is.null(data)){return(NULL)}
selectInput(inputId = "sku",
label = "Select SKU",
choice = sort(unique(data$SKU)),
multiple = TRUE)
})
# Create a checkbox option to include all SKUs in filter
observe({
data <- product_df()
updateSelectInput(
session,
"sku",
choices = sort(unique(data$SKU)),
selected = if(input$all3) unique(data$SKU)
)
})
# Filter the previous dataset of selected products based on SKUs chosen and build the dataframe based on the action button "Build Dataset"
final_df <- eventReactive(input$build, {
data <- product_df()
if(is.null(data)){return(NULL)}
data <- data[, -which(names(data) %in% c("Product"))]
subset_data <- data %>%
filter(SKU %in% input$sku)
subset_data <- subset_data %>%
my.spread(key = c("Region", "Country", "SKU"), value = c("Actuals")) %>%
pad(interval = "month")
# Replace the filled in 99999.99 values with NA
subset_data[subset_data == 99999.99] <- NA
# Remove SKUs that have less than the specified # of observations
subset_data <- subset_data[, which(as.numeric(colSums(!is.na(subset_data))) >= as.numeric(input$observations))]
# # Remove SKUs that have more than the speficied # of NA observation within the last # of specified months
# subset_data <- subset_data[, which(as.numeric(colSums(tail(is.na(subset_data), n = as.numeric(input$months1)))) <= as.numeric(input$na_obs))]
# Remove SKUs that have more than the speficied # of NA observation within the last six months
subset_data <- subset_data[, which(as.numeric(colSums(tail(is.na(subset_data), n = 6))) <= as.numeric(input$na_obs))]
if (input$checkbox) {
if(ncol(subset_data) < 3) {
return(subset_data)
} else {
subset_data$Row_Total <- rowSums(subset_data[,-1], na.rm = TRUE)
}
}
return(subset_data)
})
# Render the final filtered dataset
output$subset_df <- renderDataTable(extension = c("FixedColumns", "Scroller"), options = list(deferRender = TRUE,
scrollX = TRUE,
scrollY = 1000,
scroller = TRUE,
fixedColumns = list(leftColumns = 2)),{
final_df()
})
#################################################### DYNAMIC DROP DOWN LIST FOR TASK BASED ON INPUT FILE ###############################################
observeEvent(final_df(), {
mySeries <- final_df()
updateSelectInput(session,
'i_task_select',
label = 'Select Series',
choices = names(select(mySeries, -Date)),
names(select(mySeries, -Date))[1])
#REMOVEUPDATE
updateSelectInput(session,
'i_task_select2',
label = 'Select Series',
choices = names(select(mySeries, -Date)),
names(select(mySeries, -Date))[1])
})
############################################################ REACTIVE FILTERED DATAFRAME ##############################################################
mySeries_filtered <- eventReactive(input$goButton, {
# Dependency on 'start forecasting' button being pressed
#### Input$goButton ####
if (nrow(final_df())==0)
return()
# Reset predictions for model performance
prediction_arima <- 0 # Set the vector 0 to store predicted values
prediction_arfima <- 0 # Set the vector 0 to store predicted values
prediction_croston <- 0 # Set the vector 0 to store predicted values
prediction_ets <- 0 # Set the vector 0 to store predicted values
prediction_hw_M <- 0 # Set the vector 0 to store predicted values
prediction_hw_M_D <- 0 # Set the vector 0 to store predicted values
prediction_hw_A <- 0 # Set the vector 0 to store predicted values
prediction_hw_A_D <- 0 # Set the vector 0 to store predicted values
prediction_lobf <- 0 # Set the vector 0 to store predicted values
prediction_ma <- 0 # Set the vector 0 to store predicted values
prediction_ses <- 0 # Set the vector 0 to store predicted values
prediction_tbats <- 0 # Set the vector 0 to store predicted values
j <- 1 # Sets the first index to 1 to store predicted values
k <- 1 # Sets the first index to 1 to store predicted values
l <- 1 # Sets the first index to 1 to store predicted values
m <- 1 # Sets the first index to 1 to store predicted values
n <- 1 # Sets the first index to 1 to store predicted values
o <- 1 # Sets the first index to 1 to store predicted values
p <- 1 # Sets the first index to 1 to store predicted values
q <- 1 # Sets the first index to 1 to store predicted values
r <- 1 # Sets the first index to 1 to store predicted values
s <- 1 # Sets the first index to 1 to store predicted values
t <- 1 # Sets the first index to 1 to store predicted values
u <- 1 # Sets the first index to 1 to store predicted values
# Use existing reactive structures
mySeries <- as.data.frame(final_df())
isolate({
if(input$i_task_select ==""){
task_type = select_(mySeries,
.dots = list(quote(-Date)))
task_type = names(task_type[1])
} else
{
task_type = input$i_task_select
}
forecast_n <- input$i_forecast_n
recent_months <- input$i_recent_months
})
# Build Dataframe
mySeries_filtered <- mySeries %>%
select_(.dots = list(quote(Date),
task_type))
})
#REMOVEUPDATE
mySeries_filtered2 <- eventReactive(input$stat_button, {
#### Input$stat_button ####
if (nrow(final_df())==0)
return()
# Use existing reactive structures
mySeries <- as.data.frame(final_df())
isolate({
if(input$i_task_select2 ==""){
task_type = select_(mySeries,
.dots = list(quote(-Date)))
task_type = names(task_type[1])
} else
{
task_type = input$i_task_select2
}
})
#REMOVEUPDATE
mySeries_filtered2 <- mySeries %>%
select_(.dots = list(quote(Date),
task_type))
})
########################################################## FORECAST MODELS ########################################################################
####################################
####### AUTO ARIMA DYGRAPH #######
###################################
output$p_ARIMA <- renderDygraph({
# Use existing reactive structures
mySeries <- final_df()
mySeries_ARIMA <- mySeries_filtered()
isolate({
mySeries_ARIMA <- mySeries_ARIMA %>%
filter(Date >= input$dateRange[1] &
Date <= input$dateRange[2])
})
if (nrow(mySeries_ARIMA) == 0){
stop(
showModal(modalDialog(
title = "Important message",
'Please hit "start forecasting"!',
easyClose = TRUE,
size = 's'))
)
}
# Make inputs dependent on users hitting 'start forecasting' button
isolate({
if(input$i_task_select ==""){
task_type = select_(mySeries,
.dots = list(quote(-Date)))
task_type = names(task_type[1])
} else {
task_type = input$i_task_select
}
forecast_n <- input$i_forecast_n
recent_months <- input$i_recent_months
})
# Convert to TS object with monthly frequency
myY <- xts(select_(mySeries_ARIMA,
task_type),
order.by=ymd(mySeries_ARIMA$Date))
# Set the start of the TS object until at the start of the first numeric observation
for(i in 1:nrow(myY)){
if(is.na(myY[i])){
next
} else{
myY <- myY[i:nrow(myY)]
break
}
}
# Replace any NAs that follow with 0s optionally
isolate({
if (input$checkbox2){
myY <- myY %>%
tidyr::replace_na(0)
}
})
withProgress(message = 'Generating Graph... ',
detail = 'this may take a few seconds',
value = 0.1,
min = 0,
max = 1, {
# Forecast n periods using model with 50% and 80% confidence intervals
if(nrow(myY) < 3){
return(NULL)
} else{
isolate({
TS_mySeries_ARIMA <- forecast(auto.arima(myY,
stepwise = FALSE,
approximation = TRUE),
h = forecast_n,
level = c(as.numeric(input$conf_int)))
})
# Convert elements of time series FORECAST to dataframe for plotting
forecast_ARIMA_df <- with(TS_mySeries_ARIMA,
data.frame(Mean=TS_mySeries_ARIMA$mean,
Upper=TS_mySeries_ARIMA$upper[,1],
Lower=TS_mySeries_ARIMA$lower[,1]))
# Add Date column to the forecasted values data.frame
forecast_ARIMA_df$Date <- seq(as.Date(max(mySeries_ARIMA$Date)) %m+% months(1),
by = "month",
length.out = forecast_n)
forecast_ARIMA_df <- forecast_ARIMA_df %>%
select(Date, Mean, Upper, Lower) %>%
mutate(Mean = ifelse(as.integer(Mean) < 0,
0,
as.integer(round(Mean, 2))),
Upper = ifelse(as.integer(Upper) < 0,
0,
as.integer(round(Upper, 2))),
Lower = ifelse(as.integer(Lower) < 0,
0,
as.integer(round(Lower, 2))))
# Convert xts object to ts object
y1 <- as.numeric(format(start(myY), "%Y")) # Takes the the year of the first observation
m1 <- as.numeric(format(start(myY), "%m")) # Takes the month of the first observation
y2 <- as.numeric(format(end(myY), "%Y")) # Takes the the year of the last observation
m2 <- as.numeric(format(end(myY), "%m")) # Takes the month of the last observation
tsmyY <- ts(myY, start = c(y1, m1), end = c(y2, m2), frequency = 12) # Creates a ts object
#tsmyY2 <- replace(tsmyY, tsmyY == 0, 1) # Replaces 0s in the ts with .01 to calculate MAPE later on
# Obtain the start and end date of the time series in the form of a ratio
timeProp <- tsp(tsmyY)[1] # Takes the first observation and creates a numerical representation of the date
timeProp2 <- tsp(tsmyY)[2] # Takes the last observation and creates a numerical representation of the date
# Create start and end point of holdout period
holdout_start <- nrow(myY) - (recent_months + (forecast_n - 1))
holdout_end <- nrow(myY)-forecast_n
prediction <- 0 # Set the vector 0 to store predicted values
j <- 1 # Sets the first index to 1 to store predicted values
for (i in holdout_start:holdout_end){
if(i < 2){
prediction[j] <- NA
j <- j+1
} else{
train <- window(tsmyY, end = timeProp + ((i-1)/12)) # Creates the first training dataset to use for forecasting
if(nmonths(train) < 3){
prediction[j] <- NA
j <- j+1
} else{
FC_arima <- forecast(auto.arima(train, stepwise = FALSE, approximation = TRUE) , h = forecast_n) # Creates the model and forecasts
prediction[j] <- FC_arima[[4]][[forecast_n]] #Store the predicted forecast in the vector prediction with index j
j <- j+1 # Creates another index to store the next prediction
}
}
}
# Replace negative predictions with 0
prediction <- replace(prediction, prediction < 0, 0)
arima_FC <- prediction %>% ts(start = (timeProp2 - (recent_months-1)/12), frequency = 12) # Converts the predictions into a TS object for plotting and measureing accuracy
##### CONSTRUCT DYGRAPH VISUALIZATION #####
myX <- xts(select_(mySeries_ARIMA, series = task_type),
select_(mySeries_ARIMA, quote(Date)),
order.by=ymd(mySeries_ARIMA$Date))
# Converts prediction into xts object for plotting
myPred <- xts(select_(forecast_ARIMA_df,
quote(Mean),
quote(Upper),
quote(Lower)),
order.by = ymd(forecast_ARIMA_df$Date))
# Converts previous forecasts from ts object to xts object
xts_arima <- xts(arima_FC,
order.by = as.Date(as.yearmon(time(arima_FC))))
myDy <- cbind(myX,
myPred,
xts_arima)
# Plots the dygraph
d <- dygraph(myDy[,1:5], main=paste0('ARIMA FORECAST OF: ', task_type, ' for ', forecast_n, ' Periods' )) %>%
dyAxis("x", drawGrid = FALSE) %>%
dyOptions(colors = RColorBrewer::brewer.pal(5, "Set2")) %>%
dySeries(c('Upper','Mean','Lower'), label="predicted") %>%
dySeries('xts_arima', label = "past predictions") %>%
dySeries('series') %>%
dyHighlight(highlightSeriesOpts = list(strokeWidth = 3)) %>%
dyLegend(width = 400) %>%
dyRangeSelector()
print(d)
}
})
})
####################################
####### AUTO ARFIMA DYGRAPH #######
###################################
output$p_ARFIMA <- renderDygraph({
# Use existing reactive structures
mySeries <- final_df()
mySeries_ARFIMA <- mySeries_filtered()
isolate({
mySeries_ARFIMA <- mySeries_ARFIMA %>%
filter(Date >= input$dateRange[1] &
Date <= input$dateRange[2])
})
if (nrow(mySeries_ARFIMA) == 0){
stop(
showModal(modalDialog(
title = "Important message",
'Please hit "start forecasting"!',
easyClose = TRUE,
size = 's'))
)
}
# Make inputs dependent on users hitting 'start forecasting' button
isolate({
if(input$i_task_select ==""){
task_type = select_(mySeries,
.dots = list(quote(-Date)))
task_type = names(task_type[1])
} else {
task_type = input$i_task_select
}
forecast_n <- input$i_forecast_n
recent_months <- input$i_recent_months
})
# Convert to TS object with monthly frequency
myY <- xts(select_(mySeries_ARFIMA,
task_type),
order.by=ymd(mySeries_ARFIMA$Date))
# Set the start of the TS object until at the start of the first numeric observation
for(i in 1:nrow(myY)){ # loops through each index to check for the first non-NA value
if(is.na(myY[i])){
next
} else{
myY <- myY[i:nrow(myY)] # Once the first numeric observation is found, it subsets the TS Object at this point on forward
break # Breaks the for loop once the first numeric observation is found
}
}
# Replace any NAs that follow with 0s optionally
isolate({
if (input$checkbox2){
myY <- myY %>%
tidyr::replace_na(0)
}
})
# Convert xts object to ts object
y1 <- as.numeric(format(start(myY), "%Y")) # Takes the the year of the first observation
m1 <- as.numeric(format(start(myY), "%m")) # Takes the month of the first observation
y2 <- as.numeric(format(end(myY), "%Y")) # Takes the the year of the last observation
m2 <- as.numeric(format(end(myY), "%m")) # Takes the month of the last observation
tsmyY <- ts(myY, start = c(y1, m1), end = c(y2, m2), frequency = 12) # Creates a ts object
#tsmyY2 <- replace(tsmyY, tsmyY == 0, 1) # Replaces 0s in the ts with .01 to calculate MAPE later on
withProgress(message = 'Generating Graph... ',
detail = 'this may take a few seconds',
value = 0.1,
min = 0,
max = 1, {
if(all(myY == 0, na.rm = TRUE) == TRUE){
return(NULL)
} else{
if(sum(is.na(myY)) >= 1){
return(NULL)
} else{
# Forecast n periods using model with 50% and 80% confidence intervals
isolate({
TS_mySeries_ARFIMA <- forecast(forecast::arfima(tsmyY,
drange = c(0,.5),
estim = c("mle", "ls"),
lambda = "auto"),
h = forecast_n,
level = c(as.numeric(input$conf_int)))
})
# Convert elements of time series FORECAST to dataframe for plotting
forecast_ARFIMA_df <- with(TS_mySeries_ARFIMA,
data.frame(Mean=TS_mySeries_ARFIMA$mean,
Upper=TS_mySeries_ARFIMA$upper[,1],
Lower=TS_mySeries_ARFIMA$lower[,1]))
# Add Date column to the forecasted values data.frame
forecast_ARFIMA_df$Date <- seq(as.Date(max(mySeries_ARFIMA$Date)) %m+% months(1),
by = "month",
length.out = forecast_n)
forecast_ARFIMA_df <- forecast_ARFIMA_df %>%
select(Date, Mean, Upper, Lower) %>%
mutate(Mean = ifelse(as.integer(Mean) < 0,
0,
as.integer(round(Mean, 2))),
Upper = ifelse(as.integer(Upper) < 0,
0,
as.integer(round(Upper, 2))),
Lower = ifelse(as.integer(Lower) < 0,
0,
as.integer(round(Lower, 2))))
# Obtain the start and end date of the time series in the form of a ratio
timeProp <- tsp(tsmyY)[1] # Takes the first observation and creates a numerical representation of the date
timeProp2 <- tsp(tsmyY)[2] # Takes the last observation and creates a numerical representation of the date
# Create start and end point of holdout period
holdout_start <- nrow(myY) - (recent_months + (forecast_n - 1))
holdout_end <- nrow(myY)-forecast_n
prediction <- 0 # Set the vector 0 to store predicted values
j <- 1 # Sets the first index to 1 to store predicted values
for (i in holdout_start:holdout_end){
if(i < 2){
prediction[j] <- NA
j <- j+1
} else{
train <- window(tsmyY, end = timeProp + ((i-1)/12)) # Creates the first training dataset to use for forecasting
if(nmonths(train) < 5){
prediction[j] <- NA
j <- j+1
} else{
# Creates the model and forecasts
FC_arfima <- forecast(forecast::arfima(train,
drange = c(0,.5),
estim = c("mle", "ls"),
lambda = "auto"),
h = forecast_n)
prediction[j] <- FC_arfima[[2]][[forecast_n]] #Store the predicted forecast in the vector prediction with index j
j <- j+1 # Creates another index to store the next prediction
}
}
}
# Replace negative predictions with 0
prediction <- replace(prediction, prediction < 0, 0)
arfima_FC <- prediction %>% ts(start = (timeProp2 - (recent_months-1)/12), frequency = 12) # Converts the predictions into a TS object for plotting and measureing accuracy
##### CONSTRUCT DYGRAPH VISUALIZATION #####
myX <- xts(select_(mySeries_ARFIMA, series = task_type),
select_(mySeries_ARFIMA, quote(Date)),
order.by=ymd(mySeries_ARFIMA$Date))
# Converts prediction into xts object for plotting
myPred <- xts(select_(forecast_ARFIMA_df,
quote(Mean),
quote(Upper),
quote(Lower)),
order.by = ymd(forecast_ARFIMA_df$Date))
# Converts previous forecasts from ts object to xts object
xts_arfima <- xts(arfima_FC,
order.by = as.Date(as.yearmon(time(arfima_FC))))
myDy <- cbind(myX,
myPred,
xts_arfima)
# Plots the dygraph
d <- dygraph(myDy[,1:5], main=paste0('ARFIMA FORECAST OF: ', task_type, ' for ', forecast_n, ' Periods' )) %>%
dyAxis("x", drawGrid = FALSE) %>%
dyOptions(colors = RColorBrewer::brewer.pal(5, "Set2")) %>%
dySeries(c('Upper','Mean','Lower'), label="predicted") %>%
dySeries('xts_arfima', label = "past predictions") %>%
dySeries('series') %>%
dyHighlight(highlightSeriesOpts = list(strokeWidth = 3)) %>%
dyLegend(width = 400) %>%
dyRangeSelector()
print(d)
}
}
})
})
#############################################
##### Croston Intermittent Demand Model #####
#############################################
output$p_croston <- renderDygraph({
# Use existing reactive structures
mySeries <- final_df()
mySeries_croston <- mySeries_filtered()
isolate({
mySeries_croston <- mySeries_croston %>%
filter(Date >= input$dateRange[1] &
Date <= input$dateRange[2])
})
if (nrow(mySeries_croston) == 0){
stop(
showModal(modalDialog(
title = "Important message",
'Please hit "start forecasting"!',
easyClose = TRUE,
size = 's'))
)
}
#make inputs dependent on users hitting 'start forecasting' button
isolate({
if(input$i_task_select ==""){
task_type = select_(mySeries, .dots = list(quote(-Date)))
task_type = names(task_type[1])
} else {
task_type = input$i_task_select
}
forecast_n <- input$i_forecast_n
recent_months <- input$i_recent_months
})
# Convert to TS object with monthly frequency
myY <- xts(select_(mySeries_croston, task_type),
order.by=ymd(mySeries_croston$Date))
# Set the start of the TS object until at the start of the first numeric observation
for(i in 1:nrow(myY)){ # loops through each index to check for the first non-NA value
if(is.na(myY[i])){
next
} else{
myY <- myY[i:nrow(myY)] # Once the first numeric observation is found, it subsets the TS Object at this point on forward
break # Breaks the for loop once the first numeric observation is found
}
}
# Replace any NAs that follow with 0s optionally
isolate({
if (input$checkbox2){
myY <- myY %>%
tidyr::replace_na(0)
}
})
withProgress(message = 'Generating Graph... ',
detail = 'this may take a few seconds',
value = 0.1,
min = 0,
max = 1, {
if(sum(is.na(myY)) >= 1){
return(NULL)
} else{
y1 <- as.numeric(format(start(myY), "%Y")) # Takes the the year of the first observation
m1 <- as.numeric(format(start(myY), "%m")) # Takes the month of the first observation
y2 <- as.numeric(format(end(myY), "%Y")) # Takes the the year of the last observation
m2 <- as.numeric(format(end(myY), "%m")) # Takes the month of the last observation
tsmyY <- ts(myY, start = c(y1, m1), end = c(y2, m2), frequency = 12) # Creates a ts object
# Forecast n periods using model
isolate({
forecast_croston <- forecast::croston(tsmyY,
h=forecast_n)
})
# Convert elements of time series FORECAST to dataframe for plotting
forecast_croston_df <- with(forecast_croston,
data.frame(Mean=forecast_croston$mean,
Upper=NA,
Lower=NA))
forecast_croston_df$Date <- seq(as.Date(max(mySeries_croston$Date)) %m+% months(1),
by = "month",
length.out = forecast_n)
forecast_croston_df <- forecast_croston_df %>%
select(Date, Mean, Upper, Lower) %>%
mutate(Mean = ifelse(as.integer(Mean) < 0,
0,
as.integer(round(Mean, 2)))
)
# Obtain the start and end date of the time series in the form of a ratio
timeProp <- tsp(tsmyY)[1]
timeProp2 <- tsp(tsmyY)[2]
# Create start and end point of holdout period
holdout_start <- nrow(myY) - (recent_months + (forecast_n - 1))
holdout_end <- nrow(myY)-forecast_n
prediction <- 0
j <- 1
for (i in holdout_start:holdout_end){
if(i < 2){
prediction[j] <- NA
j <- j+1
} else {
train <- window(tsmyY, end = timeProp + ((i-1)/12))
if(nmonths(train) < 3){
prediction[j] <- NA
j <- j+1
} else{
FC_croston <- forecast::croston(train,
h=forecast_n)
prediction[j] <- FC_croston[[1]][[forecast_n]]
j <- j+1
}
}
}
# Replace negative predictions with 0
prediction <- replace(prediction, prediction < 0, 0)
croston_FC <- prediction %>% ts(start = (timeProp2 - (recent_months-1)/12), frequency = 12)
##### CONSTRUCT DYGRAPH VISUALIZATION #####
myX <- xts(select_(mySeries_croston, series = task_type),
select_(mySeries_croston, quote(Date)),
order.by=ymd(mySeries_croston$Date))
myPred <- xts(select_(forecast_croston_df,
quote(Mean),
quote(Upper),
quote(Lower)),
order.by = ymd(forecast_croston_df$Date))
xts_croston <- xts(croston_FC,
order.by = as.Date(as.yearmon(time(croston_FC))))
myDy <- cbind(myX, myPred, xts_croston)
d <- dygraph(myDy[,1:5], main=paste0('Croston FORECAST of: ', task_type, ' for ', forecast_n, ' periods' )) %>%
dyAxis("x", drawGrid = FALSE) %>%
dyOptions(colors = RColorBrewer::brewer.pal(5, "Set2")) %>%
dySeries(c('Upper','Mean','Lower'), label="predicted") %>%
dySeries('xts_croston', label = "past predictions") %>%
dySeries('series') %>%
dyHighlight(highlightSeriesOpts = list(strokeWidth = 3)) %>%
dyLegend(width = 400) %>%
dyRangeSelector()
print(d)
}
})
})
######################################
##### Error Trend Seasonal Model #####
######################################
output$p_ets <- renderDygraph({
# Use existing reactive structures
mySeries <- final_df()
mySeries_ets <- mySeries_filtered()
isolate({
mySeries_ets <- mySeries_ets %>%
filter(Date >= input$dateRange[1] &
Date <= input$dateRange[2])
})
if (nrow(mySeries_ets) == 0){
stop(
showModal(modalDialog(
title = "Important message",
'Please hit "start forecasting"!',
easyClose = TRUE,
size = 's'))
)
}
#make inputs dependent on users hitting 'start forecasting' button
isolate({
if(input$i_task_select ==""){
task_type = select_(mySeries, .dots = list(quote(-Date)))
task_type = names(task_type[1])
} else {
task_type = input$i_task_select
}
forecast_n <- input$i_forecast_n
recent_months <- input$i_recent_months
})
# Convert to TS object with monthly frequency
myY <- xts(select_(mySeries_ets, task_type),
order.by=ymd(mySeries_ets$Date))
# Set the start of the TS object until at the start of the first numeric observation
for(i in 1:nrow(myY)){ # loops through each index to check for the first non-NA value
if(is.na(myY[i])){
next
} else{
myY <- myY[i:nrow(myY)] # Once the first numeric observation is found, it subsets the TS Object at this point on forward
break # Breaks the for loop once the first numeric observation is found
}
}
# Replace any NAs that follow with 0s optionally
isolate({
if (input$checkbox2){
myY <- myY %>%
tidyr::replace_na(0)
}
})
withProgress(message = 'Generating Graph... ',
detail = 'this may take a few seconds',
value = 0.1,
min = 0,
max = 1, {
if(nrow(myY) < 3){
return(NULL)
} else{
# Finds the best ets model
TS_mySeries_ets <- ets(myY,
allow.multiplicative.trend = TRUE,
opt.crit = c("lik", "amse", "mse", "sigma", "mae"))
# Forecast n periods using model
isolate({
forecast_ets <- forecast(TS_mySeries_ets,
h=forecast_n,
level = c(as.numeric(input$conf_int)))
})
# Convert elements of time series FORECAST to dataframe for plotting
forecast_ets_df <- with(forecast_ets,
data.frame(Mean=forecast_ets$mean,
Upper=forecast_ets$upper[,1],
Lower=forecast_ets$lower[,1]))
forecast_ets_df$Date <- seq(as.Date(max(mySeries_ets$Date)) %m+% months(1),
by = "month",
length.out = forecast_n)
forecast_ets_df <- forecast_ets_df %>%
select(Date, Mean, Upper, Lower) %>%
mutate(Mean = ifelse(as.integer(Mean) < 0,
0,
as.integer(round(Mean, 2))),
Upper = ifelse(as.integer(Upper) < 0,
0,
as.integer(round(Upper, 2))),
Lower = ifelse(as.integer(Lower) < 0,
0,
as.integer(round(Lower, 2))))
y1 <- as.numeric(format(start(myY), "%Y")) # Takes the the year of the first observation
m1 <- as.numeric(format(start(myY), "%m")) # Takes the month of the first observation
y2 <- as.numeric(format(end(myY), "%Y")) # Takes the the year of the last observation
m2 <- as.numeric(format(end(myY), "%m")) # Takes the month of the last observation
tsmyY <- ts(myY, start = c(y1, m1), end = c(y2, m2), frequency = 12) # Creates a ts object
# Obtain the start and end date of the time series in the form of a ratio
timeProp <- tsp(tsmyY)[1]
timeProp2 <- tsp(tsmyY)[2]
# Create start and end point of holdout period
holdout_start <- nrow(myY) - (recent_months + (forecast_n - 1))
holdout_end <- nrow(myY)-forecast_n
prediction <- 0
j <- 1
for (i in holdout_start:holdout_end){
if(i < 2){
prediction[j] <- NA
j <- j+1
} else{
train <- window(tsmyY, end = timeProp + ((i-1)/12))