### Install agrobr Package Source: https://github.com/bruno-portfolio/agrobr/blob/main/examples/demo_colab.ipynb Installs the agrobr library. Use this command before running any other examples. ```python !pip install agrobr -q ``` -------------------------------- ### Clone Repository and Setup Development Environment Source: https://github.com/bruno-portfolio/agrobr/blob/main/CONTRIBUTING.md Clone the agrobr repository and set up a Python virtual environment. Install development dependencies and pre-commit hooks. ```bash git clone https://github.com/bruno-portfolio/agrobr.git cd agrobr python -m venv .venv source .venv/bin/activate # Linux/Mac # .venv\Scripts\activate # Windows pip install -e ".[dev]" pre-commit install ``` -------------------------------- ### Retrieve balance data examples Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/api/conab.md Usage examples for fetching supply and demand balance data. ```python from agrobr import conab # Balanço de soja df = await conab.balanco('soja') # Todos os produtos df = await conab.balanco() ``` -------------------------------- ### Python SDK Examples Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/contracts/censo_agropecuario.md Examples demonstrating how to use the `agrobr` Python library to access the Censo Agropecuário data. ```APIDOC ## Python SDK Usage ### Description Examples of how to fetch Censo Agropecuário data using the `agrobr` Python library. ### Code Examples **1. Get livestock effective data for all years and regions:** ```python from agrobr import ibge df = await ibge.censo_agro('efetivo_rebanho') print(df.head()) ``` **2. Get land use data for a specific state (Mato Grosso - MT):** ```python from agrobr import ibge df = await ibge.censo_agro('uso_terra', uf='MT') print(df.head()) ``` **3. Get soil preparation data (available for 2006 and 2017):** ```python from agrobr import ibge df = await ibge.censo_agro('preparo_solo') print(df.head()) ``` **4. Get irrigation data specifically for the year 2017:** ```python from agrobr import ibge df = await ibge.censo_agro('irrigacao', ano=2017) print(df.head()) ``` **5. Get temporary crop data at the municipal level for Paraná (PR):** ```python from agrobr import ibge df = await ibge.censo_agro('lavoura_temporaria', nivel='municipio', uf='PR') print(df.head()) ``` **6. Retrieve data along with metadata:** ```python from agrobr import ibge df, meta = await ibge.censo_agro('efetivo_rebanho', return_meta=True) print(df.head()) print(meta) ``` ``` -------------------------------- ### Run AgroBR Interactively Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/guides/docker.md Start an interactive Docker container with AgroBR installed. This opens a Python REPL. ```bash docker run -it --rm agrobr ``` ```python >>> from agrobr.sync import cepea >>> df = cepea.indicador('soja', inicio='2024-01-01') >>> print(df.head()) ``` -------------------------------- ### Retrieve crop data examples Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/api/conab.md Usage examples for fetching crop data with various filters. ```python from agrobr import conab # Todas as UFs df = await conab.safras('soja', safra='2024/25') # Apenas Mato Grosso df = await conab.safras('soja', safra='2024/25', uf='MT') # Levantamento específico df = await conab.safras('soja', safra='2024/25', levantamento=5) ``` -------------------------------- ### Install pdfplumber Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/api/anda.md Install the 'pdfplumber' library with PDF support to use the ANDA module. ```bash pip install agrobr[pdf] ``` -------------------------------- ### Install AgroBR Package Source: https://github.com/bruno-portfolio/agrobr/blob/main/index.html Install the agrobr package using pip. This is the first step to using the library. ```bash pip install agrobr ``` -------------------------------- ### Install BigQuery Dependencies Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/contracts/credito_rural.md Install the necessary dependencies to enable BigQuery as a fallback data source. ```bash pip install agrobr[bigquery] ``` -------------------------------- ### Python SDK Examples Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/sources/acervo_fundiario.md Examples demonstrating how to use the `agrobr` Python SDK to access Acervo Fundiário data, including filtering by state, data type, and returning metadata or using different data formats. ```APIDOC ## Python SDK Usage Examples ### Description Provides examples of how to use the `agrobr` Python library to fetch data from the Acervo Fundiário API. ### Code Examples ```python import asyncio from agrobr import acervo_fundiario async def main(): # Fetch SIGEF particular parcels for Goias df_sigef_go = await acervo_fundiario.sigef("GO") print("SIGEF parcels for GO fetched.") # Fetch SIGEF public parcels for Sao Paulo with metadata df_sigef_sp, meta_sigef_sp = await acervo_fundiario.sigef("SP", tipo="publico", return_meta=True) print(f"SIGEF public parcels for SP fetched with metadata: {len(meta_sigef_sp)} items.") # Fetch SNCI private certificates for Mato Grosso df_snci_mt = await acervo_fundiario.snci("MT", tipo="privado") print("SNCI private certificates for MT fetched.") # Fetch settlements for Goias with a bounding box bbox_go = (-50.0, -16.0, -49.0, -15.0) df_assentamentos_go = await acervo_fundiario.assentamentos("GO", bbox=bbox_go) print(f"Settlements for GO within bbox {bbox_go} fetched.") # Fetch SIGEF data and return as Polars DataFrame df_sigef_go_polars = await acervo_fundiario.sigef("GO", as_polars=True) print("SIGEF parcels for GO fetched as Polars DataFrame.") # Fetch SIGEF data with geometry using GeoPandas gdf_sigef_go_geo = await acervo_fundiario.sigef_geo("GO") print("SIGEF parcels for GO fetched as GeoDataFrame.") # Fetch settlements data with geometry using GeoPandas gdf_assentamentos_ba_geo = await acervo_fundiario.assentamentos_geo("BA") print("Settlements for BA fetched as GeoDataFrame.") if __name__ == "__main__": asyncio.run(main()) ``` ``` -------------------------------- ### List available products Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/api/cepea.md Example of retrieving the list of available products. ```python from agrobr import cepea prods = await cepea.produtos() # ['soja', 'soja_parana', 'milho', 'boi', 'cafe', 'algodao', 'trigo', # 'arroz', 'acucar', 'acucar_refinado', 'etanol_hidratado', 'etanol_anidro', # 'frango_congelado', 'frango_resfriado', 'suino', 'leite', # 'laranja_industria', 'laranja_in_natura'] # Aliases: boi_gordo → boi, cafe_arabica → cafe ``` -------------------------------- ### Asynchronous Data Fetching Example Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/sources/ana.md An example demonstrating how to use asyncio to fetch multiple datasets asynchronously. This includes various layers and options like bounding boxes, state filters, and geometry. ```python import asyncio from agrobr import ana async def main(): # Hidrografia (bbox obrigatorio — dataset grande) df = await ana.hidrografia(bbox=(-50, -20, -48, -18)) # Com geometria gdf = await ana.hidrografia_geo(bbox=(-50, -20, -48, -18)) # Pivos de irrigacao df = await ana.pivos_irrigacao(uf="GO") # Pivos com geometria gdf = await ana.pivos_irrigacao_geo(uf="SP", bbox=(-50, -22, -48, -20)) # Demanda de irrigacao (bbox obrigatorio) df = await ana.demanda_irrigacao(bbox=(-50, -20, -48, -18)) # Disponibilidade hidrica df = await ana.disponibilidade_hidrica(uf="MG") gdf = await ana.disponibilidade_hidrica_geo(bbox=(-46, -20, -44, -18)) # Com metadados df, meta = await ana.pivos_irrigacao(return_meta=True) # Polars df = await ana.pivos_irrigacao(as_polars=True) # Limitar features df = await ana.hidrografia(bbox=(-50, -20, -48, -18), max_features=500) asyncio.run(main()) ``` -------------------------------- ### Install agrobr package Source: https://github.com/bruno-portfolio/agrobr/blob/main/README.md Install the core package or specific extras for additional functionality. ```bash pip install agrobr ``` ```bash pip install agrobr[pdf] # pdfplumber para ANDA, Lista Suja, Rio Verde pip install agrobr[polars] # Suporte a Polars pip install agrobr[browser] # Playwright (opcional, para fontes com JS) pip install agrobr[bigquery] # Base dos Dados (fallback BCB/SICOR) pip install agrobr[geo] # GeoPandas (geometria PRODES + DETER + SICAR + FUNAI + ICMBio + INCRA + IBAMA + Queimadas + MapBiomas Alerta + ANA + SFB + EMBRAPA Solos + Acervo Fundiário) pip install agrobr[all] # Tudo incluído ``` -------------------------------- ### Fetch Data with Metadata or Polars Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/sources/ana.md Examples demonstrating how to retrieve metadata alongside the data by setting `return_meta=True`, or how to get the data directly as a Polars DataFrame using `as_polars=True`. ```python df, meta = await ana.pivos_irrigacao(return_meta=True) ``` ```python df = await ana.pivos_irrigacao(as_polars=True) ``` -------------------------------- ### CLI Examples for Censo Agro Historico Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/api/ibge.md Command-line interface examples for accessing historical agricultural census data. ```APIDOC ### CLI ```bash # All data on establishments/area by UF agrobr ibge censo-historico estabelecimentos_area # Specific year, CSV format agrobr ibge censo-historico uso_terra --ano 1985 --formato csv # Multiple years, Brazil level agrobr ibge censo-historico efetivo_animais --ano 1970,1985,2006 --nivel brasil # Filter by UF agrobr ibge censo-historico pessoal_tratores --ano 1985 --uf SP # List available themes agrobr ibge temas-historico ``` ``` -------------------------------- ### Accessing Serie Historica Safra Data Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/contracts/serie_historica_safra.md Use these examples to fetch historical harvest data. The async examples require an async context. The sync examples use a separate import path. Metadata can be returned by setting `return_meta=True`. ```python from agrobr import datasets # Async df = await datasets.serie_historica_safra("soja") df = await datasets.serie_historica_safra("soja", inicio=2020, fim=2024, uf="MT") # Com metadados df, meta = await datasets.serie_historica_safra("soja", return_meta=True) ``` ```python from agrobr.sync import datasets df = datasets.serie_historica_safra("soja") ``` -------------------------------- ### Python Usage Examples Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/sources/ana.md Illustrative Python code snippets demonstrating how to fetch data from the ANA/SNIRH API using the `agrobr` library. Examples cover different layers, geometry retrieval, filtering by state (UF), and using optional parameters. ```APIDOC ## Example Usage ```python import asyncio from agrobr import ana async def main(): # Hidrografia (bbox obrigatorio — dataset grande) df = await ana.hidrografia(bbox=(-50, -20, -48, -18)) # Com geometria gdf = await ana.hidrografia_geo(bbox=(-50, -20, -48, -18)) # Pivos de irrigacao df = await ana.pivos_irrigacao(uf="GO") # Pivos com geometria gdf = await ana.pivos_irrigacao_geo(uf="SP", bbox=(-50, -22, -48, -20)) # Demanda de irrigacao (bbox obrigatorio) df = await ana.demanda_irrigacao(bbox=(-50, -20, -48, -18)) # Disponibilidade hidrica df = await ana.disponibilidade_hidrica(uf="MG") gdf = await ana.disponibilidade_hidrica_geo(bbox=(-46, -20, -44, -18)) # Com metadados df, meta = await ana.pivos_irrigacao(return_meta=True) # Polars df = await ana.pivos_irrigacao(as_polars=True) # Limitar features df = await ana.hidrografia(bbox=(-50, -20, -48, -18), max_features=500) asyncio.run(main()) ``` ``` -------------------------------- ### Install agrobr Package Source: https://github.com/bruno-portfolio/agrobr/blob/main/examples/agrobr_demo.ipynb Installs the agrobr package quietly. Use this at the beginning of your notebook or script. ```python !pip install -q agrobr ``` -------------------------------- ### Installing AgroBR Package Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/index.md Provides instructions for installing the AgroBR package using pip. Includes an optional installation for Playwright, which is required for data sources that rely on JavaScript rendering. ```bash pip install agrobr # Com Playwright (para fontes que requerem JavaScript) pip install agrobr[browser] playwright install chromium ``` -------------------------------- ### Install Optional Development Dependencies Source: https://github.com/bruno-portfolio/agrobr/blob/main/CONTRIBUTING.md Install optional dependencies for specific features like Polars support, PDF parsing, browser automation, geospatial data, or BigQuery integration. ```bash pip install -e ".[polars]" # Suporte a Polars pip install -e ".[pdf]" # pdfplumber (ANDA) pip install -e ".[browser]" # Playwright (fontes com JS) pip install -e ".[geo]" # GeoPandas (PRODES, DETER, SICAR) pip install -e ".[bigquery]" # Base dos Dados (fallback BCB) ``` -------------------------------- ### Usage example for safras_disponiveis Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/api/rio_verde.md Retrieves a list of available seasons. ```python from agrobr import rio_verde safras = await rio_verde.safras_disponiveis() ``` -------------------------------- ### Use synchronous defensivos module Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/api/defensivos.md Example of using the synchronous version of the API. ```python from agrobr.sync import defensivos df = defensivos.formulados(ingrediente_ativo="glifosato") ``` -------------------------------- ### Usage examples for ensaio_soja and safras_disponiveis Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/api/rio_verde.md Demonstrates fetching trial data with filters and listing available seasons. ```python from agrobr import rio_verde # Ensaio da safra 2025/2026 df = await rio_verde.ensaio_soja("2025/2026") # Filtrar por empresa df = await rio_verde.ensaio_soja("2025/2026", empresa="Brasmax") # Safras disponiveis safras = await rio_verde.safras_disponiveis() ``` -------------------------------- ### Example: Get All Deliveries for 2024 Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/api/anda.md Fetch all fertilizer delivery data for the year 2024 using the asynchronous 'entregas' function. ```python from agrobr import anda # Entregas 2024 df = await anda.entregas(2024) ``` -------------------------------- ### Instalação via Docker Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/quickstart.md Comandos para construir e executar o agrobr em um container Docker. ```bash docker build -t agrobr . docker run -it --rm agrobr ``` -------------------------------- ### Example: Get Monthly Aggregated Deliveries Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/api/anda.md Fetch monthly aggregated fertilizer delivery data for 2024 using the asynchronous 'entregas' function. ```python # Agregado mensal df = await anda.entregas(2024, agregacao="mensal") ``` -------------------------------- ### Get Cerrado Land Cover in 2020 Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/sources/mapbiomas.md Fetches land cover data for the Cerrado biome in the year 2020. Requires the 'agrobr' library to be installed. ```python import agrobr # Cobertura do Cerrado em 2020 df = await agrobr.mapbiomas.cobertura(bioma="Cerrado", ano=2020) ``` -------------------------------- ### Fetch Silvicultura Area Data via IBGE Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/contracts/silvicultura.md Retrieve silviculture area data directly from IBGE. This example shows how to get the planted area for eucalyptus. ```python from agrobr import ibge df = await ibge.silvicultura("eucalipto", variavel="area") ``` -------------------------------- ### Fetch Silvicultura Data with Metadata Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/contracts/silvicultura.md This example demonstrates how to fetch silviculture production data along with associated metadata by setting `return_meta=True`. ```python # Com metadados df, meta = await datasets.silvicultura("madeira_tora", ano=2023, return_meta=True) ``` -------------------------------- ### Get Fertilizer Deliveries by UF/Month (agrobr.anda) Source: https://github.com/bruno-portfolio/agrobr/blob/main/CHANGELOG.md Fetch fertilizer delivery data by UF and month using `anda.entregas()`. Requires `pip install agrobr[pdf]` for PDF parsing. ```python anda.entregas() ``` -------------------------------- ### Get Pedological Map (Geospatial) Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/api/embrapa_solos.md Retrieves the pedological map of Brazil with geometry as a GeoDataFrame. Requires 'agrobr[geo]' to be installed. Supports filtering by 'ordem' or 'bbox'. Metadata can be returned if 'return_meta' is True. ```python async def mapa_solos_geo( *, ordem: str | None = None, bbox: tuple[float, float, float, float] | None = None, return_meta: bool = False, ) -> gpd.GeoDataFrame | tuple[gpd.GeoDataFrame, MetaInfo] ``` ```python from agrobr import embrapa_solos # Poligonos de solo em bbox gdf = await embrapa_solos.mapa_solos_geo(bbox=(-56, -16, -54, -14)) ``` -------------------------------- ### CLI Usage Examples Source: https://context7.com/bruno-portfolio/agrobr/llms.txt Commands for fetching data from CEPEA, CONAB, and IBGE, as well as system diagnostics and snapshot management. ```bash # CEPEA agrobr cepea indicador soja --ultimo agrobr cepea indicador milho --inicio 2024-01-01 --formato csv # CONAB agrobr conab safras soja --safra 2024/25 agrobr conab balanco milho # IBGE agrobr ibge pam soja --ano 2023 --nivel uf agrobr ibge lspa milho --ano 2024 --mes 6 # Health check & diagnóstico agrobr health agrobr health --source cepea --deep agrobr doctor --verbose agrobr config show # Snapshots agrobr snapshot create 2025-Q4 --sources cepea,conab,ibge agrobr snapshot list agrobr snapshot use 2025-Q4 agrobr snapshot delete 2025-Q4 ``` -------------------------------- ### Get Soil Profiles (Geospatial) Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/api/embrapa_solos.md Retrieves soil profiles with associated geometry as a GeoDataFrame. Requires 'agrobr[geo]' to be installed. Supports filtering by 'uf' or 'bbox'. Metadata can be returned if 'return_meta' is True. ```python async def perfis_geo( *, uf: str | None = None, bbox: tuple[float, float, float, float] | None = None, return_meta: bool = False, ) -> gpd.GeoDataFrame | tuple[gpd.GeoDataFrame, MetaInfo] ``` ```python from agrobr import embrapa_solos # Perfis com geometria em bbox gdf = await embrapa_solos.perfis_geo(bbox=(-56, -16, -54, -14)) ``` -------------------------------- ### Usage examples for ComexStat Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/api/comexstat.md Demonstrates how to fetch export and import data, filter by state, and request detailed records. ```python from agrobr import comexstat # Exportacao soja 2024 df = await comexstat.exportacao("soja", ano=2024) # Importacao soja 2024 df = await comexstat.importacao("soja", ano=2024) # Filtrar por UF df = await comexstat.exportacao("milho", ano=2024, uf="MT") # Detalhado (por registro) df = await comexstat.exportacao("cafe", ano=2024, agregacao="detalhado") ``` -------------------------------- ### Instalação de dependências opcionais Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/guides/dependencies.md Comandos para instalar funcionalidades extras do pacote agrobr, como suporte a PDF, navegadores ou Polars. ```bash pip install agrobr[pdf] # pdfplumber para ANDA pip install agrobr[browser] # Playwright para sites com JS pip install agrobr[polars] # Suporte a Polars DataFrames pip install agrobr[all] # Tudo ``` -------------------------------- ### Build and run with Docker Source: https://github.com/bruno-portfolio/agrobr/blob/main/README.md Commands to build the Docker image and execute the library within a container. ```bash docker build -t agrobr . docker run -it --rm agrobr ``` ```bash # CLI docker run --rm agrobr agrobr cepea indicador boi # Persistir cache entre execuções docker run -it --rm -v agrobr-cache:/home/agrobr/.agrobr agrobr # Com extras adicionais (EXTRAS substitui o default "browser,pdf") docker build --build-arg EXTRAS="browser,pdf,polars" -t agrobr:extras . # Rodar script local docker run --rm -v "$(pwd)":/work agrobr python /work/analise.py ``` -------------------------------- ### Retrieve crop conditions asynchronously Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/api/deral.md Examples of fetching crop data for all products, specific products, or including metadata. ```python from agrobr import deral # Todas as lavouras df = await deral.condicao_lavouras() # Apenas soja df = await deral.condicao_lavouras("soja") # Com metadados df, meta = await deral.condicao_lavouras("milho", return_meta=True) ``` -------------------------------- ### Instalação de dependências de desenvolvimento Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/guides/dependencies.md Comando para instalar o conjunto de ferramentas de desenvolvimento, incluindo linters e frameworks de teste. ```bash pip install agrobr[dev] ``` -------------------------------- ### Usage Examples for Apolices Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/api/mapa_psr.md Examples demonstrating how to filter rural insurance policies by culture, location, or year. ```python from agrobr.alt import mapa_psr # Todas as apolices df = await mapa_psr.apolices() # Apolices de milho no PR df = await mapa_psr.apolices(cultura="MILHO", uf="PR") # Apolices de 2023 df = await mapa_psr.apolices(ano=2023) ``` -------------------------------- ### Usage examples for vendas_diesel Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/api/anp_diesel.md Examples showing how to retrieve diesel sales volumes with optional UF filtering. ```python from agrobr.alt import anp_diesel # Volumes de diesel df = await anp_diesel.vendas_diesel() # Filtrar por UF df = await anp_diesel.vendas_diesel(uf="MT") ``` -------------------------------- ### Fetch Daily Commodity Prices (Sync) Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/contracts/preco_diario.md Synchronously fetch daily spot prices for agricultural commodities using the sync module. ```python from agrobr.sync import datasets df = datasets.preco_diario("soja") ``` -------------------------------- ### Accessing Agricultural Data Sources v0.7.0+ Source: https://github.com/bruno-portfolio/agrobr/blob/main/README.md Demonstrates fetching climate, credit, trade, and production data from various sources. ```python from agrobr import nasa_power, bcb, comexstat, anda async def main(): # NASA POWER — climatologia por ponto ou UF (v0.7.1) df = await nasa_power.clima_ponto(-12.6, -56.1, "2024-01-01", "2024-12-31") df = await nasa_power.clima_uf("MT", ano=2024) # BCB/SICOR — crédito rural df = await bcb.credito_rural(produto="soja", safra="2024/25") # BCB/SICOR — filtrar por programa df = await bcb.credito_rural(produto="soja", safra="2024/25", programa="Pronamp") # BCB/SICOR — agregar por programa df = await bcb.credito_rural(produto="soja", safra="2024/25", agregacao="programa") # ComexStat — exportações e importações mensais df = await comexstat.exportacao("soja", ano=2024, agregacao="mensal") df = await comexstat.importacao("soja", ano=2024, agregacao="mensal") # ANDA — entregas de fertilizantes (requer pip install agrobr[pdf]) df = await anda.entregas(ano=2024, uf="MT") # CONAB — custos de produção from agrobr import conab df = await conab.custo_producao(cultura="soja", uf="MT", safra="2024/25") ``` -------------------------------- ### Verificar estado determinístico Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/advanced/reproducibility.md Consulta se o modo determinístico está ativo e qual o snapshot configurado. ```python from agrobr.datasets import is_deterministic, get_snapshot async with datasets.deterministic("2025-12-31"): print(is_deterministic()) # True print(get_snapshot()) # "2025-12-31" print(is_deterministic()) # False print(get_snapshot()) # None ``` -------------------------------- ### Consultar Exportações Agrícolas (Async) Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/contracts/exportacao.md Utilize esta função para obter dados de exportação de forma assíncrona. É possível filtrar por produto e UF, e opcionalmente retornar metadados. ```python from agrobr import datasets # Async df = await datasets.exportacao("soja", ano=2024) df = await datasets.exportacao("soja", ano=2024, uf="MT") # Com metadados df, meta = await datasets.exportacao("soja", ano=2024, return_meta=True) ``` -------------------------------- ### Specific Use Case Examples Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/api/mapbiomas.md Provides practical examples for common data analysis tasks using the MapBiomas API. ```APIDOC ## Specific Use Case Examples ### Description Practical examples for common data analysis tasks using the MapBiomas API. ### Example 1: Deforestation in Cerrado (loss of native vegetation) ```python import agrobr # Transition from Forest Formation (3) to Pasture (15) in Cerrado df = await agrobr.mapbiomas.transicao( bioma="Cerrado", classe_de_id=3, classe_para_id=15, periodo="2019-2020", ) print(f"Area converted: {df['area_ha'].sum():,.0f} ha") ``` ### Example 2: Municipal Coverage (Belem, PA) ```python import agrobr # Downloads ~660 MB on the first call — filter by biome/state/municipality to reduce size df = await agrobr.mapbiomas.cobertura( nivel="municipio", estado="PA", municipio="Belém", ano=2020 ) print(df[["municipio", "classe", "area_ha"]].head()) ``` ### Example 3: Soybean Evolution in Brazil ```python import agrobr df = await agrobr.mapbiomas.cobertura(classe_id=39) # Soybeans pivot = df.groupby("ano")["area_ha"].sum() print(pivot) ``` ``` -------------------------------- ### Usage Examples for Sinistros Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/api/mapa_psr.md Examples demonstrating how to filter rural insurance claims by culture, location, event, or time range. ```python from agrobr.alt import mapa_psr # Todos os sinistros df = await mapa_psr.sinistros() # Sinistros de soja em MT df = await mapa_psr.sinistros(cultura="SOJA", uf="MT") # Sinistros por seca em 2023 df = await mapa_psr.sinistros(evento="seca", ano=2023) # Range de anos df = await mapa_psr.sinistros(ano_inicio=2020, ano_fim=2024) ``` -------------------------------- ### Usage examples for precos_diesel Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/api/anp_diesel.md Examples showing default usage, filtering by UF and date range, and changing aggregation levels. ```python from agrobr.alt import anp_diesel # Precos de DIESEL S10 df = await anp_diesel.precos_diesel() # Filtrar por UF e periodo df = await anp_diesel.precos_diesel( uf="MT", inicio="2024-01-01", fim="2024-06-30", ) # Nivel UF com agregacao mensal df = await anp_diesel.precos_diesel(nivel="uf", agregacao="mensal") ``` -------------------------------- ### Quick Usage: CEPEA, CONAB, IBGE, NASA POWER (Async) Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/index.md Illustrates quick usage of the AgroBR library for fetching data from CEPEA (price indicators), CONAB (crop data), IBGE (PAM data), and NASA POWER (climate data) using asynchronous calls. Ensure necessary imports are included. ```python from agrobr import cepea, conab, ibge, nasa_power # CEPEA - Indicadores de preços df = await cepea.indicador('soja', inicio='2024-01-01') # CONAB - Safras df = await conab.safras('soja', safra='2024/25') # IBGE - PAM df = await ibge.pam('soja', ano=2023, nivel='uf') # NASA POWER - Clima df = await nasa_power.clima_uf('MT', ano=2025) ``` -------------------------------- ### Atualizar agrobr Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/advanced/troubleshooting.md Atualiza o pacote para a versão mais recente via pip. ```bash pip install --upgrade agrobr ``` -------------------------------- ### Fetch Daily Price Data with MetaInfo Source: https://github.com/bruno-portfolio/agrobr/blob/main/examples/agrobr_demo.ipynb Retrieves daily price data and associated metadata, including provenance information like the selected source, attempted sources, and fetch duration. Use `return_meta=True` to enable this. ```python from agrobr.sync import datasets df_preco, meta = datasets.preco_diario("soja", inicio="2025-01-01", return_meta=True) print("=== MetaInfo — Proveniencia Auditavel ===") print(f" source: {meta.source}") print(f" selected_source: {meta.selected_source}") print(f" attempted_sources: {meta.attempted_sources}") print(f" dataset: {meta.dataset}") print(f" contract_version: {meta.contract_version}") print(f" schema_version: {getattr(meta, 'schema_version', 'N/A')}") print(f" fetch_timestamp: {getattr(meta, 'fetch_timestamp', 'N/A')}") print(f" records_count: {meta.records_count}") print(f" from_cache: {meta.from_cache}") print(f" fetch_duration_ms: {meta.fetch_duration_ms}") print(f" agrobr_version: {meta.agrobr_version}") print() print("Quando fallback ocorre, attempted_sources mostra a cadeia percorrida.") print("selected_source indica qual fonte efetivamente forneceu os dados.") ``` -------------------------------- ### Retrieve geospatial property records Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/api/sicar.md Fetches individual rural property records including geometry. Requires the 'geo' extra dependency installed via 'pip install agrobr[geo]'. ```python import agrobr gdf = await agrobr.alt.sicar.imoveis_geo("DF") ``` -------------------------------- ### Verificar instalação da CLI Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/advanced/troubleshooting.md Comandos para diagnosticar ou reinstalar a CLI do agrobr. ```bash pip show agrobr ``` ```bash pip install --force-reinstall agrobr ``` ```bash python -m agrobr.cli cepea soja ``` -------------------------------- ### Habilitar logs de debug Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/advanced/troubleshooting.md Ativa logs detalhados via CLI ou configuração no código Python. ```bash # Via CLI agrobr --log-level DEBUG cepea soja # Via código import logging logging.basicConfig(level=logging.DEBUG) ``` -------------------------------- ### Access EMBRAPA Soil Data with agrobr Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/sources/embrapa_solos.md Use these asynchronous functions to fetch soil profile and pedological map data. Functions ending in `_geo` require the 'geo' extra to be installed (`pip install agrobr[geo]`). ```python import asyncio from agrobr import embrapa_solos async def main(): # Perfis de solo (tabular) df = await embrapa_solos.perfis() # Filtrar por UF df = await embrapa_solos.perfis(uf="MT") # Perfis com geometria (requer geopandas) gdf = await embrapa_solos.perfis_geo(bbox=(-56, -16, -54, -14)) # Mapa pedologico (tabular) df = await embrapa_solos.mapa_solos() # Mapa pedologico com geometria gdf = await embrapa_solos.mapa_solos_geo(bbox=(-56, -16, -54, -14)) # Com metadados df, meta = await embrapa_solos.perfis(return_meta=True) # Polars df = await embrapa_solos.perfis(as_polars=True) asyncio.run(main()) ``` -------------------------------- ### Fetch CONAB Crop Estimates Source: https://github.com/bruno-portfolio/agrobr/blob/main/examples/agrobr_demo.ipynb Retrieves CONAB crop estimates for a given commodity and harvest year. This function may require Playwright to be installed (`pip install agrobr[browser]`) if accessing data directly from web pages. ```python from agrobr.sync import conab try: df_safra = conab.safras("soja", safra="2024/25") print(f"Safra 2024/25: {len(df_safra)} UFs") display(df_safra[["uf", "area_plantada", "producao", "produtividade"]].head(10)) except Exception as e: print(f"CONAB safras indisponivel: {type(e).__name__}") print("Dica: em ambientes restritos, instale playwright (pip install agrobr[browser])") ``` -------------------------------- ### List Available Datasets and Products Source: https://github.com/bruno-portfolio/agrobr/blob/main/examples/demo_colab.ipynb Provides utility functions to list available datasets, products within a specific dataset (e.g., 'preco_diario'), and general information about a dataset. ```python print("Datasets disponíveis:", datasets.list_datasets()) print("Produtos preco_diario:", datasets.list_products("preco_diario")) print("Info:", datasets.info("preco_diario")) ``` -------------------------------- ### Build Docker Image with Custom Extras Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/guides/docker.md Build the Docker image with additional extras like 'polars'. Ensure to include default extras if needed. This example adds 'polars' to the default 'browser' and 'pdf' extras. ```bash docker build --build-arg EXTRAS="browser,pdf,polars" -t agrobr:extras . ``` -------------------------------- ### Instalar dependências do Polars Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/advanced/troubleshooting.md Instala o suporte necessário para utilizar Polars com agrobr. ```bash pip install agrobr[polars] ``` -------------------------------- ### GET /Hosted/unidades_concessoes_florestais/FeatureServer/0 Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/sources/sfb.md Retrieves data regarding forest concessions. ```APIDOC ## GET /Hosted/unidades_concessoes_florestais/FeatureServer/0 ### Description Retrieves polygon data for forest concessions. ### Method GET ### Endpoint https://mapas.florestal.gov.br/server/rest/services/Hosted/unidades_concessoes_florestais/FeatureServer/0 ### Parameters #### Query Parameters - **uf** (str) - Optional - Filter by state abbreviation - **bbox** (tuple) - Optional - Filter by bounding box coordinates ``` -------------------------------- ### GET /serie_historica Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/sources/conab.md Retrieves historical crop data series. ```APIDOC ## GET /serie_historica ### Description Retrieves historical crop data since approximately 1976. ### Parameters #### Query Parameters - **produto** (str) - Required - Name of the product - **inicio** (int) - Required - Start year - **fim** (int) - Required - End year - **uf** (str) - Optional - State abbreviation ``` -------------------------------- ### GET /estacoes Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/api/inmet.md Retrieves a list of available meteorological stations. ```APIDOC ## GET /estacoes ### Description Lists available meteorological stations based on type, state, and operational status. ### Parameters #### Query Parameters - **tipo** (str) - Optional - "T" for automatic, "M" for conventional stations. Default: "T" - **uf** (str) - Optional - Filter by state (UF). - **apenas_operantes** (bool) - Optional - If True, returns only active stations. Default: True ### Response #### Success Response (200) - **DataFrame** (pd.DataFrame) - Returns a DataFrame with columns: codigo, nome, uf, situacao, tipo, latitude, longitude, altitude, inicio_operacao ``` -------------------------------- ### Configuração de Rate Limiting por Fonte Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/advanced/resilience.md Exemplo de configuração de rate limiting para diferentes fontes de dados, onde cada fonte possui um intervalo de requisição específico e uma variável de ambiente correspondente para configuração. O sistema utiliza semáforos por fonte para permitir requisições paralelas a fontes distintas. ```bash # Timeouts (segundos) export AGROBR_HTTP_TIMEOUT_CONNECT=10 export AGROBR_HTTP_TIMEOUT_READ=30 export AGROBR_HTTP_TIMEOUT_WRITE=10 export AGROBR_HTTP_TIMEOUT_POOL=10 # Retry export AGROBR_HTTP_MAX_RETRIES=3 export AGROBR_HTTP_RETRY_BASE_DELAY=1.0 export AGROBR_HTTP_RETRY_MAX_DELAY=30.0 ``` -------------------------------- ### GET /produtos Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/api/cepea.md Lists all products available in the CEPEA module. ```APIDOC ## GET /produtos ### Description Returns a list of strings containing the names of all available products. ### Response #### Success Response (200) - **products** (list[str]) - List of product identifiers ``` -------------------------------- ### GET /b3/contratos Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/api/b3.md Retrieves a list of available agricultural contracts. ```APIDOC ## GET /b3/contratos ### Description Retrieves a list of all available agricultural contracts. ### Method GET ### Endpoint /b3/contratos ### Response #### Success Response (200) - **list[str]** - A list of contract names in alphabetical order. ### Request Example ```python import agrobr print(agrobr.b3.contratos()) ``` ### Response Example ```json [ "boi", "cafe_arabica", "cafe_conillon", "etanol", "milho", "soja_cross", "soja_fob" ] ``` ``` -------------------------------- ### GET conab.ceasa_categorias() Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/api/conab_ceasa.md Retrieves the product categories (FRUTAS, HORTALICAS). ```APIDOC ## GET conab.ceasa_categorias() ### Description Retrieves the product categories (FRUTAS, HORTALICAS). ### Response #### Success Response (200) - **dict** (dict) - Dictionary containing lists of products categorized as FRUTAS and HORTALICAS. ``` -------------------------------- ### Query formulados products Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/api/defensivos.md Examples of filtering commercial products by active ingredient or class. ```python from agrobr import defensivos # Todos os formulados com glifosato df = await defensivos.formulados(ingrediente_ativo="glifosato") # Apenas herbicidas organicos df = await defensivos.formulados(classe="herbicida", organicos="SIM") ``` -------------------------------- ### List Products in a Dataset Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/contracts/index.md Use `datasets.list_products()` to see available products within a specific dataset. This is useful for understanding the granularity of data available. ```python datasets.list_products("preco_diario") # ['soja', 'milho', 'boi', 'cafe', 'trigo', 'algodao'] ``` -------------------------------- ### GET conab.lista_ceasas() Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/api/conab_ceasa.md Lists the 43 CEASAs with their respective UF. ```APIDOC ## GET conab.lista_ceasas() ### Description Lists the 43 CEASAs with their respective UF. ### Response #### Success Response (200) - **list** (list) - List of dictionaries containing 'nome' and 'uf', ordered by name. ``` -------------------------------- ### População de cache para reprodutibilidade Source: https://github.com/bruno-portfolio/agrobr/blob/main/docs/advanced/reproducibility.md Realiza uma consulta inicial para popular o cache local antes de rodar o modo determinístico. ```python df = await datasets.preco_diario("soja") async with datasets.deterministic("2025-01-15"): df_reproduzido = await datasets.preco_diario("soja") ```