tasa_de_interes <- read_excel("C:/Users/USUARIO/Downloads/datos panel.xlsx")
summary(tasa_de_interes) 
##    Ciudades              Años      Indice de precios TASA DE INTERES
##  Length:112         Min.   :2016   Min.   : 53.70    Min.   :10.70  
##  Class :character   1st Qu.:2018   1st Qu.: 81.55    1st Qu.:11.54  
##  Mode  :character   Median :2020   Median : 99.30    Median :12.07  
##                     Mean   :2020   Mean   :116.05    Mean   :12.36  
##                     3rd Qu.:2021   3rd Qu.:109.04    3rd Qu.:12.81  
##                     Max.   :2023   Max.   :499.67    Max.   :15.21  
##  VARIACION INFLACIÓN (Año corrido) STOCK DE VIVIENDA (VIS)
##  Min.   : 0.220                    Min.   :  198.0        
##  1st Qu.: 3.170                    1st Qu.:  964.8        
##  Median : 4.510                    Median : 1588.5        
##  Mean   : 5.867                    Mean   : 2809.5        
##  3rd Qu.: 7.490                    3rd Qu.: 3011.8        
##  Max.   :16.340                    Max.   :23357.0        
##  Stock de vivienda (NO VIS) Salario promedio       PIB         
##  Min.   :  219.0            Min.   : 767155   Min.   :  5.000  
##  1st Qu.:  839.5            1st Qu.: 857304   1st Qu.:  7.975  
##  Median : 1425.5            Median : 952903   Median : 13.350  
##  Mean   : 2971.0            Mean   : 974504   Mean   : 34.027  
##  3rd Qu.: 2920.5            3rd Qu.:1040528   3rd Qu.: 43.050  
##  Max.   :22134.0            Max.   :1300606   Max.   :227.100
describe(tasa_de_interes)
##                                   vars   n      mean        sd    median
## Ciudades*                            1 112      7.50      4.05      7.50
## Años                                 2 112   2019.50      2.30   2019.50
## Indice de precios                    3 112    116.05     79.60     99.30
## TASA DE INTERES                      4 112     12.36      1.29     12.07
## VARIACION INFLACIÓN (Año corrido)    5 112      5.87      3.74      4.51
## STOCK DE VIVIENDA (VIS)              6 112   2809.51   3537.05   1588.50
## Stock de vivienda (NO VIS)           7 112   2970.96   4595.93   1425.50
## Salario promedio                     8 112 974503.50 162143.25 952902.50
## PIB                                  9 112     34.03     45.98     13.35
##                                     trimmed       mad       min        max
## Ciudades*                              7.50      5.19      1.00      14.00
## Años                                2019.50      2.97   2016.00    2023.00
## Indice de precios                     97.97     20.75     53.70     499.67
## TASA DE INTERES                       12.21      0.92     10.70      15.21
## VARIACION INFLACIÓN (Año corrido)      5.42      2.64      0.22      16.34
## STOCK DE VIVIENDA (VIS)             2067.24   1074.88    198.00   23357.00
## Stock de vivienda (NO VIS)          1821.18   1199.42    219.00   22134.00
## Salario promedio                  959989.12 159746.44 767155.00 1300606.00
## PIB                                   22.96     10.60      5.00     227.10
##                                       range skew kurtosis       se
## Ciudades*                             13.00 0.00    -1.24     0.38
## Años                                   7.00 0.00    -1.27     0.22
## Indice de precios                    445.96 3.24    10.09     7.52
## TASA DE INTERES                        4.51 1.02     0.36     0.12
## VARIACION INFLACIÓN (Año corrido)     16.12 0.99     0.11     0.35
## STOCK DE VIVIENDA (VIS)            23159.00 3.26    13.05   334.22
## Stock de vivienda (NO VIS)         21915.00 3.02     8.38   434.27
## Salario promedio                  533451.00 0.70    -0.42 15321.10
## PIB                                  222.10 2.52     6.16     4.34
# Selecciona las variables numericas
datos_numericos <- tasa_de_interes[sapply(tasa_de_interes, is.numeric)]

