-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.R
2012 lines (1564 loc) · 59.4 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
# shinyHome
# Real Estate Analytics and Forecasting
# John James
# Date: June 27, 2016
# server.R
#===============================================================================
# SHINYSERVER #
#===============================================================================
shinyServer(function(input, output, session) {
#===============================================================================
# DASHBOARD SERVER FUNCTIONS #
#===============================================================================
# Render National Home Value Index Box
output$usViBox <- renderValueBox({
current <- currentState[ which(currentState$State == "United States"), ]
valueBox(
paste0("$", current$Value), paste(current$State, " Median Home Value "),
icon = icon("dollar"), color = "green"
)
})
# Highest Home Value Index by City Box
output$highestViBox <- renderValueBox({
current <- currentCity[ which.max(currentCity$Value), ]
valueBox(
paste0("$", current$Value), paste("Highest Median Home Value in ", current$location),
icon = icon("money"), color = "blue"
)
})
# Render Annual Price Growth Box
output$usAnnualBox <- renderValueBox({
current <- currentState[ which(currentState$State == "United States"), ]
valueBox(
paste0(round(current$Annual * 100,4), "%"), paste(current$State,
" Annual Change in Home Values"), icon = icon("bar-chart"), color = "red"
)
})
# Render Highest Annual Price Growth Box
output$highestAnnualBox <- renderValueBox({
current <- currentCity[ which.max(currentCity$Annual), ]
valueBox(
paste0(round(current$Annual * 100,4), "%"), paste("Highest Annual Change in Home Values in ", current$location),
icon = icon("line-chart"), color = "purple"
)
})
# Render number of states box
output$numStatesBox <- renderValueBox({
valueBox(
paste0(nrow(currentState)), paste("States"),
icon = icon("map-marker"), color = "green"
)
})
# Render number of counties box
output$numCountiesBox <- renderValueBox({
valueBox(
paste0(nrow(currentCounty)), paste("Counties"),
icon = icon("map"), color = "yellow"
)
})
# Render number of cities box
output$numCitiesBox <- renderValueBox({
valueBox(
paste0(nrow(currentCity)), paste("Cities"),
icon = icon("map-pin"), color = "red"
)
})
# Render number of cities box
output$numZipsBox <- renderValueBox({
valueBox(
paste0(nrow(currentZip)), paste("Zipcodes"),
icon = icon("map-o"), color = "navy"
)
})
# Render Top 10 States bar chart
output$top10StatesBar <- renderChart({
current <- currentState[ which(currentState$State != "United States"), ]
current <- arrange(current, desc(Annual))
current$Annual <- round(current$Annual * 100,2)
current <- subset(current[1:10,], select = c(location, Annual))
p <- nPlot(Annual~location, data = current, type = "discreteBarChart", dom = "top10StatesBar")
p$params$width <- 1000
p$params$height <- 200
p$xAxis(staggerLabels = TRUE)
p$yAxis(axisLabel = "Annual Growth (%)", width = 50)
return(p)
})
# Render Top 10 Cities bar chart
output$top10CitiesBar <- renderChart({
current <- currentCity
current <- arrange(current, desc(Annual))
current$Annual <- round(current$Annual * 100,2)
current <- subset(current[1:10,], select = c(location, Annual))
p <- nPlot(Annual~location, data = current, type = "discreteBarChart", dom = "top10CitiesBar")
p$params$width <- 1000
p$params$height <- 200
p$xAxis(staggerLabels = TRUE)
p$yAxis(axisLabel = "Annual Growth (%)", width = 50)
return(p)
})
# Render Top 10 States by Home Value Growth TimeSeries
output$top10StatesTS <- renderChart({
#Get Current Data
current <- currentState[ which(currentState$State != "United States"), ]
current <- arrange(current, desc(Annual))
current <- data.frame(current[1:10,3])
colnames(current) <- "State"
#Get Historical Data
stateDF <- hviAllState
stateDF <- merge(current, stateDF, by = "State")
stateDF <- subset(stateDF, select = c(State, X2000.01:X2015.12))
stateDF <- t(stateDF)
colnames(stateDF) <- stateDF[1,]
stateDF <- stateDF[-1,]
#Format for Plotting
timePeriod <- seq.Date(as.Date('2000/1/1'), by = "month", length.out = 192)
stateDF <- data.frame("Time" = timePeriod, stateDF)
stateDF <- melt(stateDF, id = "Time")
names(stateDF) <- c("Time", "State", "Value")
# Plot Forecast
p <- nPlot(Value ~ Time, group = "State", type = "lineChart", data = stateDF, dom = "top10StatesTS", height = 400, width = 680)
p$xAxis(
tickFormat =
"#!
function(d){
f = d3.time.format.utc('%Y-%m-%d');
return f(new Date( d*24*60*60*1000 ));
}
!#"
)
p$yAxis(tickFormat = "#! function(d) {return d3.format(',.0f')(d)} !#")
return(p)
})
#Render Top 10 Cities by Home Value Growth TimeSeries
output$top10CitiesTS <- renderChart({
#Get Current Data
current <- currentCity
current <- arrange(current, desc(Annual))
current <- data.frame(current[1:10,])
current <- subset(current, select = location)
#Get Historical Data
cityDF <- hviAllCity
cityDF$location <- paste0(cityDF$City, ", ", cityDF$State)
cityDF <- merge(current, cityDF, by = "location")
cityDF <- subset(cityDF, select = c(location, X2000.01:X2015.12))
cityDF <- t(cityDF)
colnames(cityDF) <- cityDF[1,]
cityDF <- cityDF[-1,]
#Format for Plotting
timePeriod <- seq.Date(as.Date('2000/1/1'), by = "month", length.out = 192)
cityDF <- data.frame("Time" = timePeriod, cityDF)
cityDF <- melt(cityDF, id = "Time")
names(cityDF) <- c("Time", "City", "Value")
# Plot Forecast
p <- nPlot(Value ~ Time, group = "City", type = "lineChart", data = cityDF, dom = "top10CitiesTS", height = 400, width = 680)
p$xAxis(
tickFormat =
"#!
function(d){
f = d3.time.format.utc('%Y-%m-%d');
return f(new Date( d*24*60*60*1000 ));
}
!#"
)
p$yAxis(tickFormat = "#! function(d) {return d3.format(',.0f')(d)} !#")
return(p)
})
#===============================================================================
# MARKET EXPLORER FUNCTIONS #
#===============================================================================
# Level of Analysis UI
output$levelQueryUi <- renderUI({
radioButtons("analysisLevel", label = "Level of Analysis",
choices = list("State" = 1, "County" = 2, "City" = 3, "Zip" = 4),
selected = 3)
})
# State query UI
output$stateQuery2Ui <- renderUI({
states <- sort(unique(geo$StateName))
selectInput("state2", label = "State:", choices = c(Choose='', as.character(states)), selected = dflt$state, selectize = FALSE)
})
# State query UI
output$stateQuery3Ui <- renderUI({
states <- sort(unique(geo$StateName))
selectInput("state3", label = "State:", choices = c(Choose='', as.character(states)), selected = dflt$state, selectize = FALSE)
})
# State query UI
output$stateQuery4Ui <- renderUI({
states <- sort(unique(geo$StateName))
selectInput("state4", label = "State:", choices = c(Choose='', as.character(states)), selected = dflt$state, selectize = FALSE)
})
# County Query UI
output$countyQuery3Ui <- renderUI({
if (!is.null(input$state3)) {
if (input$state3 != "") {
state <- input$state3
} else {
state <- dflt$state
}
} else {
state <- dflt$state
}
counties <- arrange(unique(subset(geo, StateName == state, select = County)), County)
selectInput("county3", label = "County:", choices = c(Choose='', as.character(counties$County)), selected = dflt$county, selectize = FALSE)
})
# County Query UI
output$countyQuery4Ui <- renderUI({
if (!is.null(input$state4)) {
if (input$state4 != "") {
state <- input$state4
} else {
state <- dflt$state
}
} else {
state <- dflt$state
}
counties <- arrange(unique(subset(geo, StateName == state, select = County)), County)
selectInput("county4", label = "County:", choices = c(Choose='', as.character(counties$County)), selected = dflt$county, selectize = FALSE)
})
output$cityQuery4Ui <- renderUI({
cities <- NULL
if (!is.null(input$state4)) {
if (input$state4 != "") {
if (!is.null(input$county4)) {
if (input$county4 != "") {
cities <- arrange(unique(subset(geo, StateName == input$state4 & County == input$county4, select = City)), City)
} else {
cities <- arrange(unique(subset(geo, StateName == input$state4, select = City)), City)
}
} else {
cities <- arrange(unique(subset(geo, StateName == input$state4, select = City)), City)
}
}
}
selectInput("city4", label = "City:", choices = c(Choose='', as.character(cities$City)), selected = dflt$city, selectize = FALSE)
})
# Get and screen data based upon home value and growth rates
screenData <- function() {
# Get Deta
d <- switch(input$analysisLevel,
"1" = currentState,
"2" = currentCounty,
"3" = currentCity,
"4" = currentZip
)
# Screen based upon home value index
minValue <- as.numeric(input$hviQuery[1]) * 1000
if (input$maxValue == TRUE) {
maxValue <- dflt$maxValue
} else {
maxValue <- as.numeric(input$hviQuery[2]) * 1000
}
d <- subset(d, Value >= minValue & Value <= maxValue)
# Screen based upon growth variable
minGrowth <- as.numeric(input$minGrowth) / 100
horizon <- input$horizon
if (horizon == "5 Year") {
horizon <- "Five"
} else if (horizon == "10 Year") {
horizon <- "Ten"
}
d <- switch(horizon,
Monthly = d[ which(d$Monthly >= minGrowth),],
Quarterly = d[ which(d$Quarterly >= minGrowth),],
Annual = d[ which(d$Annual >= minGrowth),],
Five = d[ which(d$Five_Year >= minGrowth),],
Ten = d[ which(d$Ten_Year >= minGrowth),])
return(d)
}
# Get Data for State level of analysis
getStateData <- function() {
# Get data screened by value and growth rates
d <- screenData()
# Format growth record
horizon <- input$horizon
if (horizon == "5 Year") {
horizon <- "Five"
} else if (horizon == "10 Year") {
horizon <- "Ten"
}
d <- switch(horizon,
Monthly = select(d, State, Value, Monthly, location),
Quarterly = select(d, State, Value, Quarterly, location),
Annual = select(d, State, Value, Annual, location),
Five = select(d, State, Value, Five_Year, location),
Ten = select(d, State, Value, Ten_Year, location))
return(d)
}
# Get Data for County level of analysis
getCountyData <- function() {
# Get data screened by value and growth rates
d <- screenData()
# Filter based upon state
if (!is.null(input$state2) & (input$state2 != "")) {
d <- d[ which(d$StateName == input$state2),]
}
# Format growth record
horizon <- input$horizon
if (horizon == "5 Year") {
horizon <- "Five"
} else if (horizon == "10 Year") {
horizon <- "Ten"
}
d <- switch(horizon,
Monthly = select(d, StateName, County, Value, Monthly, location),
Quarterly = select(d, StateName, County, Value, Quarterly, location),
Annual = select(d, StateName, County, Value, Annual, location),
Five = select(d, StateName, County, Value, Five_Year, location),
Ten = select(d, StateName, County, Value, Ten_Year))
return(d)
}
# Get Data for City level of analysis
getCityData <- function() {
# Get data screened by value and growth rates
d <- screenData()
# Filter based upon state and county entered
if (!is.null(input$county3) & (input$county3 != "")) {
d <- d[ which(d$County == input$county3),]
} else if (!is.null(input$state3) & (input$state3 != "")) {
d <- d[ which(d$StateName == input$state3),]
}
# Format growth record
horizon <- input$horizon
if (horizon == "5 Year") {
horizon <- "Five"
} else if (horizon == "10 Year") {
horizon <- "Ten"
}
d <- switch(horizon,
Monthly = select(d, StateName, County, City, Value, Monthly, location),
Quarterly = select(d, StateName, County, City, Value, Quarterly, location),
Annual = select(d, StateName, County, City, Value, Annual, location),
Five = select(d, StateName, County, City, Value, Five_Year, location),
Ten = select(d, StateName, County, City, Value, Ten_Year, location))
return(d)
}
# Get Data for Zip level of analysis
getZipData <- function() {
# Get data screened by value and growth rates
d <- screenData()
# Filter based upon state
if (!is.null(input$state4)) {
if (input$state4 != "") {
d <- d[ which(d$StateName == input$state4),]
}
}
# Filter based upon county
if (!is.null(input$county4)) {
if (input$county4 != "") {
d <- d[ which(d$County == input$county4 & d$StateName == input$state4),]
}
}
# Filter based upon state and county entered
if (!is.null(input$city4)) {
if (input$city4 != "") {
d <- d[ which(d$City == input$city4 & d$StateName == input$state4),]
}
}
# Format growth record
horizon <- input$horizon
if (horizon == "5 Year") {
horizon <- "Five"
} else if (horizon == "10 Year") {
horizon <- "Ten"
}
d <- switch(horizon,
Monthly = select(d, StateName, County, City, Zip, Value, Monthly, location),
Quarterly = select(d, StateName, County, City, Zip, Value, Quarterly, location),
Annual = select(d, StateName, County, City, Zip, Value, Annual, location),
Five = select(d, StateName, County, City, Zip, Value, Five_Year, location),
Ten = select(d, StateName, County, City, Zip, Value, Ten_Year, location))
return(d)
}
# Retrieves Data for Value Presentation
getData <- eventReactive(input$query, {
d <- switch(input$analysisLevel,
"1" = getStateData(),
"2" = getCountyData(),
"3" = getCityData(),
"4" = getZipData()
)
validate(
need(nrow(d)>0, "No markets meet your search criteria. Please select adjust home value range, minimum growth rate, and/or the geographic filter.")
)
return(d)
}, ignoreNULL = FALSE)
# Get Growth Data
getGrowthData <- eventReactive(input$query, {
d <- getData()
# Configure Chart based upon input horizon
horizon <- input$horizon
if (horizon == "5 Year") {
horizon <- "Five"
} else if (horizon == "10 Year") {
horizon <- "Ten"
}
# Sort by horizon
if (nrow(d) != 0) {
d <- switch(horizon,
Monthly = arrange(d, desc(Monthly)),
Quarterly = arrange(d, desc(Quarterly)),
Annual = arrange(d, desc(Annual)),
Five = arrange(d, desc(Five_Year)),
Ten = arrange(d, desc(Ten_Year)))
}
}, ignoreNULL = FALSE)
# Merge current and historical data for number of markets requested.
mergeMarketData <- function(d,n) {
#if state level of analysis, remove row for USA from data frame.
if (input$analysisLevel == 1) {
d <- d[ which(d$State != "United States"), ]
}
#Subset current data to top n markets by growth
if (!is.null(d)) {
numMarkets <- n
if (nrow(d) < numMarkets) {
numMarkets <- nrow(d)
}
d <- d[1:numMarkets,]
}
#Get historical pricing data based upon level of analysis
h <- switch (isolate(input$analysisLevel),
"1" = hviAllState,
"2" = hviAllCounty,
"3" = hviAllCity,
"4" = hviAllZip
)
m <- merge(d, h, by = "location")
return(m)
}
output$valueByGrowth <- renderPlotly({
withProgress(message = "Rendering Value By Growth Plot", {
# Get Data
d <- getGrowthData()
# Subset into top results
if (!is.null(d)) {
numBars <- 1000
if (nrow(d) < numBars) {
numBars <- nrow(d)
}
d <- d[1:numBars,]
}
# Prepare data based upon input horizon
horizon <- isolate(input$horizon)
if (horizon == "5 Year") {
horizon <- "Five"
} else if (horizon == "10 Year") {
horizon <- "Ten"
}
d <- switch(horizon,
Monthly = subset(d, select = c(location, Value, Monthly)),
Quarterly = subset(d, select = c(location, Value, Quarterly)),
Annual = subset(d, select = c(location, Value, Annual)),
Five = subset(d, select = c(location, Value, Five_Year)),
Ten = subset(d, select = c(location, Value, Ten_Year))
)
colnames(d) <- c("Location", "Value", "Growth")
# Convert Growth Rate to Percentage
d$Growth = as.numeric(d$Growth) * 100
# Designate axis labels
x <- list(title = "Median Home Value")
y <- list(title = "Percent Value Growth")
# Prepare plot
p <- plot_ly(d, x = Value, y = Growth, text = Location, mode = "markers", color = Value, size = Value) %>%
layout(xaxis = x, yaxis = y)
})
})
#Render Top Markets by Growth
output$topByGrowth <- renderChart({
withProgress(message = "Rendering Top Markets by Growth Plot", {
# Get Data
d <- getGrowthData()
# Subset into top results
if (!is.null(d)) {
numBars <- 10
if (nrow(d) < numBars) {
numBars <- nrow(d)
}
d <- d[1:numBars,]
}
# Prepare data based upon input horizon
horizon <- isolate(input$horizon)
if (horizon == "5 Year") {
horizon <- "Five"
} else if (horizon == "10 Year") {
horizon <- "Ten"
}
d <- switch(horizon,
Monthly = subset(d, select = c(location, Monthly)),
Quarterly = subset(d, select = c(location, Quarterly)),
Annual = subset(d, select = c(location, Annual)),
Five = subset(d, select = c(location, Five_Year)),
Ten = subset(d, select = c(location, Ten_Year))
)
colnames(d) <- c("location", "Growth")
d$Growth <- as.numeric(d$Growth) * 100
#Prepare plot
p <- nPlot(Growth~location, data = d)
p$addParams(dom = "topByGrowth", type = "discreteBarChart")
p$set(width = 1200, height = 300)
p$xAxis(staggerLabels = TRUE)
p$yAxis(axisLabel = "Growth Rate (%)", width = 50)
return(p)
})
})
# Render Market Data Table
output$marketTbl <- renderDataTable({
withProgress(message = "Rendering Market Table", {
d <- getGrowthData()
})
#Drop location variable
d$location <- NULL
return(d)
}, options = list(lengthMenu = c(5, 30, 50), autowidth = TRUE, pageLength = 5))
output$valueHist <- renderPlot({
withProgress(message = "Rendering Value Histogram", {
# Get Data
d <- getData()
# Render error message if not enough data to produce histogram
validate(
need(nrow(d) > 1, "Not enough data to produce histogram.")
)
# Subset Data
d <- subset(d, select = c("location", "Value"))
# Convert Value to ($000)
d$Value <- as.numeric(d$Value) / 1000
#Set Parameters
bins <- seq(min(d$Value), max(d$Value), length.out = 31)
#Draw Histogram
hist(as.numeric(d$Value), breaks = bins, col = "skyblue", border = "white",
xlab = "Median Home Values ($000)",
main = "Histogram of Median Home Values")
})
})
#Render Top Markets by Home Value Growth TimeSeries
output$topMarketsTS <- renderChart({
withProgress(message = "Rendering Top Market Time Series", {
# Get Data
d <- getGrowthData()
# Set number of markets to plot. Markets are sorted by Growth (desc)
numMarkets <- 10
# Merge current with historical data for number of markets
d <- mergeMarketData(d, numMarkets)
# Format for Plotting
d <- subset(d, select = c(location, X2000.01:X2015.12))
d <- t(d)
colnames(d) <- d[1,]
d <- d[-1,]
timePeriod <- seq.Date(as.Date('2000/1/1'), by = "month", length.out = 192)
d <- data.frame("Time" = timePeriod, d)
ts <- melt(d, id = "Time")
names(ts) <- c("Time", "Market", "Value")
#Plot Data
p <- nPlot(Value ~ Time, group = "Market", type = "lineChart", data = ts, width = 1100, height = 600, dom = "topMarketsTS")
p$xAxis(
tickFormat =
"#!
function(d){
f = d3.time.format.utc('%Y-%m-%d');
return f(new Date( d*24*60*60*1000 ));
}
!#"
)
p$yAxis(tickFormat = "#! function(d) {return d3.format(',.0f')(d)} !#")
return(p)
})
})
#===============================================================================
# MARKET SELECTOR FUNCTIONS #
#===============================================================================
# State query UI
output$stateUi <- renderUI({
states <- sort(unique(geo$StateName))
selectInput("state", label = "State:", choices = c(Choose='', as.character(states)), selected = dflt$state, selectize = FALSE)
})
# County Query UI
output$countyUi <- renderUI({
counties <- NULL
if (!is.null(input$state)) {
counties <- unique(subset(geo, StateName == input$state, select = County))
counties <- sort(counties$County)
}
selectInput("county", label = "County:", choices = c(Choose='', as.character(counties)), selected = dflt$county, selectize = FALSE)
})
# Render City Query ui
output$cityUi <- renderUI({
cities <- NULL
if (!is.null(input$state)) {
if (input$state != "") {
if (!is.null(input$county)) {
if (input$county != "") {
cities <- unique(subset(geo, StateName == input$state & County == input$county, select = City))
} else {
cities <- unique(subset(geo, StateName == input$state, select = City))
}
} else {
cities <- unique(subset(geo, StateName == input$state, select = City))
}
}
}
cities <- sort(cities$City)
selectInput("city", label = "City:", choices = c(Choose='', as.character(cities)), selected = dflt$city, selectize = FALSE)
})
# Render Zip Query UI
output$zipUi <- renderUI({
zips <- NULL
if (!is.null(input$state)) {
if (input$state != "") {
zips <- unique(subset(geo, StateName == input$state))
}
}
if (!is.null(input$county)) {
if (input$county != "") {
zips <- unique(subset(zips, StateName == input$state & County == input$county))
}
}
if (!is.null(input$city)) {
if (input$city != "") {
zips <- unique(subset(zips, StateName == input$state & City == input$city))
}
}
zips <- sort(zips$Zip)
selectInput("zip", label = "Zip:", choices = c(Choose='', as.character(zips)), selected = dflt$zip, selectize = FALSE)
})
# Determine level of market selected.
getLevel <- reactive({
#Initialize Level
level <- "0"
# Get State Data
if (!is.null(input$state)) {
if (input$state != "") {
level <- "1"
}
}
if (!is.null(input$county)) {
if (input$county != "") {
level <- "2"
}
}
if (!is.null(input$city)) {
if (input$city != "") {
level <- "3"
}
}
if (!is.null(input$zip)) {
if (input$zip != "") {
level <- "4"
}
}
return(level)
})
# Get Current Data
selectCurrentData <- reactive({
level <- getLevel()
d <- switch(level,
"1" = subset(currentState, State == input$state),
"2" = subset(currentCounty, StateName == input$state & County == input$county),
"3" = subset(currentCity, StateName == input$state & City == input$city),
"4" = subset(currentZip, Zip == input$zip)
)
})
# Get Historical Data
selectHistoricalData <- reactive({
level <- getLevel()
d <- switch(level,
"1" = subset(hviAllState, State == input$state, select = X2000.01:X2015.12),
"2" = subset(hviAllCounty, StateName == input$state & County == input$county, select = X2000.01:X2015.12),
"3" = subset(hviAllCity, StateName == input$state & City == input$city, select = X2000.01:X2015.12),
"4" = subset(hviAllZip, Zip == input$zip, select = X2000.01:X2016.01)
)
validate(
need(!is.null(d), "There are no data to analyze. Please select a market and press 'Go' to process the analysis.")
)
validate(
need(!(nrow(d) == 0), "There are no data to analyze. Please select another market and press 'Go' to process the analysis.")
)
validate(
need(!any(is.na(d)), "Unable to produce a timeseries with NA values. Please select a different market in the sidebar. ")
)
return(d)
})
#===============================================================================
# VALUE ANALYSIS FUNCTIONS #
#===============================================================================
#Render Home Value Index Box for selected market
output$hviBox <- renderValueBox({
input$analyze
d <- isolate(selectCurrentData())
validate(
need(!is.null(d),"")
)
valueBox(
paste0("$", d$Value), paste(d$location, " Median Home Value "),
icon = icon("dollar"), color = "green"
)
})
#Render Five Year Growth Box for selected market
output$annualBox <- renderValueBox({
input$analyze
d <- isolate(selectCurrentData())
validate(
need(!is.null(d), "")
)
valueBox(
paste0(round(d$Annual * 100,4), "%"), paste(d$location,
" Annual Change in Home Values"), icon = icon("bar-chart"), color = "red" )
})
#Render Annual Growth Box for selected market
output$fiveYearBox <- renderValueBox({
input$analyze
d <- isolate(selectCurrentData())
validate(
need(!is.null(d), "")
)
valueBox(
paste0(round(d$Five_Year * 100,4), "%"), paste(d$location,
" Five Year Change in Home Values"), icon = icon("bar-chart"), color = "orange" )
})
#Render Annual Growth Box for selected market
output$tenYearBox <- renderValueBox({
input$analyze
d <- isolate(selectCurrentData())
validate(
need(!is.null(d), "")
)
valueBox(
paste0(round(d$Ten_Year * 100,4), "%"), paste(d$location,
" Ten Year Change in Home Values"), icon = icon("bar-chart"), color = "blue" )
})
#Gets time series for a selected market.
getTimeSeries <- eventReactive(input$analyze, {
d <- selectHistoricalData()
d <- as.numeric(as.vector(d))
timeSeries <- ts(d, frequency = 12, start = c(2000,1))
return(timeSeries)
}, ignoreNULL = FALSE)
# Render non-seasonal trend time series
output$nsPlot <- renderPlot({
Price <- SMA(getTimeSeries(), n = input$span)
autoplot(Price, ts.colour = "blue") + theme_bw()
})
# Render seasonal time series decomposition
output$tsiPlot <- renderPlot({
Price <- decompose(getTimeSeries())
autoplot(Price, ts.colour = "blue") + theme_bw()
})
#===============================================================================
## FORECAST MODEL TRAINING FUNCTIONS #
#===============================================================================
# Render model select
output$modelsUi <- renderUI({
selectInput("model", label = "Prediction Models:", choices = c(Choose='',as.character(modelData$code)), selected = dflt$model, selectize = FALSE)
})
# Render model name
output$modelNameUi <- renderText({
if (is.null(input$model)) {
m <- dflt$model
} else {
m <- input$model
}
paste(modelData[ which(modelData$code == m), ]$name)
})
# Render model description
output$modelDescUi <- renderText({
if (is.null(input$model)) {
m <- dflt$model
} else {
m <- input$model
}
paste(modelData[ which(modelData$code == m), ]$desc)
})
# Split data into training and test/validation set
splitData <- function() {
if (is.null(input$split)) {
y <- dflt$split
} else {
y <- as.numeric(input$split)
}
validate(
need(input$state != "", "Please select a market using the geographic selectors in the sidebar. ")
)
d <- selectHistoricalData()
# Create time series object on full data
marketPrices <- as.numeric(as.vector(d))
tSeries <- ts(marketPrices, frequency = 12, start = c(2000,1))
#Split into training and test set
tsTest <- window(tSeries, start = c(y+1,1))
tsTrain <- window(tSeries, end = c(y,12))
#Combine into a list
l <- list("train" = tsTrain, "test" = tsTest)
return(l)
}
# Get plot options, specifically, number of periods to forecast and to include
getForecastOptions <- function() {
# Determine number of periods to forecast
if (is.null(input$split) || input$split == "") {
periods <- 12
} else {
periods <- (2015 - as.integer(input$split)) * 12
}
# Determine number of back periods to include
if ((periods * 3) > (192 - periods)) {
include <- 192 - periods
} else {
include <- periods * 3
}
# Determine ylimit at peak price
maximum <- as.integer(max(selectHistoricalData()))
#Combine into a list and return
l <- list(periods = periods, include = include, maximum = maximum)
}