How to make a python script to get the usd:mxn exchange rate

Bank of Mexico Currency Exchange

In this post, I’ll go over how to make a python script that downloads the official exchange rate for the Mexican Peso and the USD for a given time range 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 end of the page or the GitHub repository here (English) or here (Spanish).

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

Image of the python script executed in the Terminal. The script asks for a date range, calls the API and returns the FX for the date range.
An example of the finished script

Why I created the script

In another post, I explained the different types of currency exchange posted by the Bank of Mexico, how they are related, and which one needs to be used for tax purposes in Mexico.

This is important for Mexican companies and individuals investing in international markets, since they report all transactions (buys, sells, gains, etc.) in Mexican Pesos in their annual tax returns.

It is also important for companies with operations in both the USA and Mexico since they need a consistent way of converting their transactions into both currencies.

Measuring consistently avoids confusion and using official rates simplifies audits, avoids penalties and ensures compliance with tax authorities.

The script was made as a fast and easy way of getting the necessary values.

What the script does

The Bank of Mexico created an API where we can get Mexico’s exchange rate for any date range between the 12th of November 1991 and today.

The python script asks the user for a beginning date and end date. It then makes a request to the API to get the corresponding FX values for the date range and displays them as output in the terminal window.

How to install

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

To install use the following commands:

pip install requests
pip install pandas

You will also need a free API token from the Bank of Mexico, which you can get here.

Image of Banxico website where you can get an API token for the python script.
Getting an API token from Banxico

Once you have the token, paste it into the script in the following section:

# Get the API Token
####################
# api_token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

One way to increase security is to hide the token in a separate file and import it as an environment variable. You can find a tutorial on how to do this here.

How to use the script

Once all the dependencies are installed and you’ve pasted the token in the script, you can run it using:

python3 fx_get_terminal.py

To make it easy to execute the script on a regular basis, I would recommend that you add it as an alias in your shell.

When run, the script will ask you to input a start and end date.

It will get the daily USD:MXN values for that time period and output the values in the terminal.

You can then copy the values to wherever you need them.

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

# Script to display the MXN:USD exchange rate
# For a given time period in the terminal

# Imports
#########
import os
import requests
import pandas as pd

# Get the API Token
#####################
api_token = os.environ.get("token_banxico")
# api_token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx'  # Alternative


# Function to download data
###########################
def download_banxico(series, start_date, end_date, token):
    www = "https://www.banxico.org.mx/SieAPIRest/service/v1/series/"
    url = (www
           + series
           + "/datos/"
           + start_date
           + "/"
           + end_date
           )
    # Create a dictionary with the API Token
    headers = {"Bmx-Token": token}
    # Create a GET request to the API
    response = requests.get(url, headers=headers)
    # Check the status code
    status = response.status_code
    # If status code is Ok:
    if status == 200:
        # Return json object
        raw_data = response.json()
        # Access the data inside the object
        data = raw_data["bmx"]["series"][0]["datos"]
        # Create a dataframe from the data
        df = pd.DataFrame(data)
        # Transform values from strings to floats
        df["dato"] = df["dato"].apply(lambda x: float(x))
        # Transform dates from strings to datetime
        df["fecha"] = pd.to_datetime(df["fecha"], format="%d/%m/%Y")
        # Rename columns
        df.columns = ['Date', 'Exchange Rate']
        return(df)
    # If status fails:
    else:
        # Print the error for user to debug
        print(status)


if __name__ == '__main__':

    # Defining the date Range
    #########################
    print("\nThis script will fetch the official MXN:USD exchange rate for a period: \n")
    start_date = input("Input the start date yyyy-mm-dd: ")
    end_date = input("Input the end date yyyy-mm-dd: ")

    # Determining API series: 'Para solventar Obligaciones'
    #######################################################    
    obligaciones = "SF60653"

    # Execute the function
    ######################
    df = download_banxico(obligaciones,
                          str(start_date),
                          str(end_date),
                          api_token)

    # Display the data in the terminal
    ##################################
    print("\n")
    print(df.to_string(index=False))
    print("\n")

Go back to top


Leave a Reply

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