Universidad de El Salvador

Facultad de Ciencias Económicas

Métodos para el análisis Económico

Lic. Jefrry Isaac Bonilla Melara

API’s de datos económicos Fondo Monetario Internacional

Integrantes:

  • Laura Lissete Flores Ayala
  • Miguel Ángel López Ayala
  • Stephany lourdes García Cárcamo
  • Victor Daniel Genovez Recinos
  • Katherine Gabriela Miranda Marcia
  • Christopher Eduardo Portillo Portillo

Introducción

En la actualidad, el análisis económico y político depende cada vez más del acceso a grandes cantidades de información estadística. Indicadores como el crecimiento económico, la inflación, el desempleo, la deuda pública, el déficit fiscal, las reservas internacionales y el comercio exterior permiten estudiar la situación de los países y comprender los cambios que ocurren en sus economías.

Sin embargo, para realizar este tipo de análisis no basta con que los datos existan: también es necesario contar con mecanismos que permitan acceder a ellos, organizarlos, actualizarlos y utilizarlos de manera eficiente.

En este contexto adquieren importancia las API (Application Programming Interfaces o Interfaces de Programación de Aplicaciones). Una API permite que dos componentes de software se comuniquen entre sí mediante un conjunto definido de reglas, protocolos, solicitudes y respuestas.

En el ámbito económico, las API permiten conectar programas estadísticos y herramientas de análisis con bases de datos institucionales. Un ejemplo es la API de datos del Fondo Monetario Internacional (FMI), que permite importar datos disponibles en su plataforma hacia sistemas y aplicaciones externas.

Por ello, el uso de APIs representa una herramienta importante para la investigación económica y política, ya que facilita el acceso a información internacional, las comparaciones entre países, los análisis estadísticos y los modelos econométricos.

1. ¿Qué es una API?

Una API, cuyo significado es Application Programming Interface o Interfaz de Programación de Aplicaciones, es un mecanismo que permite que dos componentes de software se comuniquen entre sí siguiendo determinadas reglas y protocolos.

En términos sencillos, funciona como un intermediario que permite que un programa solicite información o servicios a otro programa.

Cliente → Solicitud → API / Servidor → Procesamiento → Respuesta

Por ejemplo, un programa estadístico puede solicitar mediante una API determinados datos económicos de un país. El servidor recibe la solicitud, identifica la información solicitada y devuelve los datos en un formato que el programa puede interpretar.

Una característica importante es que el investigador no necesita acceder manualmente a la base de datos cada vez que necesita información. El programa puede realizar las solicitudes automáticamente, permitiendo obtener datos de manera rápida y sistemática.

En el análisis económico, esto permite conectar herramientas como R, Python o Stata con fuentes estadísticas institucionales y utilizar los datos directamente en los análisis.

1.2. Tipos de API

Las API pueden clasificarse de diferentes maneras según la forma en que se establece la comunicación entre las aplicaciones.

Tipo de API Característica principal Utilidad
SOAP Utiliza mensajes estructurados, generalmente mediante XML. Sistemas empresariales y servicios con estructuras formales.
RPC Permite solicitar la ejecución de una función o procedimiento remoto. Ejecución de operaciones específicas en otro servidor.
WebSocket Permite comunicación bidireccional entre cliente y servidor. Aplicaciones que requieren información constante o en tiempo real.
REST Utiliza principalmente HTTP y permite realizar diferentes operaciones. Servicios web y acceso flexible a información.

API SOAP

Las API SOAP (Simple Object Access Protocol) utilizan mensajes estructurados generalmente mediante XML para establecer la comunicación entre el cliente y el servidor.

Se caracterizan por tener una estructura formal y rígida y fueron utilizadas ampliamente en determinados sistemas empresariales y servicios web.

API RPC

Las API RPC (Remote Procedure Call) permiten que un cliente solicite la ejecución de una función o procedimiento localizado en otro servidor.

El servidor ejecuta la operación solicitada y devuelve el resultado al cliente.

API WebSocket

Las WebSocket API permiten una comunicación bidireccional entre cliente y servidor.

Esto significa que no solamente el cliente puede enviar solicitudes, sino que el servidor también puede enviar información al cliente cuando sea necesario.

Este tipo de comunicación resulta útil cuando se necesitan actualizaciones constantes o información prácticamente en tiempo real.

API REST

Las API REST (Representational State Transfer) son unas de las más utilizadas en la web debido a su flexibilidad.

Utilizan principalmente el protocolo HTTP y permiten realizar diferentes operaciones mediante métodos como GET, PUT y DELETE.

Una característica fundamental de REST es que funciona de manera stateless o sin estado, es decir, el servidor no necesita conservar información del cliente entre una solicitud y otra.

Para el análisis económico, este concepto es especialmente relevante porque muchas bases de datos estadísticas modernas proporcionan información mediante servicios web y APIs que pueden ser consultados desde programas de análisis.

1.3. Características de las API

Característica Descripción
Acceso estructurado Permite obtener información de acuerdo con países, indicadores y períodos.
Automatización Reduce la necesidad de recopilar información manualmente.
Integración Permite conectar diferentes programas y sistemas.
Actualización Facilita la incorporación de nuevos datos.
Seguridad Puede utilizar mecanismos como claves, tokens y autenticación.
Reproducibilidad Permite repetir las consultas y procesos de obtención de datos.

1.4 Importancia del uso de las API

El uso de las API es importante porque permite automatizar y mejorar el acceso a la información.

En un contexto donde las instituciones generan grandes cantidades de datos, las API permiten conectar directamente las herramientas de investigación con fuentes de información estadística.

Principales aportes

  • Acceso rápido a grandes cantidades de información.
  • Automatización de la extracción de datos.
  • Actualización de bases de datos.
  • Comparación de información entre países.
  • Integración con programas como R y Python.
  • Reducción del trabajo manual.
  • Mayor reproducibilidad de las investigaciones.

1.5 La API del FMI

La API del Fondo Monetario Internacional (FMI) permite acceder de manera programática a información económica y financiera proporcionada por esta institución.

Actualmente, el FMI permite acceder a sus datos mediante APIs basadas en los estándares SDMX 2.1 y SDMX 3.0, utilizados para facilitar el intercambio de información estadística.

Además, el FMI cuenta con DataMapper API, que permite consultar indicadores, países, regiones y series temporales.

Estas herramientas facilitan el uso de información internacional en programas estadísticos y econométricos.

1.6 Limitaciones de la API del FMI

Limitación Descripción
Dependencia de los datos disponibles La API solamente proporciona los datos disponibles en las bases del FMI.
Actualización de la información Los datos pueden ser revisados debido a nuevas estimaciones o cambios metodológicos.
Complejidad técnica Se requieren conocimientos sobre programación y estructuras de consulta.
Diferencias metodológicas Los datos de diferentes países pueden presentar diferencias de medición.
Interpretación política Los datos cuantitativos no explican por sí solos las causas políticas o sociales.

1.7. Ventajas de las API en el análisis económico y político

Ventaja Aplicación
Acceso rápido Permite obtener grandes cantidades de información.
Automatización Facilita la extracción y procesamiento de datos.
Actualización Permite incorporar nuevos datos y revisiones.
Comparación internacional Facilita el análisis entre diferentes países.
Integración Puede utilizarse con R, Python, MATLAB y Stata.
Reproducibilidad Permite documentar y repetir las consultas.

1.8 Desventajas de las API en el análisis económico y político

  • Requieren conocimientos técnicos.
  • Pueden producir errores si la consulta está mal especificada.
  • Existe dependencia de la fuente de información.
  • Los datos no sustituyen la interpretación económica y política.
  • Existe riesgo de utilizar incorrectamente los indicadores.
  • Los cambios en la estructura de una API pueden afectar las investigaciones.

1.9 Importancia de la API del FMI para el análisis económico y político

La API del FMI es relevante porque permite trabajar con información económica internacional de manera estructurada y facilita su incorporación a diferentes análisis.

Aplicaciones en el análisis económico

Área Ejemplos de análisis
Crecimiento económico Evolución de la producción y actividad económica.
Inflación Comportamiento de los precios.
Deuda pública Evolución y sostenibilidad de la deuda.
Finanzas públicas Ingresos, gastos y déficit fiscal.
Balanza de pagos Relaciones económicas con el exterior.
Desempleo Situación y evolución del mercado laboral.

PARTE PRÁCTICA

Aplicación de la API del FMI

Después de conocer los conceptos fundamentales sobre las API y su importancia para el análisis económico, en esta sección se procederá a utilizar la API del Fondo Monetario Internacional (FMI) mediante el lenguaje de programación R.

La práctica permitirá consultar los datasets disponibles, explorar su estructura y posteriormente obtener información económica para realizar diferentes ejercicios de análisis.

2. Instalacion de paquetes (Ejecutar solo una vez si no están instalados)

# install.packages("imf.data")
# install.packages("dplyr")
# install.packages("knitr")
# install.packages("kableExtra")

3. Carga de librerias

library(imf.data)   # conexión y descarga desde la API SDMX 3.0 del FMI
library(dplyr)       # manipulación de datos
library(tidyr)       # pivot_wider para pasar de formato largo a ancho
library(stringr)     # búsqueda de texto en los codelists (paso de verificación)
library(ggplot2)     # gráficos
library(scales)      # formato de ejes
library(knitr)        # tablas (kable)
library(kableExtra)

4. Acceso a la API del Fondo Monetario Internacional

4.1 Exploracion de agencias en el FMI

Para acceder a la información disponible en la API del Fondo Monetario Internacional (FMI), se utiliza la librería imf.data de R. Esta herramienta permite consultar los diferentes datasets disponibles en la API y conocer la estructura y dimensiones de cada uno de ellos.

En primer lugar, se utiliza la función list_datasets() para obtener los datasets disponibles en la API del FMI. Posteriormente, se muestran los primeros 20 resultados mediante una tabla para facilitar su visualización.

Una vez identificado el dataset de interés, se puede utilizar la función list_dimensions() para conocer sus dimensiones. En este caso, se selecciona el dataset CPI, correspondiente al Índice de Precios al Consumidor, con el propósito de identificar la información y categorías disponibles dentro de este conjunto de datos.

La consulta de estos datasets permite conocer previamente la estructura de la información antes de realizar la extracción y el análisis de los datos. La documentación de la librería imf.data puede consultarse en la guía disponible en CRAN (FMI, n.d.).

funciones_imf <- ls("package:imf.data")


# Obtener TODOS los datasets disponibles en la API del FMI
todos_los_datasets <- list_datasets()

# Ver las agencias emisoras disponibles
agencias_disponibles <- unique(todos_los_datasets$agency)

# Mostrar las agencias
print(agencias_disponibles)
##  [1] "IMF.AFR" "IMF.APD" "IMF.FAD" "IMF.MCD" "IMF.MCM" "IMF.RES" "IMF.SPR"
##  [8] "IMF.STA" "IMF.WHD" "ISORA"

4.2 Obtencion y filtrado de datasets

# Obtener los datasets de las agencias IMF.STA e IMF.RES
Datasets_IMF_STA <- list_datasets("IMF.STA")
Datasets_IMF_RES <- list_datasets("IMF.RES")

# Unir ambas agencias
Datasets_IMF <- bind_rows(Datasets_IMF_STA, Datasets_IMF_RES)
Datasets_IMF %>% 
  head(10) %>% 
  kable(caption = "Datasets disponibles en la API del IMF (Agencias IMF.STA e IMF.RES)") %>% 
  kable_classic(html_font = "Times New Roman", font_size = 14) %>% 
  add_footnote(label = "Tomado de la API del IMF", notation = "symbol") %>% 
  kable_styling()