# Tabla completa de estadisticas
describe(datos_numericos)
##                                   vars   n      mean        sd    median
## Años                                 1 112   2019.50      2.30   2019.50
## Indice de precios                    2 112    116.05     79.60     99.30
## TASA DE INTERES                      3 112     12.36      1.29     12.07
## VARIACION INFLACIÓN (Año corrido)    4 112      5.87      3.74      4.51
## STOCK DE VIVIENDA (VIS)              5 112   2809.51   3537.05   1588.50
## Stock de vivienda (NO VIS)           6 112   2970.96   4595.93   1425.50
## Salario promedio                     7 112 974503.50 162143.25 952902.50
## PIB                                  8 112     34.03     45.98     13.35
##                                     trimmed       mad       min        max
## Años                                2019.50      2.97   2016.00    2023.00
## Indice de precios                     97.97     20.75     53.70     499.67
## TASA DE INTERES                       12.21      0.92     10.70      15.21
## VARIACION INFLACIÓN (Año corrido)      5.42      2.64      0.22      16.34
## STOCK DE VIVIENDA (VIS)             2067.24   1074.88    198.00   23357.00
## Stock de vivienda (NO VIS)          1821.18   1199.42    219.00   22134.00
## Salario promedio                  959989.12 159746.44 767155.00 1300606.00
## PIB                                   22.96     10.60      5.00     227.10
##                                       range skew kurtosis       se
## Años                                   7.00 0.00    -1.27     0.22
## Indice de precios                    445.96 3.24    10.09     7.52
## TASA DE INTERES                        4.51 1.02     0.36     0.12
## VARIACION INFLACIÓN (Año corrido)     16.12 0.99     0.11     0.35
## STOCK DE VIVIENDA (VIS)            23159.00 3.26    13.05   334.22
## Stock de vivienda (NO VIS)         21915.00 3.02     8.38   434.27
## Salario promedio                  533451.00 0.70    -0.42 15321.10
## PIB                                  222.10 2.52     6.16     4.34

creamos graficos

#EVOLCUIÓN POR CIUDADES

library(ggplot2)
library(dplyr)
library(patchwork)


g1 <- ggplot(tasa_de_interes, aes(x = Años, y = `Indice de precios`, color = Ciudades, group = Ciudades)) +
  geom_line(size = 1) +
  labs(title = "Índice de Precios por Ciudad", x = "Años", y = "Índice de Precios") +
  theme_minimal() +
  theme(legend.position = "none")
## 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.
g2 <- ggplot(tasa_de_interes, aes(x = Años, y = `STOCK DE VIVIENDA (VIS)`, color = Ciudades, group = Ciudades)) +
  geom_line(size = 1) +
  labs(title = "Stock de Vivienda VIS", x = "Años", y = "Stock VIS") +
  theme_minimal() +
  theme(legend.position = "none")

g3 <- ggplot(tasa_de_interes, aes(x = Años, y = `Stock de vivienda (NO VIS)`, color = Ciudades, group = Ciudades)) +
  geom_line(size = 1) +
  labs(title = "Stock de Vivienda NO VIS", x = "Años", y = "Stock NO VIS") +
  theme_minimal() +
  theme(legend.position = "none")

g4 <- ggplot(tasa_de_interes, aes(x = Años, y = PIB, color = Ciudades, group = Ciudades)) +
  geom_line(size = 1) +
  labs(title = "PIB por Ciudad", x = "Años", y = "PIB") +
  theme_minimal() # ← aquí sí dejamos la leyenda

g5 <- tasa_de_interes %>%
  group_by(Años) %>%
  summarise(inflacion = mean(`VARIACION INFLACIÓN (Año corrido)`, na.rm = TRUE)) %>%
  ggplot(aes(x = Años, y = inflacion)) +
  geom_line(color = "#000", size = 1.2) +
  geom_point(size = 2) +
  labs(title = "Inflación Anual", x = "Años", y = "Inflación") +
  theme_minimal() +
  theme(legend.position = "none")

g6 <- tasa_de_interes %>%
  group_by(Años) %>%
  summarise(tasa = mean(`TASA DE INTERES`, na.rm = TRUE)) %>%
  ggplot(aes(x = Años, y = tasa)) +
  geom_line(color = "#000", size = 1.2) +
  geom_point(size = 2) +
  labs(title = "Tasa de Interés Anual", x = "Años", y = "Tasa de Interés (%)") +
  theme_minimal() +
  theme(legend.position = "none")

g7 <- tasa_de_interes %>%
  group_by(Años) %>%
  summarise(salario = mean(`Salario promedio`, na.rm = TRUE)) %>%
  ggplot(aes(x = Años, y = salario)) +
  geom_line(color = "#000", size = 1.2) +
  geom_point(size = 2) +
  labs(title = "Salario Promedio Anual", x = "Años", y = "Salario") +
  theme_minimal() +
  theme(legend.position = "none")

