-
Notifications
You must be signed in to change notification settings - Fork 1
/
flex.Rmd
325 lines (290 loc) · 7.92 KB
/
flex.Rmd
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
---
# Set up the Environment
title: "DSE Indices"
runtime: shiny
output:
flexdashboard::flex_dashboard:
theme:
bg: "#fff"
fg: "#000"
primary: "#446E9B"
secondary: "#446E9B"
base_font: !expr bslib::font_google("Prompt")
code_font: !expr bslib::font_google("JetBrains Mono")
bootswatch: spacelab
orientation: rows
vertical_layout: fill
#social: menu
source_code: embed
navbar:
- { title: "GitHub", href: "https://github.com/tanvird3", align: right, icon: fa-github}
#- { title: "Home", href: "https://google.com", align: right, icon: fa-facebook }
---
```{r, include = FALSE}
# Import the libraries and define the theme
library(flexdashboard)
library(plotly)
library(readr)
library(dplyr)
library(shiny)
library(shinyjs)
library(prophet)
library(reticulate)
# unquote the following line if the theme customization window needed
#bslib::bs_themer()
thematic::thematic_rmd(
font = "auto",
# To get the dark bg on the geom_raster()
sequential = thematic::sequential_gradient(
fg_low = FALSE,
fg_weight = 0,
bg_weight = 1
)
)
theme_set(theme_bw(base_size = 20))
```
```{r, include = FALSE}
# load the virtual env
reticulate::virtualenv_create("python35_env", python = "python3")
reticulate::virtualenv_install("python35_env",
packages = c("investpy"),
ignore_installed = T)
reticulate::use_virtualenv("python35_env", required = TRUE)
```
Sidebar {.sidebar}
=======================================================================
###
```{r}
selectInput(
inputId = "index",
label = "Select Index",
choices =
c("DSE Broad", "DSE 30", "DSEX Shariah"),
selected = "DSE Broad"
)
dateRangeInput(
inputId = "date",
label = "Choose a Date",
start = Sys.Date() - 364,
end = Sys.Date()
)
# The Global ActionButton
actionButton("Generate", "Generate Plots")
```
```{r}
```
```{r}
# Prepare the required tables for plotting
data_gen <- function(startdate, enddate, index) {
source_python("index.py")
startdate <- format(startdate, "%d/%m/%Y")
enddate <- format(enddate, "%d/%m/%Y")
df <- index_hist(startdate, enddate, index)
df <- df %>% mutate(Date = as.Date(Date, format = "%Y-%m-%d"))
# create return series
df <- df %>% mutate(Return = c((diff(Close) * -1) /Close[-1], 0))
# Color setting related to values of Return
df <- df %>% mutate(Color = if_else(Return >= 0, "#109618", "#D62728"))
df <- df %>% mutate(WinLose = if_else(Return >= 0, "Winning Days", "Losing Days"))
max_index <- max(df$Close)
min_index <- min(df$Close)
avg_index <- mean(df$Close)
pct_var <- (max_index - min_index) / min_index * 100
pct_change <-
(df$Close[1] - df$Close[nrow(df)]) / df$Close[nrow(df)] * 100
sum_tab <-
data.frame(
Particulars = c("Max Index", "Min Index", "Avg Index"),
Values = c(max_index, min_index, avg_index)
)
pct_tab <-
data.frame(
Particulars = c("Max-Min", "End-Beginning"),
Values = c(pct_var, pct_change)
)
winlose_tab <-
df %>% group_by(WinLose) %>% summarise(Day_Count = n())
# the DSEX Time Plot
time_plot <- df %>%
plot_ly(
x = ~ Date,
y = ~ Close,
name = index,
type = "scatter",
mode = "lines",
fill = "tozeroy",
showlegend = F
)
# Return Series Plot
return_plot <- df %>%
plot_ly(
x = ~ Date,
y = ~ Return,
name = "Return",
type = "bar",
showlegend = F,
marker = list(color = ~ Color)
)
# combine the plots
index_plot <-
subplot(
time_plot,
return_plot,
nrows = 2,
shareX = TRUE,
shareY = FALSE,
which_layout = "merge"
) %>%
layout(
title = paste("<br>Timeline of", index, "Index"),
xaxis = list(title = ""),
xaxis2 = list(title = ""),
yaxis = list(title = "Index Value"),
yaxis2 = list(title = "% Return")
)
# Basic Descriptive Statistics Plot
summary_plot <- sum_tab %>%
plot_ly(
x = ~ Particulars,
y = ~ Values,
type = "bar",
name = "Index Movement",
marker = list(color = "#A777F1")
) %>%
layout(title = paste("<br>", "Movement of", index),
xaxis = list(title = ""),
yaxis = list(title = ""))
# Growth Over the Period Plot
growth_plot <- pct_tab %>%
plot_ly(
x = ~ Particulars,
y = ~ Values,
type = "bar",
name = "Index Change",
marker = list(color = "#FF6692")
) %>%
layout(title = paste("<br>", "% Change of", index),
xaxis = list(title = ""),
yaxis = list(title = ""))
# Win Lose Day Count Plot
winlose_plot <-
winlose_tab %>% plot_ly(
labels = ~ WinLose,
values = ~ Day_Count,
type = "pie",
showlegend = F
) %>%
layout(title = paste("<br>", index, "Count of W/L Days"))
# Forecast with Prophet Method
# keep only the required columns
df_mod <- df %>% select(Date, Close)
# rename the columns as per requirements
names(df_mod) <- c("ds", "y")
# fit the model
model_fit <- prophet(df_mod, seasonality.mode = "additive")
future_get <- make_future_dataframe(model_fit, periods = 64)
future_get <-
future_get %>% mutate(wd = weekdays(ds)) %>% filter(!wd %in% c("Friday", "Saturday")) %>% select(-wd)
forecast_get <-
predict(model_fit, future_get) %>% select(ds, yhat, yhat_lower, yhat_upper)
# Prepare data fro plotting
df_dt <- df %>% select(Date, Close)
names(df_dt)[1] <- "ds"
df_dt <- df_dt %>% mutate(ds = as.Date(ds, format = "%Y-%m-%d"))
df_plot <-
df_dt %>% full_join(forecast_get, by = "ds") %>% arrange(desc(ds)) %>% slice_head(n = 100)
# Plot the forecasts along with original data
pplot <- plot_ly(df_plot,
x = ~ ds) %>%
add_trace(
y = ~ yhat_upper,
name = "Upper Band",
type = "scatter",
mode = "lines",
line = list(dash = "dot", color = "#B82E2E"),
showlegend = F
) %>% add_trace(
y = ~ yhat_lower,
name = "Lower Band",
type = "scatter",
mode = "lines",
line = list(dash = "dot", color = "#990099"),
fill = "tonexty",
fillcolor = "rgba(0,100,80,0.2)",
showlegend = F
) %>%
add_trace(
y = ~ yhat,
name = "Forecasted Index",
type = "scatter",
mode = "lines",
line = list(color = "#109618")
) %>%
add_trace(
y = ~ Close,
type = "scatter",
mode = "lines",
name = "Actual Index",
line = list(color = "blue")
) %>%
layout(
title = paste(index, "Forecast"),
xaxis = list(title = ""),
yaxis = list(title = ""),
margin = list(t = 120),
legend = list(
orientation = "h",
x = 0,
y = 1.4
)
)
# The return series of plots
return(
list(
index_plot = index_plot,
summary_plot = summary_plot,
growth_plot = growth_plot,
winlose_plot = winlose_plot,
forecast_plot = pplot
)
)
}
# Generate the Output
output_get <-
eventReactive(input$Generate, {
data_gen(input$date[1], input$date[2], input$index)
}, ignoreNULL = F)
```
<!-- # This is the First Tab -->
Analysis
=======================================================================
<!-- # Rows of the Tab -->
Row
-----------------------------------------------------------------------
```{r}
Index_Plot <- renderPlotly(output_get()$index_plot)
Index_Plot
```
```{r}
```
Row
-----------------------------------------------------------------------
```{r}
Summary_Plot <- renderPlotly(output_get()$summary_plot)
Summary_Plot
```
```{r}
Growth_Plot <- renderPlotly(output_get()$growth_plot)
Growth_Plot
```
```{r}
winlose_plot <- renderPlotly(output_get()$winlose_plot)
winlose_plot
```
<!-- # Second Tab -->
Forecast
=======================================================================
```{r}
Forecast_Plot <- renderPlotly(output_get()$forecast_plot)
Forecast_Plot
```