Datasets disponibles en la API del IMF (Agencias IMF.STA e IMF.RES)
agency id version name description dsd_id
IMF.STA AEA 7.0.0 Air Emissions Accounts (AEA) Annual and quarterly greenhouse gas emissions by activity and by country and region. Regional estimates are presented by industry and household for four gases - carbon dioxide, methane, nitrous oxide, and F-gases. The F-gases constitute of hydrofluorocarbons, perfluorocarbons, sulfur hexafluoride and nitrogen trifluoride. Emissions are presented in Million metric tons of CO2 equivalent (MTCO2e). DSD_AEA
IMF.STA ANEA 6.0.1 National Economic Accounts (NEA), Annual Data This dataset presents national, official estimates of annual expenditure-based Gross Domestic Product (GDP), by economy. Estimates are presented in nominal terms (current prices) and volume terms (with the effect of price changes removed). DSD_ANEA
IMF.STA ANEA_2026_APR_VINTAGE 1.0.0 National Economic Accounts (NEA), Annual Data 2026 April National Economic Accounts (NEA), Annual Data 2026 April DSD_ANEA_VINTAGE
IMF.STA ANEA_2026_FEB_VINTAGE 1.0.0 National Economic Accounts (NEA), Annual Data 2026 February National Economic Accounts (NEA), Annual Data 2026 February DSD_ANEA_VINTAGE
IMF.STA ANEA_2026_JAN_VINTAGE 1.0.0 National Economic Accounts (NEA), Annual Data 2026 January National Economic Accounts (NEA), Annual Data 2026 January DSD_ANEA_VINTAGE
IMF.STA ANEA_2026_MAY_VINTAGE 1.0.0 National Economic Accounts (NEA), Annual Data 2026 May National Economic Accounts (NEA), Annual Data 2026 May DSD_ANEA_VINTAGE
IMF.STA BOP 21.0.0 Balance of Payments (BOP) The Balance of Payments (BOP) is a statistical statement that summarizes transactions between residents and nonresidents during a period. It consists of the goods and services account, the primary income account, the secondary income account, the capital account, and the financial account. DSD_BOP
IMF.STA BOP_2026_APR_VINTAGE 1.0.0 Balance of Payments (BOP) 2026 April Balance of Payments (BOP) 2026 April DSD_BOP_VINTAGE
IMF.STA BOP_2026_FEB_VINTAGE 1.0.0 Balance of Payments (BOP) 2026 February Balance of Payments (BOP) 2026 February DSD_BOP_VINTAGE
IMF.STA BOP_2026_JAN_VINTAGE 1.0.0 Balance of Payments (BOP) 2026 January Balance of Payments (BOP) 2026 January DSD_BOP_VINTAGE
* Tomado de la API del IMF

5 EJEMPLOS DATASET BOP

En este apartado se datalla mas ejemplos del uso de BOP

5.1 Balanza de Pagos (BOP)

El dataset BOP (Balance of Payments) de la API del FMI, perteneciente a la agencia IMF.STA, contiene información sobre las transacciones económicas de un país con el resto del mundo. Permite analizar aspectos como la cuenta corriente, de capital y financiera. Para este trabajo se utiliza El Salvador (SLV), con frecuencia anual, unidad en dólares estadounidenses (USD) y un período de análisis de 2010–2024.

5.2 Información general del dataset BOP

datasets_bop <- list_datasets(agency_id = "IMF.STA")

info_bop <- datasets_bop %>%
  filter(id == "BOP")

# Comprobación de los dos requisitos principales:
# Agencia = IMF.STA
# ID = BOP
cat("Agencia:", "IMF.STA", "\n")
## Agencia: IMF.STA
info_bop %>%
  kable(
    caption = "Información general del dataset BOP"
  ) %>%
  kable_classic(
    html_font = "Times New Roman",
    font_size = 15
  ) %>%
  kable_styling(full_width = FALSE)
Información general del dataset BOP
agency id version name description dsd_id
IMF.STA BOP 21.0.0 Balance of Payments (BOP) The Balance of Payments (BOP) is a statistical statement that summarizes transactions between residents and nonresidents during a period. It consists of the goods and services account, the primary income account, the secondary income account, the capital account, and the financial account. DSD_BOP

5.3 Ver valores validos para cada dimencion

dimensiones_bop <- list_dimensions(
  "BOP",
  agency_id = "IMF.STA"
)

dimensiones_bop
## # A tibble: 6 × 7
##   position id           type  name  codelist_agency codelist_id codelist_version
##      <int> <chr>        <chr> <chr> <chr>           <chr>       <chr>           
## 1        0 COUNTRY      Dime… Coun… IMF.STA         CL_BOP_COU… 1.0+.0          
## 2        1 BOP_ACCOUNT… Dime… BOP/… IMF.STA         CL_BOP_ACC… 3.0+.0          
## 3        2 INDICATOR    Dime… Indi… IMF.STA         CL_BOP_IND… 10.0+.0         
## 4        3 UNIT         Dime… Unit… IMF             CL_UNIT     2.0+.0          
## 5        4 FREQUENCY    Dime… FREQ… <NA>            <NA>        <NA>            
## 6        5 TIME_PERIOD  Time… TIME… <NA>            <NA>        <NA>
indicadores_bop <- list_dimension_values(
  "BOP",
  "INDICATOR",
  agency_id = "IMF.STA"
)

indicadores_bop %>%
  head(10) %>%
  kable(
    caption = "Primeros indicadores disponibles en BOP"
  ) %>%
  kable_classic(
    html_font = "Times New Roman",
    font_size = 15
  )
Primeros indicadores disponibles en BOP
code name description
ANPNFA Acquisitions nonproduced nonfinancial assets Acquisitions nonproduced nonfinancial assets.
CAB Current account balance (credit less debit) The current account balance is the balance of current transactions (transactions in goods and services, earned income and transfer income) between residents and non-residents. The term current account balance is used in the external accounts and is expressed from the perspective of resident units. The term current external balance is used in the national accounts and is expressed from the perspective of the non-resident units, and therefore with the opposite sign.
CABXEF Current account balance excluding exceptional financing Current account balance excluding exceptional financing.
CKAB Current and capital account balance (credit less debit) The combined balance of the current and capital accounts, reflecting the net flow of goods, services, income, and transfers, as well as capital transactions.
D1 Compensation of employees Payments to employees for their work, including wages, salaries, and benefits.
D1_F3 Direct investor in direct invesment enterprises, Debt securities An investor that makes direct investment in enterprises, having control or significant influence. Tradable financial instruments representing a debt, such as bonds and notes.
D1_F5A Direct investor in direct invesment enterprises, Equity and investment fund shares/units: other than reinvestment of earnings An investor that makes direct investment in enterprises, having control or significant influence. Equity and investment fund shares/units excluding those acquired through the reinvestment of earnings.
D1_F5_D42S Direct investor in direct invesment enterprises, Equity and investment fund shares, Investment income on dividends and withdrawals from income of quasi corporations and income distributed to investment fund shareholders (excluding RIE) An investor that makes direct investment in enterprises, having control or significant influence. Ownership interest in companies (equity) and shares in investment funds. Total income distributions, including dividends and withdrawals from quasi-corporations and income distributed to investment fund shareholders, excluding reverse investment.
D1_FL Direct investor in direct invesment enterprises, Debt instruments An investor that makes direct investment in enterprises, having control or significant influence. Debt instruments are financial instruments that require the payment of principal and/or interest at some point(s) in the future. Debt instruments consist of SDRs, currency and deposits, debt securities, loans, insurance technical reserves, pension and related entitlements, provision for calls under standardized guarantees, and other accounts receivable/payable.
D1_FL_D4Q Direct investor in direct invesment enterprises, Debt instruments, Investment income on interest and income attributable to policy holders An investor that makes direct investment in enterprises, having control or significant influence. Debt instruments are financial instruments that require the payment of principal and/or interest at some point(s) in the future. Debt instruments consist of SDRs, currency and deposits, debt securities, loans, insurance technical reserves, pension and related entitlements, provision for calls under standardized guarantees, and other accounts receivable/payable. Interest and income attributable to policy holders

5.4 Cuenta corrriente El Salvador

datos_BOP <- get_data(
  "BOP",
  agency_id = "IMF.STA",
  filters = list(
    COUNTRY   = "SLV",
    FREQUENCY = "A",
    INDICATOR = "CAB"
  )
)

nrow(datos_BOP)
## [1] 50
head(datos_BOP)
## # A tibble: 6 × 7
##   COUNTRY BOP_ACCOUNTING_ENTRY INDICATOR UNIT  FREQUENCY TIME_PERIOD   OBS_VALUE
##   <chr>   <chr>                <chr>     <chr> <chr>     <chr>             <dbl>
## 1 SLV     NETCD_T              CAB       USD   A         1976          23640000.
## 2 SLV     NETCD_T              CAB       USD   A         1977          37360000.
## 3 SLV     NETCD_T              CAB       USD   A         1978        -278720000 
## 4 SLV     NETCD_T              CAB       USD   A         1979          32240000 
## 5 SLV     NETCD_T              CAB       USD   A         1980          33920000.
## 6 SLV     NETCD_T              CAB       USD   A         1981        -250520000
cuenta_corriente_SLV <- datos_BOP %>%
  mutate(
    TIME_PERIOD = as.numeric(TIME_PERIOD),
    OBS_VALUE = as.numeric(OBS_VALUE)
  ) %>%
  filter(
    TIME_PERIOD >= 2010,
    TIME_PERIOD <= 2024
  )

cuenta_corriente_SLV %>%
  select(
    COUNTRY,
    INDICATOR,
    TIME_PERIOD,
    OBS_VALUE
  ) %>%
  kable(
    caption = "El Salvador: saldo de la cuenta corriente, 2010–2024"
  ) %>%
  kable_classic(
    html_font = "Times New Roman",
    font_size = 15
  ) %>%
  kable_styling(full_width = FALSE)
El Salvador: saldo de la cuenta corriente, 2010–2024
COUNTRY INDICATOR TIME_PERIOD OBS_VALUE
SLV CAB 2010 -532815819
SLV CAB 2011 -1111764528
SLV CAB 2012 -1239801103
SLV CAB 2013 -1518420127
SLV CAB 2014 -1213582708
SLV CAB 2015 -753757240
SLV CAB 2016 -550121069
SLV CAB 2017 -464589787
SLV CAB 2018 -859154621
SLV CAB 2019 -113356041
SLV CAB 2020 276701043
SLV CAB 2021 -1250461218
SLV CAB 2022 -2143721477
SLV CAB 2023 -584682906
SLV CAB 2024 -964417195
ggplot(
  cuenta_corriente_SLV,
  aes(
    x = TIME_PERIOD,
    y = OBS_VALUE
  )
) +
  geom_line(linewidth = 1) +
  geom_point(size = 2) +
  labs(
    title = "El Salvador: saldo de la cuenta corriente",
    subtitle = "BOP / IMF.STA, 2010–2024",
    x = "Año",
    y = "Millones de USD"
  ) +
  theme_minimal()

5.5 Cuenta Financiera

indicadores_financieros <- indicadores_bop %>%
  filter(
    grepl(
      "investment|financial|derivative|reserve",
      name,
      ignore.case = TRUE
    )
  ) %>%
  head(10)

indicadores_financieros %>%
  kable(
    caption = "Indicadores financieros disponibles en BOP"
  ) %>%
  kable_classic(
    html_font = "Times New Roman",
    font_size = 15
  )
