# Brazil Import & Export Data by NCM (ComexStat) (`jonpavei/comexstat-ncm`) Actor

Official Brazilian export and import statistics (MDIC/ComexStat) by NCM/HS code, country, state and month: USD FOB/CIF, net kg and quantity.

- **URL**: https://apify.com/jonpavei/comexstat-ncm.md
- **Developed by:** [Jon P](https://apify.com/jonpavei) (community)
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 92.3% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $5.00 / 1,000 trade rows

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Brazil Foreign Trade Data (ComexStat) — Exports & Imports by NCM/HS

Official Brazilian export and import statistics from **ComexStat (MDIC/Secex)**, delivered as a clean dataset: one row per product × partner country × month (or any grouping you choose), with **USD FOB, USD CIF, freight, insurance, net weight and statistical quantity**. Product labels in **English, Portuguese or Spanish**.

Use it to answer questions like:

- How much of HS 3004 (medicaments) did Brazil import from Germany each month since 2024, and through which ports?
- Which countries buy Brazilian coffee (NCM 0901.11.10) and how did volumes change year over year?
- Which Brazilian states export chapter 85 (electrical machinery), by transport mode?
- Monthly import prices (USD/kg) for a specific NCM, to benchmark a supplier quote.

No scraping of HTML pages: the Actor calls the public ComexStat API, respects its rate limits, splits large requests automatically and retries transient errors. Data is monthly from 1997 to the latest month published by MDIC (usually the previous month).

### Input

| Field | What it does |
| --- | --- |
| `flow` | `export`, `import` or `both` (default). Each row is tagged with its flow. |
| `ncmCodes` | NCM codes, 8 digits (`30049099` or `3004.90.99`). |
| `hsCodes` | HS chapters (2 digits), headings (4) or subheadings (6). You can mix lengths and combine with NCMs. |
| `countries` | Partner countries by name (English, Portuguese or Spanish) or ComexStat code. Empty = all. |
| `states` | Brazilian states (UF) by name or code. Empty = all. |
| `periodFrom` / `periodTo` | `YYYY-MM`. Default: the last 12 published months. |
| `monthly` | `true` = one row per month; `false` = one row per year. |
| `groupBy` | Dimensions that define a row: `ncm`, `subHeading`, `heading`, `chapter`, `section`, `country`, `economicBlock`, `state`, `via` (transport mode), `urf` (customs unit). Default `ncm` + `country`. |
| `metrics` | `metricFOB`, `metricKG`, `metricStatistic` (needs `ncm` in groupBy), `metricCIF`, `metricFreight`, `metricInsurance` (imports only). |
| `language` | `en` (default), `pt`, `es` — language of product, country and state names. |
| `maxRows` | Stop after this many rows (cost guard). Default 50,000; `0` = unlimited. |

At least one filter (`ncmCodes`, `hsCodes`, `countries` or `states`) is required: fully unfiltered queries exceed the ComexStat server limits.

#### Example

```json
{
  "flow": "import",
  "hsCodes": ["3004"],
  "countries": ["Germany", "United States", "India"],
  "periodFrom": "2024-01",
  "periodTo": "2026-10",
  "groupBy": ["ncm", "country", "state"],
  "metrics": ["metricFOB", "metricKG", "metricCIF"]
}
```

### Output

One dataset item per row, for example:

```json
{
  "flow": "import",
  "period": "2026-05",
  "year": 2026,
  "month": 5,
  "ncm": "30049069",
  "ncmDescription": "Ot.medicaments c/comp.heterocyc.heteroat.nitr.in doses",
  "hs6": "300490",
  "hs4": "3004",
  "hs2": "30",
  "country": "United States",
  "state": "Distrito Federal",
  "fobUsd": 59919715,
  "netKg": 1557,
  "cifUsd": 60247465,
  "source": "ComexStat/MDIC (Brazil)",
  "dataUpdatedAt": "2026-11-06"
}
```

Fields present depend on `groupBy` and `metrics`. Metric fields: `fobUsd`, `netKg`, `statisticalQty`, `cifUsd`, `freightUsd`, `insuranceUsd`. Dimension fields: `ncm`, `ncmDescription`, `hs6`, `hs6Description`, `hs4`, `hs4Description`, `hs2`, `hs2Description`, `section`, `country`, `economicBlock`, `state`, `transportMode`, `customsUnit`.

The run's key-value store gets an `OUTPUT` record with totals per flow, the period actually covered, the number of API calls and why the run stopped (`complete`, `maxRows`, budget or `timeout`).

Export the dataset as JSON, CSV, Excel or XML from the Apify Console or API, or call the Actor from your own code / scheduler to keep a trade dashboard fresh every month.

### Pricing

Pay per event: a small fee per run plus a fee per dataset row. Set `maxRows` or the run's maximum cost to cap spending; the Actor stops cleanly when either limit is reached and still saves everything collected so far.

### Limits and notes

- Data: MDIC/Secex ComexStat, the official Brazilian foreign trade statistics (same source as the ComexStat website). Rows carry `dataUpdatedAt` with MDIC's publication date. Attribution: MDIC/Secex — ComexStat.
- Company names (importers/exporters) are **not** part of ComexStat and are not provided.
- Municipality-level data (SH4 only) and the 1989–1996 historical series are not included in this version. Ask in the Issues tab if you need them.
- The ComexStat API accepts only a few data queries per minute. The Actor waits out the limit and paces itself automatically: in tests, 12 months of two NCMs, exports and imports (4 API queries, about 1,700 rows), took 1–2 minutes.
- Very large requests (a whole HS chapter, monthly, with state and transport mode) are split automatically into many API queries and can take tens of minutes.
- The Actor stops about 20 seconds before the run's timeout, keeps every row already collected and reports `stoppedBy: "timeout"` in `OUTPUT`. Raise the timeout in the run options for very large requests.

### Changelog

- 0.2 — stops cleanly before the run's timeout instead of timing out (keeps the rows collected); the example input in the Console now covers one closed year (2025), so a first run takes seconds.
- 0.1 — first release: general exports/imports query, name resolution for countries and states, automatic splitting, pay-per-event (Apify's default start and dataset-row events), output schema, patient handling of the API rate limit.

***

#### Em português

Estatísticas oficiais de exportação e importação do Brasil (**ComexStat/MDIC**) por NCM ou SH, país, UF, via de transporte e mês, com valor US$ FOB/CIF, frete, seguro, peso líquido e quantidade estatística. Informe os NCMs (ou capítulos/posições do SH), países e período; receba uma tabela limpa em JSON, CSV ou Excel, com descrições em português, inglês ou espanhol. Consultas grandes são divididas automaticamente; o Actor respeita o limite de requisições da API do MDIC.

# Actor input Schema

## `flow` (type: `string`):

Exports, imports, or both (both runs two queries and tags each row with its flow).

## `ncmCodes` (type: `array`):

Mercosur Common Nomenclature codes, e.g. 30049099 or 3004.90.99. Up to 200 codes. Leave empty to use HS codes instead.

## `hsCodes` (type: `array`):

Harmonized System chapters (2 digits), headings (4) or subheadings (6), e.g. 3004 or 300490. Mixed lengths are fine.

## `countries` (type: `array`):

Country names in English, Portuguese or Spanish (e.g. "United States", "Alemanha"), or ComexStat numeric codes. Leave empty for all countries.

## `states` (type: `array`):

State names (e.g. "São Paulo") or ComexStat numeric codes. Leave empty for all states.

## `periodFrom` (type: `string`):

First month included. Default: 12 months before the latest month published.

## `periodTo` (type: `string`):

Last month included. Default: latest month published by MDIC.

## `monthly` (type: `boolean`):

One row per month (true) or one row per year (false).

## `groupBy` (type: `array`):

Dimensions that define one output row. Default: NCM and partner country.

## `metrics` (type: `array`):

FOB value and net weight apply to both flows. Statistical quantity needs NCM in group-by. CIF, freight and insurance exist only for imports and are skipped for exports.

## `language` (type: `string`):

Language of product, country and state names in the output.

## `maxRows` (type: `integer`):

Stop after this many output rows (cost guard). 0 = no limit.

## Actor input object example

```json
{
  "flow": "both",
  "ncmCodes": [
    "30049099",
    "30049069"
  ],
  "periodFrom": "2025-01",
  "periodTo": "2025-12",
  "monthly": true,
  "groupBy": [
    "ncm",
    "country"
  ],
  "metrics": [
    "metricFOB",
    "metricKG"
  ],
  "language": "en",
  "maxRows": 50000
}
```

# Actor output Schema

## `results` (type: `string`):

One row per product × partner × month (or the chosen grouping), with USD FOB/CIF, net kg and statistical quantity.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "ncmCodes": [
        "30049099",
        "30049069"
    ],
    "periodFrom": "2025-01",
    "periodTo": "2025-12"
};

// Run the Actor and wait for it to finish
const run = await client.actor("jonpavei/comexstat-ncm").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "ncmCodes": [
        "30049099",
        "30049069",
    ],
    "periodFrom": "2025-01",
    "periodTo": "2025-12",
}

# Run the Actor and wait for it to finish
run = client.actor("jonpavei/comexstat-ncm").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "ncmCodes": [
    "30049099",
    "30049069"
  ],
  "periodFrom": "2025-01",
  "periodTo": "2025-12"
}' |
apify call jonpavei/comexstat-ncm --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,jonpavei/comexstat-ncm"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/gfDU7a7VgIJJ8Rsdb/builds/hPdyCseI0exyMkFfx/openapi.json
