Technical writing

Census Foreign Trade Statistics: The HS-Code Import and Export Database Behind Every US Trade Policy Decision

· AI Analytics
CensusTradeImportsExportsFederal Data

Every month the Census Bureau's Foreign Trade Division releases statistics that determine how the White House frames trade policy, how the Federal Reserve models external demand, and how Congress debates tariff legislation. Those figures — compiled from tens of millions of customs entry records and electronic export filings — sit inside the most granular goods-trade database in the world: monthly import and export values by 10-digit commodity code, country, and port of entry, freely downloadable from a federal website most Americans have never heard of.

The headline FT-900 trade deficit number that moves currency markets is just the aggregate of this underlying dataset. The commodity-level detail beneath it reveals which specific products are flowing through which ports from which countries, at what declared value, and under which tariff classification. This article covers the architecture of that dataset: how the Census Bureau collects it, how the Harmonized System classification works, what the current major trade flows look like, where to access the data, and how to use the Census API to analyze the most consequential sourcing shift of the past decade — the movement of semiconductor procurement away from China.

The Census Bureau's role in trade statistics

The Census Bureau Foreign Trade Division (FTD) is the federal statistical agency responsible for compiling monthly import and export statistics for goods. It does not collect this data directly — it accesses administrative data generated by two existing enforcement systems.

For imports, FTD pulls entry records from US Customs and Border Protection's Automated Commercial Environment (ACE), the electronic platform through which importers and their brokers file customs entry documents for every shipment crossing the border above the de minimis threshold. Each ACE record contains the 10-digit Harmonized Tariff Schedule (HTS) commodity code, the country of origin, the port of entry, the declared customs value, and quantity in the HTS-defined unit of measure. CBP uses this data for tariff collection and border enforcement; FTD uses it to build trade statistics.

For exports, FTD uses Electronic Export Information (EEI) submitted by exporters through the Automated Export System (AES). Exporters are required to file EEI for most shipments valued above $2,500, for all shipments requiring an export license under Export Administration Regulations or the International Traffic in Arms Regulations (ITAR), and for certain other categories. The EEI record captures the 10-digit Schedule B commodity code, the destination country, the port of export, and the FOB value at the US port.

Census trade data covers goods only. It does not include services trade (financial services, travel, insurance, intellectual property royalties, transportation), which are captured separately by the Bureau of Economic Analysis through surveys and financial account data. The monthly FT-900 U.S. International Trade in Goods and Services report — published jointly by Census and BEA — splices the two together to produce the combined balance. An advance goods-only trade balance is released approximately 30 days after the reference month closes. The full goods-plus-services report follows at roughly 60 days. Both are freely accessible, and all underlying Census trade data is downloadable at no cost from USA Trade Online (usatrade.census.gov).

The Harmonized System: chapters, headings, and subheadings

Every traded good that crosses an international border is classified under the Harmonized Commodity Description and Coding System — universally known as the Harmonized System (HS) — developed and maintained by the World Customs Organization (WCO). The HS provides a six-digit international standard for classifying traded goods; individual countries extend it to eight or ten digits for domestic tariff and statistical purposes.

The HS is hierarchical. The broadest level is the two-digit chapter. There are 97 active chapters (Chapter 77 is reserved; Chapters 98–99 are US-specific special provisions). Chapters represent the broadest product groupings: Chapter 01 covers live animals, Chapter 27 covers mineral fuels and petroleum products, Chapter 84 covers machinery and mechanical appliances, Chapter 85 covers electrical machinery and electronics, and Chapter 87 covers vehicles and their parts. For US trade, chapters 84 and 85 together represent the single largest import category by value.

Within chapters, four-digit headings provide finer classification. Chapter 85, for example, contains heading 8542 (electronic integrated circuits — semiconductors) alongside 8471 (data-processing machines), 8528 (monitors and television receivers), and dozens of others. The international standard stops at the six-digit subheading: subheading 8542.31 covers processors and controllers, 8542.32 covers memories, 8542.33 covers amplifiers, and 8542.39 covers other integrated circuits. These six-digit codes are standardized across all countries that have adopted the HS — effectively all major trading nations — enabling direct cross-country trade flow comparison.

