fill_colors_seg <- c(pre = "#E8FA22", during = "#FC886D", post = "#6DD6FC")
# ---- Funcao auxiliar: plota janelas para um conjunto de breakpoints ----
plot_windows_for_h <- function(gidx_vec, h_label, line_color) {
top5_vec <- head(gidx_vec, 5)
if (length(top5_vec) == 0) {
cat(sprintf("[%s] Nenhum breakpoint disponivel.\n", h_label))
return(invisible(NULL))
}
for (k in seq_along(top5_vec)) {
X <- top5_vec[k]
segs_df <- do.call(rbind, lapply(c("pre", "during", "post"), function(nm) {
win <- switch(nm,
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)
)
if (is.null(win)) return(NULL)
data.frame(janela = nm, xmin = win[1] - 0.5, xmax = tail(win, 1) + 0.5)
}))
zoom_s <- max(1L, X - 22000L)
zoom_e <- min(n_total, X + 32000L)
plot_df <- data.frame(index = seq_len(n_total),
price = dt1$Close.1min)[zoom_s:zoom_e, ]
crash_date <- dt1$Period[min(X, n_total)]
crash_ret <- rets_full[min(X, n_total)]
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 = X, color = line_color,
linewidth = 0.9, linetype = "solid") +
scale_fill_manual(name = "Janela", values = fill_colors_seg) +
labs(
title = paste0("[", h_label, "] Evento_", k,
" — Janelamentos sobre Preco IBM"),
subtitle = paste0(
"Linha = breakpoint (", format(crash_date, "%Y-%m-%d"),
") | Ret: ", round(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)
)
}
}
# ---- Plota para cada valor de h ----
plot_windows_for_h(crash_idx_bp, "h = 0.05", "#2980B9")