# Spain Electricity Prices – PVPC & Spot per Hour (Luz) (`flets_sv/precios-luz-espana`) Actor

Hourly electricity prices in Spain (PVPC regulated tariff and REE spot market) per day and zone, with the cheapest hours of each day.

- **URL**: https://apify.com/flets_sv/precios-luz-espana.md
- **Developed by:** [FlEtsv](https://apify.com/flets_sv) (community)
- **Categories:** Automation, Other
- **Security:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

$3.00 / 1,000 daily electricity prices

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

## Precios de la luz España – PVPC y spot hora a hora

### Use cases

- Schedule appliances, EV charging or crypto/compute jobs in the cheapest hours of the day
- Energy dashboards and home-automation (Home Assistant, n8n) fed with PVPC and spot prices
- Energy-cost reporting for businesses and comparison sites
- Price-alert bots for the Spanish electricity market

### Español

#### ¿Qué hace?

Descarga los precios de la electricidad en España hora a hora para el rango de días que indiques y la zona eléctrica que elijas. Publica dos series: el **PVPC** (la tarifa regulada de consumidores acogidos a precio voluntario para el pequeño consumidor) y el **precio spot** del mercado mayorista de REE. Por cada día devuelve la media, el mínimo y el máximo, y la lista de las horas más baratas para que puedas programar consumos.

Los datos son los que publica Red Eléctrica de España (REE) en sus servicios públicos. El Actor no almacena nada fuera de la ejecución.

#### Input

| Campo | Tipo | Por defecto | Descripción |
|---|---|---|---|
| `fechaInicio` | texto `AAAA-MM-DD` | hoy (Europe/Madrid) | Primer día a consultar. No anterior a 2014-04-01. |
| `fechaFin` | texto `AAAA-MM-DD` | mañana | Último día a consultar. REE publica hasta el día siguiente. |
| `zona` | `peninsular`, `canarias`, `baleares`, `ceuta` o `melilla` | `peninsular` | Zona eléctrica. |
| `horasBaratas` | entero 1–24 | 6 | Cuántas horas baratas listar por día. |
| `pausaMs` | entero 0–10000 | 300 | Pausa entre peticiones a REE, en milisegundos. |

Como máximo se procesan 366 días por ejecución. Si `fechaInicio` es posterior a `fechaFin`, o alguna fecha tiene otro formato, la ejecución se detiene con un error claro.

Ejemplo mínimo:

```json
{"fechaInicio":"2026-10-30","fechaFin":"2026-10-31","zona":"peninsular","horasBaratas":3}
```

#### Output

Un registro por día y zona en el dataset, con estos campos principales:

- `fecha`, `zona` y `precioReferencia` (`pvpc` o `spot`).
- `horas`: de 24 a 25 registros horarios, cada uno con `hora`, `fechaHora`, `pvpc` y `spot`.
- `horasMasBaratas`: las horas más baratas del día según `horasBaratas`.
- `precioMedio`, `precioMinimo` y `precioMaximo`, en EUR/MWh tal como los publica REE.
- `fuentes` y `extraidoEn`, para saber de dónde sale cada dato y cuándo se extrajo.

La vista «Daily prices» resume cada día en una tabla.

#### Precios (pago por evento)

Se cobra el evento `dia` a **0,003 USD por día** procesado. Un rango de 30 días cuesta 0,09 USD. Si el tope de gasto que hayas configurado se alcanza, la ejecución se detiene y guarda lo ya obtenido.

#### Pricing

You pay per event: the `dia` event costs **USD 0.003 per day** of data returned. A 30-day range costs USD 0.09. If your spending limit is reached, the run stops and keeps the results already collected.

#### Fuente y licencia

Los precios proceden de los servicios públicos de Red Eléctrica de España (REE). Consulta las condiciones de reutilización de REE antes de publicar o redistribuir los datos.

Source: Red Eléctrica de España (REE) public price services. Check REE's reuse conditions before redistributing the data.

#### Integrations (Make, Zapier, Google Sheets)

- **Make**: add the Apify module "Run an Actor" (Actor `Flets_sv/precios-luz-espana`), paste the input JSON, chain "Get Dataset Items" and map the fields to Google Sheets, Slack, Airtable or your CRM.
- **Zapier**: the Apify app offers "Run Actor" and "Fetch Dataset Items". Add a Schedule trigger and send each row to Gmail, Slack or Notion.
- **Google Sheets**: enable the official Google Sheets integration in the Actor's Integrations tab to append every run to a sheet, or call `https://api.apify.com/v2/acts/Flets_sv~precios-luz-espana/run-sync-get-dataset-items?format=csv` with POST and your input from Apps Script (`UrlFetchApp`).
- **API and webhooks**: start the Actor from the REST API, use Schedules for recurring runs and add a webhook to notify your system when a run finishes.

Input to paste into Make or Zapier:

```json
{"zona":"peninsular","horasBaratas":6,"pausaMs":300}
```

#### FAQ

**¿Por qué falta el día de mañana?** Si REE aún no ha publicado el spot del día siguiente, el Actor avisa y omite ese día en lugar de inventarlo.

**¿Qué diferencia hay entre PVPC y spot?** El PVPC es la tarifa regulada que aplican las comercializadoras a los consumidores acogidos; el spot es el precio del mercado mayorista. Los dos se publican por hora en el mismo registro.

**¿Puedo consultar un año entero?** Hay que partirlo en tramos de como máximo 366 días por ejecución.

### English

#### What does it do?

Downloads hour-by-hour electricity prices in Spain for the date range and electrical zone you choose. It publishes two series: the **PVPC** regulated tariff and the **REE spot** wholesale price. For each day it returns the average, minimum and maximum, plus the cheapest hours so you can schedule consumption.

Data comes from the public services of Red Eléctrica de España (REE). The Actor stores nothing outside the run.

#### Input

See the table in the Spanish section above: `fechaInicio`, `fechaFin`, `zona`, `horasBaratas` and `pausaMs`. Dates are `YYYY-MM-DD`, empty dates mean today and tomorrow, and a run covers at most 366 days.

#### Output

One dataset record per day and zone, with hourly `horas`, `horasMasBaratas`, daily `precioMedio`, `precioMinimo` and `precioMaximo` (EUR/MWh), sources and extraction time.

#### Pricing

You pay per event: the `dia` event costs USD 0.003 per day of data returned. A 30-day range costs USD 0.09.

#### FAQ

**Why is tomorrow's data missing?** REE publishes next-day spot prices in the afternoon. If they are not out yet, the Actor reports the day and skips it.

**Can I fetch a full year?** Split it into runs of at most 366 days.

#### Integraciones (Make, Zapier, Google Sheets)

- **Make**: añade el módulo de Apify «Run an Actor» (Actor `Flets_sv/precios-luz-espana`), pega el input JSON y encadena «Get Dataset Items»; después mapea los campos a Google Sheets, Slack, Airtable o tu CRM.
- **Zapier**: la app de Apify ofrece «Run Actor» y «Fetch Dataset Items». Ponle un disparador de horario y envía cada fila a Gmail, Slack o Notion.
- **Google Sheets**: en la pestaña Integrations del Actor activa la integración oficial con Google Sheets para añadir cada ejecución a una hoja, o llama desde Apps Script (`UrlFetchApp`) a `https://api.apify.com/v2/acts/Flets_sv~precios-luz-espana/run-sync-get-dataset-items?format=csv` con POST y tu input.
- **API y webhooks**: lanza el Actor por API REST, programa ejecuciones (Schedules) y avisa a tu sistema con un webhook al terminar.

Ejemplo de input para pegar en Make o Zapier:

```json
{"zona":"peninsular","horasBaratas":6,"pausaMs":300}
```

### Ejemplos de uso / Usage examples

#### Example output (real run, 2026-11-05)

First rows returned by a real run of this Actor on 2026-11-05 (shortened columns, values truncated):

| fecha | zona | precioMedio | precioMinimo | precioMaximo | horasMasBaratas |
|---|---|---|---|---|---|
| 2026-10-29 | peninsular | 240.04916666666668 | 107.01 | 395.97 | {"hora": 14, "fechaHora": "2026-10-29T13:00:00.000Z", "pv... |
| 2026-10-30 | peninsular | 239.04791666666662 | 140.17 | 382.47 | {"hora": 14, "fechaHora": "2026-10-30T13:00:00.000Z", "pv... |
| 2026-10-31 | peninsular | 195.2216666666667 | 21.48 | 325.94 | {"hora": 14, "fechaHora": "2026-10-31T13:00:00.000Z", "pv... |

#### Copy-paste inputs

**1. Hourly PVPC for the mainland and the 3 cheapest hours**

```json
{
  "fechaInicio": "2026-10-30",
  "fechaFin": "2026-10-31",
  "zona": "peninsular",
  "horasBaratas": 3
}
```

**2. Canary Islands, one week**

```json
{
  "fechaInicio": "2026-10-25",
  "fechaFin": "2026-10-31",
  "zona": "canarias",
  "horasBaratas": 5
}
```

#### Call it from your code (Apify API)

```bash
curl -X POST "https://api.apify.com/v2/acts/Flets_sv~precios-luz-espana/run-sync-get-dataset-items?token=YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"fechaInicio": "2026-10-30", "fechaFin": "2026-10-31", "zona": "peninsular", "horasBaratas": 3}'
```

```python
from apify_client import ApifyClient

client = ApifyClient("YOUR_API_TOKEN")
run = client.actor("Flets_sv/precios-luz-espana").call(run_input={"fechaInicio": "2026-10-30", "fechaFin": "2026-10-31", "zona": "peninsular", "horasBaratas": 3})
for item in client.dataset(run["defaultDatasetId"]).iterate_items():
    print(item)
```

No code? Use the Apify modules for **Make** and **Zapier** (run the Actor, then fetch dataset items), or the **Google Sheets** integration in the Actor's Integrations tab to append each run to a sheet.

# Actor input Schema

## `fechaInicio` (type: `string`):

First day to query, format AAAA-MM-DD. Empty means today (Europe/Madrid). Not earlier than 2014-04-01.

## `fechaFin` (type: `string`):

Last day to query, format AAAA-MM-DD. Empty means tomorrow. REE publishes up to the next day. Max 366 days per run.

## `zona` (type: `string`):

Electrical zone: peninsular, canarias, baleares, ceuta or melilla.

## `horasBaratas` (type: `integer`):

How many of the cheapest hours to list for each day.

## `pausaMs` (type: `integer`):

Delay between requests to REE.

## Actor input object example

```json
{
  "fechaInicio": "",
  "fechaFin": "",
  "zona": "peninsular",
  "horasBaratas": 6,
  "pausaMs": 300
}
```

# Actor output Schema

## `resultados` (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 = {};

// Run the Actor and wait for it to finish
const run = await client.actor("flets_sv/precios-luz-espana").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 = {}

# Run the Actor and wait for it to finish
run = client.actor("flets_sv/precios-luz-espana").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 '{}' |
apify call flets_sv/precios-luz-espana --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,flets_sv/precios-luz-espana"
        }
    }
}
```

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/QfXSmWyD5qrBdlHBE/builds/sJJTXz7bkZ9dXkhgM/openapi.json
