# Parque de vehículos DGT por cohorte (España) - open data (`rianone/spain-dgt-vehicle-fleet`) Actor

Parque de vehículos de la DGT (España) agregado por cohorte (provincia, marca, modelo, combustible, categoría, año) desde los microdatos anuales oficiales. Filtros por provincia, marca y combustible; CSV/Excel listos. Sin matrículas ni bastidores. No oficial: no afiliado a la DGT.

- **URL**: https://apify.com/rianone/spain-dgt-vehicle-fleet.md
- **Developed by:** [Riccardo Pongetti](https://apify.com/rianone) (community)
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $2.00 / 1,000 cohorte devueltos

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

## Spain DGT Vehicle Fleet — Parque de vehículos (datos por cohorte)

Actor de Apify que expone el **parque de vehículos de España** como datos agregados
por **cohorte** a partir de los microdatos oficiales de la **Dirección General de
Tráfico (DGT)**. Un vehículo = una fila del fichero oficial; el Actor agrupa por
`provincia x marca x modelo x combustible x categoría x año` y devuelve el recuento
de cada cohorte.

**Solo datos agregados** — nunca se emiten matrículas ni bastidores/VIN (regla AEPD;
el propio fichero oficial no contiene esas columnas). Este Actor no es oficial y no
está afiliado a la DGT. **Unofficial / no afiliado.**

### Fuente

- **Organismo**: DGT (Dirección General de Tráfico, Ministerio del Interior)
- **Dataset**: Parque de vehículos — microdatos consolidados anuales
- **URL**: `https://www.dgt.es/microdatos/Parque/2025/parque_consolidado_2025_PROVINCIA.zip`
- **Catálogo datos.gob.es**: [e00003801](https://datos.gob.es/catalogo/e00003801-parque-de-vehiculos) (anual);
  e00130502 (parque mensual; roadmap)
- **Formato**: ZIP de 52 TXT (uno por provincia, p.ej. `01.ARABA_ÁLAVA.txt`),
  pipe-delimited, encoding **cp1252**, **45 columnas**, cabecera en la primera línea.
- **Sin clave, sin login, sin cookies**. Un GET por run (el ZIP pesa ~1,6 GB, por eso
  no se cachea en el KV store).

#### Columnas reales del TXT (verificadas descargando el fichero)

```
PROVINCIA | MUNICIPIO | FABRICANTE | MARCA | MODELO | TIPO | VARIANTE | VERSION |
PROVINCIA_MATR | FECHA_MATR | FEC_PRIM_MATR | CLASE_MATR | PROCEDENCIA | NUEVO_USADO |
TIPO_TITULAR | NUM_TITULARES | SUBTIPO_DGT | TIPO_DGT | CAT_EURO | CLAS_CONSTRUCCION |
CLAS_UTILIZACION | SERVICIO | RENTING | TARA | PESO_MAX | MOM | MMTA | CILINDRADA |
POTENCIA | KW | PROPULSION | CATELECT | CONSUMO | AUTONOMIA | ALIMENTACION |
TIPO_DISTINTIVO | EMISIONES_EURO | EMISIONES_CO2 | CARROCERIA | DISTANCIA_EJES |
EJE_ANTERIOR | EJE_POSTERIOR | PLAZAS | PLAZAS_MAX | PLAZAS_PIE
```

No existe columna de matrícula ni de bastidor/VIN.

#### Combustible (campo PROPULSION)

El campo `PROPULSION` usa códigos. El mapeo se dedujo empíricamente del fichero real
(cilindrada media, distintivo ambiental y campo CATELECT) y se documenta en
`src/core.py`:

| Código | Etiqueta |
|--------|----------|
| 0 | Gasolina (incluye híbridos no enchufables de gasolina, motos y ciclomotores) |
| 1 | Diésel |
| 2 | Eléctrico (BEV) |
| 6 | GLP |
| 7 | GNC |
| (vacío) | No consta |
| resto | Otros |

La categoría del vehículo se toma del campo `TIPO_DGT` (TURISMOS, MOTOCICLETAS,
FURGONETAS, CAMIONES, AUTOBUSES, TRACTORES INDUSTRIALES, CICLOMOTORES, R Y S, OTROS…).

### Entrada

```json
{
  "province": "",            // código 01-52 o nombre ("28", "Madrid"); vacío = todas
  "marca": "",              // subcadena, sin mayúsculas/acentos ("seat")
  "combustible": "",        // etiqueta o código (Gasolina, Diésel, Eléctrico, GLP, GNC, 0, 1, 2, 6, 7)
  "categoria": "",          // subcadena de TIPO_DGT ("turismos", "moto", "camiones")
  "year": 2025,             // v1: solo 2025 (otros años → roadmap)
  "maxResults": 100,        // tope de cohortes devueltas (coste); 0 = sin límite
  "exportFiles": ["csv", "xlsx"],
  "exportLanguage": "es"
}
```

### Salida

Un item por cohorte:

```json
{
  "provincia": "28",
  "provinciaNombre": "MADRID",
  "marca": "VOLKSWAGEN",
  "modelo": "GOLF",
  "combustible": "Diésel",
  "combustibleCodigo": "1",
  "categoria": "TURISMOS",
  "anio": 2025,
  "vehiculos": 12345
}
```

La **SUMMARY** / `run-report` incluye: cohortes, vehículos totales, media por
cohorte, marcas y provincias únicas, distribución por combustible y por categoría,
top 10 marcas y top 10 provincias.

CSV (RFC-4180, coma) y XLSX (cabecera fija + autofiltro + hoja «Fuente») listos para
abrir.

### Precio y coste

Pay-per-event: **0,002 $/cohorte** devuelta + **0,01 $** por informe agregado.
`maxResults` es el guardarraíl: una pasada completa sin límite puede devolver decenas
de miles de cohortes. El ZIP se descarga entero aunque se filtre por provincia (el
fichero oficial es único).

### Notas operativas

- El primer run descarga ~1,6 GB. `fetch_source()` vuelca el ZIP a un directorio
  temporal; el contenedor de Apify es efímero, así que no hay limpieza persistente.
- Filtro por provincia = solo se descomprimen los ficheros de esa provincia.
- Las filas sin marca (remolques, tractores sin marca, «R Y S») se excluyen del
  agregado y se cuentan en `meta.rowsSinMarca`.

### Roadmap (v2+)

- Backfill anual 2017-2025 (el patrón de URL es idéntico por año).
- Delta mensual desde el catálogo e00130502 (paneldatos.dgt.es).
- Optimización de descarga (descarga parcial por provincia cuando el filtro lo permita).
- Cache del agregado por año en el KV store cuando el dataset mensual sea ligero.

### Desarrollo

```bash
uv venv .venv --python 3.13 && uv pip install --python .venv/bin/python 'apify>=2.0.0' openpyxl pytest
.venv/bin/python -m pytest tests -q                 # tests sin red (fixtures reales)
.venv/bin/python -m src.main --local examples/input.json   # run end-to-end (descarga real)
```

# Actor input Schema

## `province` (type: `string`):

Código oficial (01-52, con o sin cero) o nombre, sin distinguir mayúsculas/acentos. Ej.: '28', 'Madrid', 'Barcelona'. Vacío = todas las provincias.

## `marca` (type: `string`):

Subcadena de la marca, sin distinguir mayúsculas ni acentos. Ej.: 'seat', 'VOLKSWAGEN'. Vacío = todas las marcas.

## `combustible` (type: `string`):

Etiqueta o código: Gasolina, Diésel, Eléctrico, GLP, GNC (o códigos 0, 1, 2, 6, 7). Vacío = todos.

## `categoria` (type: `string`):

Subcadena de la categoría DGT. Ej.: 'turismos', 'moto', 'furgonetas', 'camiones'. Vacío = todas.

## `year` (type: `integer`):

Periodo del parque. V1 sirve el fichero anual 2025 (2017-2025 y delta mensual: roadmap).

## `maxResults` (type: `integer`):

Tope del run y de su coste: limita el número de cohortes (filas) devueltas. 0 = sin límite.

## `exportFiles` (type: `array`):

Generar CSV y/o XLSX listos para abrir en el value store (incluidos, sin cargo).

## `exportLanguage` (type: `string`):

Language of the exported files.

## Actor input object example

```json
{
  "province": "",
  "marca": "",
  "combustible": "",
  "categoria": "",
  "year": 2025,
  "maxResults": 100,
  "exportFiles": [
    "csv",
    "xlsx"
  ],
  "exportLanguage": "es"
}
```

# Actor output Schema

## `cohorts` (type: `string`):

Registros de cohortes en el dataset por defecto.

# 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("rianone/spain-dgt-vehicle-fleet").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("rianone/spain-dgt-vehicle-fleet").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 rianone/spain-dgt-vehicle-fleet --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,rianone/spain-dgt-vehicle-fleet"
        }
    }
}
```

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/C9zHlxfFJv9o7qNRS/builds/9yrUzwK26tNaa4E9d/openapi.json
