R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.

When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

summary(cars)
##      speed           dist       
##  Min.   : 4.0   Min.   :  2.00  
##  1st Qu.:12.0   1st Qu.: 26.00  
##  Median :15.0   Median : 36.00  
##  Mean   :15.4   Mean   : 42.98  
##  3rd Qu.:19.0   3rd Qu.: 56.00  
##  Max.   :25.0   Max.   :120.00

Including Plots

You can also embed plots, for example:

Note that the echo = FALSE parameter was added to the code chunk to prevent printing of the R code that generated the plot.

#Cargar librerías necesarias
library(readxl)  # Para leer archivos Excel
library(tseries)  # Para pruebas de estacionariedad
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
library(forecast)  # Para modelado ARIMA y pronósticos
library(ggplot2)  # Para visualización de datos
library(plotly)  # Para gráficos interactivos
## 
## Attaching package: '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)

# Leer el archivo correctamente
Exports <- read_excel("VALLE MENSUAL.xlsx", 
                      col_types = c("date", rep("numeric", 12)))
# Declarar la serie de tiempo mensual desde enero de 2000 hasta diciembre de 2024
exports_ts <- ts(Exports$X, start = c(2000, 1), frequency = 12)

# Mostrar la serie de tiempo
exports_ts
##            Jan       Feb       Mar       Apr       May       Jun       Jul
## 2000  94017067  75207520 103055607  68771837 115503432  93212178  79829863
## 2001 120796062  91799474 135887029 110075114 121630132 112890368 118052723
## 2002 104669345 106847002  89310637 126806088 136397213  96947475 123614146
## 2003  86004104 128620343  97356815 118448664 115544676  96275575 114631822
## 2004 115081028 130105918 121529154 128209947 106747259 139890621 149503111
## 2005 143474672 142567250 170716508 160438867 179320932 194550488 166019099
## 2006 166425786 147169147 191508096 175692770 202618678 191408299 184085422
## 2007 173897801 184500990 222168479 192494788 204564837 188374246 217487437
## 2008 204140915 211963590 218619498 239065176 241192413 208673717 239839656
## 2009 174039086 208918275 194157246 182119910 165131428 184132928 203790489
## 2010 218987008 189402362 210786855 230940251 187928584 182955428 161570957
## 2011 164892575 156398397 246455505 213019004 199066163 200004310 188535441
## 2012 159599364 180240665 191373990 161232070 198790367 172481442 194364495
## 2013 164853457 169801437 164553704 198509588 175509933 152859086 173179354
## 2014 120373398 156482020 160046060 184237919 178427402 152174190 192817659
## 2015 120882557 176969151 149977104 177977994 162833237 146026274 161483187
## 2016 128740720 189942224 167321121 147770050 150401389 124784925  94999973
## 2017 128273448 148968714 149447316 148640362 145481369 119980457 163823722
## 2018 132657531 160742577 147822277 172354823 143346837 132200919 142668441
## 2019 140010461 136674121 131806958 161263708 149089961 132475371 155450237
## 2020 139829192 135872501 136076573 120039763 135953465 135353513 163518257
## 2021 124798823 138082034 151649690 135855470  49767731  84260164 162444596
## 2022 108843084 144701812 157113802 141342682 130867409 152993170 134477390
## 2023 112288398 139351709 174700489 145292525 176664402 149265232 159393854
## 2024 117345624 140222685 141710961 157220167 161085481 142971963 149111281
##            Aug       Sep       Oct       Nov       Dec
## 2000 108058565 119332914  87513468 122380531 124449940
## 2001 136389612 128404730 106342442 142422419  90709618
## 2002  97470408 143811092 147393019  93337624  80571498
## 2003 124890774 141713748 119652990 123022305 117920345
## 2004 188969440 156323130 146571940 158300020 137939615
## 2005 181414646 193060067 170330774 173997088 163448654
## 2006 188434144 194329146 217972056 218798683 193542898
## 2007 231389870 213354380 243090346 228264672 211976896
## 2008 166149733 190283219 193304375 163413218 179550388
## 2009 146661687 222973057 206701264 189839582 270004417
## 2010 180185822 221983856 198815940 179825202 220061623
## 2011 214977883 197253184 216543940 218063638 254010544
## 2012 202149989 192678930 217124571 182018485 187917021
## 2013 159632675 165283964 186448482 176526791 177119851
## 2014 210298339 200647922 195984020 203404691 172781130
## 2015 143577467 157897446 160756671 164555028 137107036
## 2016 155183649 195113834 222055829 190173966 201443946
## 2017 151509921 170903124 151608899 162331257 148773197
## 2018 168154486 139531023 159544847 163467561 140322064
## 2019 165578025 154506012 170845927 150933116 140487586
## 2020 153355466 169110909 158758029 155184516 171559349
## 2021 150574146 142640911 130498956 163384065 168378320
## 2022 144420197 137914582 141911619 161517130 162774116
## 2023 167957125 155852975 168219469 150665774 142357816
## 2024 148585302 154743385 180276265 153499206 172084853
# Calcular estadísticas descriptivas básicas
descriptive_stats <- data.frame(
  Min = min(exports_ts),
  Max = max(exports_ts),
  Media = mean(exports_ts),
  Mediana = median(exports_ts),
  DesviacionEstandar = sd(exports_ts),
  CoefVar = sd(exports_ts) / mean(exports_ts)
)
print(descriptive_stats)
##        Min       Max     Media   Mediana DesviacionEstandar   CoefVar
## 1 49767731 270004417 159652155 159469350           36817513 0.2306108
# Cargar librerías necesarias
library(ggplot2)
library(plotly)

