fill_colors_seg <- c(pre = "#E8FA22", during = "#FC886D", post = "#6DD6FC")
# ---- Funcao auxiliar: plota janelas diarias para um conjunto de breakpoints ----
plot_windows_for_h <- function(didx_vec, h_label, line_color) {
top5_vec <- head(didx_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)) {
D <- top5_vec[k]
segs_df <- do.call(rbind, lapply(c("pre", "during", "post"), function(nm) {
win <- switch(nm,
pre = safe_window_d(D - PRE_DAYS, D - 1, n_daily),
during = safe_window_d(D, D + POST_DAYS, n_daily),
post = safe_window_d(D + POST_DAYS + 1, D + 2 * POST_DAYS, n_daily)
)
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, D - PRE_DAYS - 10L)
zoom_e <- min(n_daily, D + 2 * POST_DAYS + 10L)
plot_df <- dc_clean[zoom_s:zoom_e, ] %>%
mutate(index = zoom_s:zoom_e)
crash_date <- dc_clean$trade_date[min(D, n_daily)]
crash_ret <- ret_daily[min(D, n_daily)]
print(
ggplot(plot_df, aes(x = index, y = close_last)) +
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.5) +
geom_vline(xintercept = D, 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 Diario IBM"),
subtitle = paste0(
"Linha = breakpoint (", format(crash_date, "%Y-%m-%d"),
") | Ret diario: ", round(crash_ret * 100, 3), "%",
"\npre=[D-", PRE_DAYS, "d, D-1] | during=[D, D+", POST_DAYS,
"d] | post=[D+", POST_DAYS + 1, "d, D+", 2 * POST_DAYS, "d]"
),
x = "Dia de pregao (indice diario)", y = "Preco de Fechamento Diario"
) +
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(bp_daily_idx, "h = 0.05", "#2980B9")