Indicadores financieros disponibles en BOP
code name description
ANPNFA Acquisitions nonproduced nonfinancial assets Acquisitions nonproduced nonfinancial assets.
D1_F5A Direct investor in direct invesment enterprises, Equity and investment fund shares/units: other than reinvestment of earnings An investor that makes direct investment in enterprises, having control or significant influence. Equity and investment fund shares/units excluding those acquired through the reinvestment of earnings.
D1_F5_D42S Direct investor in direct invesment enterprises, Equity and investment fund shares, Investment income on dividends and withdrawals from income of quasi corporations and income distributed to investment fund shareholders (excluding RIE) An investor that makes direct investment in enterprises, having control or significant influence. Ownership interest in companies (equity) and shares in investment funds. Total income distributions, including dividends and withdrawals from quasi-corporations and income distributed to investment fund shareholders, excluding reverse investment.
D1_FL_D4Q Direct investor in direct invesment enterprises, Debt instruments, Investment income on interest and income attributable to policy holders An investor that makes direct investment in enterprises, having control or significant influence. Debt instruments are financial instruments that require the payment of principal and/or interest at some point(s) in the future. Debt instruments consist of SDRs, currency and deposits, debt securities, loans, insurance technical reserves, pension and related entitlements, provision for calls under standardized guarantees, and other accounts receivable/payable. Interest and income attributable to policy holders
D2_F3 Direct investment enterprises in direct investor, Debt securities Enterprises in which direct investment is made by the investor. Tradable financial instruments representing a debt, such as bonds and notes.
D2_F5A Direct investment enterprises in direct investor, Equity and investment fund shares/units: other than reinvestment of earnings Enterprises in which direct investment is made by the investor. Equity and investment fund shares/units excluding those acquired through the reinvestment of earnings.
D2_F5_D42S Direct investment enterprises in direct investor, Equity and investment fund shares, Investment income on dividends and withdrawals from income of quasi corporations and income distributed to investment fund shareholders (excluding RIE) Enterprises in which direct investment is made by the investor. Ownership interest in companies (equity) and shares in investment funds. Total income distributions, including dividends and withdrawals from quasi-corporations and income distributed to investment fund shareholders, excluding reverse investment.
D2_FL Direct investment enterprises in direct investor, Debt instruments Enterprises in which direct investment is made by the investor. Debt instruments are financial instruments that require the payment of principal and/or interest at some point(s) in the future. Debt instruments consist of SDRs, currency and deposits, debt securities, loans, insurance technical reserves, pension and related entitlements, provision for calls under standardized guarantees, and other accounts receivable/payable.
D2_FL_D4Q Direct investment enterprises in direct investor, Debt instruments, Investment income on interest and income attributable to policy holders Enterprises in which direct investment is made by the investor. Debt instruments are financial instruments that require the payment of principal and/or interest at some point(s) in the future. Debt instruments consist of SDRs, currency and deposits, debt securities, loans, insurance technical reserves, pension and related entitlements, provision for calls under standardized guarantees, and other accounts receivable/payable. Interest and income attributable to policy holders
D3_F3 Direct investment between fellow enterprises, Debt securities Investment between enterprises that are both controlled by the same parent entity. Tradable financial instruments representing a debt, such as bonds and notes.

5.6 Saldo de la cuenta corriente: comparación internacional, 2015–2024

options(scipen=999)
paises_comparacion <- c(
  "SLV",
  "GTM",
  "HND",
  "NIC",
  "CRI",
  "PAN",
  "MEX",
  "USA"
)

consultar_pais_CAB <- function(pais) {

  resultado <- tryCatch(

    get_data(
      "BOP",
      agency_id = "IMF.STA",
      filters = list(
        COUNTRY = pais,
        FREQUENCY = "A",
        INDICATOR = "CAB",
        BOP_ACCOUNTING_ENTRY = "NETCD_T",
        UNIT = "USD"
      )
    ),

    error = function(e) {
      tibble()
    }
  )

  if (nrow(resultado) == 0) {
    return(tibble())
  }

  resultado %>%
    mutate(
      TIME_PERIOD = as.numeric(TIME_PERIOD),
      OBS_VALUE = as.numeric(OBS_VALUE)
    ) %>%
    filter(
      TIME_PERIOD >= 2015,
      TIME_PERIOD <= 2024
    )
}

datos_comparacion <- bind_rows(
  lapply(
    paises_comparacion,
    consultar_pais_CAB
  )
)
datos_comparacion %>%
  select(
    COUNTRY,
    TIME_PERIOD,
    OBS_VALUE
  ) %>%
  kable(
    caption = "Saldo de la cuenta corriente: comparación internacional, 2015–2024"
  ) %>%
  kable_classic(
    html_font = "Times New Roman",
    font_size = 15
  ) %>%
  kable_styling(full_width = FALSE)
Saldo de la cuenta corriente: comparación internacional, 2015–2024
COUNTRY TIME_PERIOD OBS_VALUE
SLV 2015 -753757240
SLV 2016 -550121069
SLV 2017 -464589787
SLV 2018 -859154621
SLV 2019 -113356041
SLV 2020 276701043
SLV 2021 -1250461218
SLV 2022 -2143721477
SLV 2023 -584682906
SLV 2024 -964417195
GTM 2015 -773787480
GTM 2016 637267670
GTM 2017 857080020
GTM 2018 649564060
GTM 2019 1821490950
GTM 2020 3918080170
GTM 2021 1873410490
GTM 2022 1116174170
GTM 2023 3212019060
GTM 2024 3300417910
HND 2015 -979945387
HND 2016 -682674236
HND 2017 -288253383
HND 2018 -1581815977
HND 2019 -660874047
HND 2020 665854482
HND 2021 -1537902787
HND 2022 -2156562609
HND 2023 -1449262852
HND 2024 -1595401881
NIC 2015 -1259500000
NIC 2016 -1127100000
NIC 2017 -987100000
NIC 2018 -234100000
NIC 2019 754100000
NIC 2020 480200000
NIC 2021 -391178858
NIC 2022 -459600000
NIC 2023 1465400000
NIC 2024 817618290
CRI 2015 -1921262983
CRI 2016 -1257445124
CRI 2017 -2188723948
CRI 2018 -1867318664
CRI 2019 -750921207
CRI 2020 -625175269
CRI 2021 -2178238613
CRI 2022 -1850873043
CRI 2023 -1244166276
CRI 2024 -839431794
PAN 2015 -4848400000
PAN 2016 -4507669628
PAN 2017 -3745435583
PAN 2018 -5307360501
PAN 2019 -3589766446
PAN 2020 122856978
PAN 2021 -818191315
PAN 2022 -276704272
PAN 2023 -2676789962
PAN 2024 568132122
MEX 2015 -31535662037
MEX 2016 -25282312907
MEX 2017 -21402776864
MEX 2018 -25931803949
MEX 2019 -3871166263
MEX 2020 26873079471
MEX 2021 -4485665790
MEX 2022 -15007569273
MEX 2023 -10232313218
MEX 2024 -16790722578
USA 2015 -390780000000
USA 2016 -380011000000
USA 2017 -348862000000
USA 2018 -419443000000
USA 2019 -404302000000
USA 2020 -589622000000
USA 2021 -855203000000
USA 2022 -972359000000
USA 2023 -931394000000
USA 2024 -1198628000000

Grafico comparativo

ggplot(
  datos_comparacion,
  aes(
    x = TIME_PERIOD,
    y = OBS_VALUE,
    color = COUNTRY,
    group = COUNTRY
  )
) +
  geom_line(linewidth = 0.9) +
  geom_point(size = 1.6) +
  labs(
    title = "Saldo de la cuenta corriente",
    subtitle = "Comparación internacional, 2015–2024",
    x = "Año",
    y = "USD",
    color = "País"
  ) +
  theme_minimal()

5.7 EXPORTACIONES E IMPORTACIONES

En este apartado se detallaran las exportaciones e importaciones.

5.7.1 Exportaciones

Las exportaciones se representan como créditos de bienes y servicios, es decir, recursos que los residentes suministran al resto del mundo.

exportaciones <- get_data(
  "BOP",
  agency_id = "IMF.STA",
  filters = list(
    COUNTRY = "SLV",
    INDICATOR = "GS",
    BOP_ACCOUNTING_ENTRY = "CD_T",
    FREQUENCY = "A"
  )
)

exportaciones %>%
  filter(TIME_PERIOD %in% 2015:2024) %>%
  select(TIME_PERIOD, OBS_VALUE) %>%
  kable(
    caption = "El Salvador: exportaciones de bienes y servicios, 2010–2024"
  ) %>%
  kable_classic(
    html_font = "Times New Roman",
    font_size = 15
  )
El Salvador: exportaciones de bienes y servicios, 2010–2024
TIME_PERIOD OBS_VALUE
2015 6914058468
2016 6871196858
2017 7224712453
2018 7564979852
2019 8056709676
2020 6116846462
2021 8351390783
2022 10163921214
2023 10715612777
2024 11391665215

Interpretación: Un aumento de las exportaciones representa mayores ingresos provenientes de las ventas de bienes de El Salvador al resto del mundo. Las exportaciones forman parte de los créditos de la cuenta de bienes.

5.7.2 Importaciones

importaciones <- get_data(
  "BOP",
  agency_id = "IMF.STA",
  filters = list(
    COUNTRY = "SLV",
    INDICATOR = "GS",
    BOP_ACCOUNTING_ENTRY = "DB_T",
    FREQUENCY = "A"
  )
)

importaciones %>%
  filter(TIME_PERIOD %in% 2010:2024) %>%
  select(TIME_PERIOD, OBS_VALUE) %>%
  kable(
    caption = "El Salvador: importaciones de bienes y servicios, 2010–2024"
  ) %>%
  kable_classic(
    html_font = "Times New Roman",
    font_size = 15
  )
El Salvador: importaciones de bienes y servicios, 2010–2024
TIME_PERIOD OBS_VALUE
2010 8595024121
2011 10201664566
2012 10495794652
2013 11155198953
2014 11038774822
2015 10925078972
2016 10717286435
2017 11336179943
2018 12323286065
2019 12468596697
2020 10447390057
2021 15483434147
2022 18181049448
2023 17303271725
2024 18494176814

Interpretación: Las importaciones muestran el valor de los bienes adquiridos por residentes de El Salvador al resto del mundo. La diferencia entre exportaciones e importaciones determina el saldo comercial de bienes.

5.8 Transferencias

En el BPM6, las transferencias corrientes se registran dentro del ingreso secundario. Para El Salvador, las remesas de trabajadores constituyen un componente especialmente importante del ingreso secundario.

transferencias <- get_data(
  "BOP",
  agency_id = "IMF.STA",
  filters = list(
    COUNTRY = "SLV",
    INDICATOR = "IN2",
    FREQUENCY = "A"
  )
)

transferencias %>%
  filter(TIME_PERIOD %in% 2016:2024) %>%
  select(TIME_PERIOD, OBS_VALUE) %>%
  kable(
    caption = "El Salvador: ingreso secundario / transferencias corrientes, 2010–2024"
  ) %>%
  kable_classic(
    html_font = "Times New Roman",
    font_size = 15
  )
El Salvador: ingreso secundario / transferencias corrientes, 2010–2024
TIME_PERIOD OBS_VALUE
2016 4744612464
2017 5262013142
2018 5605742079
2019 5900441584
2020 6231726403
2021 7890352099
2022 8170482836
2023 8531280642
2024 8746737060
2016 202259882
2017 227514558
2018 236497434
2019 260807865
2020 247095235
2021 320768265
2022 349787959
2023 354816866
2024 350708718
2016 4542352583
2017 5034498584
2018 5369244644
2019 5639633719
2020 5984631169
2021 7569583834
2022 7820694877
2023 8176463777
2024 8396028342

Interpretación: Un saldo positivo del ingreso secundario significa que los créditos por transferencias corrientes superan los débitos. En El Salvador, las remesas son un componente relevante de esta cuenta.

6. EJEMPLOS DATASET_IMF.RES

6.1 Verificación del dataset en la agencia IMF.RES

# Datasets disponibles bajo la agencia de investigación (IMF.RES)
datasets_IMF.RES <- list_datasets("IMF.RES")
info_WEO <- datasets_IMF.RES[datasets_IMF.RES$id == "WEO", ]
info_WEO %>%
  kable(caption = "Información General del Dataset WEO (Agencia IMF.RES)") %>%
  kable_classic(html_font = "Times New Roman", font_size = 15) %>%
  add_footnote(label = "Tomado de la API del FMI (IMF.RES)", notation = "symbol") %>%
  kable_styling(full_width = FALSE)
Información General del Dataset WEO (Agencia IMF.RES)
agency id version name description dsd_id
IMF.RES WEO 9.0.0 World Economic Outlook (WEO) The World Economic Outlook (WEO) database is created during the biannual WEO exercise, which begins in January and June of each year and results in the April and September/October WEO publication. Selected series from the publication are available in a database format. DSD_WEO
* Tomado de la API del FMI (IMF.RES)

6.2 Revisión de dimesiones e indicadores

