# ══════════════════════════════════════════════════ # T01 · Caso práctico Macro — IPC de España (INE) # Abre primero mSeriesTemporales.Rproj en RStudio # Datos: data/ipc_mensual_espana.RData (serie INE IPC290751) # ══════════════════════════════════════════════════ library(tidyverse) library(forecast) pausa <- function(msg = "\n [Pulsa ENTER para continuar...]") { if (interactive()) { cat(msg); invisible(readline()) } } # ── 1. CARGA DE DATOS ───────────────────────────── load("data/ipc_mensual_espana.RData") ipc <- ipc_mensual_espana ipc$fecha <- as.Date(ipc$fecha) ipc_ts <- ts(ipc$ipc, start = c(2002, 1), frequency = 12) cat(sprintf("IPC de España: %d observaciones mensuales (%s a %s)\n", nrow(ipc), format(min(ipc$fecha), "%Y-%m"), format(max(ipc$fecha), "%Y-%m"))) cat(sprintf("Último valor del índice: %.3f\n", tail(ipc$ipc, 1))) pausa() # ── 2. GRÁFICO DE LA SERIE ──────────────────────── plot(ipc_ts, col = "steelblue", lwd = 1.5, ylab = "Índice (base 2021 = 100)", main = "IPC general de España") cat("Tendencia creciente con oscilaciones estacionales anuales.\n") pausa() # ── 3. DESCOMPOSICIÓN STL ───────────────────────── desc <- stl(ipc_ts, s.window = "periodic") plot(desc, main = "Descomposición STL del IPC") fac_est <- desc$time.series[, "seasonal"][1:12] cat("Factores estacionales (12 primeros meses):\n") print(round(fac_est, 3)) pausa() # ── 4. TENDENCIA POR MEDIA MÓVIL DE ORDEN 12 ────── ma12 <- forecast::ma(ipc_ts, order = 12) plot(ipc_ts, col = "grey60", ylab = "Índice", main = "IPC y media móvil (orden 12)") lines(ma12, col = "black", lwd = 2) pausa() # ── 5. FILTRO DE HODRICK-PRESCOTT ───────────────── hp_filter <- function(x, lambda = 14400) { x <- as.numeric(x); m <- length(x) D <- diff(diag(m), differences = 2) as.numeric(solve(diag(m) + lambda * crossprod(D), x)) } ipc$tend <- hp_filter(ipc$ipc, lambda = 14400) ipc$ciclo <- ipc$ipc - ipc$tend op <- par(mfrow = c(2, 1), mar = c(3, 4, 2, 1)) plot(ipc$fecha, ipc$ipc, type = "l", col = "grey60", ylab = "Índice", xlab = "", main = "Tendencia HP del IPC") lines(ipc$fecha, ipc$tend, col = "black", lwd = 2) plot(ipc$fecha, ipc$ciclo, type = "l", col = "black", ylab = "Ciclo", xlab = "Año", main = "Ciclo del IPC") abline(h = 0, col = "grey70") par(op) cat(sprintf("Desviación cíclica máxima respecto a la tendencia: %.2f puntos\n", max(abs(ipc$ciclo)))) # === FIN Caso Práctico Macro — Tema 01 (IPC) ===