← Catálogo
· Capítulo 3
T03_mST_Script_ModelosARMA.R
# ══════════════════════════════════════════════════
# T03 · Series Temporales — Modelos AR, MA y ARMA
# Abre primero mSeriesTemporales.Rproj en RStudio
# ══════════════════════════════════════════════════
library(tidyverse)
library(forecast)
pausa <- function(msg = "\n [Pulsa ENTER para continuar...]") {
if (interactive()) { cat(msg); invisible(readline()) }
}
set.seed(2026)
# ── 1. PROCESO MA(1): FAC TEORICA VS MUESTRAL ─────
# rho1 = theta / (1 + theta^2); rho_k = 0 para k >= 2.
theta <- 0.6
ma1 <- arima.sim(list(ma = theta), n = 300)
rho1_teo <- theta / (1 + theta^2)
rho1_mue <- acf(ma1, lag.max = 1, plot = FALSE)$acf[2]
cat(sprintf("MA(1) theta=%.1f -> rho1 teorico=%.3f muestral=%.3f\n",
theta, rho1_teo, rho1_mue))
op <- par(mfrow = c(1, 2))
plot(ma1, type = "l", col = "grey30", main = "MA(1), theta = 0.6", ylab = "y")
acf(ma1, main = "FAC muestral")
par(op)
cat("El correlograma se corta tras el retardo 1: firma de un MA(1).\n")
pausa()
# ── 2. PROCESO AR(1): FAC Y FACP ──────────────────
# rho_k = phi^k (decrecimiento geometrico); FACP se corta en el retardo 1.
phi <- 0.7
ar1 <- arima.sim(list(ar = phi), n = 300)
op <- par(mfrow = c(1, 2))
acf(ar1, main = "FAC AR(1), phi = 0.7")
pacf(ar1, main = "FACP AR(1), phi = 0.7")
par(op)
cat("FAC decae geometricamente; FACP se corta tras el retardo 1.\n")
pausa()
# ── 3. ESTACIONARIEDAD DE UN AR(p): RAICES ────────
# phi(L) = 1 - 0.5L - 0.3L^2. Estacionario si todas las raices |z| > 1.
raices <- polyroot(c(1, -0.5, -0.3))
cat("Raices de 1 - 0.5L - 0.3L^2:\n")
print(raices)
cat(sprintf("Modulos: %.3f y %.3f -> %s\n", Mod(raices)[1], Mod(raices)[2],
ifelse(all(Mod(raices) > 1), "ambas fuera del circulo unidad: ESTACIONARIO",
"alguna raiz dentro del circulo unidad: NO estacionario")))
pausa()
# ── 4. INVERTIBILIDAD DE UN MA(1) ─────────────────
# theta(L) = 1 + theta*L = 0 -> z = -1/theta. Invertible si |theta| < 1.
for (th in c(0.6, 1.5)) {
raiz_ma <- -1 / th
cat(sprintf("MA(1) theta=%.1f -> raiz=%.3f (modulo=%.3f) -> %s\n",
th, raiz_ma, abs(raiz_ma), ifelse(abs(raiz_ma) > 1, "invertible", "NO invertible")))
}
pausa()
# ── 5. IDENTIFICACION, ESTIMACION Y AIC/BIC ───────
# Ejemplo generico: simular un ARMA(1,1) y recuperarlo por AIC/BIC.
sim_arma <- arima.sim(list(ar = 0.5, ma = 0.4), n = 400)
candidatos <- list(c(1,0,0), c(0,0,1), c(1,0,1), c(2,0,1), c(1,0,2))
resultados <- map_dfr(candidatos, function(o) {
m <- Arima(sim_arma, order = o, include.mean = TRUE, method = "ML")
tibble(orden = paste(o, collapse = ","), AIC = AIC(m), BIC = BIC(m))
})
print(resultados[order(resultados$AIC), ])
cat("El orden verdadero (1,0,1) deberia estar entre los mejores por AIC/BIC.\n")
# === FIN Script T03 — Modelos AR, MA y ARMA ===