# US EIA Electricity Prices, Grid Load & Capacity Scraper (`groundplanes/eia-energy-grid-electricity-price-scraper`) Actor

Scrapes US Energy Information Administration (EIA) Open Data v2 for retail electricity prices, RTO grid load and fuel mix, and operating power plant capacity.

- **URL**: https://apify.com/groundplanes/eia-energy-grid-electricity-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 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

## US EIA Electricity Prices, Grid Load & Capacity Scraper

Extracts official retail electricity prices, revenues, sales, regional grid load (RTO), and power plant operating capacity from the **US Energy Information Administration (EIA) Open Data API v2 (`https://api.eia.gov/v2`)**.

***

### What It Does

The **US EIA Electricity Prices, Grid Load & Capacity Scraper** connects directly to the official EIA API v2. It provides programmatic access to benchmark US energy metrics across five core electricity routes:

1. **Retail Sales & Prices (`electricity/retail-sales/data`):** Monthly and annual retail electricity prices (¢/kWh), revenues ($M), megawatt-hour sales, and customer counts by state and sector (residential, commercial, industrial).
2. **RTO Fuel Type Generation (`electricity/rto/fuel-type-data/data`):** Hourly electricity generation by fuel type (wind, solar, natural gas, coal, nuclear, hydro) across balancing authorities (ERCOT, CAISO, PJM, NYISO, MISO, ISO-NE, SPP).
3. **RTO Region Grid Load (`electricity/rto/region-data/data`):** Hourly grid demand, net generation, and interchange.
4. **Operating Generator Capacity (`electricity/operating-generator-capacity/data`):** Nameplate and summer capacity metrics for operational power plants.
5. **State Electricity Profiles (`electricity/state-electricity-profiles/summary/data`):** Annual state-level summary profiles.

#### Key Architectural Strengths

- **Dynamic Metadata & Column Discovery:** Fetches parent route metadata at startup to dynamically discover valid frequencies, facets, and available metric columns.
- **Strict Pagination & Count Reconciliation:** Loops through pages with `offset += 5000`, reconciling delivered rows against the API's reported `total` count to guarantee no silent truncation at page boundaries.
- **Data Sentinel Integrity:** Asserts the presence of core time periods and requested metric columns on first data response, preventing hollow emissions.
- **Throttling & Backoff:** Throttles calls to 3 requests per second with jittered exponential backoff and HTTP date Retry-After handling.

***

### Target Audience

- **Energy Analysts & Traders:** Track wholesale and retail electricity price movements, spark spreads, and regional basis shifts.
- **Renewable Energy Developers:** Analyze grid capacity, hourly curtailment patterns, and generation mix by RTO.
- **Commercial & Industrial Energy Buyers:** Benchmark corporate utility tariffs, power purchasing agreements (PPAs), and state-level power costs.
- **Climate & Policy Researchers:** Ingest longitudinal federal electricity data into decarbonization and grid transition models.

***

### Source & Data Cadence

- **Source:** US Energy Information Administration (EIA) Open Data API v2 (`https://api.eia.gov/v2`).
- **Cadence:**
  - Retail sales & revenues: Monthly (typically 2-3 months lag) and Annual.
  - RTO grid load & fuel mix: Hourly (updated continuously).
  - Operating generator capacity: Monthly updates from Form EIA-860M.
