# USDA AMS MARS Commodity Spot Price Scraper (`groundplanes/usda-ams-mars-commodity-price-scraper`) Actor

Scrapes official USDA AMS MyMarketNews (MARS) spot prices, auction reports, and volumes for livestock, grain, cotton, and produce via the MARS REST API.

- **URL**: https://apify.com/groundplanes/usda-ams-mars-commodity-price-scraper.md
- **Developed by:** [Groundplane Labs](https://apify.com/groundplanes) (community)
- **Features:** Limited permissions
- **Stats:** 1 total users, 0 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $2.10 / 1,000 price records

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

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

## USDA AMS MARS Commodity Spot Price Scraper

Scrapes official spot prices, auction summaries, volume figures, and commodity specifications from the **USDA Agricultural Marketing Service (AMS) MyMarketNews (MARS) REST API (v1.2)** across livestock, grain, cotton, and produce markets.

***

### What It Does

The **USDA AMS MARS Commodity Spot Price Scraper** connects directly to the official USDA Agricultural Marketing Service MyMarketNews portal. It retrieves structured spot market reports, feeder cattle summaries, grain bids, terminal produce prices, and auction results without browser automation or HTML parsing.

Key capabilities:

- **Comprehensive Coverage:** Queries multiple USDA report slugs in a single run. The default set is Oklahoma National Stockyards Feeder Cattle, Oklahoma City, OK (`1280`), Daily Spot Cotton Quotations, provided by Memphis, TN (`3804`), and Lake Cumberland Livestock, Somerset, KY (`2194`). The default set contains no grain report; add a grain report slug ID to `reportSlugIds` if you need one.
- **Full Report Details:** Recursively extracts all report sections and tables (`allSections=true`) into clean tabular rows.
- **Commodity & Date Filtering:** Filter by commodity name (e.g. `Cattle`, `Corn`, `Soybeans`) and restrict historical ranges with `reportBeginDateRange`.
- **Corrections Tracking:** Supports retrieving official USDA published corrections notices via `correctionsOnly`.
- **Data Integrity Sentinels:** Enforces exact casing on whitelisted API parameters, performs startup key validation, validates report slug existence, and audits per-row schemas before emission.
- **Streamed Processing:** Report responses are parsed incrementally as they download and flattened section by section, so a multi-section response (up to 100,000 records) is never loaded into memory in full.

### Target Audience

- **Agricultural Economists & Commodity Traders:** Track live physical cash market spot prices and national basis trends.
- **Agribusiness & Feedlot Operators:** Benchmark livestock purchases, feeder cattle weight brackets, and grain procurement costs.
- **Food Processors & Supply Chain Analysts:** Monitor historical agricultural commodity pricing and seasonal price swings.
- **Academic & Public Policy Researchers:** Ingest verified, official USDA price reports into quantitative models.

***

### Source & Data Cadence

- **Source:** Official USDA Agricultural Marketing Service MyMarketNews (MARS) REST JSON API, version 1.2 (`https://marsapi.ams.usda.gov/services/v1.2`).
- **Cadence:** Updated continuously throughout trading days as auction markets report. Individual market reports publish daily, weekly, or semi-weekly depending on the commodity.
- **API Authentication:** Requires a personal MyMarketNews API key (free of charge). See the [API Key Setup](#api-key-setup) section below.

***

### API Key Setup

USDA AMS requires a registered API key to access the MyMarketNews REST endpoints:

1. Visit <https://mymarketnews.ams.usda.gov> and register for a free account.
2. Generate your personal API key in your account profile.
3. Provide your key in the **`usdaMarsApiKey`** input field when configuring this actor.
4. **Security Notice:** The key is marked as a secret field (`isSecret: true`). It is transmitted securely directly to the USDA endpoints via HTTP Basic authentication and is never stored, pooled, or logged.

***

### Input Parameters

| Field | Type | Default | Description |
|---|---|---|---|
| `usdaMarsApiKey` | String (Secret) | *Required* | Your free USDA MyMarketNews API key. |
| `reportSlugIds` | Array of Strings | `["1280", "3804", "2194"]` | List of USDA report slug IDs to retrieve. |
| `commodityFilter` | String | `""` | Optional case-insensitive keyword filter (e.g. `"Cattle"`, `"Corn"`). |
| `reportBeginDateRange` | String | `""` | Optional date range formatted as `MM/DD/YYYY:MM/DD/YYYY` (e.g. `01/01/2026:01/31/2026`). |
| `lastReportsCount` | Integer | `1` | Number of most recent report releases to fetch per slug (1 to 20). |
| `includeAllSections` | Boolean | `true` | When true, retrieves all report subsections/tables. |
| `correctionsOnly` | Boolean | `false` | When true, retrieves only published correction records. |
| `maxItems` | Integer | `1000` | Maximum number of price records to emit across all reports. |

#### Labeled Canary Input

To verify actor functionality and API connectivity, use the following canary input (slug `1280`, Oklahoma National Stockyards Feeder Cattle, Oklahoma City, OK):

```json
{
  "usdaMarsApiKey": "YOUR_MYMARKETNEWS_API_KEY",
  "reportSlugIds": ["1280"],
  "commodityFilter": "",
  "lastReportsCount": 1,
  "includeAllSections": true,
  "correctionsOnly": false,
  "maxItems": 50
}
```

***

### Output Dataset Schema

Each emitted row represents a price, weight, or volume observation from a USDA market report:

| Field | Type | Description |
|---|---|---|
| `slugId` | String | USDA AMS unique report slug identifier (e.g. `"1280"`). |
| `reportTitle` | String | Official publication title of the market report. |
| `publishedDate` | String | Publication date in `YYYY-MM-DD` format. |
| `marketType` | String or Null | USDA market category (e.g. `"Livestock"`, `"Grain"`, `"Produce"`). |
| `officeName` | String or Null | USDA reporting office or city that compiled the report. |
| `reportSection` | String | Report section or table header name (e.g. `"Feeder Steers"`). |
| `commodity` | String or Null | Commodity name (e.g. `"Feeder Cattle"`). |
| `classOrGrade` | String or Null | Class, grade, or quality specification (e.g. `"Medium and Large 1"`). |
| `frameSize` | String or Null | Livestock frame size (e.g. `"Large"`, `"Medium"`). Null for grain/produce. |
| `weightRangeLbs` | String or Null | Weight range bracket in pounds (e.g. `"500-600"`). |
| `headCount` | Integer or Null | Number of head or transaction units reported. |
| `avgWeightLbs` | Number or Null | Average weight in pounds. |
| `priceLowUsd` | Number or Null | Lowest reported price in USD per unit/cwt. |
| `priceHighUsd` | Number or Null | Highest reported price in USD per unit/cwt. |
| `weightedAvgPriceUsd` | Number or Null | Weighted average price in USD per unit/cwt. |
| `isCorrection` | Boolean | True if this record represents a published correction notice. |

*Note on Nulls:* Fields such as `frameSize`, `headCount`, and `weightRangeLbs` are specific to livestock auctions and will be null on grain or produce reports by disclosure.

***

### Troubleshooting & Status Messages

- **Invalid or Missing API Key:** If `usdaMarsApiKey` is missing or rejected with HTTP 401/403, the actor fails immediately with clear setup instructions. No data is fetched.
- **Unknown Slug IDs:** If a requested slug ID does not exist in the USDA Table of Contents, the actor flags the invalid ID in the status message and continues with any remaining valid slugs.
- **Zero Matches:** If the query returns 0 rows due to an overly restrictive `commodityFilter` or `reportBeginDateRange`, the actor exits cleanly with `Complete: 0 rows pushed`.
- **Truncation:** When the total matching records exceed `maxItems`, the run concludes with `PARTIAL: ... (stopped at maxItems limit)`.

If this keeps happening, please open an issue on this actor's Issues tab and we'll fix it fast.

***

### Changelog

- **v0.1.2 (2026-11-02):** Red Team fix round: corrected the three default slug identities in this README and the input schema (1280 is Oklahoma National Stockyards Feeder Cattle, Oklahoma City, OK; 3804 is Daily Spot Cotton Quotations, Memphis, TN; 2194 is Lake Cumberland Livestock, Somerset, KY; the default set contains no grain report). `commodityFilter` now matches the commodity field only. Commodity was added to the core-column sentinel, which now runs on the first row of every section. Unparseable non-empty price, head-count, weight, and date values (including impossible calendar dates) are now counted as value-format drift, skipped, and disclosed in the status instead of shipping as nulls under Complete. Missing report titles or sections count rows as skipped instead of substituting invented values. Report responses are now streamed and parsed incrementally section by section instead of being loaded in full. If the report listing cannot be fetched or parsed, the status now states that slug validation was skipped. Status counts now report the number of reports actually processed in truncated runs.
- **v0.1.1 (2026-11-01):** Review fixes: Retry-After HTTP-date crash fixed, all API calls (key validation, report listing, report fetch) now use the 6-try retry standard and carry authentication, rows are flattened and pushed section by section with totals reconciliation, skipped rows are disclosed as a PARTIAL reason, string and zero field values are parsed correctly, and the input schema now marks `usdaMarsApiKey` required with no default.
- **v0.1.0 (2026-11-01):**
  - Initial release targeting USDA AMS MARS API v1.2.
  - Multi-report slug ingestion with full section extraction.
  - Buyer-supplied secret key model with startup authentication verification.
  - Schema drift and parameter casing sentinels.

# Actor input Schema

## `commodityFilter` (type: `string`):

Optional case-insensitive keyword to filter commodity names (e.g. 'Cattle', 'Corn', 'Soybeans').

## `correctionsOnly` (type: `boolean`):

When True, fetches only published report corrections rather than regular reports.

## `includeAllSections` (type: `boolean`):

Whether to retrieve all report sections/tables (True) or only summary sections (False).

## `lastReportsCount` (type: `integer`):

Number of most recent report releases to fetch for each slug ID (1 to 20).

## `maxItems` (type: `integer`):

Maximum number of price records to emit into the dataset across all reports.

## `reportBeginDateRange` (type: `string`):

Optional date range filter in MM/DD/YYYY:MM/DD/YYYY format (e.g. '01/01/2026:01/31/2026').

## `reportSlugIds` (type: `array`):

List of report slug IDs to retrieve (e.g. '1280' for Oklahoma National Stockyards Feeder Cattle, Oklahoma City, OK; '3804' for Daily Spot Cotton Quotations, Memphis, TN; '2194' for Lake Cumberland Livestock, Somerset, KY).

## `usdaMarsApiKey` (type: `string`):

Your personal USDA AMS MyMarketNews API key. Required. Register for free at https://mymarketnews.ams.usda.gov to obtain a key. Entered as a secret.

## Actor input object example

```json
{
  "commodityFilter": "",
  "correctionsOnly": false,
  "includeAllSections": true,
  "lastReportsCount": 1,
  "maxItems": 1000,
  "reportBeginDateRange": "",
  "reportSlugIds": [
    "1280",
    "3804",
    "2194"
  ]
}
```

# Actor output Schema

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

No description

# 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 = {
    "commodityFilter": "",
    "correctionsOnly": false,
    "includeAllSections": true,
    "lastReportsCount": 1,
    "maxItems": 1000,
    "reportBeginDateRange": "",
    "reportSlugIds": [
        "1280",
        "3804",
        "2194"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("groundplanes/usda-ams-mars-commodity-price-scraper").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 = {
    "commodityFilter": "",
    "correctionsOnly": False,
    "includeAllSections": True,
    "lastReportsCount": 1,
    "maxItems": 1000,
    "reportBeginDateRange": "",
    "reportSlugIds": [
        "1280",
        "3804",
        "2194",
    ],
}

# Run the Actor and wait for it to finish
run = client.actor("groundplanes/usda-ams-mars-commodity-price-scraper").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 '{
  "commodityFilter": "",
  "correctionsOnly": false,
  "includeAllSections": true,
  "lastReportsCount": 1,
  "maxItems": 1000,
  "reportBeginDateRange": "",
  "reportSlugIds": [
    "1280",
    "3804",
    "2194"
  ]
}' |
apify call groundplanes/usda-ams-mars-commodity-price-scraper --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,groundplanes/usda-ams-mars-commodity-price-scraper"
        }
    }
}
```

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/pkKBIGbvV2RjSeo1k/builds/G7VYcylmjgToyfaYJ/openapi.json