The United States extends HS-6 to ten digits for domestic purposes using two separate national schedules. Imports are classified under the Harmonized Tariff Schedule of the United States (HTS), administered by the US International Trade Commission (USITC). The HTS is the authoritative tariff schedule: the duty rate, any preferential rates for free trade agreement partners, and any additional tariff actions (Section 301 or Section 232) are all tied to the 10-digit HTS subheading. Exports are classified under the Schedule B system, maintained by the Census Bureau. Schedule B mirrors the HS and HTS through the six-digit international level but uses its own eight- and ten-digit breakdowns. The Schedule B lookup tool at scheduleB.census.gov allows exporters to find the correct code by keyword or product description.

Harmonized System hierarchy -- example: semiconductor chip

  85           Chapter:     Electrical machinery and equipment
  8542         Heading:     Electronic integrated circuits
  8542.31      HS-6 subhd:  Processors and controllers (internationally standardized)
  8542.31.00   HTS-8:       US tariff schedule (adds 2 more digits)
  8542.31.0001 HTS-10:      Statistical suffix (full US classification)

Selected chapters with largest US trade impact:
  01   Live animals
  12   Oilseeds (soybeans: 1201)
  27   Mineral fuels, petroleum (crude oil: 2709; LNG: 2711)
  30   Pharmaceutical products
  84   Machinery, mechanical appliances, nuclear reactors, computers
  85   Electrical machinery, electronics, semiconductors
  87   Vehicles, parts and accessories
  88   Aircraft, spacecraft
  90   Optical, photographic, precision instruments

Section 301 tariffs (China) applied at HTS-10 subheading level.
  Lists 1-3: 25% on ~$250B of imports (machinery, electronics, steel)
  List 4A:   7.5% on ~$120B of imports (consumer goods, apparel)
Specific HTS codes subject to additional duties published by USTR at:
  ustr.gov/issue-areas/enforcement/section-301-investigations

Key trade aggregates

In 2023, the United States exported approximately $2.02 trillion in goods and imported approximately $3.08 trillion, yielding a goods trade deficit of $1.06 trillion — the largest in US history to that point. The goods deficit is partially offset by a services surplus: the United States earns more from exporting financial services, travel, higher education, and intellectual property licenses than it pays for imported services, though not enough to close the goods gap entirely.

On the export side, the five largest categories by value are petroleum products and liquefied natural gas (approximately $190 billion — a category that barely existed before the shale revolution), civilian aircraft and parts (around $131 billion, dominated by Boeing deliveries), industrial machinery and equipment, soybeans and grains, and semiconductor manufacturing equipment and components. The United States' emergence as a major petroleum exporter — it became a net petroleum exporter on a monthly basis in late 2019 and has remained so in many subsequent months — represents the largest structural shift in US export composition in decades, driven entirely by tight-oil production from the Permian Basin and other shale plays.

On the import side, the five largest categories are vehicles and automotive parts (approximately $215 billion), smartphones, computers, and consumer electronics (approximately $180 billion), petroleum products (approximately $130–$160 billion depending on oil price), pharmaceutical preparations (approximately $140 billion), and semiconductor devices and manufacturing equipment (approximately $130 billion). The pharmaceutical import figure has grown sharply as more active pharmaceutical ingredients and finished drugs are sourced from Ireland, India, Germany, and, historically, China.

Country-level bilateral trade flows

The United States' top five export destinations — Canada (roughly 18 percent of goods exports), Mexico (16 percent), China (8 percent), Japan (4 percent), and the United Kingdom (4 percent) — reflect the gravitational pull of geographic proximity and the USMCA free trade agreement. Canada and Mexico together absorb more than a third of all US goods exports, a share that has been remarkably stable across administrations and trade disputes because the economic integration of North American manufacturing supply chains makes substitution extremely difficult even when political friction is high.

