active_crash_vec <- crash_idx_za
top5_vec <- head(active_crash_vec, 5)
events_viz <- lapply(seq_along(top5_vec), function(k) {
X <- top5_vec[k]
list(
crash_idx = X,
crash_date = dt1$Period[min(X, n_total)],
crash_ret = rets_full[min(X, n_total)],
event_label = paste0("Evento_", k),
pre = safe_window(X - 10000, X, n_total),
during = safe_window(X, X + 10000, n_total),
post = safe_window(X + 10000, X + 20000, n_total)
)
})
fill_colors_seg <- c(pre = "#E8FA22", during = "#FC886D", post = "#6DD6FC")
for (ev in events_viz) {
segs_df <- do.call(rbind, lapply(c("pre", "during", "post"), function(nm) {
idx <- ev[[nm]]
if (is.null(idx)) return(NULL)
data.frame(janela = nm, xmin = idx[1] - 0.5, xmax = tail(idx, 1) + 0.5)
}))
zoom_s <- max(1L, ev$crash_idx - 22000L)
zoom_e <- min(n_total, ev$crash_idx + 32000L)
plot_df <- data.frame(index = seq_len(n_total),
price = dt1$Close.1min)[zoom_s:zoom_e, ]
print(
ggplot(plot_df, aes(x = index, y = price)) +
geom_rect(data = segs_df,
aes(xmin = xmin, xmax = xmax, ymin = -Inf, ymax = Inf, fill = janela),
inherit.aes = FALSE, alpha = 0.30) +
geom_line(color = "black", linewidth = 0.35) +
geom_vline(xintercept = ev$crash_idx, color = "red",
linewidth = 0.9, linetype = "solid") +
scale_fill_manual(name = "Janela", values = fill_colors_seg) +
labs(
title = paste0(ev$event_label, " - Janelamentos sobre Preco IBM"),
subtitle = paste0(
"Linha vermelha = breakpoint (", format(ev$crash_date, "%Y-%m-%d"),
") | Ret: ", round(ev$crash_ret * 100, 3), "%",
"\npre=[X-10k, X] | during=[X, X+10k] | post=[X+10k, X+20k]"
),
x = "Indice (observacao global)", y = "Preco de Fechamento"
) +
theme_minimal(base_size = 11) +
theme(plot.title = element_text(face = "bold"), legend.position = "top") +
coord_cartesian(expand = FALSE)
)
}