#Cargar librerías necesarias
library(readxl)  # Para leer archivos Excel
library(tseries)  # Para pruebas de estacionariedad
## Warning: package 'tseries' was built under R version 4.4.3
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
library(forecast)  # Para modelado ARIMA y pronósticos
## Warning: package 'forecast' was built under R version 4.4.3
library(ggplot2)  # Para visualización de datos
## Warning: package 'ggplot2' was built under R version 4.4.3
library(plotly)  # Para gráficos interactivos
## 
## Adjuntando el paquete: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
library(timetk)   
library(readxl)
data_col <- read_excel("C:/Users/Usuario/Desktop/UNIVERSIDAD/SEMESTRE 1/ANALITICA DE DATOS/modulo 2/PACCIONES COL.xlsx", col_types = c("date", "numeric", "numeric", 
        "numeric", "numeric", "numeric", 
        "numeric", "numeric", "numeric", 
        "numeric"))
## New names:
## • `` -> `...1`
# Extraer la columna VAL
val_ts <- ts(data_col$VAL, start = c(2010, 1), frequency = 12)
# Calcular estadísticas descriptivas básicas
descriptive_stats <- data.frame(
  Min = min(val_ts),
  Max = max(val_ts),
  Media = mean(val_ts),
  Mediana = median(val_ts),
  DesviacionEstandar = sd(val_ts),
  CoefVar = sd(val_ts) / mean(val_ts)
)
print(descriptive_stats)
##     Min      Max    Media  Mediana DesviacionEstandar   CoefVar
## 1 10500 37266.63 26488.17 27553.58           6948.943 0.2623414
# Descomposición de la serie temporal
stl_decomp <- stl(val_ts, s.window = "periodic")

# Convertir la descomposición a un data frame para graficar con ggplot2
stl_df <- data.frame(
  Time = rep(time(val_ts), 4),  # Tiempo repetido para cada componente
  Value = c(stl_decomp$time.series[, "seasonal"], 
            stl_decomp$time.series[, "trend"], 
            stl_decomp$time.series[, "remainder"], 
            val_ts),
  Component = rep(c("Estacional", "Tendencia", "Residuo", "Serie Original"), each = length(val_ts))
)

# Crear gráfico con ggplot2
p <- ggplot(stl_df, aes(x = Time, y = Value, color = Component)) +
  geom_line() +
  facet_wrap(~Component, scales = "free_y", ncol = 1) + 
  theme_minimal() +
  labs(title = "Figura A. Descomposición de la variable VAL",
       x = "Tiempo",
       y = "Valor")

# Convertir a gráfico interactivo con plotly
ggplotly(p)
# Extraer los componentes de la descomposición
val_sa <- val_ts - stl_decomp$time.series[, "seasonal"]

# Crear vector de fechas correctamente alineado con la serie
fechas <- seq.Date(from = as.Date("2010-01-01"), by = "month", length.out = length(val_ts))

# Gráfico mejorado con fechas en el eje X
grafico_ajustada <- ggplot() +
  geom_line(aes(x = fechas, y = val_ts), color = "grey", size = 0.5, linetype = "solid", name = "Serie Original") +
  geom_line(aes(x = fechas, y = val_sa), color = "black", size = 0.6, linetype = "solid", name = "Serie Ajustada") +
  ggtitle("Figura 2. VAL: Serie Original vs Serie Ajustada por Estacionalidad") +
  xlab("Tiempo") +
  ylab("Valor de VAL") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) # Rotar etiquetas para mejor visualización
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
## Warning in geom_line(aes(x = fechas, y = val_ts), color = "grey", size = 0.5, :
## Ignoring unknown parameters: `name`
## Warning in geom_line(aes(x = fechas, y = val_sa), color = "black", size = 0.6,
## : Ignoring unknown parameters: `name`
# Convertir a gráfico interactivo
ggplotly(grafico_ajustada)
## Don't know how to automatically pick scale for object of type <ts>. Defaulting
## to continuous.
# Extraer la tendencia de la descomposición STL
tendencia <- stl_decomp$time.series[, "trend"]

# Gráfico interactivo de la serie original vs tendencia
grafico_tendencia <- ggplot() +
  geom_line(aes(x = fechas, y = val_ts), color = "grey", size = 0.7, linetype = "solid", name = "Serie Original") +
  geom_line(aes(x = fechas, y = tendencia), color = "black", size = 0.8, linetype = "solid", name = "Tendencia") +
  ggtitle("Figura 3. VAL: Serie Original vs Tendencia") +
  xlab("Tiempo") +
  ylab("Valor de VAL") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) # Rotar etiquetas del eje X para mejor visualización
## Warning in geom_line(aes(x = fechas, y = val_ts), color = "grey", size = 0.7, :
## Ignoring unknown parameters: `name`
## Warning in geom_line(aes(x = fechas, y = tendencia), color = "black", size =
## 0.8, : Ignoring unknown parameters: `name`
# Convertir a gráfico interactivo
ggplotly(grafico_tendencia)
## Don't know how to automatically pick scale for object of type <ts>. Defaulting
## to continuous.
# Cálculo de la tasa de crecimiento anual correctamente alineada
tasa_crecimiento <- (val_ts[(13:length(val_ts))] / val_ts[1:(length(val_ts) - 12)] - 1) * 100
tasa_tendencia <- (tendencia[(13:length(tendencia))] / tendencia[1:(length(tendencia) - 12)] - 1) * 100

# Crear vector de fechas corregido
fechas_corregidas <- seq(from = as.Date("2011-01-01"), by = "month", length.out = length(tasa_crecimiento))

# Verificar longitudes
print(length(fechas_corregidas))
## [1] 170
print(length(tasa_crecimiento))
## [1] 170
print(length(tasa_tendencia))
## [1] 170
# Gráfico de la tasa de crecimiento anual
grafico_crecimiento <- ggplot() +
  geom_line(aes(x = fechas_corregidas, y = tasa_crecimiento), color = "grey", size = 0.7) +
  geom_line(aes(x = fechas_corregidas, y = tasa_tendencia), color = "black", size = 0.8, linetype = "dashed") +
  ggtitle("Figura 4. VAL: Tasa de crecimiento anual % de la serie Original vs Tendencia") +
  xlab("Tiempo") +
  ylab("% de Crecimiento Anual") +
  theme_minimal()

# Convertir a gráfico interactivo
ggplotly(grafico_crecimiento)