Dimensiones_WEO <- list_dimensions("WEO", agency_id = "IMF.RES")
Indicadores_WEO <- list_dimension_values("WEO", dimension = c("INDICATOR"), agency_id = "IMF.RES")
Indicadores_WEO %>%
  filter(code %in% c("NGDP_RPCH", "PCPIPCH", "LUR")) %>%
  kable(caption = "Indicadores Seleccionados para el Análisis (WEO - FMI)") %>%
  kable_classic(html_font = "Times New Roman", font_size = 15) %>%
  kable_styling()
Indicadores Seleccionados para el Análisis (WEO - FMI)
code name description
LUR Unemployment rate The percentage of the labor force that is unemployed and actively seeking employment. It is calculated as the number of unemployed persons divided by the total labor force. A measure that expresses the frequency of occurrence of an event or phenomenon in relation to another quantity.
NGDP_RPCH Gross domestic product (GDP), Constant prices, Percent change Gross domestic product reflects the total income earned through the production of goods and services in an economic territory during an accounting period. It can be measured in three different ways: using either the expenditure approach, the income approach, or the production approach. Values that have had the effect of price changes removed, expressed as time series in constant prices (fixed base) or chain-linked volume terms, or as non-time series in previous year’s prices This measures the relative change in a value over time, expressed as a percentage. It is calculated as the difference between the new value and the old value, divided by the old value, and multiplied by 100. 1 A ratio expressed as a fraction of 100.
PCPIPCH All Items, Consumer price index (CPI), Period average, percent change All items in the context of the consumer price index indicates that the index includes prices for all items included in the consumer price index basket. This includes prices related to food, beverages, clothing, housing, health, transport, communications, recreation, education, restaurants and hotels and other miscellanoues goods and services. The Consumer Price Index (CPI) is an index of the prices of consumption goods and services, as compared to a certain reference period. This calculates the change relative to the average value over the entire period, not just the starting point. This is often used when the data fluctuates significantly within the period, and the average provides a more representative value for comparison. A ratio expressed as a fraction of 100.

6.2.1 Tabla de resultados

Datos_WEO <- get_data("WEO",
  agency_id  = "IMF.RES",
  filters    = list(
    COUNTRY   = c("SLV","PAN","CRI","GTM","HND","NIC"), 
    INDICATOR = "NGDP_RPCH",                   
    FREQUENCY = "A"                           
  )
)
Datos_WEO %>%
  filter(as.numeric(TIME_PERIOD) >= 2020) %>%
  kable(caption = "Proyecciones de Crecimiento del PIB Real (%) - WEO (FMI)") %>%
  kable_classic(html_font = "Times New Roman", font_size = 14) %>%
  add_footnote(label = "Fuente: API FMI (IMF.RES / WEO)", notation = "symbol") %>%
  kable_styling(full_width = FALSE)
Proyecciones de Crecimiento del PIB Real (%) - WEO (FMI)
COUNTRY INDICATOR FREQUENCY TIME_PERIOD OBS_VALUE
CRI NGDP_RPCH A 2020 -4.141593
CRI NGDP_RPCH A 2021 8.218179
CRI NGDP_RPCH A 2022 5.461195
CRI NGDP_RPCH A 2023 4.791877
CRI NGDP_RPCH A 2024 4.082925
CRI NGDP_RPCH A 2025 4.560335
CRI NGDP_RPCH A 2026 3.560304
CRI NGDP_RPCH A 2027 3.566547
CRI NGDP_RPCH A 2028 3.556088
CRI NGDP_RPCH A 2029 3.510000
CRI NGDP_RPCH A 2030 3.460000
CRI NGDP_RPCH A 2031 3.460000
GTM NGDP_RPCH A 2020 -1.785552
GTM NGDP_RPCH A 2021 8.041704
GTM NGDP_RPCH A 2022 4.184518
GTM NGDP_RPCH A 2023 3.533157
GTM NGDP_RPCH A 2024 3.651864
GTM NGDP_RPCH A 2025 4.118144
GTM NGDP_RPCH A 2026 3.940000
GTM NGDP_RPCH A 2027 3.980000
GTM NGDP_RPCH A 2028 3.920000
GTM NGDP_RPCH A 2029 3.840000
GTM NGDP_RPCH A 2030 3.880000
GTM NGDP_RPCH A 2031 3.920000
HND NGDP_RPCH A 2020 -8.965041
HND NGDP_RPCH A 2021 12.565185
HND NGDP_RPCH A 2022 4.143610
HND NGDP_RPCH A 2023 3.575892
HND NGDP_RPCH A 2024 3.554011
HND NGDP_RPCH A 2025 3.700000
HND NGDP_RPCH A 2026 3.300000
HND NGDP_RPCH A 2027 3.700000
HND NGDP_RPCH A 2028 3.800000
HND NGDP_RPCH A 2029 3.800000
HND NGDP_RPCH A 2030 3.800000
HND NGDP_RPCH A 2031 3.800000
NIC NGDP_RPCH A 2020 -2.236542
NIC NGDP_RPCH A 2021 10.454389
NIC NGDP_RPCH A 2022 3.550275
NIC NGDP_RPCH A 2023 4.427794
NIC NGDP_RPCH A 2024 3.580945
NIC NGDP_RPCH A 2025 4.923526
NIC NGDP_RPCH A 2026 3.840000
NIC NGDP_RPCH A 2027 3.800000
NIC NGDP_RPCH A 2028 3.530000
NIC NGDP_RPCH A 2029 3.530000
NIC NGDP_RPCH A 2030 3.530000
NIC NGDP_RPCH A 2031 3.530000
PAN NGDP_RPCH A 2020 -17.821230
PAN NGDP_RPCH A 2021 16.467125
PAN NGDP_RPCH A 2022 11.038548
PAN NGDP_RPCH A 2023 7.166329
PAN NGDP_RPCH A 2024 2.747885
PAN NGDP_RPCH A 2025 4.350252
PAN NGDP_RPCH A 2026 3.840000
PAN NGDP_RPCH A 2027 4.540000
PAN NGDP_RPCH A 2028 4.540000
PAN NGDP_RPCH A 2029 4.754000
PAN NGDP_RPCH A 2030 4.540000
PAN NGDP_RPCH A 2031 4.540000
SLV NGDP_RPCH A 2020 -7.893101
SLV NGDP_RPCH A 2021 11.904762
SLV NGDP_RPCH A 2022 2.954604
SLV NGDP_RPCH A 2023 3.539157
SLV NGDP_RPCH A 2024 2.602020
SLV NGDP_RPCH A 2025 3.700000
SLV NGDP_RPCH A 2026 3.300000
SLV NGDP_RPCH A 2027 3.000000
SLV NGDP_RPCH A 2028 3.000000
SLV NGDP_RPCH A 2029 3.000000
SLV NGDP_RPCH A 2030 3.000000
SLV NGDP_RPCH A 2031 3.000000
* Fuente: API FMI (IMF.RES / WEO)

6.2.2 Gráfico proyecciones de crecimiento del PIB (%)

library(plotly)
library(dplyr)
library(ggplot2)
datos_grafica <- Datos_WEO %>%
  mutate(
    TIME_PERIOD = as.numeric(TIME_PERIOD),
    OBS_VALUE   = as.numeric(OBS_VALUE)
  ) %>%
  filter(TIME_PERIOD >= 2020 & TIME_PERIOD <= 2029)
grafico <- ggplot(datos_grafica, aes(
  x = TIME_PERIOD, 
  y = OBS_VALUE, 
  color = COUNTRY, 
  group = COUNTRY,
  text = paste("País:", COUNTRY, "Año:", TIME_PERIOD, "Crecimiento:", round(OBS_VALUE, 2), "%")
)) +
  geom_line(size = 0.9) +
  geom_point(size = 2) +
  scale_color_brewer(palette = "Set1", name = "País") +
  scale_x_continuous(breaks = seq(2020, 2029, by = 2)) +
  labs(
    title = "Proyecciones de Crecimiento del PIB Real (%)",
    x = "Año",
    y = "Variación Porcentual (%)"
  ) +
  theme_minimal() 
Grafico_Proyecc <- ggplotly(grafico, tooltip = "text") %>%
  layout(
    legend = list(
      title = list(text = "Hacer clic sobre la leyenda<br>para ver la información del país"),
      orientation = "h", 
      x = 0,
      y = -0.2
    )
  )
Grafico_Proyecc

6.3 Inflación (Variación Porcentual Anual)- Indicador WEO: “PCPIPCH”

6.3.1 Tabla de Resultados

datos_inflacion <- get_data(
  "WEO",
  agency_id = "IMF.RES",
  filters = list(
    COUNTRY   = c("SLV", "PAN", "CRI", "GTM", "HND", "NIC"),
    INDICATOR = "PCPIPCH", 
    FREQUENCY = "A"
  )
)
datos_inflacion %>%
  mutate(TIME_PERIOD = as.numeric(TIME_PERIOD),
         OBS_VALUE = round(as.numeric(OBS_VALUE), 2)) %>%
  filter(TIME_PERIOD >= 2020) %>%
  kable(caption = "Proyecciones de Inflación (%) - WEO (FMI)",
        col.names = c("País", "Indicador", "Frecuencia", "Año", "Inflación (%)")) %>%
  kable_classic(html_font = "Times New Roman", font_size = 14) %>%
  add_footnote(label = "Fuente: API FMI (IMF.RES / WEO). Datos a partir de 2020 con proyecciones.", 
               notation = "symbol") %>%
  kable_styling(full_width = FALSE, bootstrap_options = c("striped", "hover"))
Proyecciones de Inflación (%) - WEO (FMI)
País Indicador Frecuencia Año Inflación (%)
CRI PCPIPCH A 2020 0.72
CRI PCPIPCH A 2021 1.73
CRI PCPIPCH A 2022 8.27
CRI PCPIPCH A 2023 0.53
CRI PCPIPCH A 2024 -0.41
CRI PCPIPCH A 2025 -0.07
CRI PCPIPCH A 2026 -0.44
CRI PCPIPCH A 2027 2.05
CRI PCPIPCH A 2028 2.30
CRI PCPIPCH A 2029 2.50
CRI PCPIPCH A 2030 3.00
CRI PCPIPCH A 2031 3.00
GTM PCPIPCH A 2020 3.21
GTM PCPIPCH A 2021 4.26
GTM PCPIPCH A 2022 6.88
GTM PCPIPCH A 2023 6.21
GTM PCPIPCH A 2024 2.87
GTM PCPIPCH A 2025 1.58
GTM PCPIPCH A 2026 2.57
GTM PCPIPCH A 2027 4.05
GTM PCPIPCH A 2028 3.64
GTM PCPIPCH A 2029 3.85
GTM PCPIPCH A 2030 4.01
GTM PCPIPCH A 2031 4.00
HND PCPIPCH A 2020 3.47
HND PCPIPCH A 2021 4.48
HND PCPIPCH A 2022 9.09
HND PCPIPCH A 2023 6.66
HND PCPIPCH A 2024 4.61
HND PCPIPCH A 2025 4.60
HND PCPIPCH A 2026 4.40
HND PCPIPCH A 2027 4.49
HND PCPIPCH A 2028 4.00
HND PCPIPCH A 2029 4.00
HND PCPIPCH A 2030 4.00
HND PCPIPCH A 2031 4.00
NIC PCPIPCH A 2020 3.68
NIC PCPIPCH A 2021 4.93
NIC PCPIPCH A 2022 10.47
NIC PCPIPCH A 2023 8.45
NIC PCPIPCH A 2024 4.64
NIC PCPIPCH A 2025 2.08
NIC PCPIPCH A 2026 3.50
NIC PCPIPCH A 2027 3.00
NIC PCPIPCH A 2028 3.00
NIC PCPIPCH A 2029 3.00
NIC PCPIPCH A 2030 3.00
NIC PCPIPCH A 2031 3.00
PAN PCPIPCH A 2020 -1.55
PAN PCPIPCH A 2021 1.63
PAN PCPIPCH A 2022 2.86
PAN PCPIPCH A 2023 1.49
PAN PCPIPCH A 2024 0.69
PAN PCPIPCH A 2025 0.01
PAN PCPIPCH A 2026 1.44
PAN PCPIPCH A 2027 2.00
PAN PCPIPCH A 2028 2.00
PAN PCPIPCH A 2029 2.00
PAN PCPIPCH A 2030 2.00
PAN PCPIPCH A 2031 2.00
SLV PCPIPCH A 2020 -0.37
SLV PCPIPCH A 2021 3.47
SLV PCPIPCH A 2022 7.20
SLV PCPIPCH A 2023 4.05
SLV PCPIPCH A 2024 0.85
SLV PCPIPCH A 2025 0.26
SLV PCPIPCH A 2026 2.50
SLV PCPIPCH A 2027 2.00
SLV PCPIPCH A 2028 1.80
SLV PCPIPCH A 2029 1.80
SLV PCPIPCH A 2030 1.80
SLV PCPIPCH A 2031 1.80
* Fuente: API FMI (IMF.RES / WEO). Datos a partir de 2020 con proyecciones.

