How to calculate inflation in Mexico with INEGI’s API in python


In this post, I’ll go over how to make a python script that downloads the consumer price index in Mexico, calculates inflation, and outputs the values to the terminal.

Below is an explanation of the script and how to set it up.

If you want to skip to the code, you can jump to the end of the post or look at the GitHub repository here.

You can see an example of the script being executed below:

Gif of the python script being run from start to finish. The script is called through an alias.

What is Inflation

Inflation is the rate at which prices for goods and services rise over time. To measure it, governments track the price of a basket of selected goods over a period of time.

In Mexico, the the National Institute of Statistics and Geography (INEGI) is charged with this task and the metric is called: Indice de precios al consumidor https://www.inegi.org.mx/temas/inpc/(INPC). It is the equivalent to the Consumer Price Index (CPI) in the USA.

Why keep track on inflation

Keeping track of inflation may be useful, as lots of things are tied to it, for example:

  • Prices of assets
  • Rent renewal amounts
  • Loan interest rates
  • Taxes
  • Wage increases (hopefully)

What the python script does

INEGI created an API where we can fetch Mexico’s consumer price index data , so I created a python script to fetch the information, calculate the inflation rate, and display it in the terminal as output.

Since inflation is a rate of change, with the script you can chose any two dates and calculate the inflation rate for that time period.

How to Install

To use this script, you must have previously installed python3 and the following python libraries:

You will also need a (free) API token from INEGI, which you can get here:

Once you have the API token, paste it in the file named:

api_key_blank.py

Rename the file to:

    api_key.py

You can then run the python script from your terminal using the command:

python3 INPC.py

How to use the python script

When running the script, the terminal will automatically display the last consumer price index value.

Terminal output of python script showing last CPI value.
The last value is automatically reported

To calculate inflation for a period, the script will then ask the user to input an initial month and year in the following format: yyyy-mm.

As an example, October 1998 would be: 1998-10.

Then the script will ask the user to input a final date in the same format: yyyy-mm.

Terminal output of python script showing the input start and end dates.
An example showing the terminal after the user inputs a start and end date

After both dates have been entered the terminal will output ¡ the following data:

  • The INPC values for every month in the period. (in case you want the raw data).
  • The INPC value for the start date
  • The INPC value for the end date
  • The adjustment factor (1.0588 in the example)
  • The inflation rate for the period (5.88% in the example)

You can use the adjustment factor to adjust any value to account for inflation.

For example, a rent that was originally $10,000 would be multiplied by 1.0588 (in the example) and would be adjusted to $10,580 after inflation.

Terminal output of python script showing the CPI outputs for the period selected, as well as inflation for the period.

Use cases for the inflation script

It can help to quickly make calculations for adjusting:

– Rent prices.
– A stock’s cost basis.
– The minimum salary increase to maintain purchasing power.
– Any asset value that is periodically adjusted for inflation.

In the news, when the inflation rate is mentioned, it refers to the change in prices in the last 12 months. With the script,

In the news, when the inflation rate is mentioned, it refers to the change in prices in the last 12 months.

With the script, I’m able to calculate the difference for any period I need in less than 60 seconds. It’s a simple script that I use a at work constantly, since it saves me time and allows me to fetch inflation data with ease.

Conclusion

I hope you found this post interesting.

Feel free to contact me if you have any suggestions or comments.

You can check out my other projects here.

Pablo.

Full Script

# Programa para mostrar los valores del INPC de un periodo
# y calcular la inflacion durante ese periodo.

# Imports del Programa
#######################
import api_key
# Para importar el token de INEGI
import locale
# Para mostrar las fechas en Español
import requests
# Para enviar HTTP requests usando Python
import pandas as pd
# Para transformar los datos en un DataFrame

# Descargando la base de datos de INEGI
#######################################
locale.setlocale(locale.LC_ALL, "es_ES.UTF-8")
# Mostrar los meses en Español
token = api_key.token_inegi
# token = open('api_key', 'r').read()
# Alternative to try out

# Token de Consulta INEGI
inpc = "628194"  # INPC Mensual
# Serie de Consulta:
consulta = "false"
# Consulta de ultimo dato o serie completa:
#     Serie completa = "false"
#     Ultimo dato = "true"