- **Authentication:** Requires a personal EIA Open Data API key (free of charge). See [API Key Setup](#api-key-setup).

***

### API Key Setup

EIA requires a registered API key to access Open Data v2 endpoints:

1. Register for a free API key at <https://www.eia.gov/opendata/register.php>.
2. You will receive an alphanumeric key via email immediately.
3. Supply the key in the **`eiaApiKey`** secret input when running this actor.
4. **Security Notice:** The key is marked secret (`isSecret: true`) and is a required input with no default. It is sent only in the `X-Api-Key` header directly to `api.eia.gov`, never as a URL query parameter, and is never saved to console storage, shared, or logged.

***

### Input Parameters

| Field | Type | Default | Description |
|---|---|---|---|
| `eiaApiKey` | String (Secret) | *Required* | Your free US EIA API key. |
| `routeEndpoint` | String Enum | `"electricity/retail-sales/data"` | The target EIA route. Supported: `electricity/retail-sales/data`, `electricity/rto/fuel-type-data/data`, `electricity/rto/region-data/data`, `electricity/operating-generator-capacity/data`, `electricity/state-electricity-profiles/summary/data`. |
| `frequency` | String Enum | `"monthly"` | Reporting frequency (`monthly`, `hourly`, `local-hourly`, `annual`). Must match route capabilities. |
| `stateIds` | Array of Strings | `["TX", "CA", "NY", "FL", "VA"]` | 2-letter US state postal codes to filter (e.g. `["TX", "CA"]`). |
| `sectorIds` | Array of Strings | `["RES", "COM", "IND"]` | Sector codes: `RES` (Residential), `COM` (Commercial), `IND` (Industrial), `TRA` (Transportation), `OTH` (Other), `ALL` (All Sectors). |
| `startPeriod` | String | `"2025-01"` | Starting time period (`YYYY-MM` for monthly, `YYYY` for annual, `YYYY-MM-DDTHH` for hourly). |
| `maxItems` | Integer | `5000` | Maximum number of rows to retrieve across pages. |

#### Labeled Canary Input

```json
{
  "eiaApiKey": "YOUR_EIA_API_KEY",
  "routeEndpoint": "electricity/retail-sales/data",
  "frequency": "monthly",
  "stateIds": ["TX", "CA"],
  "sectorIds": ["RES"],
  "startPeriod": "2025-01",
  "maxItems": 100
}
```

***

### Output Dataset Schema

| Field | Type | Description |
|---|---|---|
| `period` | String | Reporting time period (e.g. `"2025-01"`, `"2024"`, or `"2025-01-01T00"`). |
| `routeSource` | String | EIA v2 route path that published the record. |
| `stateId` | String or Null | 2-letter US state code (e.g. `"TX"`). Null for RTO/balancing authority routes. |
| `stateDescription` | String or Null | Full state name (e.g. `"Texas"`). |
| `sectorId` | String or Null | Electricity consumer sector code (e.g. `"RES"`). |
| `sectorName` | String or Null | Full sector description (e.g. `"residential"`). |
| `respondentId` | String or Null | Balancing authority code (e.g. `"ERCO"`, `"CISO"`). Populated on RTO routes. |
| `respondentName` | String or Null | Full balancing authority name. |
| `fuelType` | String or Null | Generation fuel code (e.g. `"WND"`, `"SUN"`, `"NG"`). |
| `priceCentsPerKwh` | Number or Null | Retail price in cents per kilowatt-hour. |
| `revenueMillionUsd` | Number or Null | Total revenue in millions of dollars. |
| `salesMegawattHours` | Number or Null | Total retail electricity sales in MWh. |
| `customersCount` | Integer or Null | Number of customer accounts. |
| `value` | Number or Null | Numeric metric value for generic/RTO routes. |
| `valueUnits` | String or Null | Metric unit of measure (e.g. `"megawatthours"`). |
| `metrics` | Object | Every metric column the route metadata publishes for the selected route, keyed by the EIA column name (for example `capacity-mw` on the operating generator capacity route), with numeric values or null. Route-dependent metrics are carried here, so no published metric is silently dropped. |

***

### Troubleshooting & Status Messages

- **Missing or Rejected Key:** If `eiaApiKey` is omitted or invalid, the actor terminates immediately with HTTP 403 details and registration instructions.
- **Route / Frequency Mismatch:** Specifying an unsupported frequency (such as `hourly` on retail sales) fails fast before data pagination starts.
- **Zero Matches:** If a combination of filters yields no rows, the run returns `Complete: 0 rows pushed`.
- **Truncation:** When matching records exceed `maxItems`, the run concludes with `PARTIAL: ... (stopped at maxItems limit ({maxItems}); {total} total available)`.
- **Start period format:** `startPeriod` must match the selected frequency: `YYYY-MM` for monthly, `YYYY` for annual, `YYYY-MM-DDTHH` for hourly and local-hourly. A mismatched format fails fast as invalid input. Hourly RTO runs are bounded by `startPeriod` and `maxItems` only; pick a recent start hour for a small run, and expect a `PARTIAL` maxItems status on a long window.
- **Filters that do not apply:** `stateIds` and `sectorIds` apply only where the route metadata exposes the matching facet. On a route without that facet (for example the RTO routes) the filter is ignored and the run log says so.
- **Skipped rows:** Rows whose period or metric values no longer parse are skipped and counted; the run ends `PARTIAL` naming the skipped count, or fails when more than 20% of rows are affected.

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: a row with any present-but-unparseable metric value is now counted as skipped (disclosed as `PARTIAL`, or a failure above 20%) instead of shipping that value as a silent null; genuinely absent (null) values still ship null by disclosure. A data response missing the `response` object, the `data` array, or the `total` field now fails loudly as a source shape change instead of ending `Complete: 0` or inventing a total; a well-formed empty response (`total: 0`, `data: []`) still ends `Complete: 0`. Period patterns are fully anchored and period components are validated as real calendar values for both `startPeriod` and emitted rows. The pagination-ended-early reason now accounts for skipped rows, counts wording no longer claims an ordering the actor does not establish, the RTO fuel type route is described as hourly, and the input table lists all accepted sector codes (`RES`, `COM`, `IND`, `TRA`, `OTH`, `ALL`).
- **v0.1.1 (2026-11-01):**
  - Review fixes: the EIA key now travels only in the `X-Api-Key` header (never in a URL) and is a required secret input with no default; metadata and data calls use the 6-try retry standard with jittered backoff and Retry-After handling; pagination advances by a full 5,000-row page and terminates on the API reported total; period and metric value-format drift is counted as skipped rows (disclosed as `PARTIAL`, or a failure above 20%); `sectorName` is read from the source `sectorDescription` column; route-dependent metrics are preserved in a `metrics` object; state, sector, frequency, and start period inputs are validated before any data call.
- **v0.1.0 (2026-11-01):**
  - Initial release targeting EIA Open Data v2.
  - Multi-route support for retail sales, RTO grid load, fuel type generation, and generator capacity.
  - Dynamic metadata introspection for facet mapping and column selection.
  - Total count reconciliation and schema validation sentinels.

# Actor input Schema

## `eiaApiKey` (type: `string`):

Your personal US EIA Open Data API v2 key. Required. Register for free at https://www.eia.gov/opendata/register.php. Entered as a secret.

## `frequency` (type: `string`):

Reporting frequency for the selected route (monthly, annual, hourly, local-hourly).

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

Maximum number of rows to retrieve across pages (API pageSize=5000).

## `routeEndpoint` (type: `string`):

The EIA v2 electricity route to query.

## `sectorIds` (type: `array`):

Electricity consumer sector codes to filter (e.g. 'RES'=Residential, 'COM'=Commercial, 'IND'=Industrial, 'ALL'=All Sectors).

## `startPeriod` (type: `string`):

Starting time period filter in YYYY-MM (monthly), YYYY (annual), or YYYY-MM-DDTHH (hourly) format.

## `stateIds` (type: `array`):

2-letter US state postal codes to filter (e.g. \['TX', 'CA', 'NY']). Applied where supported by route.

## Actor input object example

```json
{
  "frequency": "monthly",
  "maxItems": 5000,
  "routeEndpoint": "electricity/retail-sales/data",
  "sectorIds": [
    "RES",
    "COM",
    "IND"
  ],
  "startPeriod": "2025-01",
  "stateIds": [
    "TX",
    "CA",
    "NY",
    "FL",
    "VA"
  ]
}
```

# 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 = {
    "frequency": "monthly",
    "maxItems": 5000,
    "routeEndpoint": "electricity/retail-sales/data",
    "sectorIds": [
        "RES",
        "COM",
        "IND"
    ],
    "startPeriod": "2025-01",
    "stateIds": [
        "TX",
        "CA",
        "NY",
        "FL",
        "VA"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("groundplanes/eia-energy-grid-electricity-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 = {
    "frequency": "monthly",
    "maxItems": 5000,
    "routeEndpoint": "electricity/retail-sales/data",
    "sectorIds": [
        "RES",
        "COM",
        "IND",
    ],
    "startPeriod": "2025-01",
    "stateIds": [
        "TX",
        "CA",
        "NY",
        "FL",
        "VA",
    ],
}

# Run the Actor and wait for it to finish
run = client.actor("groundplanes/eia-energy-grid-electricity-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 '{
  "frequency": "monthly",
  "maxItems": 5000,
  "routeEndpoint": "electricity/retail-sales/data",
  "sectorIds": [
    "RES",
    "COM",
    "IND"
  ],
  "startPeriod": "2025-01",
  "stateIds": [
    "TX",
    "CA",
    "NY",
    "FL",
    "VA"
  ]
}' |
apify call groundplanes/eia-energy-grid-electricity-price-scraper --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,groundplanes/eia-energy-grid-electricity-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/ldoKqIjcYXfR2Rcoy/builds/mFMADS5Co0cadh4su/openapi.json