6.3.2 Gráfico de proyeciones de la inflación (%)

Datos_grafico_inflacion <- datos_inflacion %>%
  mutate(
    TIME_PERIOD = as.numeric(TIME_PERIOD),
    OBS_VALUE   = as.numeric(OBS_VALUE)
  ) %>%
  filter(TIME_PERIOD >= 2020 & TIME_PERIOD <= 2029)
Grafico_inflacion <- ggplot(Datos_grafico_inflacion, aes(
  x = TIME_PERIOD, 
  y = OBS_VALUE, 
  color = COUNTRY, 
  group = COUNTRY,
  text = paste("País:", COUNTRY, "<br>Año:", TIME_PERIOD, "<br>Inflación:", round(OBS_VALUE, 2), "%")
)) +
  geom_line(size = 0.9) +
  geom_point(size = 2) +
  scale_color_brewer(palette = "Set1", name = "País") +
  scale_x_continuous(breaks = seq(2020, 2029, by = 1)) +
  labs(
    title = "Proyecciones de Inflación (Precios al Consumidor)",
    x = "Año",
    y = "Variación Porcentual Anual (%)"
  ) +
  theme_minimal()
Proyecc_inflacion <- ggplotly(Grafico_inflacion, tooltip = "text") %>%
  layout(
    legend = list(
      title = list(text = "Hacer clic sobre la leyenda<br>para ver la información del país"),
      orientation = "h",
      x = 0,
      y = -0.2
    )
  )

Proyecc_inflacion

6.4 Tasa de desempleo (% de la fuerza laboral)- WEO: “LUR”

6.4.1 Tabla de resultados

Datos_desempleo <- get_data(
  "WEO",
  agency_id = "IMF.RES",
  filters = list(
    COUNTRY   = c("SLV", "PAN", "CRI", "GTM", "HND", "NIC"),
    INDICATOR = "LUR", 
    FREQUENCY = "A"
  )
)
Datos_desempleo %>%
  mutate(TIME_PERIOD = as.numeric(TIME_PERIOD),
         OBS_VALUE = round(as.numeric(OBS_VALUE), 2)) %>%
  filter(TIME_PERIOD >= 2020) %>%
  kable(caption = "Proyecciones de Tasa de desempleo (% de la fuerza laboral) - WEO (FMI)",
        col.names = c("País", "Indicador", "Frecuencia", "Año", "Inflación (%)")) %>%
  kable_classic(html_font = "Times New Roman", font_size = 14) %>%
  add_footnote(label = "Fuente: API FMI (IMF.RES / WEO). Datos a partir de 2020 con proyecciones.", 
               notation = "symbol") %>%
  kable_styling(full_width = FALSE, bootstrap_options = c("striped", "hover"))
Proyecciones de Tasa de desempleo (% de la fuerza laboral) - WEO (FMI)
País Indicador Frecuencia Año Inflación (%)
CRI LUR A 2020 19.98
CRI LUR A 2021 13.68
CRI LUR A 2022 11.67
CRI LUR A 2023 7.30
CRI LUR A 2024 6.88
CRI LUR A 2025 6.33
CRI LUR A 2026 7.00
CRI LUR A 2027 7.20
CRI LUR A 2028 7.50
CRI LUR A 2029 8.00
CRI LUR A 2030 8.00
CRI LUR A 2031 8.00
HND LUR A 2020 10.91
HND LUR A 2021 8.57
HND LUR A 2022 8.94
HND LUR A 2023 6.40
HND LUR A 2024 5.20
HND LUR A 2025 5.90
HND LUR A 2026 6.80
HND LUR A 2027 6.80
HND LUR A 2028 6.50
HND LUR A 2029 6.50
HND LUR A 2030 6.50
HND LUR A 2031 6.50
NIC LUR A 2020 4.82
NIC LUR A 2021 3.67
NIC LUR A 2022 3.53
NIC LUR A 2023 3.36
NIC LUR A 2024 3.06
NIC LUR A 2025 2.69
NIC LUR A 2026 2.69
NIC LUR A 2027 2.69
NIC LUR A 2028 2.69
NIC LUR A 2029 2.69
NIC LUR A 2030 2.69
NIC LUR A 2031 3.00
PAN LUR A 2020 18.55
PAN LUR A 2021 11.29
PAN LUR A 2022 9.92
PAN LUR A 2023 7.43
PAN LUR A 2024 9.53
PAN LUR A 2025 10.40
PAN LUR A 2026 10.40
PAN LUR A 2027 9.52
PAN LUR A 2028 8.64
PAN LUR A 2029 7.76
PAN LUR A 2030 6.88
PAN LUR A 2031 6.00
SLV LUR A 2020 7.04
SLV LUR A 2021 6.34
SLV LUR A 2022 5.05
SLV LUR A 2023 5.22
SLV LUR A 2024 4.65
SLV LUR A 2025 4.20
SLV LUR A 2026 4.32
SLV LUR A 2027 4.43
SLV LUR A 2028 4.55
SLV LUR A 2029 4.67
SLV LUR A 2030 4.78
SLV LUR A 2031 4.78
* Fuente: API FMI (IMF.RES / WEO). Datos a partir de 2020 con proyecciones.

6.4.2 Gráfico de proyecciones tasa de desempleo (% DE LA FUERZA LABORAL)

Datos_grafico_desempleo <- Datos_desempleo %>%
  mutate(
    TIME_PERIOD = as.numeric(TIME_PERIOD),
    OBS_VALUE   = as.numeric(OBS_VALUE)
  ) %>%
  filter(TIME_PERIOD >= 2020 & TIME_PERIOD <= 2029)
Grafico_desempleo <- ggplot(Datos_grafico_desempleo, aes(
  x = TIME_PERIOD, 
  y = OBS_VALUE, 
  color = COUNTRY, 
  group = COUNTRY,
  text = paste("País:", COUNTRY, "<br>Año:", TIME_PERIOD, "<br>Desempleo:", round(OBS_VALUE, 2), "%")
)) +
  geom_line(size = 0.9) +
  geom_point(size = 2) +
  scale_color_brewer(palette = "Set1", name = "País") +
  scale_x_continuous(breaks = seq(2020, 2029, by = 2)) +
  labs(
    title = "Proyecciones de la Tasa de Desempleo",
    x = "Año",
    y = "Porcentaje de la Fuerza Laboral Total (%)"
  ) +
  theme_minimal()
Proyecc_desempleo <- ggplotly(Grafico_desempleo, tooltip = "text") %>%
  layout(
    legend = list(
      title = list(text = "Hacer clic sobre la leyenda<br>para ver la información del país"),
      orientation = "h", 
      x = 0,
      y = -0.2
    )
  )

Proyecc_desempleo

7 EJEMPLO DATASET— GFS_SOO

GFS_SOO (Statement of Operations) es el dataflow que trae ingresos, gastos y resultado fiscal. Antes de consultar datos, se confirma la estructura real de sus dimensiones.

list_dimensions("GFS_SOO")
## # A tibble: 7 × 7
##   position id           type  name  codelist_agency codelist_id codelist_version
##      <int> <chr>        <chr> <chr> <chr>           <chr>       <chr>           
## 1        0 COUNTRY      Dime… Coun… IMF             CL_COUNTRY  1.0+.0          
## 2        1 SECTOR       Dime… Sect… IMF             CL_SECTOR   2.0+.0          
## 3        2 GFS_GRP      Dime… GFS … IMF.STA         CL_GFS_GRP  1.0+.0          
## 4        3 INDICATOR    Dime… Indi… IMF.STA         CL_GFS_IND… 12.0+.0         
## 5        4 TYPE_OF_TRA… Dime… Type… IMF.STA         CL_GFS_TYP… 1.0+.0          
## 6        5 FREQUENCY    Dime… FREQ… <NA>            <NA>        <NA>            
## 7        6 TIME_PERIOD  Time… TIME… <NA>            <NA>        <NA>

Sector. El Salvador sí reporta bajo el sector “Gobierno General”:

list_dimension_values("GFS_SOO", "SECTOR", filters = list(COUNTRY = "SLV"))
## # A tibble: 8 × 3
##   code       name                                         description           
##   <chr>      <chr>                                        <chr>                 
## 1 S13        General government                           The general governmen…
## 2 S1311      Central government excluding social security Central government op…
## 3 S13112     Extrabudgetary central government            Units of central gove…
## 4 S1311B     Budgetary central government                 Central government op…
## 5 S1312MIXED State Government                             State Government.     
## 6 S1313MIXED Local Government                             Local Government.     
## 7 S1314      Social security funds                        Funds established to …
## 8 S1321      Central government including social security Central government op…

Categoría de flujo (GFS_GRP). Confirmado para El Salvador + sector S13:

list_dimension_values("GFS_SOO", "GFS_GRP", filters = list(COUNTRY = "SLV", SECTOR = "S13"))
## # A tibble: 5 × 3
##   code  name                                             description            
##   <chr> <chr>                                            <chr>                  
## 1 BI    Balancing Items                                  Balancing Items        
## 2 BS    Balance Sheet                                    Balance Sheet          
## 3 G1    Revenue                                          Revenue                
## 4 G2M   Expenditure                                      Expenditure            
## 5 TFAL  Transactions in financial assets and liabilities Transactions in financ…

Los códigos relevantes para este documento son G1 (Revenue / Ingresos) y G2M (Expenditure / Gastos) — no G2 (Expense), que es un concepto GFSM distinto y que, además, no aparece entre lo que El Salvador reporta en este dataflow.

Indicador. Se filtra el catálogo completo de indicadores por los que sí trae este sector, buscando ingresos y gastos:

list_dimension_values("GFS_SOO", "INDICATOR", filters = list(COUNTRY = "SLV", SECTOR = "S13")) %>%
  filter(str_detect(name, regex("Revenue|Expenditure", ignore_case = TRUE)))
## # A tibble: 3 × 3
##   code  name                        description                                 
##   <chr> <chr>                       <chr>                                       
## 1 G14_T Other revenue, Transactions Revenue collected by the government from va…
## 2 G1_T  Revenue, Transactions       Revenue refers to the total inflow of resou…
## 3 G2M_T Expenditure, Transactions   Expenditure refers to the total outflow of …

Códigos confirmados: G1_T (Revenue, Transactions) y G2M_T (Expenditure, Transactions).

Tipo de transformación. Determina si el dato viene en niveles o como porcentaje del PIB:

list_dimension_values("GFS_SOO", "TYPE_OF_TRANSFORMATION", filters = list(COUNTRY = "SLV", SECTOR = "S13"))
## # A tibble: 2 × 3
##   code     name              description                                        
##   <chr>    <chr>             <chr>                                              
## 1 POGDP_PT Percent of GDP    Value expressed as a percent of the Gross Domestic…
## 2 XDC      Domestic currency Currency issued by the country of origin, used int…

Se usa XDC (moneda doméstica, niveles nominales) para los gráficos de este documento. El código POGDP_PT (porcentaje del PIB) queda disponible como alternativa si se prefiere esa unidad.

Frecuencia. Solo hay una opción reportada:

list_dimension_values("GFS_SOO", "FREQUENCY", filters = list(COUNTRY = "SLV", SECTOR = "S13"))
## # A tibble: 1 × 3
##   code  name  description
##   <chr> <chr> <chr>      
## 1 A     <NA>  <NA>

7.1 Ingresos y gastos del Gobierno General (GFS_SOO)

Con los seis valores ya verificados arriba (no supuestos), se arma la consulta final:

