from __future__ import annotations import calendar import csv import json import re from datetime import datetime from pathlib import Path import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt from matplotlib.ticker import StrMethodFormatter from openpyxl import load_workbook HERE = Path(__file__).resolve().parent ROOT = HERE.parents[3] SOURCE = "https://www.trade.gov/i-94-arrivals-program" EXTRACT = "relevant_ntto_visitor_arrivals_monthly" ALL = "TOTAL ALL COUNTRIES" OVERSEAS = "OVERSEAS" MONTHS = range(1, 9) INK = "#142334" COLORS = ("#21615e", "#9c3930", "#2b527f", "#5d7831") def read_workbook(): manifest = ROOT / "research/relevant_data_manifest_2026-12-02.json" record = next(x for x in json.loads(manifest.read_text(encoding="utf-8"))["items"] if x["id"] == EXTRACT) workbook = load_workbook(ROOT / record["local_path"], data_only=True, read_only=True) try: rows = list(workbook["Monthly"].values) finally: workbook.close() months = {} for index in range(3, 323): label = rows[0][index] if isinstance(label, datetime): month = (label.year, label.month) else: match = re.fullmatch(r"(20\d\d)-(\d{1,2})", label) if match is None: raise ValueError(f"Unexpected month label {label!r}") month = tuple(map(int, match.groups())) expected = (2000 + (index - 3) // 12, (index - 3) % 12 + 1) if month != expected: raise ValueError(f"Missing or out-of-order month {expected}") months[index] = month data = { row[1].strip(): {month: row[index] for index, month in months.items() if isinstance(row[index], int)} for row in rows[2:] if isinstance(row[1], str) and any(isinstance(row[index], int) for index in months) } return data, record def total(data, key, year): return sum(data[key][year, month] for month in MONTHS) def compute(data): regional = ["AFRICA", "ASIA", "CARIBBEAN", "CENTRAL AMERICA", "EASTERN EUROPE", "WESTERN EUROPE", "MIDDLE EAST", "OCEANIA", "SOUTH AMERICA"] years = list(range(2019, 2027)) categories = ["Canada", "Mexico", OVERSEAS] annual = {key: [total(data, key, year) for year in years] for key in (ALL, *categories, *regional)} for i, year in enumerate(years): if annual[ALL][i] != sum(annual[key][i] for key in categories): raise ValueError(f"Published geographic totals do not add to the world subtotal in {year}") month_delta = { key: [data[key][2026, month] - data[key][2025, month] for month in MONTHS] for key in (ALL, *categories) } market_lists = {"Western Europe": ("United Kingdom", "Germany", "France", "Italy"), "Asia": ("Japan", "China", "South Korea", "India")} markets = { region: {country: {year: total(data, country, year) for year in (2019, 2025, 2026)} for country in countries} for region, countries in market_lists.items() } return years, annual, month_delta, regional, markets def make_chart(folder, number, tag, title, question, period, unit, takeaway, labels, series, kind="bar"): stem = f"chart-{number:02d}-{tag}" folder.mkdir(parents=True, exist_ok=True) with (folder / (stem + ".csv")).open("w", encoding="utf-8", newline="") as output: writer = csv.writer(output) writer.writerow(["Group", *series]) writer.writerows(zip(labels, *series.values(), strict=True)) figure, ax = plt.subplots(figsize=(7.3, 4.3), layout="constrained") figure.patch.set_facecolor("#fbf7ef") ax.set_facecolor("#fbf7ef") ax.set_title(title, color=INK, fontsize=13, fontweight="bold", loc="left", pad=13) xs = list(range(len(labels))) if kind == "line": for color, (label, values) in zip(COLORS, series.items()): ax.plot(xs, values, label=label, marker="o", linewidth=2, color=color) ax.set_xticks(xs, labels) ax.set_ylabel(unit, color=INK) ax.yaxis.set_major_formatter(StrMethodFormatter("{x:,.0f}")) ax.grid(axis="y", alpha=.22) else: step = .78 / len(series) for position, (label, values) in enumerate(series.items()): locations = [point + step * (position - (len(series) - 1) / 2) for point in xs] colors = [COLORS[0] if v >= 0 else COLORS[1] for v in values] if len(series) == 1 else COLORS[position] ax.barh(locations, values, height=step * .92, label=label, color=colors) ax.set_yticks(xs, labels) ax.set_xlabel(unit, color=INK) ax.invert_yaxis() ax.axvline(0, color=INK, linewidth=.8) ax.xaxis.set_major_formatter(StrMethodFormatter("{x:,.0f}")) ax.grid(axis="x", alpha=.22) if len(series) > 1: ax.legend(frameon=False, fontsize=8, loc="best") ax.tick_params(colors=INK, labelsize=9) for spine in ax.spines.values(): spine.set_visible(False) figure.text(.015, .005, "Source: National Travel and Tourism Office, I-94 Arrivals, country of residence", color=INK, fontsize=7) figure.get_layout_engine().set(rect=(0, .035, 1, .965)) figure.savefig(folder / (stem + ".png"), dpi=165) plt.close(figure) return {"asset": "charts/" + stem + ".png", "data": "charts/" + stem + ".csv", "question": question, "source": SOURCE, "population": "NTTO eligible nonresident visitor arrivals by country of residence", "period": period, "unit": unit, "takeaway": takeaway} def main(): data, record = read_workbook() years, annual, monthly, regions, markets = compute(data) folder = HERE / "charts" citations = [] def add(*args, **kwargs): citations.append(make_chart(folder, len(citations) + 1, *args, **kwargs)) add("recovery", "The 2024 recovery lost ground in 2025 and 2026", "How far has the national count recovered?", "January–August 2019–2026", "Million arrivals", "The same eight months in 2026 fell below the 2024 recovery high.", years, {"All countries": [y / 1e6 for y in annual[ALL]]}, kind="line") places = ["Canada", "Mexico", OVERSEAS] add("offset", "Mexico offset most of two declines", "How much did each of the three published components change?", "January–August 2025 to January–August 2026", "Change in thousands of arrivals", "An increase of roughly 1.52 million in the Mexico row offset most of the overseas and Canada losses.", ["Canada", "Mexico", "Overseas", "Net change"], {"Change": [(annual[k][-1] - annual[k][-2]) / 1000 for k in (*places, ALL)]}) add("mix", "Mexico took a larger share of the total", "How did the composition change across the recovery?", "January–August 2019, 2024, 2025 and 2026", "Share of total arrivals (%)", "The Canada and overseas shares were lower in 2026 than in 2019, while Mexico's was higher.", [2019, 2024, 2025, 2026], {k.title(): [100 * annual[k][i] / annual[ALL][i] for i in (0, 5, 6, 7)] for k in places}, kind="line") add("months", "The national and overseas series parted in May and June", "Which 2026 months differed from the same month in 2025?", "January–August 2025 and 2026", "Year-over-year change in thousands", "All-country arrivals rose in May and June while overseas arrivals fell in both months.", [calendar.month_abbr[m] for m in MONTHS], {k.title(): [v / 1000 for v in monthly[k]] for k in (ALL, OVERSEAS)}) add("regional-recovery", "Overseas recovery varies by region", "Which printed overseas regions returned to their 2019 level?", "January–August 2019, 2025 and 2026", "2026 change from baseline (%)", "South America moved closer to its 2019 level, while Western Europe and Asia moved farther away compared with 2025.", [x.title() for x in regions], {str(yr): [100 * (annual[k][-1] / annual[k][years.index(yr)] - 1) for k in regions] for yr in (2019, 2025)}) add("summer-gap", "The 2019 summer gap widened toward August", "How far below the corresponding 2019 month were overseas arrivals?", "January–August 2019 and 2026", "Gap in thousands of overseas arrivals", "August's gap was larger than July's and just below one million arrivals.", [calendar.month_abbr[m] for m in MONTHS], {"2026 minus 2019": [(data[OVERSEAS][2026, m] - data[OVERSEAS][2019, m]) / 1000 for m in MONTHS]}, kind="line") for region, baseline in (("Western Europe", 2025), ("Asia", 2019)): panel = markets[region] parent = annual[region.upper()] net = parent[-1] - parent[years.index(baseline)] selected = {k: v[2026] - v[baseline] for k, v in panel.items()} remaining = net - sum(selected.values()) unit = "Change in thousands of arrivals" if region == "Western Europe": title = "Germany and France account for sizable European losses" question = "How did selected residence markets contribute to the Western European change?" insight = "The United Kingdom decline was relatively small beside Germany and France." else: title = "India is above 2019 while Japan and China are below it" question = "Which large Asian markets moved in different directions from 2019?" insight = "India offsets part of the declines in Japan, China and South Korea." add(region.casefold().replace(" ", "-"), title, question, f"January–August {baseline} and 2026", unit, insight, [*selected, "Rest of region"], {"Change": [v / 1000 for v in [*selected.values(), remaining]]}) (HERE / "CHART-PLAN.json").write_text(json.dumps(citations, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") evidence = {"snapshot": {k: record[k] for k in ("source_url", "local_path", "sha256", "captured_utc")}, "years": years, "first_eight_months": annual, "changes_by_month": monthly, "regional_market_detail": markets} (HERE / "evidence.json").write_text(json.dumps(evidence, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") if __name__ == "__main__": main()