# ══════════════════════════════════════════════════ # T08 · Series Temporales — Cointegración y VECM # Abre primero mSeriesTemporales.Rproj en RStudio # ══════════════════════════════════════════════════ library(tidyverse) library(urca) library(tsDyn) library(tseries) pausa <- function(msg = "\n [Pulsa ENTER para continuar...]") { if (interactive()) { cat(msg); invisible(readline()) } } set.seed(2026) # ── 1. REGRESION ESPURIA ────────────────────────── # Dos paseos aleatorios independientes: "significativos" sin ninguna relacion real. n <- 118 x <- cumsum(rnorm(n)); y <- cumsum(rnorm(n)) reg_esp <- lm(y ~ x) cat(sprintf("Regresion espuria: R2=%.3f, t=%.2f, p=%.4f (¡sin relacion real!)\n", summary(reg_esp)$r.squared, coef(summary(reg_esp))["x", "t value"], coef(summary(reg_esp))["x", "Pr(>|t|)"])) pausa() # ── 2. UN SISTEMA COINTEGRADO POR CONSTRUCCION ──── # y2 = 2*x2 + ruido estacionario -> SI cointegrados. x2 <- cumsum(rnorm(n)) y2 <- 2 * x2 + rnorm(n) po_no <- po.test(cbind(y, x)) # no cointegrados po_si <- po.test(cbind(y2, x2)) # si cointegrados cat(sprintf("Phillips-Ouliaris (NO cointegrados): stat=%.2f p=%.3f\n", po_no$statistic, po_no$p.value)) cat(sprintf("Phillips-Ouliaris (SI cointegrados) : stat=%.2f p=%.3f\n", po_si$statistic, po_si$p.value)) pausa() # ── 3. JOHANSEN SOBRE EL SISTEMA COINTEGRADO ────── Y2 <- cbind(y2 = y2, x2 = x2) jo <- ca.jo(Y2, type = "trace", ecdet = "const", K = 2, spec = "transitory") print(summary(jo)) pausa() # ── 4. VECM DEL SISTEMA COINTEGRADO ─────────────── m_vecm <- VECM(Y2, lag = 1, r = 1, estim = "ML", LRinclude = "const") print(summary(m_vecm)) cat("Coeficiente de ajuste esperado: negativo en al menos una ecuacion (correccion estable).\n") # === FIN Script T08 — Cointegración y VECM ===