datos_soo <- get_data(
  "GFS_SOO",
  filters = list(
    COUNTRY = "SLV",
    SECTOR = "S13",
    GFS_GRP = c("G1", "G2M"),
    INDICATOR = c("G1_T", "G2M_T"),
    TYPE_OF_TRANSFORMATION = "XDC",
    FREQUENCY = "A"
  ),
  last_n_obs = 40
)

datos_soo <- datos_soo %>%
  mutate(
    TIME_PERIOD = as.integer(TIME_PERIOD),
    indicador   = recode(INDICATOR, "G1_T" = "Ingresos", "G2M_T" = "Gastos")
  ) %>%
  filter(!is.na(OBS_VALUE))

kable(head(datos_soo, 10))
COUNTRY SECTOR GFS_GRP INDICATOR TYPE_OF_TRANSFORMATION FREQUENCY TIME_PERIOD OBS_VALUE indicador
SLV S13 G1 G1_T XDC A 2002 2380800000 Ingresos
SLV S13 G1 G1_T XDC A 2003 2400200000 Ingresos
SLV S13 G1 G1_T XDC A 2004 2615500000 Ingresos
SLV S13 G1 G1_T XDC A 2005 2897400000 Ingresos
SLV S13 G1 G1_T XDC A 2006 3396500000 Ingresos
SLV S13 G1 G1_T XDC A 2007 4119600000 Ingresos
SLV S13 G1 G1_T XDC A 2008 4618800000 Ingresos
SLV S13 G1 G1_T XDC A 2009 3943000000 Ingresos
SLV S13 G1 G1_T XDC A 2010 4311300000 Ingresos
SLV S13 G1 G1_T XDC A 2011 5102993168 Ingresos

7.2 Tablas por separado: ingresos y gastos

datos_soo %>%
  filter(indicador == "Ingresos") %>%
  select(TIME_PERIOD, OBS_VALUE) %>%
  arrange(TIME_PERIOD) %>%
  tail(10) %>%
  kable(caption = "Ingresos del Gobierno General de El Salvador (moneda doméstica) - Últimos 10 años",
        col.names = c("Período", "Ingresos")) %>%
  kable_classic(html_font = "Times New Roman", font_size = 14) %>%
  add_footnote(label = "Fuente: API FMI (IMF.RES / WEO).", notation = "symbol") %>%
  kable_styling(full_width = FALSE, bootstrap_options = c("striped", "hover"))
Ingresos del Gobierno General de El Salvador (moneda doméstica) - Últimos 10 años
Período Ingresos
2015 5244615070
2016 6139671826
2017 6596442349
2018 6816100000
2019 6814400000
2020 6369700000
2021 8811300000
2022 9476900000
2023 9505638793
2024 10497900000
* Fuente: API FMI (IMF.RES / WEO).
datos_soo %>%
  filter(indicador == "Gastos") %>%
  select(TIME_PERIOD, OBS_VALUE) %>%
  arrange(TIME_PERIOD) %>%
  tail(10) %>%
  kable(caption = "Gastos del Gobierno General de El Salvador (moneda doméstica) - Últimos 10 años",
        col.names = c("Período", "Gastos")) %>%
  kable_classic(html_font = "Times New Roman", font_size = 14) %>%
  add_footnote(label = "Fuente: API FMI (IMF.RES / WEO).", notation = "symbol") %>%
  kable_styling(full_width = FALSE, bootstrap_options = c("striped", "hover"))
Gastos del Gobierno General de El Salvador (moneda doméstica) - Últimos 10 años
Período Gastos
2015 5560686780
2016 6078967401
2017 6741449255
2018 6977500000
2019 7023900000
2020 8763200000
2021 9482200000
2022 10365800000
2023 10427400000
2024 11222500000
* Fuente: API FMI (IMF.RES / WEO).

Nota: El Salvador cambió de colón a dólar estadounidense como moneda de curso legal en 2001. El código XDC (“moneda doméstica”) puede reflejar ese cambio de unidad dentro de la misma serie histórica — no se ha verificado en este documento si el FMI homogeniza la serie completa a una sola moneda. Si al graficar aparece un salto artificial alrededor de 2001, esa es la causa más probable a revisar primero.

7.3 Ingresos vs. gastos

ggplot(datos_soo, aes(x = TIME_PERIOD, y = OBS_VALUE / 1e9, color = indicador)) +
  geom_line(linewidth = 1) +
  geom_point() +
  scale_x_continuous(breaks = pretty_breaks()) +
  labs(title = "Ingresos y gastos del Gobierno General de El Salvador",
       subtitle = "Miles de millones, moneda doméstica corriente. Fuente: FMI, GFS_SOO",
       x = NULL, y = "Miles de millones", color = NULL) +
  theme_minimal() +
  theme(legend.position = "top")

7.3.1 Resultado operativo neto (aproximación)

resultado_operativo <- datos_soo %>%
  select(TIME_PERIOD, indicador, OBS_VALUE) %>%
  pivot_wider(names_from = indicador, values_from = OBS_VALUE) %>%
  mutate(resultado = Ingresos - Gastos)

resultado_operativo %>%
  head(10) %>%
  kable(caption = "Resultado Operativo del Gobierno General de El Salvador",
        col.names = c("Período", "Ingresos", "Gastos", "Resultado"),
        digits = 2,
        format.args = list(big.mark = ",")) %>%
  kable_classic(html_font = "Times New Roman", font_size = 14) %>%
  add_footnote(label = "Fuente: API FMI (IMF.RES / WEO).", notation = "symbol") %>%
  kable_styling(full_width = FALSE, bootstrap_options = c("striped", "hover"))
Resultado Operativo del Gobierno General de El Salvador
Período Ingresos Gastos Resultado
2,002 2,380,800,000 3,061,800,000 -681,000,000
2,003 2,400,200,000 2,784,300,000 -384,100,000
2,004 2,615,500,000 3,120,600,000 -505,100,000
2,005 2,897,400,000 3,636,799,990 -739,399,990
2,006 3,396,500,000 3,973,200,000 -576,700,000
2,007 4,119,600,000 3,934,050,000 185,550,000
2,008 4,618,800,000 4,586,700,000 32,100,000
2,009 3,943,000,000 4,977,800,000 -1,034,800,000
2,010 4,311,300,000 4,862,600,000 -551,300,000
2,011 5,102,993,168 5,634,180,235 -531,187,067
* Fuente: API FMI (IMF.RES / WEO).

Precisión conceptual: Ingresos - Gastos corresponde al resultado operativo neto (GFSM 2014), no al préstamo/endeudamiento neto (NLB) que el FMI reporta como “resultado fiscal” oficial. La diferencia entre ambos es la inversión neta en activos no financieros del gobierno, que este documento no resta porque GFS_GRP/INDICATOR para ese concepto no se verificaron en esta sesión. El gráfico y su etiqueta reflejan esa distinción.

ggplot(resultado_operativo, aes(x = TIME_PERIOD, y = resultado / 1e9, fill = resultado >= 0)) +
  geom_col() +
  geom_hline(yintercept = 0, linewidth = 0.4) +
  scale_fill_manual(values = c(`TRUE` = "#2c7fb8", `FALSE` = "#d7301f"),
                     labels = c(`TRUE` = "Superávit operativo", `FALSE` = "Déficit operativo")) +
  scale_x_continuous(breaks = pretty_breaks()) +
  labs(title = "Resultado operativo neto del Gobierno General de El Salvador",
       subtitle = "Aproximación (Ingresos - Gastos); no equivale al resultado fiscal oficial (NLB) del FMI. Fuente: GFS_SOO",
       x = NULL, y = "Miles de millones", fill = NULL) +
  theme_minimal() +
  theme(legend.position = "top")

7.4 Deuda pública (GFS_BS)

GFS_BS (Balance Sheet) es un dataflow distinto al de ingresos/gastos. Se verificó que usa los mismos nombres de dimensión que GFS_SOO (COUNTRY, SECTOR, GFS_GRP, INDICATOR, TYPE_OF_TRANSFORMATION, FREQUENCY) y que El Salvador reporta bajo el mismo codelist de sector (S13, Gobierno General). Aun así, GFS_GRP e INDICATOR son propios de este dataflow — no se reutilizan los códigos de GFS_SOO sin verificar.

list_dimensions("GFS_BS")
## # A tibble: 7 × 7
##   position id           type  name  codelist_agency codelist_id codelist_version
##      <int> <chr>        <chr> <chr> <chr>           <chr>       <chr>           
## 1        0 COUNTRY      Dime… Coun… IMF             CL_COUNTRY  1.0+.0          
## 2        1 SECTOR       Dime… Sect… IMF             CL_SECTOR   2.0+.0          
## 3        2 GFS_GRP      Dime… GFS … IMF.STA         CL_GFS_GRP  1.0+.0          
## 4        3 INDICATOR    Dime… Indi… IMF.STA         CL_GFS_IND… 12.0+.0         
## 5        4 TYPE_OF_TRA… Dime… Type… IMF.STA         CL_GFS_TYP… 1.0+.0          
## 6        5 FREQUENCY    Dime… FREQ… <NA>            <NA>        <NA>            
## 7        6 TIME_PERIOD  Time… TIME… <NA>            <NA>        <NA>
list_dimension_values("GFS_BS", "SECTOR", filters = list(COUNTRY = "SLV"))
## # A tibble: 8 × 3
##   code       name                                         description           
##   <chr>      <chr>                                        <chr>                 
## 1 S13        General government                           The general governmen…
## 2 S1311      Central government excluding social security Central government op…
## 3 S13112     Extrabudgetary central government            Units of central gove…
## 4 S1311B     Budgetary central government                 Central government op…
## 5 S1312MIXED State Government                             State Government.     
## 6 S1313MIXED Local Government                             Local Government.     
## 7 S1314      Social security funds                        Funds established to …
## 8 S1321      Central government including social security Central government op…

Categoría de flujo/saldo (GFS_GRP). Para deuda interesa la categoría de pasivos del balance:

grp_bs <- list_dimension_values("GFS_BS", "GFS_GRP", filters = list(COUNTRY = "SLV", SECTOR = "S13"))
kable(grp_bs)
code name description
BI Balancing Items Balancing Items
BS Balance Sheet Balance Sheet
TFAL Transactions in financial assets and liabilities Transactions in financial assets and liabilities
grp_deuda <- grp_bs %>%
  filter(str_detect(name, regex("Liabilit|Balance Sheet", ignore_case = TRUE)))

if (nrow(grp_deuda) == 0) {
  stop("No se encontró una categoría de pasivos en GFS_GRP. Revisa la tabla completa impresa arriba.")
}
kable(grp_deuda)
code name description
BS Balance Sheet Balance Sheet
TFAL Transactions in financial assets and liabilities Transactions in financial assets and liabilities

Indicador. Se busca el concepto de deuda bruta o pasivos totales entre lo que El Salvador sí reporta:

indicadores_bs <- list_dimension_values("GFS_BS", "INDICATOR",
                                         filters = list(COUNTRY = "SLV", SECTOR = "S13",
                                                          GFS_GRP = grp_deuda$code))

ind_deuda <- indicadores_bs %>%
  filter(str_detect(name, regex("Gross debt|Total liabilities|Debt securities", ignore_case = TRUE))) %>%
  head(10)