On the import side, the ranking differs. Mexico (approximately 15 percent) and China (approximately 14 percent) trade the top position periodically, with Canada close behind at 14 percent. Germany and Japan each supply around 5 percent. Vietnam, which supplied less than 2 percent of US goods imports in 2016, had risen to approximately 4–5 percent by 2023, a shift attributable largely to Section 301 tariff-driven trade diversion from China (discussed further below).

The United States runs bilateral goods trade deficits with China, Mexico, Vietnam, Germany, Japan, and Ireland. The deficit with Ireland is driven almost entirely by pharmaceutical transfer pricing: US multinationals book intellectual property income and pharmaceutical manufacturing in Ireland for tax purposes, generating large declared export values from Ireland to the United States that show up as imports in the Census data. The deficit with Mexico surpassed China's in 2023, partly reflecting genuine nearshoring of manufacturing and partly reflecting trade diversion of Chinese goods assembled in Mexico.

One significant measurement distortion involves re-exports through entrepot hubs. Hong Kong historically served as a transit point for US goods destined for mainland China and for Chinese goods en route to the United States. When US exports are shipped to Hong Kong and then re-exported to China, the Census data records the destination as Hong Kong, understating the bilateral flow to China and overstating the flow to Hong Kong. Since 2019, given political changes in Hong Kong, much of this transit trade has shifted to Singapore and Taiwan, creating similar measurement challenges.

Free trade agreement partner trade volumes are disproportionately large relative to GDP because FTA relationships reduce tariff barriers and encourage deeper supply chain integration. USMCA partners (Canada and Mexico combined) account for more than 30 percent of all US goods trade. The fourteen other US FTA partners — including South Korea, Australia, Chile, Colombia, and the Central American nations under CAFTA-DR — collectively account for another 15–20 percent. Non-FTA partners, including China, the European Union, Japan, and most of Asia, supply the remainder.

USA Trade Online: the public data portal

The primary public interface for US import and export statistics is USA Trade Online at usatrade.census.gov. Free registration is required to build custom queries. The platform allows users to filter by HS commodity code (at any level from 2-digit chapter through 10-digit HTS or Schedule B), by country or country group, by customs district and port, and by date range. Data can be downloaded as CSV or Microsoft Excel. Coverage extends back to 1989 for most country-commodity combinations.

USA Trade Online supports two import concepts that are frequently confused. General imports count all goods entering US customs territory, including goods placed in bonded warehouses or foreign trade zones before customs clearance. Imports for consumption count goods that have actually cleared customs and entered the US economy. For most analytical purposes, imports for consumption is the relevant measure because it reflects actual economic activity. General imports tend to be slightly larger and lead imports for consumption slightly in time when warehouse inventories are building.

The export side has an analogous distinction between domestic exports (goods of US origin or manufacture) and foreign exports (goods previously imported and now re-exported without substantial transformation). The foreign-export category is significant for understanding US role as a global redistribution hub: crude oil imported from the Middle East, refined at US Gulf Coast facilities, and exported as gasoline or diesel counts as domestic exports of refined petroleum, not foreign exports, because the manufacturing transformation is substantial. Simple re-shipment of unchanged imported goods counts as foreign exports.

USA Trade Online also provides port-level data covering approximately 420 customs districts and ports of entry. The top US import ports by value are the Port of Los Angeles/Long Beach (the largest in volume for containerized imports from Asia), the Port of New York/New Jersey, and the Port of Houston (dominant for petroleum and petrochemical imports). For exports, the Port of Houston leads by value due to petroleum and agricultural exports through Gulf Coast terminals, followed by the Port of Savannah and the Port of Los Angeles.

The Census Foreign Trade API

For programmatic access, the Census Bureau exposes trade time-series data through its standard data API at api.census.gov. The trade endpoints are part of the timeseries/intltrade dataset family. Two primary endpoints cover imports and exports:

# Import values by HTS commodity code and country
https://api.census.gov/data/timeseries/intltrade/imports/hs
  ?get=GEN_VAL_MO,CON_VAL_MO,CTY_CODE,CTY_NAME,I_COMMODITY,I_COMMODITY_LDESC,time
  &CTY_CODE=5700        # Census country code: 5700 = China
  &COMM_LVL=HS6         # aggregation level: HS2, HS4, HS6, or HS10
  &time=2024-01
  &key=YOUR_KEY