# Funcion de Descarga de Datos:
###############################
def serie_inegi():
    # Al site de INEGI se le añaden los datos de consulta
    url = (
        "https://www.inegi.org.mx/app/api/indicadores/"
        + "desarrolladores/jsonxml/INDICATOR/"
        + inpc
        + "/es/0700/"
        + consulta
        + "/BIE/2.0/"
        + token
    )

    global status
    # Status global para unitest
    response = requests.get(url)
    # Se pasa como un request con metodo get
    status = response.status_code
    # Se le solicita el codigo de respuesta al servidor.

    if status == 200:
        # Si el estatus esta Ok crear el dataframe
        content = response.json()
        # Guarda la respuesta como una variable
        data = content["Series"][0]["OBSERVATIONS"]
        # Se filtra el json
        # Se accesa el diccionario con los datos
        global df
        # Hacemos que la variable df sea global para poder accesarla despues
        df = pd.DataFrame(data)
        # Creamos un dataframe con la informacion
        df.drop(columns=["OBS_EXCEPTION",
                         "OBS_STATUS",
                         "OBS_SOURCE",
                         "OBS_NOTE",
                         "COBER_GEO",
                         ],
                inplace=True,)
        # Eliminiamos las columnas que no necesitamos
        df.columns = ["Fecha", "INPC"]
        # Renombramos las columnas a Fecha e INPC
        df["INPC"] = df["INPC"].apply(lambda x: float(x))
        # Volvemos los datos del INPC floats en vez de strings
        df["Fecha"] = pd.to_datetime(df["Fecha"], format="%Y/%m")
        # Volvemos las fechas a formato de fecha
        df["Año"] = pd.DatetimeIndex(df["Fecha"]).year
        # Creamos las columna de Año
        df["Mes"] = (pd.DatetimeIndex(df["Fecha"])
                     .month_name(locale="es_ES.UTF-8"))
        # Creamos las columna de Mes en español
        df = df.reindex(columns=["Fecha", "Año", "Mes", "INPC"])
        # Reordenamos las columnas
        df.set_index("Fecha", inplace=True)
        # Volvemos la fecha la columna indice
        return df
        # Regresa el Dataframe
    else:
        # Si el estatus esta mal imprimir el Error en la consulta.
        print(status)


# Ejecutando la Solicitud de Descarga
#####################################
consulta_inpc = serie_inegi()

if __name__ == "__main__":

    # Obteniendo fechas para filtrar tabla del INPC
    #################################################
    print("\n Calculadora de Inflacion V1. 17-Feb-21 \n")
    print("Ultimo Valor reportado por el INEGI: \n")
    print((df.iloc[[0], [0, 1, 2]]).to_string(index=False))
    print("\n Fecha Inicial de Cálculo yyyy-mm: ")
    start_date = pd.to_datetime(input())
    print("Fecha Final de Cálculo yyyy-mm: ")
    end_date = pd.to_datetime(input())

    # Mostrando la informacion Filtrada
    ###################################
    df2 = df.loc[end_date:start_date]
    # Creamos un nuevo DataFrame solo con la info que nos interesa ver

    # Calculamos la inflacion del Periodo
    #####################################
    start_value = df2["INPC"].values[-1]
    end_value = df2["INPC"].values[0]
    inflacion = ((end_value / start_value) - 1) * 100
    inflacion_redondeada = round(inflacion, 2)
    factor_ajuste = end_value / start_value
    factor_ajuste_truncado = round(factor_ajuste, 4)

    # Mostramos la informacion sin el indice
    ########################################
    print("\n")
    print(df2.to_string(index=False))

    # Mostramos la inflacion del periodo
    ####################################
    print("\nEl INPC Inicial del periodo es: " + str(start_value))
    print("El INPC Final del periodo es:: " + str(end_value))
    print("El Factor de ajuste es: " + str(factor_ajuste_truncado))
    print(("La inflacion del periodo fue de: "
           + str(inflacion_redondeada)
           + "%\n"
           ))

Go back to top


Leave a Reply

Your email address will not be published. Required fields are marked *