if (nrow(ind_deuda) == 0) {
  stop("No se encontró un indicador de deuda bruta/pasivos totales. Revisa 'indicadores_bs' completo: ",
       paste(indicadores_bs$code, collapse = ", "))
}
kable(ind_deuda)
code name description
F3_A_SP Debt securities, Assets, Stock positions Tradable financial instruments representing a debt, such as bonds and notes. Assets are a store of value representing a benefit or series of benefits accruing to the economic owner by holding or using the item over a period of time. It is a means of carrying forward value from one accounting period to another. The values of assets, liabilities, and equity held at a specific point in time.
F3_DC_L_SP Debt securities, Domestic Creditors, Liabilities, Stock positions Tradable financial instruments representing a debt, such as bonds and notes. Domestic Creditors Obligations where one unit (the debtor) is obliged, under specific circumstances, to provide funds or other resources to another unit (the creditor). These include shares and other equity in corporations. The values of assets, liabilities, and equity held at a specific point in time.
F3_DD_A_SP Debt securities, Domestic Debtors, Assets, Stock positions Tradable financial instruments representing a debt, such as bonds and notes. Domestic Debtors Assets are a store of value representing a benefit or series of benefits accruing to the economic owner by holding or using the item over a period of time. It is a means of carrying forward value from one accounting period to another. The values of assets, liabilities, and equity held at a specific point in time.
F3_FC_L_SP Debt securities, Foreign Creditors, Liabilities, Stock positions Tradable financial instruments representing a debt, such as bonds and notes. Foreign Creditors Obligations where one unit (the debtor) is obliged, under specific circumstances, to provide funds or other resources to another unit (the creditor). These include shares and other equity in corporations. The values of assets, liabilities, and equity held at a specific point in time.
F3_FD_A_SP Debt securities, Foreign Debtors, Assets, Stock positions Tradable financial instruments representing a debt, such as bonds and notes. Foreign Debtors Assets are a store of value representing a benefit or series of benefits accruing to the economic owner by holding or using the item over a period of time. It is a means of carrying forward value from one accounting period to another. The values of assets, liabilities, and equity held at a specific point in time.
F3_L_SP Debt securities, Liabilities, Stock positions Tradable financial instruments representing a debt, such as bonds and notes. Obligations where one unit (the debtor) is obliged, under specific circumstances, to provide funds or other resources to another unit (the creditor). These include shares and other equity in corporations. The values of assets, liabilities, and equity held at a specific point in time.
GDD4D1_L_SP_FV_MI Gross debt (D1) debt liabilities, Stock positions, Face value, Memorandum Item The total debt liabilities categorized under classification D1, specifically including D1 debt liabilities. Obligations where one unit (the debtor) is obliged, under specific circumstances, to provide funds or other resources to another unit (the creditor). These include shares and other equity in corporations. The values of assets, liabilities, and equity held at a specific point in time. Face value Memorandum Item
GDD4D1_L_SP_LAG1O_MI Gross debt (D1) debt liabilities, Stock positions, Lag 1 (Opening), Memorandum Item The total debt liabilities categorized under classification D1, specifically including D1 debt liabilities. Obligations where one unit (the debtor) is obliged, under specific circumstances, to provide funds or other resources to another unit (the creditor). These include shares and other equity in corporations. The values of assets, liabilities, and equity held at a specific point in time. A variable used in calculations or comparisons to assess price movement or trends, referring to the opening price or value of the first period. Memorandum Item
GDD4D1_L_SP_MV_MI Gross debt (D1) debt liabilities, Stock positions, Market value, Memorandum Item The total debt liabilities categorized under classification D1, specifically including D1 debt liabilities. Obligations where one unit (the debtor) is obliged, under specific circumstances, to provide funds or other resources to another unit (the creditor). These include shares and other equity in corporations. The values of assets, liabilities, and equity held at a specific point in time. Market value Memorandum Item
GDD4D1_L_SP_NV_MI Gross debt (D1) debt liabilities, Stock positions, Nominal value, Memorandum Item The total debt liabilities categorized under classification D1, specifically including D1 debt liabilities. Obligations where one unit (the debtor) is obliged, under specific circumstances, to provide funds or other resources to another unit (the creditor). These include shares and other equity in corporations. The values of assets, liabilities, and equity held at a specific point in time. Nominal value Memorandum Item

Tipo de transformación:

list_dimension_values("GFS_BS", "TYPE_OF_TRANSFORMATION", filters = list(COUNTRY = "SLV", SECTOR = "S13"))
## # A tibble: 2 × 3
##   code     name              description                                        
##   <chr>    <chr>             <chr>                                              
## 1 POGDP_PT Percent of GDP    Value expressed as a percent of the Gross Domestic…
## 2 XDC      Domestic currency Currency issued by the country of origin, used int…

Se usa XDC para mantener la misma unidad (moneda doméstica, niveles) que en la sección de ingresos y gastos, y así poder comparar deuda contra ingresos/gastos en la misma escala si se desea más adelante.

datos_bs <- get_data(
  "GFS_BS",
  filters = list(
    COUNTRY = "SLV",
    SECTOR = "S13",
    GFS_GRP = grp_deuda$code[1],
    INDICATOR = ind_deuda$code[1],
    TYPE_OF_TRANSFORMATION = "XDC",
    FREQUENCY = "A"
  ),
  last_n_obs = 40
)

datos_bs <- datos_bs %>%
  mutate(TIME_PERIOD = as.integer(TIME_PERIOD)) %>%
  filter(!is.na(OBS_VALUE))

kable(head(datos_bs, 10))
COUNTRY SECTOR GFS_GRP INDICATOR TYPE_OF_TRANSFORMATION FREQUENCY TIME_PERIOD OBS_VALUE
SLV S13 BS F3_A_SP XDC A 2005 359400000
SLV S13 BS F3_A_SP XDC A 2006 292700000
SLV S13 BS F3_A_SP XDC A 2007 303700000
SLV S13 BS F3_A_SP XDC A 2008 388400000
SLV S13 BS F3_A_SP XDC A 2009 76300000
SLV S13 BS F3_A_SP XDC A 2010 79300000
SLV S13 BS F3_A_SP XDC A 2011 49602838
SLV S13 BS F3_A_SP XDC A 2012 -210303506
SLV S13 BS F3_A_SP XDC A 2013 252300000
SLV S13 BS F3_A_SP XDC A 2014 361066053
datos_bs %>%
  select(TIME_PERIOD, OBS_VALUE) %>%
  arrange(TIME_PERIOD) %>%
  tail(10) %>%
  kable(caption = "Deuda pública bruta del Gobierno General de El Salvador (moneda doméstica) - Últimos 10 años",
        col.names = c("Período", "Deuda Pública Bruta")) %>%
  kable_classic(html_font = "Times New Roman", font_size = 14) %>%
  add_footnote(label = "Fuente: API FMI (IMF.RES / WEO).", notation = "symbol") %>%
  kable_styling(full_width = FALSE, bootstrap_options = c("striped", "hover"))
Deuda pública bruta del Gobierno General de El Salvador (moneda doméstica) - Últimos 10 años
Período Deuda Pública Bruta
2015 279169600
2016 298573519
2017 326413241
2018 332800000
2019 379800000
2020 193700000
2021 443600000
2022 2403100000
2023 2226700000
2024 1380600000
* Fuente: API FMI (IMF.RES / WEO).

7.5 Deuda pública bruta

ggplot(datos_bs, aes(x = TIME_PERIOD, y = OBS_VALUE / 1e9)) +
  geom_line(linewidth = 1.1, color = "#542788") +
  geom_point(color = "#542788") +
  scale_x_continuous(breaks = pretty_breaks()) +
  labs(title = "Deuda pública bruta del Gobierno General de El Salvador",
       subtitle = "Miles de millones, moneda doméstica corriente. Fuente: FMI, GFS_BS",
       x = NULL, y = "Miles de millones") +
  theme_minimal()

7.6 Limitaciones

  • Los años sin datos (OBS_VALUE = NA) para El Salvador anteriores a 2002 se descartaron antes de graficar; no se investigó si corresponden a falta de reporte del país o a un vacío general de la base para esos años.
  • El “resultado operativo neto” de este documento es una aproximación metodológica, no el resultado fiscal oficial del FMI (NLB) — ver nota en la sección correspondiente.
  • La posible mezcla de colón/dólar dentro de la serie XDC (ver nota en la sección de ingresos y gastos) no se verificó directamente; aplica igual a la serie de deuda pública.
  • En la sección de deuda, grp_deuda$code[1] e ind_deuda$code[1] toman automáticamente la primera coincidencia si el filtro por palabra clave ("Liabilit|Balance Sheet", "Gross debt|Total liabilities|Debt securities") encuentra más de una. Antes de dar el resultado por definitivo, revisa las tablas grp_bs/grp_deuda e indicadores_bs/ind_deuda completas (impresas en la sección correspondiente) para confirmar que la primera fila es efectivamente el concepto de deuda bruta y no otro pasivo — no se verificó a mano cuál de las coincidencias es la correcta, solo que al menos una existe.

8. Dataset IMF.STA-LS (Labor Statistics)

El dataset Labor Statistics (LS) del Fondo Monetario Internacional contiene información relacionada con el mercado laboral de diferentes países. Sus datos permiten analizar aspectos como el empleo, el desempleo y la participación de la población en la fuerza laboral. Esta información es útil para conocer la situación y evolución del mercado de trabajo y realizar análisis económicos y sociales.

# --- Dataset LS de la agencia IMF.STA ---
datasets4 <- list_datasets(agency_id = "IMF.STA")
info_ls <- datasets4[datasets4$id == "LS", ]

# --- Consultar las dimensiones del dataset ---
dimensiones_ls <- list_dimensions("LS", agency_id = "IMF.STA")

dimensiones_ls %>% 
  kable(
    caption = "Dimensiones del Dataset LS del FMI"
  ) %>% 
  kable_classic(
    html_font = "Times New Roman",
    font_size = 14
  ) %>% 
  add_footnote(
    label = "Tomado de la API del FMI",
    notation = "symbol"
  ) %>% 
  kable_styling()
Dimensiones del Dataset LS del FMI
position id type name codelist_agency codelist_id codelist_version
0 COUNTRY Dimension Country IMF CL_COUNTRY 1.0+.0
1 INDICATOR Dimension INDICATOR NA NA NA
2 TYPE_OF_TRANSFORMATION Dimension TYPE_OF_TRANSFORMATION NA NA NA
3 FREQUENCY Dimension FREQUENCY NA NA NA
4 TIME_PERIOD TimeDimension TIME_PERIOD NA NA NA
* Tomado de la API del FMI

8.1 Ver valores validos para cada dimencion

# Ejemplo: países disponibles
paises_ls <- list_dimension_values("LS", "COUNTRY", agency_id = "IMF.STA")
print(paises_ls)
## # A tibble: 191 × 3
##    code  name                                                description
##    <chr> <chr>                                               <chr>      
##  1 ABW   Aruba, Kingdom of the Netherlands                   <NA>       
##  2 AFG   Afghanistan, Islamic Republic of                    <NA>       
##  3 AGO   Angola                                              <NA>       
##  4 AIA   Anguilla, United Kingdom-British Overseas Territory <NA>       
##  5 ALB   Albania                                             <NA>       
##  6 ARE   United Arab Emirates                                <NA>       
##  7 ARG   Argentina                                           <NA>       
##  8 ARM   Armenia, Republic of                                <NA>       
##  9 ATG   Antigua and Barbuda                                 <NA>       
## 10 AUS   Australia                                           <NA>       
## # ℹ 181 more rows

8.2 Indicadores disponibles

# --- Ver los valores de la dimensión INDICATOR dentro del dataset LS ---
indicadores_ls <- list_dimension_values(
  "LS",
  "INDICATOR"
)

indicadores_ls %>% 
  kable(
    caption = "Indicadores del Dataset LS del FMI"
  ) %>% 
  kable_classic(
    html_font = "Times New Roman",
    font_size = 14
  ) %>% 
  add_footnote(
    label = "Tomado de la API del FMI",
    notation = "symbol"
  ) %>% 
  kable_styling()
Indicadores del Dataset LS del FMI
code name description
E NA NA
LF NA NA
U NA NA
UP NA NA
WR NA NA
* Tomado de la API del FMI

E = Empleo (Employment) LF = Fuerza Laboral (Labor Force) U = Desempleo (Unemployment) UP = Tasa de Desempleo WR = Tasa Salarial / Salarios (Wage Rate / Wages)

Código Significado IX Index (Índice, con año base = 100) RT Rate (Tasa, generalmente %) NM Number (Número absoluto, ej. personas) PT Percent (Porcentaje)

8.3 EJEMPLOS DATASET LABOR STATISTICS (LS)

8.3.1 indicador WR (Tasa Salarial)

Datos de México (MEX) con indicador WR (Tasa Salarial)

