Building a U.S.–Cuba Export Tracker with Python and the Census API

in StemSocial • 5 days ago (edited)

The latest U.S.-Cuba Trade and Economic Council report, published on October 8, 2026, propelled me to a new endeavour related to my work on technical solutions to make U.S. Cuba policy more readable. American agricultural and food exports to Cuba reached $60.1 million in August 2026, a 54.6% increase over August 2025. For January–August, the corresponding total was $314.3 million. These figures introduce questions about product composition, market opportunities, monthly fluctuations, and the commercial space that remains accessible despite the complex U.S. sanctions regime I cover with this tracker. Thus, I have been developing a Python-based tool with Claude's Sonnet 5.5 to explore these questions independently, using publicly available data from the U.S. Census Bureau, the source of all this data.

The technical architecture

The application combines five components:

  • Census API: retrieves monthly export data directly from the official source.

  • Python and Requests: handle API requests, responses, and errors.

  • Pandas and NumPy: clean, aggregate, and analyze time series.

  • Streamlit: provides an interactive interface without requiring a separate frontend.

  • Plotly: generates interactive charts for exploring trade patterns.

The API endpoint used by the tracker is:

BASE_URL = (
    "https://api.census.gov/data/"
    "timeseries/intltrade/exports/hs"
)

params = {
    "get": (
        "YEAR,MONTH,E_COMMODITY,"
        "E_COMMODITY_LDESC,ALL_VAL_MO,ALL_VAL_YR"
    ),
    "CTY_CODE": "2390",  # Cuba
    "COMM_LVL": "HS6",
    "time": "from 2025-01 to 2025-12",
    "key": api_key,
}

response = requests.get(
    BASE_URL, params=params, timeout=90
)
response.raise_for_status()

Rather than downloading a static report, we query a structured data service and choose the dimensions we need. The API supports product classifications at different levels of detail, from broad categories to ten-digit codes. One particularly useful feature is customizable product filtering. For example, we can investigate agricultural and food products using Harmonized System chapter prefixes, then narrow the selection to specific commodities. The tracker also offers selectable year ranges and months. Thus, users examine monthly totals, month-over-month changes, year-over-year variations, and individual product categories. Results can also be exported as CSV files for further analysis.

def classify_mask(codes, include, exclude):
    mask = codes.str.startswith(
        tuple(include)
    ) if include else codes.notna()

    if exclude:
        mask &= ~codes.str.startswith(
            tuple(exclude)
        )

    return mask

The interface also supports detailed product-by-port analysis at the HS10 level, so we can explore trade composition and U.S. export districts rather than relying solely on aggregate figures. Historical totals are available through Census's separate trade-balance page, extending the timeline to 1992; detailed API-based product analysis begins in 2013. Keeping these sources distinct prevents us from confusing historical totals with more granular observations.

Why this matters beyond programming

The broader project connects data analysis with practical education about Cuba–U.S. commercial regulations. Identifying product classifications and examining actual trade flows can help (private) entrepreneurs formulate better questions and investigate potential markets.

The same approach supports independent verification of published reports. The Council remains a useful reference, but its periodic analyses are no longer the only practical starting point: we can develop our own queries, test alternative product definitions, and update our analysis as new data become available.

That is precisely why this tracker belongs in STEM education. It combines API literacy, data engineering, statistical reasoning, visualization, and critical interpretation in one practical project. The goal is not merely to read trade data more efficiently, but to make evidence accessible, reproducible, and useful.

Sort:  

Los $60.1 millones de agosto, un 54.6% arriba contra 2025, es el dato que engancha. ¿El tracker ya te deja ver qué productos HS6 explican ese salto o todavía estás peleando con la agregación en Pandas? Está bueno que consultes la API en vivo en vez de comerte el PDF estático.

Acabo de agregar la funcionalidad. Como notas en la imagen, el aumento está determinado por las exportaciones de aceite. El año pasado, literalmente, no se exportaba. Al parecer, dadas las restricciones impuestas incluso al transporte marítimo hacia Cuba, se está importando más de USA gracias al sistema de licencias para los productos agrícolas.

no sabia que existia una api publica para eso :D

Pues sí, y es súper productiva; he añadido más consultas para casi todos los endpoints. Saludos.

Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).

Thanks for including @stemsocial as a beneficiary of this post and your support for promoting science and education on Hive. 
 

Congratulations @limonta! You have completed the following achievement on the Hive blockchain And have been rewarded with New badge(s)

You received more than 17000 HP as payout for your posts, comments and curation.
Your next payout target is 18000 HP.
The unit is Hive Power equivalent because post and comment rewards can be split into HP and HBD

You can view your badges on your board and compare yourself to others in the Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

@limonta's week on scrobble.life 🎵

limonta — this week

This week: 42 music scrobbles · 2 hrs listened · top artists: Wisin & Yandel, Machito, Ibeyi.

All-time

limonta — all-time

Full breakdown → https://scrobble.life/u/limonta/stats


Auto-posted by scrobble.life, the open music scrobbler on Hive. Author rewards are burned. Don't want these? Reply STOP or turn them off on your profile.