# Export values by Schedule B commodity code and country
https://api.census.gov/data/timeseries/intltrade/exports/schb
  ?get=ALL_VAL_MO,CTY_CODE,CTY_NAME,E_COMMODITY,E_COMMODITY_LDESC,time
  &CTY_CODE=5700
  &COMM_LVL=HS6
  &time=2024-01
  &key=YOUR_KEY

Key variables:
  GEN_VAL_MO   -- general imports value (monthly, USD)
  CON_VAL_MO   -- imports for consumption value (monthly, USD)
  ALL_VAL_MO   -- total export value (domestic + foreign)
  DOM_VAL_MO   -- domestic exports value
  CTY_CODE     -- Census country code (see country code list at census.gov)
  COMM_LVL     -- HS2 | HS4 | HS6 | HS10
  I_COMMODITY  -- HTS code (imports) at the requested COMM_LVL
  E_COMMODITY  -- Schedule B code (exports) at the requested COMM_LVL
  time         -- YYYY-MM (monthly), or range: from+2018-01+to+2024-12

Selected Census country codes:
  2010 = Canada       2050 = Mexico       5700 = China
  5830 = Taiwan       5520 = Vietnam      5490 = Malaysia
  5800 = South Korea  4120 = Germany      5490 = Malaysia
  4279 = Ireland      3290 = United Kingdom

A free API key is available at api.census.gov/data/key_signup.html. Without a key, the API allows 500 requests per day, which is adequate for exploratory queries. The complete list of country codes, commodity aggregation options, and variable definitions is documented in the API metadata at api.census.gov/data/timeseries/intltrade/imports/hs/variables.json.

The API supports filtering by specific commodity codes by passing the I_COMMODITY parameter with comma-separated values at the appropriate digit level. This enables targeted queries — pulling only semiconductor codes (8542xx) from specific countries — without downloading the full HS-2 chapter. For bulk analysis requiring all commodities and all countries in a given month, the API is less efficient than the bulk monthly CSV files published at census.gov/foreign-trade/data/index.html, which can be loaded directly into analytical tools like DuckDB without loading the full dataset into memory.

Python: tracking the semiconductor sourcing shift, 2018–2024

The most consequential US trade policy shift of the past decade — the imposition of Section 301 tariffs on Chinese goods and the CHIPS Act investment incentives — is directly visible in semiconductor import data. HS heading 8542 covers electronic integrated circuits: processors, memory chips, amplifiers, and other ICs. Before 2018, China was a significant source of US integrated circuit imports, both for chips manufactured in China and for chips assembled in China from dies fabricated elsewhere.

After September 2018, when List 3 of the Section 301 tariffs took effect at 25 percent on machinery and electronics categories, semiconductor procurement began shifting. Taiwan — already the source of the most advanced logic chips from TSMC — increased in share. Vietnam and Malaysia, which host backend semiconductor assembly, test, and packaging (ATP) operations for Intel, Texas Instruments, and others, expanded substantially. The Python example below downloads monthly import values for the key 8542 subheadings from five source countries across 2018–2024 and produces a stacked area chart visualizing the shift.

import requests
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker

# Census Foreign Trade API -- monthly semiconductor imports (HS 8542) by source country
# Endpoint: api.census.gov/data/timeseries/intltrade/imports/hs
# HS 8542 = Electronic integrated circuits

BASE = "https://api.census.gov/data/timeseries/intltrade/imports/hs"
API_KEY = "YOUR_CENSUS_API_KEY"

COUNTRIES = {
    "5700": "China",
    "5830": "Taiwan",
    "5520": "Vietnam",
    "5800": "South Korea",
    "5490": "Malaysia",
}

years = range(2018, 2025)
months = range(1, 13)


