Quick Start¶
This guide shows how to get started with agrobr in a few minutes.
Installation¶
# Basic install
pip install agrobr
# With Polars support (recommended for large volumes)
pip install agrobr[polars]
# With Playwright (sources that require JavaScript)
pip install agrobr[browser]
playwright install chromium
agrobr requires httpx<1: httpx 1.0, still in development, changes the API (AsyncClient, HTTPStatusError and Timeout are gone), and agrobr does not import with it. An environment that already has httpx 1.0 needs a separate virtual environment for agrobr.
Via Docker (no local Python)¶
See the Docker guide for extras and advanced options.
Datasets — Semantic Layer¶
The datasets layer organizes data by subject (daily price, annual production, crop estimate, supply and demand...),
with output validated against each dataset's versioned contract and provenance in MetaInfo.
Where a dataset has more than one source, it tries the next one when a source fails.
import asyncio
from agrobr import datasets
async def main():
df = await datasets.preco_diario("soja")
df = await datasets.producao_anual("soja", ano=2023)
df = await datasets.estimativa_safra("soja", safra="2024/25")
# Provenance: source used, sources attempted and contract version
df, meta = await datasets.balanco("soja", return_meta=True)
print(meta.selected_source, meta.attempted_sources, meta.schema_version)
asyncio.run(main())
print(datasets.list_datasets())
print(datasets.describe("preco_diario"))
The sections below show each source's API, with its own parameters.
CEPEA - Price Indicators¶
CEPEA (Center for Advanced Studies in Applied Economics) publishes daily agricultural price indicators.
Async (recommended for pipelines)¶
import asyncio
from agrobr import cepea
async def main():
# Soybean indicator
df = await cepea.indicador('soja')
print(df)
# With a specific period
df = await cepea.indicador(
'soja',
inicio='2024-01-01',
fim='2024-12-31'
)
# Latest available value
ultimo = await cepea.ultimo('soja')
print(f"Soybean: R$ {ultimo.valor}/bag on {ultimo.data}")
# List of available products
produtos = await cepea.produtos()
print(produtos)
asyncio.run(main())
Sync (simple use)¶
from agrobr.sync import cepea
# Same API, no async/await
df = cepea.indicador('soja')
print(df.head())
# Latest value
ultimo = cepea.ultimo('milho')
print(f"Corn: R$ {ultimo.valor}")
Available Products¶
| Product | Description | Unit |
|---|---|---|
soja |
Soybean grain (Paranaguá) | BRL/sc60kg |
soja_parana |
Soybean (Paraná) | BRL/sc60kg |
milho |
Corn (Campinas) | BRL/sc60kg |
boi / boi_gordo |
Live cattle (São Paulo) | BRL/@ |
bezerro |
Feeder calf (Mato Grosso do Sul) | BRL/cabeca |
cafe / cafe_arabica |
Arabica coffee (São Paulo) | BRL/sc60kg |
cafe_robusta |
Robusta/Conilon coffee (Espírito Santo) | BRL/sc60kg |
algodao |
Cotton lint | cBRL/lb |
trigo |
Wheat (Paraná + RS) | BRL/ton |
arroz |
Paddy rice (ESALQ/BBM) | BRL/sc50kg |
acucar |
Crystal sugar | BRL/sc50kg |
acucar_refinado |
Refined amorphous sugar | BRL/kg |
etanol_hidratado |
Hydrous ethanol (weekly) | BRL/L |
etanol_anidro |
Anhydrous ethanol (weekly) | BRL/L |
frango_congelado |
Frozen chicken | BRL/kg |
frango_resfriado |
Chilled chicken | BRL/kg |
suino |
Live hog | BRL/kg |
leite |
Farm-gate milk | BRL/L |
laranja_industria |
Industry orange | BRL/cx40.8kg |
laranja_in_natura |
Pera orange (fresh) | BRL/cx40.8kg |
CONAB - Crop Surveys¶
CONAB (National Supply Company) publishes monthly crop survey estimates.
from agrobr import conab
async def main():
# Crop survey data
df = await conab.safras('soja', safra='2024/25')
print(df)
# By state
df = await conab.safras('soja', safra='2024/25', uf='MT')
# Supply/demand balance
df = await conab.balanco('soja')
# Brazil totals
df = await conab.brasil_total()
# List of available surveys
levs = await conab.levantamentos()
print(levs)
asyncio.run(main())
CONAB Products¶
Soybean, corn, rice, beans, cotton, wheat, sorghum, oats, rye, barley, sunflower, castor bean, peanut, sesame, canola, triticale.
CONAB - Crop Progress¶
Weekly planting and harvest progress by crop and state.
from agrobr import conab
async def main():
# Progress for all crops (latest week)
df = await conab.progresso_safra()
# Filter by product and state
df = await conab.progresso_safra(produto="soja", uf="MT")
# Harvest only
df = await conab.progresso_safra(operacao="Colheita")
# List available weeks
semanas = await conab.semanas_disponiveis()
print(semanas[0]) # {'descricao': '...', 'url': '...'}
asyncio.run(main())
Progress Crops¶
Soybean, Corn 1st, Corn 2nd, Rice, Cotton, Beans 1st and Wheat.
IBGE - PAM and LSPA¶
IBGE provides data through the SIDRA API.
PAM - Municipal Agricultural Production¶
Annual agricultural production data by municipality.
from agrobr import ibge
async def main():
# PAM by state
df = await ibge.pam('soja', ano=2023, nivel='uf')
print(df)
# PAM by municipality (large volume!)
df = await ibge.pam('soja', ano=2023, nivel='municipio', uf='MT')
# Multiple years
df = await ibge.pam('soja', ano=[2020, 2021, 2022, 2023])
asyncio.run(main())
LSPA - Systematic Survey¶
Monthly crop estimates.
from agrobr import ibge
async def main():
# Monthly LSPA
df = await ibge.lspa('soja', ano=2024, mes=6)
print(df)
# Corn 1st and 2nd crop
df1 = await ibge.lspa('milho_1', ano=2024)
df2 = await ibge.lspa('milho_2', ano=2024)
# Generic aliases — automatically expand into sub-crops
df = await ibge.lspa('milho', ano=2024) # → milho_1 + milho_2
df = await ibge.lspa('feijao', ano=2024) # → feijao_1 + feijao_2 + feijao_3
df = await ibge.lspa('batata', ano=2024) # → batata_1 + batata_2 + batata_3
asyncio.run(main())
PEVS — Silviculture and Plant Extraction¶
Annual silvicultural and plant-extraction production data.
from agrobr import ibge
async def main():
# Silviculture — log wood production
df = await ibge.silvicultura('madeira_tora', ano=2023)
# Plant extraction — açaí production
df = await ibge.extracao_vegetal('acai', ano=2023)
# Eucalyptus planted area
df = await ibge.silvicultura('eucalipto', variavel='area')
asyncio.run(main())
Quarterly Milk and Agricultural GDP¶
from agrobr import ibge
async def main():
# Milk — acquisition + processing + price
df = await ibge.leite_trimestral(trimestre='202303')
# Quarterly agricultural GDP
df = await ibge.pib_agro(trimestre='202501')
asyncio.run(main())
ComexStat - Exports¶
Foreign-trade data from MDIC/SECEX by NCM, state and country.
from agrobr import comexstat
async def main():
# Monthly soybean exports
df = await comexstat.exportacao("soja", ano=2024)
# By state
df = await comexstat.exportacao("soja", ano=2024, uf="MT")
# Cotton (prefix match captures all NCM subheadings)
df = await comexstat.exportacao("algodao", ano=2024)
asyncio.run(main())
ComexStat Products¶
Soybean, corn, coffee, cotton, wheat, rice, sugar, ethanol, beef/poultry/pork, and more. See the ComexStat source docs for the full NCM table.
NASA POWER - Climate Data¶
Global climate data from NASA (an alternative to INMET, with no token). Global coverage, 0.5-degree grid, since 1981, no authentication.
from agrobr import nasa_power
async def main():
# Monthly climate for MT in 2024
df = await nasa_power.clima_uf("MT", ano=2024)
# Daily data for a single point
df = await nasa_power.clima_ponto(
lat=-12.6, lon=-56.1,
inicio="2024-01-01", fim="2024-01-31"
)
# Monthly aggregation for a point
df = await nasa_power.clima_ponto(
lat=-12.6, lon=-56.1,
inicio="2024-01-01", fim="2024-12-31",
agregacao="mensal"
)
asyncio.run(main())
INMET - Meteorology¶
Note: the station catalog and the annual historical ZIPs (
historico,historico_periodo,historico_uf) are public, with no token; the observational route (estacao,clima_uf) requiresAGROBR_INMET_TOKEN. See the source.
Climate data from 600+ automatic INMET stations.
from agrobr import inmet
async def main():
# Automatic stations in MT
df = await inmet.estacoes(tipo="T", uf="MT")
# Monthly climate aggregated by state
df = await inmet.clima_uf("MT", ano=2024)
# Hourly data for a station
df = await inmet.estacao("A001", inicio="2024-01-01", fim="2024-01-31")
asyncio.run(main())
BCB - Rural Credit¶
Rural credit data from SICOR (Rural Credit Operations System).
from agrobr import bcb
async def main():
# Working-capital credit for soybean
df = await bcb.credito_rural("soja", safra="2024/25")
# Filter by state
df = await bcb.credito_rural("soja", safra="2024/25", uf="MT")
asyncio.run(main())
ANDA - Fertilizers¶
Monthly fertilizer deliveries (national total). Requires pip install agrobr[pdf].
from agrobr import anda
async def main():
# National deliveries
df = await anda.entregas(ano=2024)
asyncio.run(main())
CONAB - Production Cost¶
Detailed costs per hectare, crop and state. The example automatically selects the last workbook in alphabetical order in the catalog and an identified MT sheet with the latest reference year. Workbooks published in different years may cover overlapping periods; the price reference year is not the crop season.
import asyncio
from agrobr import conab
async def main():
catalogo = await conab.catalogo_custos("soja")
planilha = catalogo["planilha"].max()
contextos = await conab.catalogo_custos("soja", planilha=planilha)
mt = contextos[contextos["uf"].eq("MT") & contextos["status"].eq("identified")]
aba = mt.sort_values("ano_referencia")["aba"].iloc[-1]
df = await conab.custo_producao("soja", uf="MT", planilha=planilha, aba=aba)
totais = await conab.custo_producao_total("soja", uf="MT", planilha=planilha, aba=aba)
print(df)
print(totais)
asyncio.run(main())
Using Polars¶
Functions that return a table accept as_polars=True (the _geo outputs, the catalogs and cepea.ultimo do not have the option):
import asyncio
import polars as pl
from agrobr import cepea
async def main():
# Returns polars.DataFrame instead of pandas
df = await cepea.indicador('soja', as_polars=True)
# Polars operations are much faster
resultado = (
df
.filter(pl.col('valor') > 100)
.group_by('produto')
.agg(pl.col('valor').mean())
)
asyncio.run(main())
CLI - Command Line¶
agrobr ships with a full CLI:
# CEPEA
agrobr cepea indicador soja
agrobr cepea indicador soja --inicio 2024-01-01 --formato csv > soja.csv
agrobr cepea indicador soja --ultimo
# CONAB
agrobr conab safras soja --safra 2024/25
agrobr conab balanco milho
agrobr conab levantamentos
# IBGE
agrobr ibge pam soja --ano 2023 --nivel uf
agrobr ibge lspa milho --ano 2024 --mes 6
# Health check
agrobr health # all sources
agrobr health --deep # CEPEA: fingerprint against the packaged baseline + parse
# Cache (status via doctor; clear = remove the file)
agrobr doctor
rm ~/.agrobr/cache/agrobr.duckdb
--formato json writes dates in ISO 8601 ("2026-09-22T00:00:00.000"). With --ultimo, the row has the same
columns and types as the table without it.
--formato accepts table, csv and json (any other value exits with code 2), and the output is UTF-8, also when
redirected on Windows. Every command and option is in the CLI reference.
Configuration¶
Environment Variables¶
The full list, with defaults and when each one takes effect, is in Environment variables.
# Cache
export AGROBR_CACHE_DIR=~/.agrobr/cache
export AGROBR_CACHE_DB_NAME=agrobr.duckdb
# HTTP
export AGROBR_HTTP_TIMEOUT_READ=30
export AGROBR_HTTP_MAX_RETRIES=3
# Alerts (optional)
export AGROBR_ALERT_SLACK_WEBHOOK=https://hooks.slack.com/...
export AGROBR_ALERT_DISCORD_WEBHOOK=https://discord.com/api/webhooks/...
Via Code¶
Set the variables before importing the package. offline=True reads data already present in the configured cache.
import os
os.environ["AGROBR_CACHE_DIR"] = "./my_cache"
os.environ["AGROBR_HTTP_TIMEOUT_READ"] = "60"
os.environ["AGROBR_HTTP_MAX_RETRIES"] = "5"
from agrobr.sync import cepea
df = cepea.indicador("soja", offline=True)
Error Handling¶
from agrobr import cepea
from agrobr.exceptions import (
SourceUnavailableError,
ParseError
)
async def main():
try:
df = await cepea.indicador('soja')
except SourceUnavailableError as e:
print(f"Source unavailable: {e.source}")
# Use offline cache
df = await cepea.indicador('soja', offline=True)
except ParseError as e:
print(f"Parsing error: {e.reason}")
cepea.indicador does not raise ValidationError: with validate_sanity=True, anomalies go to the anomalies column and to meta.validation_warnings.
Interactive Notebook¶
Try every source right in your browser:
Next Steps¶
- See the full examples
- Check the API Reference
- Learn about resilience and fallbacks