# Crear columna de fechas si aún no existe
Exports$Fecha <- seq.Date(from = as.Date("2000-01-01"), by = "month", length.out = nrow(Exports))

# Graficar serie de tiempo
grafico_serie <- ggplot(Exports, aes(x = Fecha, y = exports_ts)) +
  geom_line(color = "grey", size = 0.4) +
  geom_point(color = "black", size = 0.7) +  # Ajusté el tamaño del punto para mayor visibilidad
  ggtitle("Figura 1. Evolución de las exportaciones en Cali") +
  xlab("Tiempo") +
  ylab("Exportaciones (USD)") +
  theme_minimal()
## 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.
# Convertir a gráfico interactivo
ggplotly(grafico_serie)
## Don't know how to automatically pick scale for object of type <ts>. Defaulting
## to continuous.
# Cargar librerías necesarias
library(ggplot2)
library(plotly)
library(scales)  # Para formatear el eje Y

# Crear columna de fechas si aún no existe
Exports$Fecha <- seq.Date(from = as.Date("2000-01-01"), by = "month", length.out = nrow(Exports))

# Graficar serie de tiempo con ajustes en los ejes
grafico_serie <- ggplot(Exports, aes(x = Fecha, y = exports_ts / 1e6)) +  # Convertir a millones
  geom_line(color = "grey", size = 0.4) +
  geom_point(color = "black", size = 0.7) +  
  ggtitle("Figura 1. Evolución de las exportaciones en Cali") +
  xlab("Tiempo") +
  ylab("Exportaciones (Millones de USD)") +
  scale_x_date(date_breaks = "5 years", date_labels = "%Y") +  # Etiquetas cada 5 años
  scale_y_continuous(labels = label_number(scale_cut = cut_short_scale())) +  # Formato en millones
  theme_minimal()

# Convertir a gráfico interactivo
ggplotly(grafico_serie)
# Cargar librerías necesarias
library(ggplot2)
library(plotly)

# Convertir exports_ts a un objeto de serie de tiempo si aún no lo es
if (!inherits(exports_ts, "ts")) {
  exports_ts <- ts(Exports$exports_ts, start = c(2000, 1), frequency = 12)  
}

# Descomposición de la serie temporal
stl_decomp <- stl(exports_ts, s.window = "periodic")

# Crear un data frame para graficar
stl_df <- data.frame(
  Time = rep(time(exports_ts), 4),  # Repetir los valores de tiempo para cada componente
  Value = c(stl_decomp$time.series[, "seasonal"], 
            stl_decomp$time.series[, "trend"], 
            stl_decomp$time.series[, "remainder"], 
            exports_ts),  # Usamos exports_ts como la serie original
  Component = rep(c("Estacional", "Tendencia", "Residuo", "Serie Original"), each = length(exports_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 del valor de las exportaciones en Cali",
       x = "Tiempo",
       y = "Valor")

# Convertir a gráfico interactivo con plotly
ggplotly(p)
# Cargar librerías necesarias
library(ggplot2)
library(plotly)

# Verificar que la columna de fechas existe
if (!"Fecha" %in% colnames(Exports)) {
  Exports$Fecha <- seq.Date(from = as.Date("2000-01-01"), by = "month", length.out = nrow(Exports))
}

# Crear la serie de tiempo con todos los años disponibles
exports_ts <- ts(Exports$X, start = c(2000, 1), frequency = 12)  

# Descomposición de la serie temporal
stl_decomp <- stl(exports_ts, s.window = "periodic")

# Extraer los componentes de la descomposición
exports_sea <- exports_ts - stl_decomp$time.series[, "seasonal"]
# Crear vector de fechas correctamente alineado con la serie
fechas <- seq.Date(from = as.Date("2000-01-01"), by = "month", length.out = length(exports_ts))

# Crear data frame para ggplot
df_grafico <- data.frame(
  Fecha = rep(fechas, 2),  
  Exportaciones = c(exports_ts, exports_sea),  
  Tipo = rep(c("Serie Original", "Serie Ajustada"), each = length(exports_ts))
)

# Gráfico mejorado con fechas en el eje X
grafico_ajustada <- ggplot(df_grafico, aes(x = Fecha, y = Exportaciones, color = Tipo)) +
  geom_line(size = 0.6) +
  ggtitle("Figura 2. Exportaciones: Serie Original vs Serie Ajustada por Estacionalidad") +
  xlab("Tiempo") +
  ylab("Exportaciones (USD)") +
  scale_color_manual(values = c("grey", "black")) +  # Definir colores manualmente
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))  # Rotar etiquetas para mejor visualización