# Panel organizado y con leyenda global abajo
((g1 | g2 | g3) /
 (g4 | g5 | g6) /
 (g7 + plot_spacer() + plot_spacer())) +
  plot_layout(guides = "collect") &
  theme(legend.position = "bottom")

# BOXPLOT POR CIUDADES

ggplot(tasa_de_interes, aes(x = Ciudades, y = `Indice de precios`)) +
  geom_boxplot(fill = "white", color = "black") +
  labs(title = ,
       x = "Ciudades", y = "Índice de Precios") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

#HETEROGENEIDAD

#heterogeneidad 

# Gráfico por ciudad
g1 <- ggplot(tasa_de_interes, aes(x = Ciudades, y = `Indice de precios`)) +
  stat_summary(fun = mean, geom = "point", color = "black") +
  stat_summary(fun.data = mean_se, geom = "errorbar", width = 0.4, color = "red") +
  stat_summary(fun = mean, geom = "line", aes(group = 1), color = "black") +
  labs(title = ,
       x = "Ciudad", y = "Índice de Precios") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))

# Gráfico por año
g2 <- ggplot(tasa_de_interes, aes(x = Años, y = `Indice de precios`)) +
  stat_summary(fun = mean, geom = "point", color = "black") +
  stat_summary(fun.data = mean_se, geom = "errorbar", width = 0.4, color = "red") +
  stat_summary(fun = mean, geom = "line", aes(group = 1), color = "black") +
  labs(title = ,
       x = "Año", y = "Índice de Precios") +
  theme_minimal()

# Unir los dos gráficos
g1 / g2

#Estimación del modelo

library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ lubridate 1.9.4     ✔ tibble    3.2.1
## ✔ purrr     1.0.4     ✔ tidyr     1.3.1
## ✔ readr     2.1.5     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ psych::%+%()        masks ggplot2::%+%()
## ✖ scales::alpha()     masks psych::alpha(), ggplot2::alpha()
## ✖ plm::between()      masks dplyr::between()
## ✖ readr::col_factor() masks scales::col_factor()
## ✖ purrr::discard()    masks scales::discard()
## ✖ dplyr::filter()     masks stats::filter()
## ✖ plm::lag()          masks dplyr::lag(), stats::lag()
## ✖ plm::lead()         masks dplyr::lead()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(plm)
library(lmtest)
## Cargando paquete requerido: zoo
## 
## Adjuntando el paquete: 'zoo'
## 
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
library(sandwich)

# Transformación de nombres y logaritmos
tasa_de_interes <- tasa_de_interes %>%
  rename_all(~str_replace_all(., " ", "_")) %>%
  rename_all(~str_replace_all(., "\\(", "")) %>%
  rename_all(~str_replace_all(., "\\)", "")) %>%
  rename_all(~str_replace_all(., "\\.", "")) %>%
  mutate(
    log_indice_precios = log(Indice_de_precios),
    log_PIB = log(PIB),
    log_stock_vis = log(STOCK_DE_VIVIENDA_VIS),
    log_stock_no_vis = log(Stock_de_vivienda_NO_VIS)
  )

panel_data <- pdata.frame(tasa_de_interes, index = c("Ciudades", "Años"))

  modelo <- plm(
    log(Indice_de_precios) ~ TASA_DE_INTERES + VARIACION_INFLACIÓN_Año_corrido +
      log(Salario_promedio) + log(PIB) + log(STOCK_DE_VIVIENDA_VIS) + log(Stock_de_vivienda_NO_VIS),
    data = panel_data,
    model = "within"
    
    )
  
  summary(modelo)