# Datos de México (MEX) con indicador WR (Tasa Salarial)
datos_LS <- get_data(
  "LS",
  agency_id = "IMF.STA",
  filters = list(
    COUNTRY                = "MEX",
    FREQUENCY              = "A",
    INDICATOR               = "WR",
    TYPE_OF_TRANSFORMATION = "IX"   
  )
)

# --- TABLA DE DATOS ---
datos_LS %>% 
  mutate(TIME_PERIOD = as.numeric(TIME_PERIOD)) %>%
  arrange(desc(TIME_PERIOD)) %>%
  slice_head(n = 14) %>%
  arrange(TIME_PERIOD) %>%
  mutate(Variacion = (OBS_VALUE / lag(OBS_VALUE) - 1) * 100) %>%
  select(TIME_PERIOD, OBS_VALUE, Variacion) %>%
  kable(
    caption = "Tasa Salarial (WR) - FMI",
    digits  = 2,
    col.names = c("Año", "Tasa Salarial (Índice)", "Variación (%)")
  ) %>% 
  kable_classic(html_font = "Times New Roman", font_size = 14) %>% 
  add_footnote(label = "Tomado de la API del IMF", notation = "symbol") %>% 
  kable_styling(full_width = FALSE, bootstrap_options = c("striped", "hover"))
Tasa Salarial (WR) - FMI
Año Tasa Salarial (Índice) Variación (%)
2007 100.59 NA
2008 101.46 0.87
2009 100.69 -0.76
2010 100.00 -0.69
2011 100.22 0.22
2012 100.33 0.12
2013 100.45 0.12
2014 101.08 0.62
2015 102.05 0.96
2016 104.13 2.04
2017 104.34 0.19
2018 105.27 0.90
2019 108.09 2.68
2020 109.09 0.92
* Tomado de la API del IMF

Nota: 2020 (109.09) → los salario estaban un 9.09% por encima del nivel de 2010

8.3.2 Tasa de desempleo para Brasil (BRA) con indicador U (Desempleo)

# Tasa de desempleo para Brasil (BRA) con indicador U (Desempleo)
datos_LS <- get_data(
  "LS",
  agency_id = "IMF.STA",
  filters = list(
    COUNTRY                = "BRA",
    FREQUENCY              = "A",
    INDICATOR              = "U",
    TYPE_OF_TRANSFORMATION = "PT" 
  )
)

# --- TABLA DE DATOS CON TRANSFORMACIONES ---
datos_LS %>% 
  arrange(TIME_PERIOD) %>%                     # orden ascendente para calcular bien las variaciones
  mutate(
    Variacion_anual   = OBS_VALUE - lag(OBS_VALUE),        # diferencia en p.p. respecto al año anterior
    Promedio_movil_3a = zoo::rollmean(OBS_VALUE, k = 3, fill = NA, align = "right") # tendencia suavizada
  ) %>% 
  arrange(desc(TIME_PERIOD)) %>%     
  slice_head(n = 10) %>%             
  arrange(TIME_PERIOD) %>%           
  kable(
    caption = "Tasa de Desempleo (U) - FMI",
    col.names = c("País", "Indicador", "Transformación", "Frecuencia", "Año", 
                  "Tasa (%)", "Variación anual (p.p.)", "Promedio móvil 3 años (%)"),
    digits = 2
  ) %>% 
  kable_classic(html_font = "Times New Roman", font_size = 14) %>% 
  add_footnote(label = "Tomado de la API del IMF", notation = "symbol") %>% 
  kable_styling()
Tasa de Desempleo (U) - FMI
País Indicador Transformación Frecuencia Año Tasa (%) Variación anual (p.p.) Promedio móvil 3 años (%)
BRA U PT A 2015 8.31 1.52 7.43
BRA U PT A 2016 11.26 2.96 8.79
BRA U PT A 2017 12.77 1.51 10.78
BRA U PT A 2018 12.26 -0.51 12.10
BRA U PT A 2019 11.93 -0.33 12.32
BRA U PT A 2020 13.49 1.56 12.56
BRA U PT A 2021 13.50 0.01 12.97
BRA U PT A 2022 9.52 -3.98 12.17
BRA U PT A 2023 8.05 -1.47 10.36
BRA U PT A 2024 6.93 -1.11 8.17
* Tomado de la API del IMF
library(ggplot2)

# --- GRÁFICA: Tasa de Desempleo en Brasil (FMI) ---
ggplot(datos_LS, aes(x = as.numeric(TIME_PERIOD), y = as.numeric(OBS_VALUE))) +
  geom_line(color = "#2C3E50", linewidth = 1) +
  geom_point(color = "#E74C3C", size = 2) +
  labs(
    title = "Tasa de Desempleo en Brasil",
    subtitle = "Fuente: API del FMI (Dataset LS, Indicador U)",
    x = "Año",
    y = "Tasa de Desempleo (%)"
  ) +
  theme_minimal(base_size = 13) +
  theme(
    plot.title = element_text(face = "bold"),
    panel.grid.minor = element_blank()
  )

8.3.3 Fuerza laboral (LF) - Chile

datos_LS_LF_chile <- get_data(
  "LS",
  agency_id = "IMF.STA",
  filters = list(
    COUNTRY                = "CHL",
    FREQUENCY              = "A",
    INDICATOR               = "LF",
    TYPE_OF_TRANSFORMATION = "PE"
  )
)

datos_LF_chile_analisis <- datos_LS_LF_chile %>%
  mutate(
    TIME_PERIOD = as.numeric(TIME_PERIOD),
    OBS_VALUE   = as.numeric(OBS_VALUE)
  ) %>%
  arrange(TIME_PERIOD) %>%
  mutate(
    crecimiento_pct = (OBS_VALUE / lag(OBS_VALUE) - 1) * 100,
    media_movil_5   = zoo::rollmean(OBS_VALUE, k = 5, fill = NA, align = "right")
  )

datos_LF_chile_analisis %>%
  arrange(desc(TIME_PERIOD)) %>%
  slice_head(n = 10) %>%
  arrange(TIME_PERIOD) %>%
  select(TIME_PERIOD, OBS_VALUE, crecimiento_pct, media_movil_5) %>%
  kable(
    caption = "Fuerza Laboral en Chile - Últimos 10 Años",
    digits  = 2,
    col.names = c("Año", "Fuerza Laboral", "Crecimiento (%)", "Media Móvil (5 años)")
  ) %>% 
  kable_classic(html_font = "Times New Roman", font_size = 14) %>% 
  add_footnote(label = "Tomado de la API del IMF", notation = "symbol") %>% 
  kable_styling()
Fuerza Laboral en Chile - Últimos 10 Años
Año Fuerza Laboral Crecimiento (%) Media Móvil (5 años)
2016 9030564 1.61 8743464
2017 9279798 2.76 8908062
2018 9520909 2.60 9093498
2019 9715627 2.05 9286839
2020 8856914 -8.84 9280763
2021 9181799 3.67 9311010
2022 9684811 5.48 9392012
2023 9998005 3.23 9487431
2024 10218082 2.20 9587922
2025 10330338 1.10 9882607
* Tomado de la API del IMF
library(ggplot2)

grafico_LF_chile <- datos_LF_chile_analisis %>%
  arrange(desc(TIME_PERIOD)) %>%
  slice_head(n = 10) %>%
  arrange(TIME_PERIOD) %>%
  ggplot(aes(x = TIME_PERIOD)) +
  geom_line(aes(y = OBS_VALUE, color = "Fuerza Laboral"), linewidth = 1) +
  geom_point(aes(y = OBS_VALUE, color = "Fuerza Laboral"), size = 2) +
  geom_line(aes(y = media_movil_5, color = "Media Móvil (5 años)"),
            linewidth = 1, linetype = "dashed") +
  scale_color_manual(
    name = NULL,
    values = c("Fuerza Laboral" = "#1f77b4", "Media Móvil (5 años)" = "#d62728")
  ) +
  scale_x_continuous(breaks = unique(datos_LF_chile_analisis$TIME_PERIOD)) +
  labs(
    title    = "Fuerza Laboral en Chile - Últimos 10 Años",
    subtitle = "Datos anuales con media móvil de 5 años",
    x        = "Año",
    y        = "Fuerza Laboral (personas)",
    caption  = "Fuente: API del IMF"
  ) +
  theme_minimal(base_size = 13) +
  theme(
    plot.title    = element_text(face = "bold"),
    legend.position = "bottom",
    axis.text.x   = element_text(angle = 45, hjust = 1)
  )

grafico_LF_chile

9. Conclusiones

Las API constituyen una herramienta fundamental para el análisis económico, ya que facilitan el acceso, automatización, organización y actualización de grandes cantidades de información estadística. En particular, la API del Fondo Monetario Internacional (FMI) permite conectar herramientas como R con bases de datos internacionales, haciendo posible obtener información de manera sistemática, reproducible y útil para el análisis económico.

La aplicación práctica mediante los datasets BOP y WEO permitió observar cómo esta herramienta puede pasar de un concepto técnico a una herramienta concreta de investigación económica. En el caso de El Salvador, los datos de la balanza de pagos muestran que, aunque las exportaciones de bienes y servicios aumentaron de aproximadamente US$4,971 millones en 2010 a US$11,392 millones en 2024, las importaciones también mantuvieron un nivel superior, alcanzando aproximadamente US$18,494 millones en 2024.

Esto se relaciona con la persistencia de saldos negativos en la cuenta corriente durante la mayor parte del período analizado, con la excepción de 2020. Por otra parte, el dataset WEO permitió ampliar el análisis hacia variables como crecimiento económico e inflación y realizar comparaciones con otros países de Centroamérica. Los resultados muestran que El Salvador experimentó una fuerte contracción del PIB real en 2020 (-7.89 %), seguida de una recuperación de 11.90 % en 2021; posteriormente, el crecimiento se desaceleró hasta 2.60 % en 2024. Las proyecciones utilizadas en el ejercicio señalan una tendencia hacia tasas cercanas al 3 % anual en los años siguientes.

En materia de inflación, después del aumento registrado en 2022 (7.20 %), esta disminuyó hasta 0.85 % en 2024, con proyecciones de moderación en los años posteriores. En este sentido, el valor de una API no se limita a obtener datos rápidamente, sino que reside en la posibilidad de convertir información estadística en evidencia para interpretar la realidad económica. Sin embargo, los resultados también evidencian que los datos por sí mismos no explican las causas de los fenómenos económicos; requieren conocimientos estadísticos, económicos y políticos para ser correctamente interpretados. Además, existen limitaciones relacionadas con la disponibilidad y actualización de los datos, las diferencias metodológicas entre países y la posibilidad de cometer errores al realizar las consultas.

10. Referencias Bibliograficas

Referencias

Amazon Web Services. (s. f.). ¿Qué es una interfaz de programación de aplicaciones (API)? https://aws.amazon.com/es/what-is/api/

Fondo Monetario Internacional. (s. f.). Balance of Payments (BOP). IMF Data. https://data.imf.org/Datasets/BOP

Fondo Monetario Internacional. (2009). Balance of Payments and International Investment Position Manual (BPM6). International Monetary Fund. https://data.imf.org/-/media/iData/External-Storage/Documents/73FBCD5B6CDE4D289C60B9B0CAA40622/en/2-bpm6.pdf

Fondo Monetario Internacional. (2025). IMF SDMX Central Web Services Guide. https://dsbb.imf.org/content/pdfs/IMFSDMXCentralWebServicesGuide.pdf

Fondo Monetario Internacional. (2026). IMF Data APIs. IMF Data. https://data.imf.org/en/Resource-Pages/IMF-API

Fondo Monetario Internacional. (2026). IMF DataMapper API documentation. https://www.imf.org/external/datamapper/api/

Fondo Monetario Internacional. (2026). IMF SDMX Central: REST Web Service. https://sdmxcentral.imf.org/webservice/structure.html

R Core Team. (2026). R: A language and environment for statistical computing. R Foundation for Statistical Computing. https://www.R-project.org/

SDMX. (2026). Statistical Data and Metadata eXchange (SDMX). https://sdmx.org/

Teal Insights, Smith, C. C., & Scheuch, C. (2025). imfapi: Econdataverse ‘IMF Data API’ Client (Version 0.1.2) [Paquete de R]. CRAN. https://CRAN.R-project.org/package=imfapi