# Convertir a gráfico interactivo
ggplotly(grafico_ajustada)
# Crear vector de fechas correctamente alineado con la serie
fechas <- seq.Date(from = as.Date("2000-01-01"), by = "month", length.out = length(exports_ts))

# Crear data frame para ggplot
df_grafico <- data.frame(
  Fecha = rep(fechas, 2),  
  Exportaciones = c(exports_ts, exports_sea) / 1e6,  # Convertir a millones de USD
  Tipo = rep(c("Serie Original", "Serie Ajustada"), each = length(exports_ts))
)

# Gráfico mejorado con fechas en el eje X
grafico_ajustada <- ggplot(df_grafico, aes(x = Fecha, y = Exportaciones, color = Tipo)) +
  geom_line(size = 0.6) +
  ggtitle("Figura 2. Exportaciones: Serie Original vs Serie Ajustada por Estacionalidad") +
  xlab("Tiempo") +
  ylab("Exportaciones (Millones de USD)") +  # Ajuste de la unidad
  scale_color_manual(values = c("grey", "black")) +  # Definir colores manualmente
  scale_y_continuous(labels = scales::label_number(scale_cut = cut_short_scale())) +  # Mejor formato en millones
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))  # Rotar etiquetas para mejor visualización

# Convertir a gráfico interactivo
ggplotly(grafico_ajustada)
# 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 = exports_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. Exportaciones:Serie Original vs Tendencia") +
  xlab("Tiempo") +
  ylab("Exportaciones USD") +
  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 = exports_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.
# Extraer la tendencia de la descomposición STL
tendencia <- stl_decomp$time.series[, "trend"]

# Gráfico interactivo de la serie original vs tendencia (en millones de USD)
grafico_tendencia <- ggplot() +
  geom_line(aes(x = fechas, y = exports_ts / 1e6), color = "grey", size = 0.7, linetype = "solid") +  # Serie Original
  geom_line(aes(x = fechas, y = tendencia / 1e6), color = "black", size = 0.8, linetype = "solid") +  # Tendencia
  ggtitle("Figura 3. Exportaciones: Serie Original vs Tendencia") +
  xlab("Tiempo") +
  ylab("Exportaciones (Millones USD)") +  # Escala corregida
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))  # Rotar etiquetas del eje X para mejor visualización

# Convertir a gráfico interactivo
ggplotly(grafico_tendencia)
## Don't know how to automatically pick scale for object of type <ts>. Defaulting
## to continuous.
# Cargar librerías necesarias
library(ggplot2)
library(plotly)

# Cálculo de la tasa de crecimiento anual correctamente alineada
tasa_crecimiento <- (exports_ts[13:length(exports_ts)] / exports_ts[1:(length(exports_ts) - 12)] - 1) * 100
tasa_tendencia <- (tendencia[13:length(tendencia)] / tendencia[1:(length(tendencia) - 12)] - 1) * 100

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

# Verificar longitudes
print(length(fechas_corregidas))
## [1] 288
print(length(tasa_crecimiento))
## [1] 288
print(length(tasa_tendencia))
## [1] 288
# 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. Exportaciones: 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)
# Definir la fecha de inicio para los últimos 5 años
fecha_inicio <- as.Date("2020-01-01")

# Filtrar datos de los últimos 5 años
datos_ultimos5 <- data.frame(
  Fecha = fechas_corregidas,
  Crecimiento = tasa_crecimiento,
  Tendencia = tasa_tendencia
) %>%
  filter(Fecha >= fecha_inicio)

# Gráfico de la tasa de crecimiento anual (últimos 5 años)
grafico_crecimiento <- ggplot(datos_ultimos5) +
  geom_line(aes(x = Fecha, y = Crecimiento), color = "grey", size = 0.7) +
  geom_line(aes(x = Fecha, y = Tendencia), color = "black", size = 0.8, linetype = "dashed") +
  ggtitle("Figura 4. Exportaciones: Tasa de Crecimiento Anual (%) - Últimos 5 años") +
  xlab("Tiempo") +
  ylab("% de Crecimiento Anual") +
  scale_x_date(date_breaks = "1 year", date_labels = "%Y") +  # Etiquetas cada año
  theme_minimal()

# Convertir a gráfico interactivo
ggplotly(grafico_crecimiento)