## Oneway (individual) effect Within Model
## 
## Call:
## plm(formula = log(Indice_de_precios) ~ TASA_DE_INTERES + VARIACION_INFLACIÓN_Año_corrido + 
##     log(Salario_promedio) + log(PIB) + log(STOCK_DE_VIVIENDA_VIS) + 
##     log(Stock_de_vivienda_NO_VIS), data = panel_data, model = "within")
## 
## Balanced Panel: n = 14, T = 8, N = 112
## 
## Residuals:
##       Min.    1st Qu.     Median    3rd Qu.       Max. 
## -0.2055405 -0.0565683 -0.0034825  0.0604864  0.3581005 
## 
## Coefficients:
##                                   Estimate Std. Error t-value Pr(>|t|)  
## TASA_DE_INTERES                 -0.0056403  0.0109255 -0.5163  0.60692  
## VARIACION_INFLACIÓN_Año_corrido -0.0096086  0.0052085 -1.8448  0.06829 .
## log(Salario_promedio)            0.5338116  0.3100236  1.7218  0.08846 .
## log(PIB)                         0.3887678  0.2902517  1.3394  0.18373  
## log(STOCK_DE_VIVIENDA_VIS)       0.0319864  0.0246011  1.3002  0.19678  
## log(Stock_de_vivienda_NO_VIS)    0.0630368  0.0305449  2.0637  0.04186 *
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Total Sum of Squares:    2.4042
## Residual Sum of Squares: 0.99556
## R-Squared:      0.5859
## Adj. R-Squared: 0.50038
## F-statistic: 21.6947 on 6 and 92 DF, p-value: 9.7248e-16
# Crear un dataframe en formato largo
datos_largos <- tasa_de_interes %>%
  pivot_longer(cols = c(TASA_DE_INTERES,
                        VARIACION_INFLACIÓN_Año_corrido,
                        STOCK_DE_VIVIENDA_VIS,
                        Stock_de_vivienda_NO_VIS,
                        Salario_promedio,
                        PIB),
               names_to = "Variable_Independiente",
               values_to = "Valor_Independiente")

ggplot(datos_largos, aes(x = Valor_Independiente, y = Indice_de_precios)) +
  geom_point(alpha = 0.6, color = "#000") +
  geom_smooth(method = "lm", se = FALSE, linetype = "dashed", color = "red") +
  facet_wrap(~ Variable_Independiente, scales = "free_x") +
  labs(title = ,
       x = "Variable Independiente",
       y = "Índice de Precios") +
  theme_minimal()
## `geom_smooth()` using formula = 'y ~ x'

#ESTIMACIÓN DEL MODELO

library(plm)
library(stargazer)

# Convertir a panel
panel_data <- pdata.frame(panel_data, index = c("Ciudades", "Años"))

# Modelo de efectos fijos
modelo_fe <- plm(log_indice_precios ~ 
                   log_PIB +
                   log_stock_vis +
                   log_stock_no_vis +
                   log(Salario_promedio) +
                   TASA_DE_INTERES +
                   VARIACION_INFLACIÓN_Año_corrido,
                 data = panel_data,
                 model = "within")

# Modelo de efectos aleatorios
modelo_re <- plm(log_indice_precios ~ 
                   log_PIB +
                   log_stock_vis +
                   log_stock_no_vis +
                 log(Salario_promedio) +
                    TASA_DE_INTERES +
                   VARIACION_INFLACIÓN_Año_corrido,
                 data = panel_data,
                 model = "random")

# Mostrar resultados
stargazer(modelo_fe, modelo_re, type = "text", digits = 5,
          title = "Comparación de modelos: Efectos Fijos vs Aleatorios")
## 
## Comparación de modelos: Efectos Fijos vs Aleatorios
## =====================================================================
##                                          Dependent variable:         
##                                 -------------------------------------
##                                          log_indice_precios          
##                                           (1)                (2)     
## ---------------------------------------------------------------------
## log_PIB                                 0.38877           0.21514**  
##                                        (0.29025)          (0.09173)  
##                                                                      
## log_stock_vis                           0.03199            0.03053   
##                                        (0.02460)          (0.02373)  
##                                                                      
## log_stock_no_vis                       0.06304**          0.06666**  
##                                        (0.03054)          (0.02924)  
##                                                                      
## log(Salario_promedio)                   0.53381*          0.70491*** 
##                                        (0.31002)          (0.15324)  
##                                                                      
## TASA_DE_INTERES                         -0.00564           -0.00672  
##                                        (0.01093)          (0.01060)  
##                                                                      
## VARIACION_INFLACIÓN_Año_corrido        -0.00961*          -0.00766*  
##                                        (0.00521)          (0.00402)  
##                                                                      
## Constant                                                 -6.29982*** 
##                                                           (2.13055)  
##                                                                      
## ---------------------------------------------------------------------
## Observations                              112                112     
## R2                                      0.58590            0.57539   
## Adjusted R2                             0.50038            0.55113   
## F Statistic                     21.69471*** (df = 6; 92) 142.28680***
## =====================================================================
## Note:                                     *p<0.1; **p<0.05; ***p<0.01
hausman_test <- phtest(modelo_fe, modelo_re)
print(hausman_test)
## 
##  Hausman Test
## 
## data:  log_indice_precios ~ log_PIB + log_stock_vis + log_stock_no_vis +  ...
## chisq = 0.40884, df = 6, p-value = 0.9988
## alternative hypothesis: one model is inconsistent