def fetch_hs_imports(cty_code, year, month):
    month_str = str(month).zfill(2)
    params = {
        "get": "GEN_VAL_MO,CTY_CODE,I_COMMODITY,time",
        "CTY_CODE": cty_code,
        "I_COMMODITY": "854231,854232,854233,854239",
        "COMM_LVL": "HS10",
        "time": str(year) + "-" + month_str,
        "key": API_KEY,
    }
    try:
        resp = requests.get(BASE, params=params, timeout=20)
        resp.raise_for_status()
        rows = resp.json()
        if len(rows) < 2:
            return 0
        total = sum(int(r[0]) for r in rows[1:] if r[0] and r[0] != "0")
        return total
    except Exception:
        return 0


records = []
for cty_code, cty_name in COUNTRIES.items():
    for year in years:
        for month in months:
            val = fetch_hs_imports(cty_code, year, month)
            records.append({
                "country": cty_name,
                "year": year,
                "month": month,
                "value_usd": val,
            })

df = pd.DataFrame(records)
df["period"] = pd.to_datetime(df[["year", "month"]].assign(day=1))

# Annual totals by country
annual = (
    df.groupby(["country", "year"])["value_usd"]
    .sum()
    .unstack("country")
    .fillna(0)
)

print("Annual US semiconductor (HS 8542x) imports by source country:")
print(annual.to_string())

# Stacked area chart -- sourcing shift 2018-2024
fig, ax = plt.subplots(figsize=(11, 6))
countries_ordered = ["China", "Taiwan", "South Korea", "Malaysia", "Vietnam"]
annual[countries_ordered].plot.area(ax=ax, alpha=0.85)

