# Configuración de fechas - CAMBIAR SOLO AQUÍ
fecha_inicio_entrenamiento <- "2022-10-31"
fecha_fin_entrenamiento <- "2025-10-31"
fecha_inicio_prueba <- "2025-11-03"
fecha_fin_prueba <- "2025-11-21" # ← FECHA FINAL AGREGADA
AccionesEX <- getSymbols("GLTR", src = "yahoo", auto.assign = FALSE,
from = fecha_inicio_entrenamiento)
GLTR <- AccionesEX$GLTR.Close
Entrenamiento_GLTR <- window(GLTR, start = fecha_inicio_entrenamiento, end = fecha_fin_entrenamiento)
Prueba_GLTR <- window(GLTR, start = fecha_inicio_prueba, end = fecha_fin_prueba)
df_train_GLTR <- data.frame(
Fecha = index(Entrenamiento_GLTR),
Precio = as.numeric(Entrenamiento_GLTR),
Conjunto = "Entrenamiento"
)
df_test_GLTR <- data.frame(
Fecha = index(Prueba_GLTR),
Precio = as.numeric(Prueba_GLTR),
Conjunto = "Prueba"
)
df_completo_GLTR <- bind_rows(df_train_GLTR, df_test_GLTR)
fecha_corte_GLTR <- as.Date("2025-11-01")ggplot(df_completo_GLTR, aes(x = Fecha, y = Precio)) +
geom_ribbon(data = df_train_GLTR,
aes(ymin = min(df_completo_GLTR$Precio) * 0.95, ymax = Precio),
fill = gltr_pal$primary, alpha = 0.08) +
geom_ribbon(data = df_test_GLTR,
aes(ymin = min(df_completo_GLTR$Precio) * 0.95, ymax = Precio),
fill = gltr_pal$secondary, alpha = 0.15) +
geom_line(data = df_train_GLTR, color = gltr_pal$primary, linewidth = 0.9) +
geom_line(data = df_test_GLTR, color = gltr_pal$secondary, linewidth = 1.1) +
geom_vline(xintercept = fecha_corte_GLTR,
linetype = "dashed", color = gltr_pal$negative, linewidth = 0.8) +
annotate("text", x = fecha_corte_GLTR, y = max(df_completo_GLTR$Precio) * 1.02,
label = "Corte: 01-Nov-2025", hjust = -0.05, vjust = 0,
color = gltr_pal$negative, fontface = "bold", size = 3.5) +
annotate("label",
x = as.Date("2024-01-01"),
y = max(df_completo_GLTR$Precio) * 0.85,
label = paste0("ENTRENAMIENTO\n", nrow(df_train_GLTR), " observaciones"),
fill = gltr_pal$primary, color = "white",
fontface = "bold", size = 3.5, label.padding = unit(0.5, "lines")) +
annotate("label",
x = max(df_test_GLTR$Fecha) - 1,
y = min(df_completo_GLTR$Precio) * 1.15,
label = paste0("PRUEBA\n", nrow(df_test_GLTR), " obs."),
fill = gltr_pal$secondary, color = "white",
fontface = "bold", size = 3.2, label.padding = unit(0.4, "lines")) +
scale_x_date(date_breaks = "4 months", date_labels = "%b %Y",
expand = expansion(mult = c(0.02, 0.05))) +
scale_y_continuous(labels = dollar_format(prefix = "$"),
expand = expansion(mult = c(0.05, 0.08))) +
labs(
title = "Partición de Datos: Entrenamiento vs Prueba",
subtitle = "GLTR | Serie de precios de cierre diarios",
x = NULL,
y = "Precio de Cierre (USD)",
caption = paste0("Fuente: Yahoo Finance | Período: ",
min(df_completo_GLTR$Fecha), " a ", max(df_completo_GLTR$Fecha))
) +
theme_minimal(base_size = 12) +
theme(
plot.background = element_rect(fill = "transparent", color = NA),
panel.background = element_rect(fill = "transparent", color = NA),
plot.title = element_text(face = "bold", size = 16, color = gltr_pal$text_dark,
margin = margin(b = 5)),
plot.subtitle = element_text(size = 11, color = gltr_pal$secondary,
margin = margin(b = 15)),
plot.caption = element_text(size = 9, color = gltr_pal$text_gray,
margin = margin(t = 15), hjust = 0),
axis.title.y = element_text(face = "bold", size = 10, color = gltr_pal$text_gray),
axis.text = element_text(size = 9, color = gltr_pal$text_gray),
axis.text.x = element_text(angle = 45, hjust = 1),
panel.grid.major = element_line(color = gltr_pal$grid, linetype = "dashed", linewidth = 0.4),
panel.grid.minor = element_blank(),
plot.margin = margin(20, 25, 15, 15)
)acf_data_GLTR <- acf(Entrenamiento_GLTR, lag.max = 30, plot = FALSE)
df_acf_GLTR <- data.frame(
Lag = acf_data_GLTR$lag[-1],
ACF = acf_data_GLTR$acf[-1]
)
n_GLTR <- length(Entrenamiento_GLTR)
limite_sup_GLTR <- qnorm(0.975) / sqrt(n_GLTR)
limite_inf_GLTR <- -limite_sup_GLTR
ggplot(df_acf_GLTR, aes(x = Lag, y = ACF)) +
geom_segment(aes(xend = Lag, yend = 0),
color = gltr_pal$primary, linewidth = 0.8) +
geom_point(color = gltr_pal$primary, size = 2) +
geom_hline(yintercept = limite_sup_GLTR, linetype = "dashed",
color = gltr_pal$secondary, linewidth = 0.7) +
geom_hline(yintercept = limite_inf_GLTR, linetype = "dashed",
color = gltr_pal$secondary, linewidth = 0.7) +
geom_hline(yintercept = 0, color = gltr_pal$text_gray, linewidth = 0.5) +
annotate("rect", xmin = -Inf, xmax = Inf,
ymin = limite_inf_GLTR, ymax = limite_sup_GLTR,
fill = gltr_pal$secondary, alpha = 0.1) +
annotate("label", x = 20, y = 0.5,
label = "Serie NO estacionaria",
fill = gltr_pal$negative, color = "white",
fontface = "bold", size = 3.5, label.padding = unit(0.5, "lines")) +
scale_x_continuous(breaks = seq(0, 30, 5)) +
scale_y_continuous(limits = c(-0.1, 1.05), breaks = seq(0, 1, 0.25)) +
labs(
title = "Función de Autocorrelación (ACF) - Serie en Niveles",
subtitle = "GLTR: Precio de cierre | Datos de entrenamiento",
x = "Rezago (Lag)",
y = "Autocorrelación",
caption = "Bandas rojas: Límites de significancia al 95%"
) +
theme_minimal(base_size = 12) +
theme(
plot.background = element_rect(fill = "transparent", color = NA),
panel.background = element_rect(fill = "transparent", color = NA),
plot.title = element_text(face = "bold", size = 14, color = gltr_pal$text_dark),
plot.subtitle = element_text(size = 10, color = gltr_pal$secondary),
plot.caption = element_text(size = 9, color = gltr_pal$text_gray, hjust = 0),
axis.title = element_text(face = "bold", size = 10, color = gltr_pal$text_gray),
axis.text = element_text(size = 9, color = gltr_pal$text_gray),
panel.grid.major = element_line(color = gltr_pal$grid, linetype = "dashed", linewidth = 0.4),
panel.grid.minor = element_blank()
)adf_resultado_GLTR <- adf.test(Entrenamiento_GLTR)
tabla_adf_GLTR <- data.frame(
Métrica = c("Estadístico Dickey-Fuller",
"Orden de Rezagos (Lag)",
"P-valor",
"Nivel de Significancia (α)",
"Hipótesis Nula (H₀)",
"Decisión"),
Valor = c(round(adf_resultado_GLTR$statistic, 4),
adf_resultado_GLTR$parameter,
round(adf_resultado_GLTR$p.value, 4),
"0.05",
"Serie tiene raíz unitaria",
ifelse(adf_resultado_GLTR$p.value > 0.05,
"No rechazar H₀", "Rechazar H₀")),
Interpretación = c("Valor del estadístico de prueba",
"Rezagos incluidos en el test",
"Probabilidad bajo H₀",
"Umbral de decisión",
"La serie NO es estacionaria",
ifelse(adf_resultado_GLTR$p.value > 0.05,
"Serie NO estacionaria",
"Serie estacionaria"))
)
kable(tabla_adf_GLTR,
caption = "Prueba de Dickey-Fuller Aumentada (ADF) - Serie en Niveles GLTR",
align = c("l", "c", "l")) %>%
kable_styling(bootstrap_options = c("striped", "hover", "condensed"),
full_width = FALSE,
position = "center") %>%
row_spec(3, bold = TRUE, color = "#e17055") %>%
row_spec(6, bold = TRUE, background = "#fef3f2")| Métrica | Valor | Interpretación |
|---|---|---|
| Estadístico Dickey-Fuller | -0.4513 | Valor del estadístico de prueba |
| Orden de Rezagos (Lag) | 9 | Rezagos incluidos en el test |
| P-valor | 0.984 | Probabilidad bajo H₀ |
| Nivel de Significancia (α) | 0.05 | Umbral de decisión |
| Hipótesis Nula (H₀) | Serie tiene raíz unitaria | La serie NO es estacionaria |
| Decisión | No rechazar H₀ | Serie NO estacionaria |
GLTR_diff <- diff(Entrenamiento_GLTR) %>% na.omit()
GLTR_diff_df <- data.frame(
Fecha = as.Date(time(GLTR_diff)),
Cambio = as.numeric(GLTR_diff)
)
GLTR_diff_df$ID <- seq.int(nrow(GLTR_diff_df))accumulate_by <- function(dat, var) {
var <- lazyeval::f_eval(var, dat)
lvls <- plotly:::getLevels(var)
dats <- lapply(seq_along(lvls), function(x) {
cbind(dat[var %in% lvls[seq(1, x)], ], frame = lvls[[x]])
})
dplyr::bind_rows(dats)
}
GLTR_diff_df <- GLTR_diff_df %>% accumulate_by(~ID)
fig_diff_animated <- plot_ly(
data = GLTR_diff_df,
x = ~Fecha,
y = ~Cambio,
frame = ~frame,
type = 'scatter',
mode = 'lines',
fill = 'tozeroy',
fillcolor = 'rgba(0, 100, 200, 0.3)',
line = list(color = 'rgb(0, 0, 0)', width = 1.5),
text = ~paste(
"Fecha: ", format(Fecha, "%d/%m/%Y"),
"<br>Cambio: $", round(Cambio, 4)
),
hoverinfo = 'text'
) %>%
layout(
title = list(
text = "<b>Serie diferenciada GLTR</b>",
font = list(size = 16, family = "Arial"),
x = 0.5,
xanchor = 'center'
),
xaxis = list(
title = "Fecha",
range = c(min(GLTR_diff_df$Fecha), max(GLTR_diff_df$Fecha)),
showgrid = TRUE,
gridcolor = 'rgba(200, 200, 200, 0.3)',
zeroline = FALSE
),
yaxis = list(
title = "Cambio en Precio",
showgrid = TRUE,
gridcolor = 'rgba(200, 200, 200, 0.3)',
zeroline = TRUE,
zerolinecolor = 'rgba(0, 0, 0, 0.3)',
zerolinewidth = 1
),
plot_bgcolor = '#f0f0f0',
paper_bgcolor = 'white',
hovermode = 'closest'
) %>%
animation_opts(
frame = 50,
transition = 0,
redraw = FALSE
) %>%
animation_slider(
currentvalue = list(
prefix = "Fecha: ",
font = list(color = "black")
)
)
fig_diff_animated