| usda_nass_get_acreageA | Planted or harvested acreage of a crop for a year, state or national, in acres. Annual final totals (unit_desc ACRES, domain_desc TOTAL,
prodn_practice_desc ALL PRODUCTION PRACTICES, reference_period_desc
YEAR), so breakdowns by size group, irrigation or biotech type and the in-season
forecasts are left out; get_acreage_forecasts serves the latter. Harvested
acreage comes per utilisation (grain, silage); planted acreage as one figure.
Sorted by state, utilisation and source. Args:
commodity: Upstream commodity_desc, e.g. "CORN", "SOYBEANS", "WHEAT".
year: Crop year, e.g. 2023.
statistic: AreaStatistic.AREA_PLANTED or AreaStatistic.AREA_HARVESTED.
state: Two-letter state code for the state figure; None returns the national
US TOTAL figure. |
| usda_nass_get_acreage_forecastsA | The in-season acreage reports for a crop and year, in acres, oldest first. Every report except the final figure: the March prospective plantings, the June
acreage report and the monthly forecasts, each row naming its
reference_period_desc (YEAR - JUN ACREAGE, YEAR - AUG FORECAST, ...).
Same fixed filters as get_acreage otherwise, so the series is comparable with
the final figure. Sorted by load_time, then utilisation. Args:
commodity: Upstream commodity_desc, e.g. "CORN", "SOYBEANS", "WHEAT".
year: Crop year, e.g. 2023.
statistic: AreaStatistic.AREA_PLANTED or AreaStatistic.AREA_HARVESTED.
state: Two-letter state code for the state series; None returns the national
series. |
| usda_nass_get_census_farmsA | Census of Agriculture farm counts or land in farms for a year, national, by state or county. The farm totals of the five-yearly Census (source_desc CENSUS, group_desc
FARMS & LAND & ASSETS, commodity_desc FARM OPERATIONS, class_desc
ALL CLASSES, prodn_practice_desc ALL PRODUCTION PRACTICES,
domain_desc TOTAL), so the breakdowns by farm size, sales class, typology,
organization and the like are left out; get_data reaches them. unit_desc
tells the rows of one place apart: for OPERATIONS the number of farms
("OPERATIONS") and, above the county level, "PCT OF FARM OPERATIONS"; for
AREA OPERATED the land in farms ("ACRES"), "ACRES / OPERATION",
"ACRES / OPERATION, MEDIAN", "PCT OF TOTAL LAND" and, above the county
level, "PCT OF AG LAND", as the 2022 Census publishes them; another year may
carry fewer. value is the figure as published and value_number its parsed
form; cv_percent is the coefficient of variation, None where upstream prints
a code such as "(L)" or "(H)" in its place. Sorted by state, county and
unit. Every county of the country is a large answer (2022: 3,078 rows for
OPERATIONS, 12,312 for AREA OPERATED, counted 2026-10-28), well under the
50,000-record limit: the MCP tool returns its first rows within the result cap
(64 KB, about 100 rows, a projected row being about 600 bytes) with a note, so give
state there. A state's counties are cut too past about 100 rows, so for
AREA OPERATED, four rows a county, a state of more than about 25 counties is cut. Args:
year: A Census year, e.g. 2022 or 2017; the Census of Agriculture is
taken every five years, and a year without rows under these filters raises
NotFoundError.
statistic: FarmStatistic.OPERATIONS (the number of farms) or
FarmStatistic.AREA_OPERATED (land in farms).
state: Two-letter state code, e.g. StateAlpha.IA: that state's figures, or
with by_county its counties'. None returns the national
US TOTAL figures, or with by_county every county of the country.
The 2022 Census counts no state rows for StateAlpha.PR, and a code
without rows raises NotFoundError.
by_county: True returns county figures (agg_level_desc COUNTY), of
state when given; False, the default, the state or national ones. |
| usda_nass_get_county_productionA | County production of a crop for a year, one row per county, utilisation and practice. Annual final estimates (statisticcat_desc PRODUCTION, reference_period_desc
YEAR) at agg_level_desc COUNTY, sorted by state, county, utilisation and
practice. unit_desc names the unit, "BU" for grain and "TONS" for silage;
value is the quantity. Args:
commodity: Upstream commodity_desc, e.g. "CORN", "SOYBEANS", "WHEAT".
year: Crop year, e.g. 2023.
state: Two-letter state code to restrict to one state; None returns every
county in the country. |
| usda_nass_get_county_yieldA | County yields of a crop for a year, one row per county, utilisation and practice. Annual final estimates (statisticcat_desc YIELD, reference_period_desc
YEAR) at agg_level_desc COUNTY, sorted by state, county, utilisation and
practice. unit_desc names the unit, "BU / ACRE" for grain and "TONS / ACRE"
for silage; value is the yield. Args:
commodity: Upstream commodity_desc, e.g. "CORN", "SOYBEANS", "WHEAT".
year: Crop year, e.g. 2023. County estimates for a year appear the following
spring.
state: Two-letter state code to restrict to one state; None returns every
county in the country, which stays under the 50,000-record limit for one crop
and year. |
| usda_nass_get_crop_conditionA | Weekly crop condition: the percentage of a crop rated very poor through excellent. One row per week and category, from the NASS Crop Progress survey
(statisticcat_desc CONDITION, freq_desc WEEKLY), sorted by week.
unit_desc names the category and value is the percentage. Args:
commodity: Upstream commodity_desc, e.g. "CORN", "SOYBEANS",
"WINTER WHEAT".
year: Crop year, e.g. 2024.
state: Two-letter state code for the state series; None returns the
national US TOTAL series.
category: One of ConditionCategory.PCT_VERY_POOR, PCT_POOR, PCT_FAIR,
PCT_GOOD, PCT_EXCELLENT; None returns all five. |
| usda_nass_get_crop_progressA | Weekly crop progress: the percentage planted, emerged, silking, harvested and so on. One row per week and stage, from the NASS Crop Progress survey (statisticcat_desc
PROGRESS, freq_desc WEEKLY), sorted by week. Stages differ by crop;
unit_desc names each one and value is the percentage. Args:
commodity: Upstream commodity_desc, e.g. "CORN", "SOYBEANS",
"WINTER WHEAT", "COTTON"; list_param_values("commodity_desc")
lists them.
year: Crop year, e.g. 2024.
state: Two-letter state code for the state series; None returns the
national US TOTAL series.
stage: A single stage, e.g. ProgressStage.PCT_PLANTED,
ProgressStage.PCT_SILKING, ProgressStage.PCT_HARVESTED; the enum
lists every stage any crop uses, and None returns every stage of this
crop. |
| usda_nass_get_dataA | Fetch published Quick Stats estimates for a set of filters, up to 50,000 records a call. Without split_by_year, calls get_counts first: a count of zero returns an empty
result without a second call, and a count above 50,000 raises QueryTooLarge with
the count and a hint (narrower filters, or split_by_year) before anything is
fetched. With split_by_year, a two-sided year range is fetched year by year, each
year counted first and no count of the range sent; year__GE alone is counted
first and split by year only when that count is above 50,000; year is counted
first, and above 50,000 still raises QueryTooLarge. meta.total is the count
get_counts reported, 0 for the empty result, and the yearly counts summed for
a split. Each record carries every Quick Stats column;
value is the published figure as a string ("510,000", or a suppression code
such as "(D)") and value_number the parsed number. Args:
filters: Quick Stats columns, optionally suffixed with an operator, mapped to
values; the same shape and the same checks as for get_counts: an
unknown value of a packaged parameter raises UnknownCode naming the
list, its fetch date and the closest known values, or pointing at
list_param_values (the tool usda_nass_list_param_values) when none
is close. A query that stays well under the limit names the commodity, the
statistic, the level and the time, e.g.
{"commodity_desc": "CORN", "statisticcat_desc": "AREA PLANTED", "agg_level_desc": "STATE", "state_alpha": "VA", "year": 2012}. Quick Stats
keeps one bound on year per query (recorded 2026-10-28): it counts
year__GE with year__LE as year__GE alone, in either order, and
drops year__GE beside year__LT, so a two-sided year range is served
only by split_by_year.
split_by_year: True fetches the years one at a time where one call cannot serve
them, splitting one call into at most 20 years in Python and over HTTP and 5 by
default on the MCP server, whose --split-years sets 1 to 20. The filters
bound the years in one of three forms, checked before any call: year
(2022), year__GE with year__LE (2020 and 2023), or
year__GE alone, up to the current UTC year. Another year filter
(year__LE alone, year__GT, year__NE, ...), a mix or none raises
InvalidRequestError naming the three forms, and a year__GE or
year__LE past the current UTC year raises it naming that year. year is
counted and fetched once, as without the flag; over the limit it raises
QueryTooLarge naming the year. year__GE with year__LE is always
split, without a count of the range, which Quick Stats would count as
year__GE alone; more years than the ceiling raise InvalidRequestError
naming it before any call. year__GE alone is counted first and fetched once
when the count is within the limit, however far back it starts; over the limit
it is split, and more years than the ceiling raise InvalidRequestError
naming it after that count, before the split. A split counts each year with
year=<y> in place of the year filters, every year before the first fetch, so
a year over 50,000 on its own raises QueryTooLarge naming it before anything
is fetched; it then fetches each year holding records, the records in year
order, each year's in upstream's order. A year counting 0 is skipped: it has no
records, or none published yet, which Quick Stats does not tell apart;
meta.vintage stays None, since Quick Stats names no release. Cost: up to
two keyed calls per year, plus the first count for year__GE alone, paced at
30 a minute, so 5 years take up to 11 calls and 20 years up to 41, about 80
seconds. meta.request carries split_by_year beside the filters.
False, the default, never splits. |
| usda_nass_get_grain_stocksA | Quarterly grain stocks of a commodity in a year, on farm, off farm and in total, in bushels. The NASS Grain Stocks estimates (statisticcat_desc STOCKS, unit_desc
BU, domain_desc TOTAL, freq_desc POINT IN TIME, source_desc
SURVEY), state or national, every stocks day of the year together: one row per
day, position and class, sorted by day (begin_code, then
reference_period_desc), then util_practice_desc, then class_desc.
reference_period_desc names the day, FIRST OF MAR, FIRST OF JUN,
FIRST OF SEP or FIRST OF DEC, and begin_code its month (03 ... 12).
util_practice_desc tells the position as upstream spells it for the commodity:
for corn GRAIN (the total), ON FARM, GRAIN and OFF FARM, GRAIN; for
soybeans and wheat ALL UTILIZATION PRACTICES (the total), ON FARM and
OFF FARM. class_desc is ALL CLASSES; wheat's durum comes as rows of its
own, class_desc SPRING, DURUM, where NASS publishes it, as in the national
estimates. value is the quantity in bushels as published and value_number its
parsed form. Args:
commodity: Upstream commodity_desc, e.g. "CORN", "SOYBEANS",
"WHEAT"; list_param_values("commodity_desc") lists them.
year: Year of the stocks days, e.g. 2024 for the stocks on 1 March, 1 June,
1 September and 1 December 2024; the current year returns only the stocks
days published so far.
state: Two-letter state code for the state estimates, e.g. "IA", "ND";
None returns the national US TOTAL estimates. |
| usda_nass_get_livestock_inventoryA | Head counts of cattle, hogs or sheep on hand on the survey days of a year, by class. Survey inventories (statisticcat_desc INVENTORY, unit_desc HEAD,
domain_desc TOTAL, freq_desc POINT IN TIME, source_desc
SURVEY), state or national, one row per survey day, class and short_desc
(cattle on feed carry the class ALL CLASSES with prodn_practice_desc
ON FEED), sorted by the day (begin_code, its month), then
reference_period_desc, class_desc and short_desc.
reference_period_desc names the day: FIRST OF JAN in the national cattle
series of 2024; the four quarterly days FIRST OF MAR, FIRST OF JUN,
FIRST OF SEP and FIRST OF DEC in Iowa's hogs series of 2024. The whole herd is
the class INCL CALVES for cattle, ALL CLASSES for hogs and INCL LAMBS for
sheep. value is the head count as published. Args:
commodity: Upstream commodity_desc: LivestockCommodity.CATTLE,
LivestockCommodity.HOGS or LivestockCommodity.SHEEP.
year: Year of the survey days, e.g. 2024.
state: Two-letter state code for the state series, e.g. StateAlpha.IA,
StateAlpha.TX; None returns the national US TOTAL series.
class_desc: One upstream class_desc to keep, e.g. "INCL CALVES",
"COWS, BEEF" or "COWS, MILK" for cattle, "ALL CLASSES",
"BREEDING" or "MARKET" for hogs, "INCL LAMBS" for sheep; None
returns every class. A class with no record for the commodity, year and
place raises NotFoundError. |
| usda_nass_get_milk_productionA | Milk produced in a year, in pounds, by month and quarter and for the year. The milk production series, state or national (commodity_desc MILK,
class_desc ALL CLASSES, statisticcat_desc PRODUCTION, unit_desc
LB, domain_desc TOTAL, source_desc SURVEY; short_desc
MILK - PRODUCTION, MEASURED IN LB); ALL CLASSES leaves out the manufactured
dairy products (dry and condensed milk) that upstream files nationally under the same
statistic and unit. Sorted by frequency, then period: the year first
(freq_desc ANNUAL, reference_period_desc YEAR), then the months, each
quarter (JAN THRU MAR, ...) after its first month, since upstream files months and
quarters alike as MONTHLY. value is the quantity in pounds as published. Args:
year: Calendar year, e.g. 2024.
state: Two-letter state code for the state series, e.g. StateAlpha.WI,
StateAlpha.CA; None returns the national US TOTAL series.
frequency: FreqDesc.MONTHLY (the months and quarters) or FreqDesc.ANNUAL
(the year) to keep one; None returns both. FreqDesc.WEEKLY,
FreqDesc.SEASON and FreqDesc.POINT_IN_TIME raise NotFoundError,
since upstream files no milk production under them. |
| usda_nass_get_prices_receivedA | Prices farmers received for a commodity in a year, monthly and marketing-year. statisticcat_desc PRICE RECEIVED at domain_desc TOTAL, state or
national, sorted by frequency and period: the marketing-year average first, then
the months. The national series also carries the price as a percentage of parity
(unit_desc "PCT OF PARITY") next to the dollar price; the column tells them
apart.
Args:
commodity: Upstream commodity_desc, e.g. "CORN", "SOYBEANS", "MILK",
"CATTLE".
year: Calendar year of the months, e.g. 2023.
state: Two-letter state code for the state series; None returns the
national series.
frequency: FreqDesc.MONTHLY or FreqDesc.ANNUAL to keep one; None
returns both. |
| usda_nass_get_productionA | The final production or yield of a crop for a year, state or national. Annual final figures (reference_period_desc YEAR, domain_desc TOTAL,
prodn_practice_desc ALL PRODUCTION PRACTICES, freq_desc ANNUAL), so
breakdowns by irrigation and the like and the in-season forecasts are left out;
get_production_forecasts serves the latter. Utilisations, classes and units come
as rows, the columns tell them apart: util_practice_desc grain from silage,
class_desc a crop's classes (wheat's ALL CLASSES, WINTER, ...),
unit_desc the unit (BU, TONS, BU / ACRE), and the value of production
comes as rows with unit_desc $. value is the figure as published,
value_number its parsed form. Sorted by state, utilisation, class, unit and
source. Cost: one keyed call, without a count first; meta.total stays None. Args:
commodity: Upstream commodity_desc, e.g. "CORN", "SOYBEANS",
"WHEAT", "COTTON"; list_param_values("commodity_desc") lists them.
year: Crop year, e.g. 2023.
statistic: ProductionStatistic.PRODUCTION or ProductionStatistic.YIELD.
state: Two-letter state code for the state figure, e.g. StateAlpha.IA;
None returns the national US TOTAL figure. |
| usda_nass_get_production_forecastsA | The in-season production or yield forecasts for a crop and year, oldest first. The Crop Production reports' forecasts, each row naming its
reference_period_desc (YEAR - AUG FORECAST, YEAR - SEP FORECAST, ...),
selected with reference_period_desc__LIKE FORECAST; the final figure,
YEAR, is get_production's. Annual totals (domain_desc TOTAL,
prodn_practice_desc ALL PRODUCTION PRACTICES, freq_desc ANNUAL), so
breakdowns by irrigation and the like are left out and the series is comparable with
the final figure. Utilisations, classes and units come as rows, the columns tell them
apart: util_practice_desc grain from silage, class_desc a crop's classes
(wheat's ALL CLASSES, WINTER, SPRING, (EXCL DURUM), SPRING, DURUM),
unit_desc the unit (BU, BU / ACRE). value is the figure as published,
value_number its parsed form. Sorted by load_time, then utilisation, class
and unit. Cost: one keyed call, without a count first; meta.total stays None. Args:
commodity: Upstream commodity_desc, e.g. "CORN", "SOYBEANS",
"WHEAT", "COTTON"; list_param_values("commodity_desc") lists them.
year: Crop year, e.g. 2023.
statistic: ProductionStatistic.PRODUCTION or ProductionStatistic.YIELD.
state: Two-letter state code for the state series, e.g. StateAlpha.IA;
None returns the national series. |
| usda_nass_list_param_valuesA | List every value a Quick Stats filter parameter can take, to form valid queries. Nine lists are answered from data packaged with this version, with no upstream call
(meta.endpoint is "get_param_values", the operation they were fetched from,
and meta.retrieved_at the time they were fetched): source_desc,
sector_desc, group_desc, agg_level_desc, freq_desc, state_alpha,
statisticcat_desc, unit_desc, domain_desc. Every other parameter is
fetched live and cached for 24 hours in this process, so a repeated lookup sends
nothing; meta.retrieved_at is the time the cached answer was fetched. Args:
param: A Quick Stats column name, e.g. "statisticcat_desc" or "unit_desc"
(packaged), or "commodity_desc", "short_desc", "county_name",
"year" (fetched live). Definitions are in
docs/upstream/param_define.md. |
| usda_psd_get_balance_sheetA | One country's PSD supply and distribution of a commodity in a market year, as one record. One request to PSDData_GetCountryCommodityDataByYear; its records, one per
attribute, become the entries of attributes, keyed by the attribute's upstream
name ("Production", "Imports", "Ending Stocks", 15 of them for wheat in
the United States), in upstream order. Each entry carries attribute_id,
unit_id, value, calendar_year and month exactly as the record had
them. Units differ per attribute (wheat US: 1000 HA for area, 1000 MT for
quantities, MT/HA for yield), so read each entry's unit_id (enums.UnitId).
Nothing is derived, converted or renamed. Names are not unique upstream: an id
whose name the packaged list gives to several ids ("Total Disappearance" is 126
and 173, "Fresh Dom. Consumption" 133 and 135) is always keyed with its id,
"Total Disappearance (126)", so an id has the same key in every answer of a
package version; an id the packaged list lacks is keyed "attribute <id>". Keys
come from the packaged list: a reference refresh that renames an attribute, or adds
an id under an existing name, changes keys and is a breaking change (conventions
§12), recorded in the CHANGELOG. meta.vintage is the PSD release that last
revised the figures ("2026-07"); meta.published_at stays empty, since PSD
gives no day. Codes and the year are checked before the call. Valid codes without
data (PSD answers an empty list) raise NotFoundError, a market year without data
errors.NoDataForYear, both naming commodity, country and year. Args:
commodity_code: PSD commodity code, seven digits, e.g. "0410000" (Wheat),
"0440000" (Corn), "2222000" (Oilseed, Soybean).
country_code: PSD country code (not ISO), e.g. "US" (United States), "BR"
(Brazil), "E4" (European Union). For the world use get_world_data.
market_year: PSD market year, e.g. 2023, 2022, 2021; data goes back to
1960 for most commodities. |
| usda_psd_get_dataA | PSD supply and distribution forecasts for one commodity and market year, by country. One record per country and attribute (area, production, imports, exports,
consumption, stocks, ...): attribute_id and unit_id are PSD's integer ids,
which enums.AttributeId and enums.UnitId name; value is in that unit.
Codes and the year are checked against the packaged lists before any call; an
unknown code raises InvalidRequestError naming the closest ones. Each record's
calendar_year and month are the PSD release that last revised it: for one
country all records share one release, for every country they differ by country.
meta.vintage is the latest of them as upstream names it ("2026-07");
meta.published_at stays empty, since PSD gives no day. An empty list means PSD
has no records for that combination; a market year without data raises
NotFoundError. Every country is up to about 1,900 rows (1,875 for corn in 2023). Args:
commodity_code: PSD commodity code, seven digits, e.g. "0410000" (Wheat),
"0440000" (Corn), "2222000" (Oilseed, Soybean).
market_year: PSD market year, e.g. 2023; data goes back to 1960 for most
commodities.
country_code: PSD country code (not ISO), e.g. "US" (United States), "BR"
(Brazil), "E4" (European Union). Omit it (None) for every country:
one record per country and attribute. For the world total use
get_world_data. |
| usda_psd_get_latest_releaseA | Which countries and market years PSD's newest release of a commodity revised. One request to PSDData_GetDataReleaseInfo, which lists the last release of every
country and market year (7,754 records for wheat); the records of the newest
release_year and release_month are kept, unchanged and in upstream's order.
For wheat as recorded on 2026-10-23 that was release 2026-10, 146 records: 123
countries for market year 2026 and a few revisions of earlier years.
meta.vintage names the release ("2026-10") in the form meta.vintage of
get_data takes, so a stored vintage older than it means the listed countries and
market years have changed since. To poll, pass your stored vintage as since: the
answer is the newest release's records when that release is later than since,
and an empty list when it is not, with meta.vintage still naming the newest
release, so an empty list says nothing newer exists. A commodity without any release
gives an empty list and meta.vintage None; meta.published_at stays empty,
since PSD gives no day. A release that adds a market year and revises earlier ones
lists many records: the wheat list recorded on 2026-10-23 had 146 records of 2026-10
and 130 more still carrying 2026-09, so the September answer held between 130 and 276
rows. get_release_dates(commodity_code, market_year=..., country_code=..., since=...) returns any part of the list. Args:
commodity_code: PSD commodity code, seven digits, e.g. "0410000" (Wheat),
"0440000" (Corn), "2222000" (Oilseed, Soybean).
since: A release month "YYYY-MM", e.g. "2026-09", typically the
meta.vintage you stored last time: the newest release's records come back
only when that release is later (strictly after), else an empty list.
None always returns the newest release's records. |
| usda_psd_get_release_datesA | When PSD last revised each country and market year of a commodity: poll for releases. One record per country and market year: release_year and release_month name
the PSD release, a month without a day. Compare them with a stored meta.vintage
of get_data, or pass that vintage as since, to fetch only what changed.
Upstream answers every country and every market year since 1960 at once (7,754
records for wheat), ordered by market year; market_year, country_code and
since keep only the matching records, after the one call, in upstream's order. Args:
commodity_code: PSD commodity code, seven digits, e.g. "0410000" (Wheat),
"0440000" (Corn), "2222000" (Oilseed, Soybean).
market_year: Keep only this PSD market year, e.g. 2023; None keeps all.
country_code: Keep only this PSD country code (not ISO), e.g. "US", "BR";
None keeps all.
since: Keep only the records revised in a release later than this month,
"YYYY-MM", e.g. "2026-09"; the form meta.vintage takes, so a
stored vintage passes as it is, and that release itself is not kept (strictly
after). None keeps all. |
| usda_psd_get_time_seriesA | One country's PSD figures for a commodity over a range of market years. One request to PSDData_GetCountryCommodityDataByYear per market year, oldest
first, at the client's pace of one request per second, and each counts against
api.data.gov's quota of 1,000 requests per hour per key: 2021 to 2023 is three
requests and about three seconds, 1960 to 2026 sixty-seven, so ask for the years you
need; a range of more than 100 market years is refused. Of each answer the records
of the attributes asked for, or all of them when attribute_id is omitted, are
kept exactly as upstream sent them, ordered by market year and within a year in
upstream's order: value is in its unit_id, and calendar_year and
month name the release that last revised that year, which may differ from year
to year. A market year PSD has no data for (its empty HTTP 404, recorded for 1900),
or whose answer has no record for the attributes, is absent from the list: no gap is
filled, nothing interpolated, no error raised; a range without any record is an
empty list. A year beyond PSD's forecasts is expected to answer the same 404 (not
recorded) and still costs its request. Any other error, the gateway's own 404
included, is raised. meta.vintage is the latest release across the records
("2026-07"); meta.published_at stays empty. Codes, every attribute id, both
years and the range are checked before the first request. Args:
commodity_code: PSD commodity code, seven digits, e.g. "0410000" (Wheat),
"0440000" (Corn), "2222000" (Oilseed, Soybean).
country_code: PSD country code (not ISO), e.g. "US" (United States), "BR"
(Brazil), "E4" (European Union).
start_year: First PSD market year, 1960 or later (PSD: "PSD Database has data
for most commodities since year 1960"), e.g. 2021.
end_year: Last PSD market year, included, e.g. 2023; not before
start_year and at most 99 years after it. No other bound.
attribute_id: PSD attribute id, or a list of them, e.g. 28 (Production),
[28, 88] (Production and Exports), 176 (Ending Stocks);
list_commodity_attributes lists them. Omit it (None) for every
attribute of each answer, 15 a year for wheat in the United States. An empty
list is refused. |
| usda_psd_get_top_countriesA | The n countries with the largest value of one PSD attribute for a commodity and year. One request to PSDData_GetCommodityDataByYear (every country); its records with
attribute_id are sorted by value, largest first, and the first n kept,
each exactly as upstream sent it. Equal values keep upstream's order. Values are
compared as sent, with no unit check: each record carries its own unit_id, the
unit of its value (in the recorded answers, wheat and corn 2023, every country
reports an attribute in the same unit). By default nothing is excluded: PSD's country
list holds groupings that rank alongside countries, above all the European Union
("E4", second in wheat production for 2023), and residual aggregates such as
"T3" (Africa, NEC), "X8" (Southern Asia NEC) and "Z7" (Other Pacific
Islands, NEC); exclude_groupings=True leaves those out, and region_code keeps
the countries of one PSD region. The data records carry no region, so each record's
country is looked up in the packaged country list; a country it lacks has no region
and is left out when region_code is given. meta.vintage is the latest release
among every record that was ranked, after region_code and exclude_groupings
apply, not only the n returned, since each of them could have changed the order;
for wheat 2023 that is "2026-10", and None when nothing was ranked.
meta.published_at stays empty. Codes and arguments are checked before the call;
a market year without data raises NotFoundError. Args:
commodity_code: PSD commodity code, seven digits, e.g. "0410000" (Wheat),
"0440000" (Corn), "2222000" (Oilseed, Soybean).
market_year: PSD market year, e.g. 2023, 2022, 2021.
attribute_id: PSD attribute id to rank by, e.g. 28 (Production), 88
(Exports), 57 (Imports), 176 (Ending Stocks);
list_commodity_attributes lists them.
n: How many records to keep, at least 1, e.g. 5, 10 (the default); more
than the countries reporting the attribute returns them all.
region_code: Rank only the countries of this PSD region, as list_countries
gives it, e.g. "R04" (South America), "R18" (East Asia), "R15"
(Africa, NEC and three more, a region list_regions lacks). A code no
packaged country carries is refused; "R00" (World) is one, and the world
total is get_world_data's. Omit (None) for every region.
exclude_groupings: True leaves PSD's aggregates out of the ranking: "E4"
European Union, "E2" EU-15, "E3" EU-25, "C1" Caribbean Basin,
"T3" Africa, NEC, "X8" Southern Asia NEC, "Z7" Other Pacific
Islands, NEC and "ZZ" Other. False, the default, ranks them like
countries. |
| usda_psd_get_world_dataA | PSD supply and distribution forecasts for one commodity and market year, world total. One record per attribute, aggregated by PSD over every applicable country
(country_code "00"). attribute_id and unit_id are PSD's integer ids,
which enums.AttributeId and enums.UnitId name; value is in that unit.
meta.vintage is the PSD release that last revised the figures, as upstream names
it ("2026-10"), the latest release of any country for this commodity and market
year (in the whole answers recorded on 2026-10-23, commit 07b88ad);
meta.published_at stays empty, since PSD gives no day. The code and the
year are checked before any call; a market year without data raises
NotFoundError. Args:
commodity_code: PSD commodity code, seven digits, e.g. "0410000" (Wheat),
"0440000" (Corn), "2222000" (Oilseed, Soybean).
market_year: PSD market year, e.g. 2023; data goes back to 1960 for most
commodities. |
| usda_psd_list_commoditiesA | List PSD's commodities with their codes, the values commodity_code takes. Answered from PSDData_GetCommodities as packaged with this version
(reference/commodities.json), without an upstream call: 63 commodities when
packaged, in upstream order, e.g. "0410000" Wheat, "0440000" Corn,
"2222000" Oilseed, Soybean. meta.retrieved_at is when the package fetched the
list (2026-10-28, UTC); meta.vintage is empty, as upstream gives the list no
release identifier. Args:
search: Keep the commodities where this text occurs, ignoring case, in the code
or the name, e.g. "wheat" (0410000 Wheat), "soybean" (meal, oil and
oilseed, each also "(Local)"), "0440000" (Corn). Omit (None) for all. |
| usda_psd_list_commodity_attributesA | List PSD's commodity attributes with their ids, the attribute_id of every data record. Answered from PSDData_GetCommodityAttributes as packaged with this version
(reference/commodityAttributes.json), without an upstream call: 85 attributes
when packaged, in upstream order, e.g. 28 Production, 57 Imports, 88
Exports, 176 Ending Stocks. Names are not unique: "Total Disappearance" is
126 and 173, "Fresh Dom. Consumption" 133 and 135; the id tells them apart.
enums.AttributeId names the same ids. meta.retrieved_at is when the package
fetched the list (2026-10-28, UTC); meta.vintage is empty, as upstream gives the
list no release identifier. Args:
search: Keep the attributes where this text occurs, ignoring case, in the id
(as digits) or the name, e.g. "stocks", "disappearance" (126 and 173
Total Disappearance, 151 Other Disappearance), "28" (28 Production, and
128 Dom. Leaf Consumption: the id matches as text). Omit (None) for all. |
| usda_psd_list_countriesA | List PSD's countries with their codes and regions, the values country_code takes. Answered from PSDData_GetCountries as packaged with this version
(reference/countries.json), without an upstream call: 251 countries when
packaged, in upstream order, each with its PSD region (list_regions) and its GENC
code where upstream has one. Codes are PSD's own, not ISO: "US" United States,
"BR" Brazil, "CH" China, "E4" European Union; aggregates such as "T3"
Africa, NEC have no GENC code. meta.retrieved_at is when the package fetched the
list (2026-10-28, UTC); meta.vintage is empty, as upstream gives the list no
release identifier. Args:
region_code: Keep the countries of this PSD region, spelled exactly as
list_regions spells it, e.g. "R01" (North America, 5 countries),
"R05" (European Union), "R11" (Sub-Saharan Africa). "R15" holds
four countries (Africa, NEC; Fernando Po; French Equatorial Africa; Other)
although list_regions lacks it. A code no country carries yields an
empty list. Omit (None) for every region.
search: Keep the countries where this text occurs, ignoring case, in the code,
the name or the GENC code, e.g. "united" (TC United Arab Emirates, UK
United Kingdom, US United States), "USA" (US United States, by its GENC
code), "E4", "brazil". Omit (None) for every country. |
| usda_psd_list_regionsA | List PSD's regions with their codes, the values region_code of list_countries takes. Answered from PSDData_GetRegions as packaged with this version
(reference/regions.json), without an upstream call: 15 regions when packaged, in
upstream order, from "R00" World and "R01" North America to "R18" East
Asia. Upstream's list lacks "R15", the region of four countries in
list_countries (Africa, NEC and three more); it is kept as upstream sends it.
meta.retrieved_at is when the package fetched the list (2026-10-28, UTC);
meta.vintage is empty, as upstream gives the list no release identifier. |
| usda_psd_list_units_of_measureA | List PSD's units of measure with their ids, the unit_id of every data record. Answered from PSDData_GetUnitsOfMeasure as packaged with this version
(reference/unitsOfMeasure.json), without an upstream call: 42 units when
packaged, in upstream order, e.g. 8 (1000 MT), 4 (1000 HA), 26 (MT/HA).
Descriptions are upstream's, padded with spaces to 20 characters
("(1000 MT) "). enums.UnitId names the same ids.
meta.retrieved_at is when the package fetched the list (2026-10-28, UTC);
meta.vintage is empty, as upstream gives the list no release identifier. |
| comtrade_get_bilateral_dataA | Compare a reporter's trade figures with its partners' mirror figures, row by row. Upstream's getBilateralData, which its spec marks "EXPERIMENTAL - USE SPARINGLY":
one keyed call, "basic trade data joined with mirror partner data", useful to analyse
bilateral trade asymmetries. Its result is not a list, nor is get_mirror_flows':
data is a BilateralData holding upstream's note, its
timestamp_requested and the rows, data.data, because the note qualifies the
mirror values. It counts the partners with a data gap and gives their share of world
trade without naming them ("a data gap for 2 partner(s) ... approximately 0.015% of the
accumulated world's share").
Each row, a BilateralDataRecord, is one reporter, partner, product code, flow and
period at the total of every breakdown (customs_code "C00", mot_code 0): the
reporter's figures (primary_value, qty, net_wgt, ...) beside the mirror
(mirror_primary_value, mirror_qty, ...), for a reporter's exports "the import
data reported by" its partners, as UN Comtrade's Help Center puts it. It warns that "the
outcome of the mirror data depends on the availability of other reporters rather than
no-trade": a mirror of 0 is no evidence of no trade. For Switzerland's 2023 exports
Afghanistan's mirror of 0 showed which partner the gap was, inferred from the counts
(DPRK alone: 1, the USA alone: none, the three together: 2), not stated. That is no
general rule: the note speaks of a gap "during specific periods" and says "the
calculation of mirror data may be incomplete", and a mirror of 0 can also be a partner
that reported no such imports. primary_value_disc is upstream's, its meaning not
stated; in every recorded row it equals (mirror_primary_value - primary_value) / primary_value, a relative difference (-0.16 for Switzerland's 2023 exports to the
USA, -1.0 where the mirror is 0). The mirror2_* fields are not described
upstream and were None or 0 in every recorded row. A pair upstream holds nothing for
has no row. meta.total is upstream's count. Over MCP the rows are not cut to the
result cap one by one: an answer above it (about 40 rows) comes as a preview of its
text, so name a few partners or periods per call. The query must name reporter_code
or partner_code, and cmd_code: upstream offers no count to check a query's size
before the call (it ignores countOnly), so a broader query is refused before it is
sent. Arguments are checked before the call; an unknown reporter or partner code raises
UnknownCode, an InvalidRequestError naming the packaged list and the closest
area, another mistake InvalidRequestError naming the closest valid value. Args:
type_code: "C" goods or "S" services.
freq_code: "A" annual or "M" monthly.
cl_code: Product classification, checked against the package's list: "HS"
(all HS editions as reported, the one recorded here; rows name the edition in
classification_code, e.g. "H6"), an edition "H0" to "H6",
SITC "SS", "S1" to "S4", BEC "B4", "B5", "BE",
"TM", for services EBOPS "EB", "EB02", "EB10", "EB10S".
The Tools spec lists HS, S1 to S4, BE4, BE5, EB,
EB02, EB10 and EBSDMX; BE4, BE5 and EBSDMX are not in
the package's list (upstream refused BE5 on data/v1/get and
EBSDMX on getDa) and are refused before the call.
reporter_code: Reporting areas as UN Comtrade's numeric codes, comma-separated,
e.g. "757" Switzerland, "842" USA, "276" Germany, "156" China,
"757,842", as list_reporters lists them. Some differ from ISO numeric
codes: Switzerland is 757, not 756. Required unless partner_code is given.
period: Years "2023" (annual) or months "202305" (monthly),
comma-separated, e.g. "2021,2022,2023"; unlike get_data, more than 12
are accepted (13 answered 13 rows).
partner_code: Partner areas, comma-separated, as list_partners lists them:
"842" USA, "276" Germany, "842,276", one row each. Required
unless reporter_code is given.
cmd_code: Product codes of cl_code, comma-separated, as
list_commodities(cl_code) lists them: "TOTAL" for all goods,
"AG2" for every chapter, codes such as "27", "0901" or
"090111", wildcards such as "27??".
flow_code: One trade flow: "X" exports or "M" imports; upstream refuses
both in one call ("M,X"), so call once per flow.
include_desc: Upstream's includeDesc, sent on as given: the recorded answers
carry no descriptions with or without it (the *_iso and *_desc fields
stay None); list_reporters and list_partners name the codes. |
| comtrade_get_bilateral_flowsA | Trade between one reporter and one partner, one row per product code and period. One data/v1/get call for goods (typeCode C), pinned to the total of every
breakdown (partner2Code 0, customsCode C00, motCode 0, breakdownMode
classic) and with descriptions (includeDesc), so each row is UN Comtrade's figure
for the reporter's side of the trade in one product code and period. At TOTAL
and chapter level these are mostly UNSD aggregates (is_aggregate true,
is_reported false) with no quantity (qty 0, qty_unit_abbr "N/A",
net_wgt 0 or None): read the trade values. Rows are TradeFlowRecord,
sorted by period, then product code; a code or period upstream holds nothing for has
no row. Bounded by construction at product codes times periods rows (at most 12
periods), so there is no count call; a bound above 100,000 raises QueryTooLarge
before the call. Arguments are resolved and checked before the call; an unknown area
raises UnknownCode, an InvalidRequestError naming the packaged list and the
closest area, another mistake InvalidRequestError naming the closest valid value.
meta.request holds the get_data arguments that were sent, codes resolved. Args:
reporter: The reporting area, as UN Comtrade's code or its ISO alpha-3 code:
"757" or "CHE" Switzerland, "842" or "USA", "276" or "DEU"
Germany, "156" or "CHN" China; list_reporters(search=...) finds them.
Codes are UN Comtrade's, not ISO numeric (Switzerland is 757, not 756). An
alpha-3 code that several codes share resolves to the one still in use
("DEU" is 276, not 280 Fed. Rep. of Germany until 1990).
partner: The partner area, as code or ISO alpha-3 code: "842" or "USA"
(842, the code the USA reports under, not 840), "276" or "DEU", "0"
or "W00" World, the total over all partners; list_partners(search=...)
finds them.
commodities: Product codes of cl_code, comma-separated, each naming one code:
"TOTAL" all goods, an HS chapter "27", heading "2709" or subheading
"270900", e.g. "TOTAL,27". Levels such as "AG2" and wildcards such
as "27??" are for get_data. list_commodities("HS", search="crude")
finds codes.
periods: Years "2022,2023" (annual data) or months "202301,202302" (monthly
data), comma-separated, at most 12, one format: the format sets freqCode.
flow: One trade flow: "X" exports, "M" imports, "RX" re-exports,
"RM" re-imports.
cl_code: Product classification, "HS" by default: all HS editions as each
reporter reported them (rows name the edition in classification_code, e.g.
"H6"); an edition "H0" to "H5", SITC "SS" or "S1" to "S4",
BEC "B4", "B5" also work. "H6" is valid but upstream answered HTTP 500
to every try on 2026-10-23, so "HS" stays the default. EBOPS "EB",
"EB02", "EB10", "EB10S" (services), "BE" and "TM" are
accepted but untested with the pinned typeCode C. |
| comtrade_get_commodity_seriesA | A reporter's trade in one product with the World over many periods, oldest first. data/v1/get for goods (typeCode C) with partner 0, World (the total over all
partners), pinned to the total of every breakdown (partner2Code 0, customsCode
C00, motCode 0, breakdownMode classic), with descriptions (includeDesc).
Upstream takes at most 12 periods per call, so the periods are sent in chunks of 12,
one call after the other in the order given (14 periods: two calls, 1.5 s apart), and
the rows are joined and sorted by period; a period upstream holds nothing for has no
row. A period the reporter has not released yet has no row either, which cannot be
told from a period without trade; get_data_availability names the periods a
reporter has released. One row per period at most, so there is no count call. Every
chunk is a keyed call and a free key allows 500 calls a day, so one series takes at
most 120 periods (ten calls); more raise InvalidRequestError before any call:
split the series. Arguments are resolved and checked before any call; an unknown
reporter raises UnknownCode, an InvalidRequestError naming the packaged list
and the closest area, another mistake InvalidRequestError naming the closest valid
value. meta.request holds the get_data arguments with every period; they were
sent 12 at a time.
Args:
reporter: The reporting area, as UN Comtrade's code or its ISO alpha-3 code:
"757" or "CHE" Switzerland, "842" or "USA", "276" or "DEU"
Germany, "156" or "CHN" China; list_reporters(search=...) finds them.
Codes are UN Comtrade's, not ISO numeric (Switzerland is 757, not 756). An
alpha-3 code that several codes share resolves to the one still in use
("DEU" is 276, not 280 Fed. Rep. of Germany until 1990).
commodity: One product code of cl_code: "TOTAL" all goods, an HS chapter
"27", heading "0901" or subheading "090111".
list_commodities("HS", search="coffee") finds codes.
flow: One trade flow: "X" exports, "M" imports, "RX" re-exports,
"RM" re-imports.
periods: Years (annual data) or months (monthly data), comma-separated, one
format, each once, at most 120: "2018,2019,2020,2021,2022,2023",
"202201,202202,202203"; every year from 2010 to 2023 is 14 periods, two
calls.
cl_code: Product classification, "HS" by default: all HS editions as each
reporter reported them (rows name the edition in classification_code, e.g.
"H6"); an edition "H0" to "H5", SITC "SS" or "S1" to "S4",
BEC "B4", "B5" also work. "H6" is valid but upstream answered HTTP 500
to every try on 2026-10-23, so "HS" stays the default. EBOPS "EB",
"EB02", "EB10", "EB10S" (services), "BE" and "TM" are
accepted but untested with the pinned typeCode C. |
| comtrade_get_comtrade_releasesA | List UN Comtrade's recent data releases: which reporter's dataset came out when. Upstream's public getComtradeReleases, "the list of the recent releases, the same
with the UI live update page" (https://comtradeplus.un.org/RecentReleases); the spec
calls each row "A recent or upcoming dataset release". Keyless: no key is sent and no
daily quota is spent, but the call shares the client's pace (the Public tier allows 1
call per second) and its quota policy, so once upstream has said the key's daily quota
is spent it is held back too; the Public tier's preview API's 500 records a call is far
above the rows recorded. One row per release: reporter_code (UN Comtrade's code,
e.g. 757 Switzerland), dataset_desc (e.g. "Switzerland CM 202601"),
flag_code and nr, whose meanings upstream does not state (recorded: two letters,
"CH" for 757; "N" or "R"), and date_release, a naive datetime: upstream
prints it without a UTC offset and states no zone, so none is attached. When recorded on
2026-10-28 it listed 38 releases from 2026-10-22 to 2026-10-28, newest first, every one
at midnight, none in the future; the spec states no order. UN Comtrade keeps one version
of each dataset, so a revised release replaces the earlier data, which is not archived.
meta.total is upstream's count; meta.published_at stays None, since each row
has its own date. No arguments, one call; get_data_availability gives a dataset's
first and latest release. |
| comtrade_get_countsA | Count the UN Comtrade trade records a query would return, without fetching them. The same request as get_data with upstream's countOnly. One call returns at
most 100,000 records, so count first and split a larger query. A count of 0 means no
data matches: an unreported period, a code that is not a reporter, a flow the
reporter does not record. Every count costs one call of the key's daily quota (500
on a free key). Arguments are checked before the call, reporter, partner, customs and
transport codes against the packaged lists: an unknown one raises UnknownCode, an
InvalidRequestError naming the packaged list, its fetch date and the closest code
(756 names 757, Switzerland); another mistake raises InvalidRequestError naming
the closest valid value. Args:
type_code: "C" goods or "S" services.
freq_code: "A" annual or "M" monthly.
cl_code: Product classification: "HS" (all HS editions as reported; prefer
it), an edition "H0" to "H5", SITC "SS", "S1" to "S4", BEC
"B4", "B5", for services EBOPS "EB", "EB02", "EB10",
"EB10S"; also "BE" and "TM", which the spec lists and upstream
accepts. "H6" is valid but upstream answered HTTP 500 to all five tries on
2026-10-23 (two reporters, two product codes); "HS" rows carry the edition
the reporter used, e.g. classification_code "H6" for Switzerland 2023.
reporter_code: Reporting areas as UN Comtrade's numeric codes, comma-separated,
e.g. "757" Switzerland, "842" USA, "276" Germany, "156" China,
"757,842", as list_reporters lists them. Some differ from ISO numeric
codes: Switzerland is 757, not 756. Omit for every reporter.
partner_code: Partner areas, comma-separated, as list_partners lists them:
"0" World (the total over all partners), "276" Germany. Omit for every
partner, one row each.
partner2_code: Second partner (consignment) areas, comma-separated, codes of
list_partners; "0" is the total.
period: Years "2023" (annual) or months "202305" (monthly), at most 12
comma-separated, e.g. "2021,2022,2023".
cmd_code: Product codes of cl_code, comma-separated, as
list_commodities(cl_code) lists them: "TOTAL" for all goods,
"AG2", "AG4", "AG6" for every code at that level, codes such as
"0901" or "090111", wildcards such as "27??" (every four-digit code
under 27) or "27*". For services the classification files name "200"
(EB, EB02, EB10) or "S" (EB10S) as the total; recorded counts confirm
"200" on EB10 and EB02, where "TOTAL" counted 0 (EB10). A code
upstream does not have counts 0 too, so a 0 does not prove that a code exists.
flow_code: Trade flows, comma-separated: "X" exports, "M" imports,
"RX" re-exports, "RM" re-imports, also "DX", "FM", "MIP",
"MOP", "XIP", "XOP", "MIF", "XIF"; e.g. "M,X".
mot_code: Modes of transport, comma-separated: "0" the total, "1000" air,
"2100" sea, "3100" railway, "3200" road, "9100" pipelines and
cables. Omit for every mode, one row each.
customs_code: Customs procedures, comma-separated: "C00" the total, "C01"
clearance for home use, "C03" outright exportation. Omit for every
procedure, one row each.
aggregate_by: Upstream parameters to aggregate the results over, comma-separated
from cmdCode, period, partnerCode, partner2Code,
reporterCode, customsCode, motCode; e.g. "cmdCode" sums the
products of "AG2" into one row per remaining breakdown. The aggregated
parameters come back as -2 (cmd_code "-2", partner_code -2)
with classification_code "GG"; the count matches the rows.
breakdown_mode: "plus", upstream's default (omitting it gives the same rows):
every customs procedure, mode of transport and second partner;
"classic": only the total row (partner2_code 0, customs_code
"C00", mot_code 0).
include_desc: Upstream's includeDesc, "Include descriptions of data
variables": fills the *_iso and *_desc fields of get_data rows;
sent on as given. |
| comtrade_get_dataA | Fetch UN Comtrade final trade data for one query, up to 100,000 records. Counts first (one extra call, as get_counts): a count of 0 returns an empty list
without fetching, since no matching data is an answer, not an error; a count above
100,000 raises QueryTooLarge with the count before anything is fetched, because
upstream would cut the answer at 100,000 rows without saying so. Each row carries
every field of upstream's TradeDataRecord under its snake_case name;
primary_value is upstream's primary trade value (taken from the CIF or FOB value,
in cifvalue/fobvalue). Leaving out partner2_code,
customs_code and mot_code returns every breakdown upstream holds (32 rows for
Switzerland's 2023 exports to the World); the row with partner2_code 0,
customs_code "C00" and mot_code 0 is the total, and pinning those three
(or breakdown_mode="classic") returns that row alone. Arguments are checked
before any call; an unknown reporter, partner, customs or transport code raises
UnknownCode, an InvalidRequestError naming the packaged list and the closest
code, another mistake InvalidRequestError naming the closest valid value. Args:
type_code: "C" goods or "S" services.
freq_code: "A" annual or "M" monthly.
cl_code: Product classification: "HS" (all HS editions as reported; prefer
it), an edition "H0" to "H5", SITC "SS", "S1" to "S4", BEC
"B4", "B5", for services EBOPS "EB", "EB02", "EB10",
"EB10S"; also "BE" and "TM", which the spec lists and upstream
accepts. "H6" is valid but upstream answered HTTP 500 to all five tries on
2026-10-23 (two reporters, two product codes); "HS" rows carry the edition
the reporter used, e.g. classification_code "H6" for Switzerland 2023.
reporter_code: Reporting areas as UN Comtrade's numeric codes, comma-separated,
e.g. "757" Switzerland, "842" USA, "276" Germany, "156" China,
"757,842", as list_reporters lists them. Some differ from ISO numeric
codes: Switzerland is 757, not 756. Omit for every reporter.
partner_code: Partner areas, comma-separated, as list_partners lists them:
"0" World (the total over all partners), "276" Germany. Omit for every
partner, one row each.
partner2_code: Second partner (consignment) areas, comma-separated, codes of
list_partners; "0" is the total.
period: Years "2023" (annual) or months "202305" (monthly), at most 12
comma-separated, e.g. "2021,2022,2023".
cmd_code: Product codes of cl_code, comma-separated, as
list_commodities(cl_code) lists them: "TOTAL" for all goods,
"AG2", "AG4", "AG6" for every code at that level, codes such as
"0901" or "090111", wildcards such as "27??" (every four-digit code
under 27) or "27*". For services the classification files name "200"
(EB, EB02, EB10) or "S" (EB10S) as the total; recorded counts confirm
"200" on EB10 and EB02, where "TOTAL" counted 0 (EB10). A code
upstream does not have counts 0 too, so a 0 does not prove that a code exists.
flow_code: Trade flows, comma-separated: "X" exports, "M" imports,
"RX" re-exports, "RM" re-imports, also "DX", "FM", "MIP",
"MOP", "XIP", "XOP", "MIF", "XIF"; e.g. "M,X".
mot_code: Modes of transport, comma-separated: "0" the total, "1000" air,
"2100" sea, "3100" railway, "3200" road, "9100" pipelines and
cables. Omit for every mode, one row each.
customs_code: Customs procedures, comma-separated: "C00" the total, "C01"
clearance for home use, "C03" outright exportation. Omit for every
procedure, one row each.
aggregate_by: Upstream parameters to aggregate the results over, comma-separated
from cmdCode, period, partnerCode, partner2Code,
reporterCode, customsCode, motCode; e.g. "cmdCode" sums the
products of "AG2" into one row per remaining breakdown. The aggregated
parameters come back as -2 (cmd_code "-2", partner_code -2)
with classification_code "GG"; the count matches the rows.
breakdown_mode: "plus", upstream's default (omitting it gives the same rows):
every customs procedure, mode of transport and second partner;
"classic": only the total row (partner2_code 0, customs_code
"C00", mot_code 0).
include_desc: Upstream's includeDesc, "Include descriptions of data
variables": fills reporter_iso/reporter_desc, the partner and second
partner ones, flow_desc, cmd_desc, customs_desc, mot_desc, the
quantity unit abbreviations, aggr_level and is_leaf; without it they
are None. |
| comtrade_get_data_availabilityA | List the UN Comtrade datasets a query covers, per reporter and period, with release dates. Upstream's getDa: which reporters have published data for which periods, in which
classification, how many records each dataset holds and when it was first and last
released (first_released, last_released, naive datetimes as upstream sends
them). One call. A period nobody reported returns an empty list. Arguments are checked
before the call; an unknown reporter code raises UnknownCode, an
InvalidRequestError naming the packaged list and the closest area, another
mistake InvalidRequestError naming the closest valid value. Args:
type_code: "C" goods or "S" services.
freq_code: "A" annual or "M" monthly.
cl_code: Classification: "HS" for the data as reported (Switzerland 2023 is
an "H6" dataset), an HS edition "H0" to "H6", SITC "S1" to
"S4", "BE", for services "EB", "EB02", "EB10".
reporter_code: Reporters, comma-separated, as list_reporters lists them:
"757" Switzerland, "842" USA, "276" Germany, "156" China,
"757,842". Omit for every reporter (169 datasets for 2023, annual HS).
period: Years "2023" or months "202305", comma-separated, e.g.
"2021,2022,2023"; unlike get_data, more than 12 are accepted.
published_date_from: Upstream's publishedDateFrom, a day "2024-01-01":
datasets published from then on. A dataset revised in the range counts
(Switzerland 2022, first released 2023-02-01, revised 2024-04-29, is in 2024).
published_date_to: Upstream's publishedDateTo, a day "2024-12-31". |
| comtrade_get_live_updateA | List the 50 most recent releases in UN Comtrade's release pipeline, newest first. Upstream's getLiveUpdate: for each release the reporter (reporter_code, a
string here, e.g. "842"), type_code, freq_code, classification_code,
period, file size, status and release_status (e.g. "Released"),
and four times: started_at and completed_at (UTC), last_updated (a day)
and queued_at (no zone given, kept naive). There is no publication date field;
get_data_availability and get_metadata carry those per dataset. One call, no
arguments. Upstream's count (174 when recorded) is not the number of rows, so it
is not returned. |
| comtrade_get_metadataA | List UN Comtrade's publication notes for a reporter's datasets, one per publication. Upstream's getMetadata: per dataset (reporter and period), a note for its first
publication ("New Data") and one for each revision ("Revised Data"), each with its
publication_date and what the reporter's data rests on: currency, the import
and export conversion factors (Decimal), trade_system ("General" or
"Special"), the valuation ("CIF", "FOB") and partner attribution. One call.
reporter_code and period are not in upstream's spec, but upstream honours them
as the official comtradeapicall package sends them; without reporter_code the
answer holds every reporter's notes, so name one. Args:
type_code: "C" goods or "S" services.
freq_code: "A" annual or "M" monthly.
cl_code: Classification: "HS" ("H6" is answered the same), SITC
"SS" or "S1" to "S4", "BE", "TM", for services "EB",
"EB02", "EB10".
reporter_code: Reporters, comma-separated, as list_reporters lists them:
"757" Switzerland (38 annual datasets, 1988 onwards), "842" USA,
"276" Germany, "156" China.
period: Years "2023" or months "202305", comma-separated. Omit for every
period. |
| comtrade_get_mirror_flowsA | A reporter's reported trade with one partner beside the partner's reported mirror of it. The two sides of one trade, per product code and period: what the reporter reported
(primary_value, its quantities and weights) and what the partner reported for the
same trade (mirror_primary_value, mirror_qty, ...): for a reporter's exports,
"the import data reported by" the partner. UN Comtrade's Help Center calls the tool
Bilateral Data Comparison, which "puts the reported data and its mirror data
side-by-side, allowing the analysis of bilateral trade asymmetries"
(un-comtrade-tools.md); the two sides differ for documented reasons, imports valued
CIF and exports FOB, partner attribution, time lags, goods passing through third
countries (bilateral-asymmetries.md). One call of upstream's getBilateralData
for goods (typeCode C), which its spec marks "EXPERIMENTAL - USE SPARINGLY"; it
answers at the total of every breakdown (classic mode). data is one
MirrorFlows, not a list: upstream's note, its timestamp_requested (UTC) and
the rows, data.data, one MirrorFlowRecord per product code and period, in
upstream's order (period order in every recording); a code or period upstream holds
nothing for has no row.
The note qualifies the mirror: it counts the partners with a data gap and gives their
share of world trade without naming them, and "the outcome of the mirror data depends
on the availability of other reporters rather than no-trade", so a mirror of 0 is no
evidence of no trade. For Switzerland's 2023 exports Afghanistan's mirror of 0 showed
which partner the gap was, inferred from the counts, not stated; that is no general
rule. primary_value_disc is upstream's, its meaning not stated: in every recorded
row it equals (mirror_primary_value - primary_value) / primary_value (-0.949
for Switzerland's 2023 exports of HS chapter 27 to the USA). mirror2_primary_value
is not described upstream and was 0 in every recorded row; the other mirror2
fields are left out (empty in every recording; get_bilateral_data carries them).
Descriptions are None: getBilateralData filled none even with includeDesc, so
it is not sent; list_reporters and list_partners name the codes. Bounded by
construction at product codes times periods rows, so there is no count call (upstream
offers none here); a bound above 100,000 raises QueryTooLarge before the call.
Over MCP a result above 64 KB (about 60 rows) reaches the agent as a preview of its
text, so name a few product codes or periods per call. Arguments are resolved and
checked before the call; an unknown area raises UnknownCode, an
InvalidRequestError naming the packaged list and the closest area, another mistake
InvalidRequestError naming the closest valid value. meta.request holds the
get_bilateral_data arguments that were sent, codes resolved; meta.total is
upstream's count. Args:
reporter: The reporting area, as UN Comtrade's code or its ISO alpha-3 code:
"757" or "CHE" Switzerland, "842" or "USA", "276" or "DEU"
Germany, "156" or "CHN" China; list_reporters(search=...) finds them.
Codes are UN Comtrade's, not ISO numeric (Switzerland is 757, not 756).
partner: The partner area whose report is the mirror, as code or ISO alpha-3
code: "842" or "USA" (842, the code the USA reports under, not 840),
"757" or "CHE", "276" or "DEU"; list_partners(search=...)
finds them. "0" World is passed on, upstream's answer to it unrecorded.
commodities: Product codes of cl_code, comma-separated, each naming one code:
"TOTAL" all goods, an HS chapter "27", headings "2709,2710".
Levels such as "AG2" and wildcards such as "27??" are refused (one row
per code and period bounds the call). list_commodities("HS", search="crude")
finds codes.
periods: Years "2022,2023" (annual data) or months "202301" (monthly
data), comma-separated, one format: the format sets freqCode. At most 12,
the bound of the slices, though getBilateralData answered 13
(get_bilateral_data takes more).
flow: The reporter's flow, one of the two getBilateralData takes: "X" exports,
whose mirror is the partner's reported imports, or "M" imports, the spec's
other value (not recorded here).
cl_code: Product classification, "HS" by default and the one recorded: all HS
editions as each reporter reported them (rows name the edition in
classification_code, e.g. "H6"). Checked against the package's list:
an edition "H0" to "H6", SITC "SS" or "S1" to "S4", BEC
"B4", "B5" are accepted but untested here; the Tools spec's "BE4",
"BE5" and "EBSDMX" are refused before the call. EBOPS "EB",
"EB02", "EB10", "EB10S" (services), "BE" and "TM" are
accepted but untested with the pinned typeCode C. |
| comtrade_get_top_partnersA | A reporter's n largest partners in one product and period, by primary value. One data/v1/get call for goods (typeCode C) without partnerCode (every
partner), pinned to the total of every breakdown (partner2Code 0, customsCode
C00, motCode 0, breakdownMode classic), with descriptions (includeDesc).
The rows are sorted by primary_value, largest first, here rather than upstream;
partner 0, World, is dropped because it is the total over all partners, not a
partner; the first n rows are returned and nothing else is changed. Areas that
are not countries, such as 490 "Other Asia, nes", stay in the ranking where the
reporter reported them. Bounded by construction at one row per partner (310 in the
packaged partnerAreas.json), so there is no count call. Arguments are resolved and
checked before the call; an unknown reporter raises UnknownCode, an
InvalidRequestError naming the packaged list and the closest area, another
mistake InvalidRequestError naming the closest valid value. meta.request holds
the get_data arguments that were sent, and n. Args:
reporter: The reporting area, as UN Comtrade's code or its ISO alpha-3 code:
"757" or "CHE" Switzerland, "842" or "USA", "276" or "DEU"
Germany, "156" or "CHN" China; list_reporters(search=...) finds them.
Codes are UN Comtrade's, not ISO numeric (Switzerland is 757, not 756). An
alpha-3 code that several codes share resolves to the one still in use
("DEU" is 276, not 280 Fed. Rep. of Germany until 1990).
commodity: One product code of cl_code: "TOTAL" all goods, an HS chapter
"27", heading "3004" or subheading "300490".
list_commodities("HS", search="medicament") finds codes.
period: One year "2023" (annual data) or month "202305" (monthly data).
flow: One trade flow: "X" exports, "M" imports, "RX" re-exports,
"RM" re-imports.
n: How many partners, at least 1, e.g. 10; fewer come back when fewer
partners have a row.
cl_code: Product classification, "HS" by default: all HS editions as each
reporter reported them (rows name the edition in classification_code, e.g.
"H6"); an edition "H0" to "H5", SITC "SS" or "S1" to "S4",
BEC "B4", "B5" also work. "H6" is valid but upstream answered HTTP 500
to every try on 2026-10-23, so "HS" stays the default. EBOPS "EB",
"EB02", "EB10", "EB10S" (services), "BE" and "TM" are
accepted but untested with the pinned typeCode C. |
| comtrade_get_trade_balanceA | Fetch UN Comtrade trade data with a reporter's exports and imports side by side. Upstream's getTradeBalance, which its spec marks "EXPERIMENTAL - USE SPARINGLY":
one keyed call, no count first. Each row, a TradeBalanceRecord, holds a reporter's
exports (*_x: primary_value_x, qty_x, net_wgt_x, ...) and imports
(*_m) with one partner, second partner, product code, customs procedure, mode of
transport and period, and primary_value_bal, which the spec defines as "X - M":
upstream's value, passed through (54550055814.504944 for Switzerland and the World
in 2023). Without breakdown_mode upstream answers every breakdown (48 rows for
Switzerland and the World, 2023, all goods); breakdown_mode="classic" returns the
total row alone. A query nothing matches returns an empty list. meta.total is
upstream's count. The query must name reporter_code or partner_code, and
cmd_code: upstream offers no count to check a query's size before the call
(countOnly answered 0 for those 48 rows), so a broader query is refused before it
is sent. Arguments are checked before the call; an unknown reporter, partner, customs
or transport code raises UnknownCode, an InvalidRequestError naming the
packaged list and the closest code, another mistake InvalidRequestError naming the
closest valid value. The spec says a free-tier key that is not on UN Comtrade's
allow-list is refused with HTTP 403 "User not allowed" (AuthError); the key the
package was recorded with was answered (2026-10-28). Args:
type_code: "C" goods or "S" services.
freq_code: "A" annual or "M" monthly.
cl_code: Product classification, checked against the package's list: "HS"
(all HS editions as reported, the one recorded here; rows name the edition in
classification_code, e.g. "H6"), an edition "H0" to "H6",
SITC "SS", "S1" to "S4", BEC "B4", "B5", "BE",
"TM", for services EBOPS "EB", "EB02", "EB10", "EB10S".
The Tools spec lists HS, S1 to S4, BE4, BE5, EB,
EB02, EB10 and EBSDMX; BE4, BE5 and EBSDMX are not in
the package's list (upstream refused BE5 on data/v1/get and
EBSDMX on getDa) and are refused before the call.
reporter_code: Reporting areas as UN Comtrade's numeric codes, comma-separated,
e.g. "757" Switzerland, "842" USA, "276" Germany, "156" China,
"757,842", as list_reporters lists them. Some differ from ISO numeric
codes: Switzerland is 757, not 756. Required unless partner_code is given.
period: Years "2023" (annual) or months "202305" (monthly), at most 12
comma-separated, e.g. "2021,2022,2023".
partner_code: Partner areas, comma-separated, as list_partners lists them:
"0" World (the total over all partners), "276" Germany. Required
unless reporter_code is given; omitted, upstream's default applies, which
on get_data is every partner, one row each.
partner2_code: Second partner (consignment) areas, comma-separated, codes of
list_partners; "0" is the total.
cmd_code: Product codes of cl_code, comma-separated, as
list_commodities(cl_code) lists them: "TOTAL" for all goods,
"AG2" for every chapter, codes such as "27", "0901" or
"090111", wildcards such as "27??".
customs_code: Customs procedures, comma-separated: "C00" the total, "C01"
clearance for home use, "C03" outright exportation. Omit for every
procedure, one row each.
mot_code: Modes of transport, comma-separated: "0" the total, "1000" air,
"2100" sea, "3100" railway, "3200" road, "9100" pipelines and
cables. Omit for every mode, one row each.
aggregate_by: Upstream parameters to aggregate the results over, comma-separated
from cmdCode, period, partnerCode, partner2Code,
reporterCode, customsCode, motCode, e.g. "cmdCode"; sent on as
given (not recorded on this operation; on get_data the aggregated
parameters come back as -2).
breakdown_mode: Omitted, upstream's default: every customs procedure, mode of
transport and second partner, one row each. "classic": the total row only
(customs_code "C00", mot_code 0, partner2_code 0). "plus",
the spec's other value, gives every breakdown on get_data.
include_desc: Upstream's includeDesc, "Include descriptions of data
variables": with it the recorded rows have reporter_iso/reporter_desc,
the partner and second partner ones, cmd_desc, customs_desc,
mot_desc, the quantity unit abbreviations, aggr_level and is_leaf
filled; no answer with rows was recorded without it. |
| comtrade_get_world_shareA | List each reporter's share of world trade per period, with its release dates. Upstream's public getWorldShare, "Get the World Share (including estimates)"; the
spec calls a row "A reporter's share of world trade for one period". The spec states
neither whether world_share (a Decimal) is a fraction or a percentage nor of
which trade; when recorded, the 214 values for 2023 (annual goods, every reporter) sum
to 1.0 and Switzerland's is 0.0165. A row with is_available false (47 of those 214)
still carries a world_share, but first_released and last_released read
0001-01-01T00:00:00, upstream's placeholder on unavailable datasets, kept as sent,
not a release; upstream states no meaning for is_available or data_count. The
four times (first_released, last_released, created, updated) are naive
datetimes: upstream prints them without a UTC offset and states no zone, so none is
attached. Keyless: no key is sent and no daily quota is spent, but the call shares the
client's pace (the Public tier allows 1 call per second) and its quota policy, so once
upstream has said the key's daily quota is spent it is held back too. Upstream's
subscription page limits the Public tier's preview API to 500 records a call; whether
that binds this operation is not stated, and the recorded answers (214 rows at most) did
not reach it. One call, rows in upstream's order; a period nobody reported returns an
empty list. The MCP tool returns up to 400 rows or 100 KB, so the whole 214-row answer
for one period reaches an agent; beyond that its note says to narrow by
reporter_code or period. Arguments are checked before the call; an unknown
reporter code raises UnknownCode, an InvalidRequestError naming the packaged
list and the closest area, another mistake InvalidRequestError. Args:
type_code: "C" goods or "S" services.
freq_code: "A" annual or "M" monthly.
period: Years "2023" (annual) or months "202301" (monthly),
comma-separated, e.g. "2022,2023". The spec also lists "recent", which
is accepted, but upstream answered it with HTTP 500 on all three tries on
2026-10-28, with and without a reporter (ch_recent.json,
all_reporters_recent.json): the client makes 4 attempts (3 retries) on a
5xx and then raises UpstreamError, and what "recent" selects is
unknown, so name the periods. Omit for every period (64 annual rows for
Switzerland, 1962 to 2025).
reporter_code: Reporters, comma-separated, as list_reporters lists them:
"757" Switzerland, "842" USA, "156" China, "757,842". Omit for
every reporter (214 rows for 2023, annual goods). |
| comtrade_get_world_tradeA | Every reporter's trade in one product with the World for one period, largest first. One data/v1/get call for goods (typeCode C) without reporterCode (every
reporter) and with partner 0, World, pinned to the total of every breakdown
(partner2Code 0, customsCode C00, motCode 0, breakdownMode classic),
with descriptions (includeDesc): one row per reporter that reported the period
(167 for 2023 imports of HS chapter 27 when recorded), sorted by primary_value,
largest first. Bounded by construction at one row per reporter (255 in the packaged
Reporters.json), so there is no count call. Arguments are checked before the
call; a mistake raises InvalidRequestError naming the closest valid value.
meta.request holds the get_data arguments that were sent. Args:
commodity: One product code of cl_code: "TOTAL" all goods, an HS chapter
"27", heading "2709" or subheading "270900".
list_commodities("HS", search="crude") finds codes.
period: One year "2023" (annual data) or month "202305" (monthly data).
Recent periods fill as reporters publish; get_data_availability tells who
has.
flow: One trade flow: "X" exports, "M" imports, "RX" re-exports,
"RM" re-imports.
cl_code: Product classification, "HS" by default: all HS editions as each
reporter reported them (rows name the edition in classification_code, e.g.
"H6"); an edition "H0" to "H5", SITC "SS" or "S1" to "S4",
BEC "B4", "B5" also work. "H6" is valid but upstream answered HTTP 500
to every try on 2026-10-23, so "HS" stays the default. EBOPS "EB",
"EB02", "EB10", "EB10S" (services), "BE" and "TM" are
accepted but untested with the pinned typeCode C. |
| comtrade_list_classificationsA | List UN Comtrade's reference files, the product classifications among them, by category. Answered from upstream's index of the files, ListofReferences.json, as packaged
with this version (reference/ListofReferences.json), without an upstream call;
meta.retrieved_at is when the package fetched it, meta.vintage is None.
28 rows when packaged, one per file: its category ("flow", "reporter",
"cmd:HS"), the variable it lists ("Product [HS 2022]"), upstream's
description and where the file is served, fileuri. A category
cmd:<clCode> is a product classification, 19 of them: the cl_code that
get_data and list_commodities take ("cmd:H6" is "H6", HS 2022). Args:
category: Keep the row of this category, as upstream writes it, e.g.
"cmd:HS", "cmd:H6", "cmd:EB10", "flow", "reporter",
"qtyunit". Omit for every row. |
| comtrade_list_codesA | List the values one UN Comtrade parameter takes, each with upstream's words for it. Answered from the list packaged with this version (reference/<param>.json),
without an upstream call; meta.endpoint is the reference file or the spec the list
came from, meta.retrieved_at when the package fetched it, meta.vintage is
None. Each row holds the value under the parameter's name in snake_case
(flow_code, qty_unit_code) and upstream's words for it, under upstream's
names: text from the reference files for flowCode (tradeRegimes.json),
customsCode, motCode and mosCode; qty_abbr and qty_description for
qtyUnitCode; variable and description from ListofReferences.json for
clCode; for typeCode and freqCode text is the spec's wording ("C"
commodities, "A" annual). A value the package takes from the spec carries none:
"MIF" and "XIF" (flowCode), "BE" and "TM" (clCode), and
breakdownMode and aggregateBy, whose descriptions word no value. mosCode
lists ModeOfSupply.json's ids, not proven parameter values (data/v1/get
refused "Mode 1" and accepted "0" and "1"). At most 41 rows
(qtyUnitCode). Args:
param: The parameter, as upstream names it: "flowCode", "customsCode",
"motCode", "clCode", "typeCode", "freqCode",
"breakdownMode", "aggregateBy", "qtyUnitCode" or "mosCode". |
| comtrade_list_commoditiesA | List the product codes of one UN Comtrade classification, the values cmd_code takes. Fetched live from upstream's public classification file <cl_code>.json (no key, no
quota) and kept for the life of the process: meta.retrieved_at is when the file
was fetched, the first call's time on a later one. The lists are large: "HS" has
8,262 codes (about 2 MB), each HS edition 6,000 to 7,000, SITC "SS" 7,863, BEC
"B5" 178, EBOPS "EB" 423, so search narrows them. Every row has id (the
code), text and parent; the goods files add is_leaf and aggr_level (0
for TOTAL, then 2, 4 and 6 digits for HS). meta.vintage stays None: the
files carry no release identifier. Args:
cl_code: The classification, with a file upstream: "HS" (all HS editions
combined), an edition "H0" (1992) to "H6" (2022), SITC "SS"
(combined) or "S1" to "S4", BEC "B4" or "B5", EBOPS "EB"
(combined), "EB02", "EB10" or "EB10S". "BE" and "TM",
which get_data takes, have no file.
search: Keep the rows where this text occurs, ignoring case, in the code (id,
and cmd_code in SS) or the description (text, and
description_original in SS), e.g. "coffee", "crude",
"0901". HS texts start with the code ("0901 - Coffee, ..."). Omit for
every row. |
| comtrade_list_partnersA | List the partner areas UN Comtrade records trade with, for partner_code and partner2_code. Answered from upstream's partnerAreas.json as packaged with this version
(reference/partnerAreas.json), without an upstream call; meta.retrieved_at is
when the package fetched it, meta.vintage is None. 310 rows when packaged:
0 World (the total over all partners), countries in the reporters' code space
(757 Switzerland, 842 USA, 276 Germany, 156 China) and areas that only
occur as partners, such as 899 "Areas, nes" or 756 Switzerland under its ISO
code. search finds a code without reading the whole list. Args:
search: Keep the rows where this text occurs, ignoring case, in the code
(partner_code), the ISO alpha-3 code or the names (text,
partner_desc, partner_note), e.g. "world", "W00", "USA"
(840 United States of America, 841, 842 USA), "nes". Omit for every row. |
| comtrade_list_reportersA | List the reporters UN Comtrade has trade data from, with the codes reporter_code takes. Answered from upstream's Reporters.json as packaged with this version
(reference/Reporters.json), without an upstream call; meta.retrieved_at is
when the package fetched it, meta.vintage is None. 255 rows when packaged,
one per reporter code, current and historical (entry_expired_date is set on codes
no longer used, such as 280 Fed. Rep. of Germany until 1990 or 810 USSR).
Codes are UN Comtrade's, not always ISO numeric: 757 Switzerland (not 756),
842 USA, 276 Germany, 156 China; 97 European Union and 975 ASEAN
are groups (is_group). search finds a code without reading the whole list. Args:
search: Keep the rows where this text occurs, ignoring case, in the code
(reporter_code), the ISO alpha-3 code or the names (text,
reporter_desc, reporter_note), e.g. "switz", "757", "CHE"
(757 Switzerland, and 690 Seychelles by its name), "germany" (276 Germany,
278 and 280 until 1990). Omit for every row. |