ax.set_title(
    "US Semiconductor Imports (HS 8542) by Source Country, 2018-2024"
    "\nSection 301 tariffs on China (List 3) took effect Sept 2018",
    fontsize=11,
)
ax.set_xlabel("Year")
ax.set_ylabel("Import Value (USD)")
ax.yaxis.set_major_formatter(mticker.FuncFormatter(lambda x, _: "$" + str(int(x // 1_000_000_000)) + "B"))
ax.legend(title="Source Country", bbox_to_anchor=(1.02, 1), loc="upper left")
plt.tight_layout()
plt.savefig("semiconductor_sourcing_shift.png", dpi=150)
print("Chart saved to semiconductor_sourcing_shift.png")

The chart produced by this code typically shows China's share of integrated circuit imports declining sharply after 2018 while Taiwan, Vietnam, and Malaysia expand to fill the gap. The decline is not uniform across all 8542 subheadings: advanced logic (8542.31, processors) was already concentrated in Taiwan and South Korea rather than China, so the tariff shift is most visible in memory (8542.32) and discretes (8542.39). This granularity is only accessible at the HS-6 or HS-10 level — the HS-2 chapter totals would mask the intra-chapter compositional change.

For production pipelines requiring the full HS-10 monthly detail across all countries, the Census bulk data files are more practical than per-query API calls. The monthly import and export files are available as fixed-width text files at census.gov/foreign-trade/data/index.html and can be queried efficiently using DuckDB's CSV scanning capability without loading the full file into Python memory.

Section 301 and Section 232 tariff effects on trade flows

Section 301 tariffs on Chinese goods, Section 232 tariffs on steel (25 percent) and aluminum (10 percent, later raised) imposed in 2018, and subsequent tariff escalations are all visible in the Census trade data at the HS-chapter and HS-6 level. The pattern is broadly consistent with trade theory: tariffs on Chinese goods reduced US imports from China in those specific HTS categories, but total US imports in those categories did not fall by a commensurate amount. Instead, imports shifted to third countries — a process economists call trade diversion.

For steel (Chapter 72–73), the Section 232 tariff reduced imports from directly targeted countries while imports from tariff-exempt countries (those granted exemptions under quota agreements — Argentina, Australia, Brazil, South Korea, and later the EU and UK under tariff rate quotas) increased. Vietnam and India, which were not initially exempted, showed complex patterns of both diversion and downstream supply chain adjustments.

For Chinese electronics and machinery under Section 301, Vietnam became the most documented diversion destination. US imports from Vietnam in HS chapters 84–85 more than tripled between 2017 and 2023, while Vietnamese imports from China in the same chapters rose in parallel. The pattern is consistent with Chinese manufacturers relocating or contracting final assembly operations to Vietnam to obtain Vietnamese certificates of origin. CBP has opened country-of-origin enforcement actions in cases where the Vietnamese transformation was found to be insufficiently substantial — a point of tension between customs enforcement capacity and the volume of goods flowing through Vietnamese assembly operations.

The specific HTS codes subject to Section 301 additional duties are published in annexes to the USTR Federal Register notices and maintained on the USTR website. Matching those HTS codes to the Census import data — filtering to the tariffed codes specifically and comparing import values before and after the tariff implementation date for both China and potential diversion destinations — is the standard analytical approach for measuring tariff incidence and diversion magnitude.

NAICS-to-HS concordance and economic analysis

A frequent challenge in integrating trade data with other federal economic datasets is the mismatch between commodity-based classification (HS and HTS, which classify products) and industry-based classification (North American Industry Classification System, NAICS, which classifies business establishments by their primary activity). A pharmaceutical manufacturer (NAICS 3254) imports both raw chemicals (HS 28–29) and finished dosage-form drugs (HS 30), and exports finished pharmaceutical products (HS 30) — so matching trade flows to BLS employment by industry or BEA GDP by industry requires a concordance table.

The Census Bureau publishes an official HS-to-NAICS concordance at census.gov/foreign-trade/reference/codes/naics/index.html. This concordance is approximate rather than one-to-one — many HS codes can be produced by multiple NAICS industries, and many NAICS industries produce output spanning multiple HS chapters. Despite its limitations, the concordance is the standard reference for analyzing import competition effects on domestic industries or for mapping trade flows to BLS Occupational Employment data to estimate trade-exposed employment.

Methodological notes and limitations

Several features of Census trade statistics require care in interpretation before drawing policy conclusions.

De minimis shipments. Imports valued below $800 per shipment are exempt from formal customs entry under Section 321 of the Tariff Act. These low-value direct-to-consumer e-commerce shipments — dominant in fast-fashion apparel and consumer electronics accessories shipped from Chinese marketplaces — are not fully captured in the Census trade statistics. The Census Bureau estimates their aggregate value and includes an aggregate line, but country and commodity detail for de minimis shipments is limited. This creates a known undercount of imports in apparel (HS 61–62) and electronic accessories (HS 85) from China in particular.

Country of origin vs. country of shipment.Trade statistics record country of origin, not last port of shipment. A good manufactured in China, consolidated in a Vietnamese distribution facility, and shipped to the United States should be declared as Chinese origin. In practice, documentation gaps and the incentive to avoid Section 301 tariffs create pressure to declare Vietnamese origin. CBP enforcement of origin rules is risk-based rather than universal, so systematic misclassification can persist for months or years before enforcement catches up.

Revision schedule. Monthly trade figures are published approximately five weeks after the reference month ends. An initial revision appears in the following month's release as late entries are processed. Annual revisions, published each spring for the prior year, can be material for specific commodity-country combinations. Time series analysis that compares across years should use the revised annual data rather than the initial monthly estimates to avoid comparing revised and unrevised figures.

Valuation basis. Import values in Census statistics are reported on a customs value basis — the transaction price at the foreign port of export, excluding international freight and insurance. Export values are reported FOB at the US port of exit. Neither measure captures the cost, insurance, and freight (CIF) price that the importer actually pays delivered to US shores. For goods with high freight costs relative to value (bulk commodities, heavy machinery), the difference between customs value and CIF can be 5–15 percent, affecting the apparent bilateral trade balance when compared to partner-country mirror statistics that report imports on a CIF basis.

Related writing

BEA International Transactions: The Balance of Payments Data Behind Every US Trade Deficit Headline — The broader balance of payments framework that places Census goods trade in context, including services, primary income, and the financial account that finances the current account deficit.

CBP US Trade Statistics: The Federal Dataset Behind Every Import and Export — The customs enforcement angle: how CBP collects import entry data, how HTS misclassification is identified, and how the same data drives both tariff collection and trade statistics.