# Spain Green Grants Radar (BDNS): Subvenciones verdes (`rubenpa/spain-green-grants`) Actor

Open Spanish grant calls for waste, energy, forestry, water, biodiversity, mobility and agriculture from the official BDNS/SNPSAP open-data API. 0-100 relevance score, open/closing-soon, beneficiary and region filters. Calls only, no beneficiary data. Unofficial service.

- **URL**: https://apify.com/rubenpa/spain-green-grants.md
- **Developed by:** [Ruben](https://apify.com/rubenpa) (community)
- **Categories:** Business, Lead generation, Other
- **Features:** 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 green grant call delivereds

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 Green Grants Radar (BDNS)

**Find the open Spanish grant calls that matter for the green economy (waste & circular economy, energy efficiency & renewables, forestry & wildfire prevention, water, biodiversity, sustainable mobility, sustainable agriculture, climate), already scored 0-100, filtered by who can apply, region, budget and deadline, and without personal data.**

Built exclusively on the **official open-data API of the Base de Datos Nacional de Subvenciones (BDNS)**, the Sistema Nacional de Publicidad de Subvenciones y Ayudas Públicas (SNPSAP, `infosubvenciones.es`). No HTML scraping, no login. The actor reads **grant calls (convocatorias) only**: it never reads awarded grants (concesiones) or beneficiary data.

> Unofficial service. **Not affiliated with, endorsed, sponsored or supported by the Intervención General de la Administración del Estado (IGAE), the Ministerio de Hacienda or any Spanish public body.** Data is dynamic and can be corrected or withdrawn by the issuing body: always check the official call and its regulatory bases (`officialUrl`, `basesUrl`) before applying. Not legal or financial advice.
>
> **Origen de los datos: Intervención General de la Administración del Estado.**

### Why this actor and not a generic BDNS scraper?

The Apify Store has about fifteen BDNS / Spanish-grants actors (checked 2026-11-09, 1-6 users each, typically $0.0015-0.003 per item plus a start fee). They return calls in bulk or search them by keyword. This one answers a specific question, *"which open grants in Spain are really about the green economy, and can my kind of organisation apply?"*:

| | Generic BDNS scrapers | **Spain Green Grants Radar** |
|---|---|---|
| Focus | every call, you filter | **8 green sectors** with curated Spanish phrase rules (waste, circular economy, energy efficiency, renewables, forestry, wildfire, water, irrigation, biodiversity, e-mobility, organic farming, climate...) |
| Relevance | none | **0-100 score + `matchReason`** (which phrase counted, which issuing body or official metadata agreed, which penalty applied) |
| False positives | many (waste-fee or water-bill aid for families, student "mobility", accessibility / reduced-mobility vehicles, prizes and scholarships, fire-damage compensation, animal-disease aid, sport/culture lists that mention "medio ambiente") | **actively removed** with auditable penalties |
| Status | raw flag | **`status`**: `open`, `closing_soon`, `upcoming`, `deadline_unspecified`, `closed`; `daysToDeadline`; deadline read from free text when the API has no date; calls whose window has surely elapsed are dropped |
| Who can apply | one raw code | **`beneficiaryTags`** (`companies`, `smes`, `self_employed`, `local_entities`, `ngos`, `individuals`) and a filter, plus the official type |
| Region | raw NUTS list | **region filter** by name or NUTS code; nationwide calls always kept |
| Budget, deadline | no filter | `minBudget`, `deadlineBefore`, `closingSoonDays` |
| Direct grants | mixed in | **excluded by default** (no public application window: not actionable) |
| Personal data | whatever the API returns | **calls only**; free text scrubbed (emails, phones, IBAN, DNI/NIE, `Don/Doña` names, researcher names); person-like body names withheld |
| Legal | rarely documented | **attribution, reuse basis and unofficial disclaimer in every item**; polite, sequential, rate-limited API use |

### What you get (output)

Each dataset item (English field names, source text kept as published):

| Field | Description |
|---|---|
| `bdnsCode` | BDNS call code (stable official identifier) |
| `title`, `titleCoOfficial` | Call title as published (Spanish) and the co-official-language title when different |
| `issuingBody`, `adminLevel` | Granting body and level: `state`, `regional`, `local`, `other` |
| `regions`, `nationwide` | Official regions (`ES51 - CATALUÑA`) and whether the call covers all Spain |
| `callType`, `instruments`, `purpose` | e.g. *Concurrencia competitiva*, *Subvención y entrega dineraria sin contraprestación*, official purpose |
| `totalBudgetEur` | Total budget of the call in EUR (`null` when not published) |
| `status`, `openForApplications`, `statusNote` | See above; the note explains estimates |
| `applicationStart`, `applicationDeadline`, `deadlineSource`, `daysToDeadline`, `deadlineText` | Window as published; `deadlineSource` is `official` or `text` |
| `beneficiaryTypes`, `beneficiaryTags` | Official beneficiary types and derived tags (who can apply) |
| `fundingSources`, `recoveryPlan`, `stateAidRegulation` | EU funds (FEADER, FEDER...), Recovery Plan flag, de minimis / state-aid regulation |
| `categories`, `primaryCategory`, `relevanceScore`, `matchReason` | Sector(s), 0-100 score and evidence |
| `registeredDate`, `retrievedAt` | Date registered in the BDNS and the time this item was fetched |
| `officialUrl`, `basesUrl`, `electronicOfficeUrl`, `documents` | Official BDNS page, link to the regulatory bases, electronic office, and official document download links |
| `basesDescription` | Name of the regulatory bases |
| `source`, `legalNotice` | Attribution and reuse basis; unofficial / not-affiliated disclaimer |

A run summary (calls per sector, status and level; queries and API requests used) is stored in the key-value store under `SUMMARY`. See [`examples/sample-output.json`](examples/sample-output.json) for real output.

### Quick start

**In the Apify Console:** open the actor, keep the defaults (all eight sectors, open or upcoming calls registered in the last 90 days, 100 calls) and press **Start**. A typical run takes 1-2 minutes.

**Via API (curl):**

```bash
curl -X POST "https://api.apify.com/v2/acts/rubenpa~spain-green-grants/run-sync-get-dataset-items?token=$APIFY_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"categories":["energy","waste_circular"],"beneficiaryTypes":["smes"],"regions":["Andalucía","Cataluña"],"minBudget":50000,"maxItems":50}'
```

**With the JavaScript client:**

```js
import { ApifyClient } from 'apify-client';
const client = new ApifyClient({ token: process.env.APIFY_TOKEN });
const run = await client.actor('rubenpa/spain-green-grants').call({ applicationStatus: 'closing_soon', closingSoonDays: 21, minRelevance: 60 });
const { items } = await client.dataset(run.defaultDatasetId).listItems();
```

Schedule it weekly (Apify Schedules, `daysBack: 14`) to get a fresh feed of new green grant calls.

### Input

| Field | Default | Description |
|---|---|---|
| `categories` | all 8 | `waste_circular`, `energy`, `forestry_wildfire`, `water`, `biodiversity`, `mobility`, `agriculture`, `climate_environment`. Spanish aliases accepted (`residuos`, `energia`, `forestal`, `agua`, `biodiversidad`, `movilidad`, `agricultura`, `medio_ambiente`...) |
| `applicationStatus` | `open_or_upcoming` | `open_or_upcoming`, `closing_soon` or `any` (also closed) |
| `closingSoonDays` | 15 | Calls with a deadline within N days get `closing_soon` |
| `deadlineBefore` | none | Keep calls whose deadline is on or before this date (YYYY-MM-DD) |
| `beneficiaryTypes` | all | `companies`, `smes`, `self_employed`, `local_entities`, `ngos`, `individuals` (aliases: `empresas`, `pymes`, `autonomos`, `entidades_locales`, `ong`) |
| `regions` | all Spain | Region names or NUTS codes (`Cataluña`, `ES61`...). Nationwide calls always pass |
| `minBudget` | 0 | Minimum total budget in EUR (calls without budget are dropped when set) |
| `includeUnknownBudget` | no | When `minBudget` is set, also keep calls with no published budget (flagged as `budgetUnknown`). Off by default: they are dropped and not charged (pay-per-event) |
| `minRelevance` | 40 | Minimum score (60+ for clear-cut cases only) |
| `includeDirectGrants` | false | Include *concesión directa* grants (named beneficiary, no public window) |
| `daysBack` | 90 | Window on the BDNS registration date (1-730) |
| `keywords` | none | Your own Spanish words/phrases, counted as strong title evidence (`custom` sector) |
| `excludeKeywords` | none | Drop calls whose title or bases contain these words |
| `maxItems` | 100 | Stop after N relevant calls, best first (you pay per delivered call) |
| `maxDetailRequests` | 400 | Safety cap on the per-call lookups to the official API |

### How relevance is scored

- **Text evidence** (title in Spanish and co-official language): a specific green phrase in the title (e.g. *eficiencia energética*, *incendios forestales*, *depuración*, *economía circular*, *movilidad eléctrica*) = 60 points; an ambiguous word (*agua*, *energía*, *transporte*) = 30. Phrases found only in the name of the regulatory bases = 35 / 15.
- **Context bonuses:** +15 when the issuing body is typical for the sector (a water agency, a forestry department, IDAE...), +10 when official metadata agrees (purpose, CNAE sector, EU fund such as FEADER), +10 when the title has two different strong phrases. Metadata or issuing body alone never produce a match.
- **Penalties** remove false friends: aid for household taxes and bills, student or staff "mobility", accessibility / reduced-mobility vehicles and taxis (unless also electric / zero-emission), transport of waste/materials billed as mobility, mining exploration billed as energy, cooperation abroad, compensation for fire/drought damage to businesses and farms, prizes and scholarships, multi-topic association calls, festivals/sport/tourism, animal-disease aid, swimming pools, fuel/bill payments.
- Everything is shown in `matchReason`, so you can audit every decision.

### Legal, licence and data protection

- **Source:** Base de Datos Nacional de Subvenciones (BDNS) / Sistema Nacional de Publicidad de Subvenciones y Ayudas Públicas (SNPSAP), managed by the Intervención General de la Administración del Estado (IGAE), via its official REST API (`https://www.infosubvenciones.es/bdnstrans/api/convocatorias/...`, Swagger at <https://www.infosubvenciones.es/bdnstrans/doc/swagger>).
- **Reuse conditions (SNPSAP legal notice, <https://www.infosubvenciones.es/bdnstrans/GE/es/avisolegal>):** reuse of the documents is authorised **for commercial and non-commercial purposes** (Ley 37/2007 and Real Decreto 1495/2011) provided it is not a public administrative activity, with these general conditions: do not distort the meaning of the information; cite the source (*"Origen de los datos: Intervención General de la Administración del Estado"*); mention the date of last update when the original includes it; keep the update-date and reuse-condition metadata; do not suggest that the IGAE takes part in, sponsors or supports the reuse; and, if personal data are dissociated, say so and who did it. This actor complies as follows: every item carries the attribution (`source`), the registration date (`registeredDate`) and fetch time (`retrievedAt`); titles are kept as published; the only edit is the removal of personal data (declared in `legalNotice`); and every item and this README state that the service is unofficial.
- **Personal data:** the legal notice restricts reuse of documents containing personal data. The actor therefore reads **calls only**, which describe programmes and issuing bodies. Awarded grants (concesiones) and beneficiary identities (which can be natural persons) are never requested. Free text is scrubbed for emails, phones, IBANs, DNI/NIE, names after *Don/Doña/D./Dña.* and researcher names; person-like issuing-body names are withheld. If awarded grants are ever added, natural-person beneficiaries must be output only as `{ naturalPerson: true }` (this rule is implemented and tested in `privacy.ts`).
- **No logos or emblems:** the actor icon is original; no government emblems are used. The IGAE, the Ministerio de Hacienda and the issuing bodies keep responsibility for their content (art. 9.1 RD 130/2019). Reuse is at the user's own risk; the Ley 37/2007 sanctioning regime applies to reusers.
- **API etiquette** (SNPSAP API good-practice guide): sequential requests (no concurrency), at least 0.2 s between requests (the portal allows 10 per second per IP), paged queries, back-off on HTTP 429/403/5xx, identifying `User-Agent`. The portal may restrict access in cases of abuse.
- **No guarantees:** data can be incomplete, late or wrong. The official call and its regulatory bases prevail.
- **Your responsibility:** you must comply with the SNPSAP legal notice and applicable law when you reuse the data (keep the attribution in your own products).

### Related actors (green public-money toolkit)

- [Spain Green Public Tenders Radar (PLACSP)](https://apify.com/rubenpa/placsp-green-radar) — Spanish sub-threshold green public tenders
- [EU Green Public Tenders Radar (TED)](https://apify.com/rubenpa/ted-green-radar) — EU-wide green public tenders
- [EU Green Funding Calls Radar](https://apify.com/rubenpa/eu-green-funding-calls-radar) — LIFE, Horizon Europe and other EU green funding calls
- [Spain Wildfire Risk & Active Fires (EFFIS)](https://apify.com/rubenpa/spain-fire-risk) — fire-weather index and active fires for Spain

### Pricing

Pay-per-event: **$0.003 per delivered grant call** (event `grant-item`). A default run of 100 calls costs $0.30 plus a negligible amount of Apify platform usage. You can cap spending with the standard Apify "maximum cost per run" setting; the actor stops cleanly when the limit is reached.

### Limitations

- Only calls registered in the BDNS in the chosen window (`daysBack`) are searched. Long-running calls registered earlier will not appear unless you raise `daysBack`.
- The BDNS full-text search matches the title of the call. Calls whose title says nothing about the topic (only the bases do) can be missed.
- Many local calls publish the window only as text ("20 días hábiles desde la publicación"): they get `deadline_unspecified` (or `closed` when the window has surely elapsed); check `deadlineText` and the official call.
- `beneficiaryTags` are derived from the official beneficiary type plus wording in the title and bases: the official type is always output.
- Scoring rules are heuristics; use `minRelevance`, `excludeKeywords` and `matchReason` to tune precision.
- Titles are in the issuing body's language (Spanish, sometimes co-official language); no translation is attempted so that the meaning is never altered.

***

## Radar de subvenciones verdes (BDNS)

**Encuentra las convocatorias de subvenciones españolas abiertas que importan para la economía verde (residuos y economía circular, eficiencia energética y renovables, forestal y prevención de incendios, agua, biodiversidad, movilidad sostenible, agricultura sostenible, clima), ya puntuadas de 0 a 100, filtradas por quién puede solicitarlas, región, presupuesto y plazo, y sin datos personales.**

Se basa únicamente en la **API oficial de datos abiertos de la Base de Datos Nacional de Subvenciones (BDNS)**, el Sistema Nacional de Publicidad de Subvenciones y Ayudas Públicas (SNPSAP, `infosubvenciones.es`). Sin scraping de HTML ni login. El actor lee **solo convocatorias**: nunca lee concesiones ni datos de beneficiarios.

> Servicio no oficial. **Sin vinculación, respaldo, patrocinio ni apoyo de la Intervención General de la Administración del Estado (IGAE), el Ministerio de Hacienda ni ningún organismo público.** Los datos son dinámicos y el órgano convocante puede corregirlos o retirarlos: comprueba siempre la convocatoria oficial y sus bases reguladoras (`officialUrl`, `basesUrl`) antes de solicitar. No es asesoramiento jurídico ni financiero.
>
> **Origen de los datos: Intervención General de la Administración del Estado.**

### ¿Por qué este actor y no un scraper genérico de la BDNS?

- **Enfoque verde:** 8 sectores con reglas de frases en español (residuos, economía circular, eficiencia energética, renovables, forestal, incendios, agua, regadío, biodiversidad, movilidad eléctrica, producción ecológica, clima...).
- **Puntuación 0-100 y `matchReason`:** sabes por qué entró cada convocatoria y qué penalización se aplicó.
- **Falsos positivos eliminados:** ayudas a familias para tasa de basuras o recibo del agua, "movilidad" de estudiantes, vehículos/taxis adaptados a movilidad reducida (salvo flotas eléctricas), transporte de residuos como "movilidad", exploración minera como "energía", premios y becas, compensaciones por daños de incendios o sequía, ayudas por enfermedades del ganado, convocatorias de asociaciones deportivas/culturales que citan el medio ambiente.
- **Estado del plazo:** `open`, `closing_soon`, `upcoming`, `deadline_unspecified`, `closed`, con `daysToDeadline`; si la API no trae fecha, se lee del texto del plazo; se descartan las convocatorias cuyo plazo ya ha vencido de forma segura.
- **Quién puede solicitar:** `beneficiaryTags` (`companies`, `smes`, `self_employed`, `local_entities`, `ngos`, `individuals`) y filtro, además del tipo oficial.
- **Filtros:** región (nombre o código NUTS; las convocatorias de ámbito nacional siempre pasan), presupuesto mínimo, fecha límite, "cierra pronto".
- **Concesión directa excluida por defecto:** no tiene plazo público de solicitud, así que no es accionable.
- **Privacidad (RGPD):** solo convocatorias; los textos se depuran (correos, teléfonos, IBAN, DNI/NIE, nombres tras Don/Doña, nombres de investigadores) y los nombres de órgano que parecen de persona física se ocultan.
- **Legal:** atribución, base de reutilización y aviso de servicio no oficial en cada ítem; uso respetuoso de la API (secuencial y con pausas).

### Qué obtienes (salida)

Cada ítem del dataset (campos en inglés, textos tal como se publican): `bdnsCode`, `title`, `titleCoOfficial`, `issuingBody`, `adminLevel` (`state`, `regional`, `local`, `other`), `regions`, `nationwide`, `callType`, `instruments`, `purpose`, `totalBudgetEur`, `status`, `openForApplications`, `statusNote`, `applicationStart`, `applicationDeadline`, `deadlineSource`, `daysToDeadline`, `deadlineText`, `beneficiaryTypes`, `beneficiaryTags`, `fundingSources`, `recoveryPlan`, `stateAidRegulation`, `categories`, `primaryCategory`, `relevanceScore`, `matchReason`, `registeredDate`, `retrievedAt`, `officialUrl` (ficha oficial de la BDNS), `basesUrl` (bases reguladoras), `electronicOfficeUrl`, `documents` (descargas oficiales), `basesDescription`, `source` (atribución) y `legalNotice` (aviso de servicio no oficial). El resumen de la ejecución (convocatorias por sector, estado y nivel; consultas y peticiones) queda en el almacén clave-valor, bajo `SUMMARY`. Ejemplo real en [`examples/sample-output.json`](examples/sample-output.json).

### Inicio rápido

**En la Consola de Apify:** abre el actor, deja los valores por defecto (ocho sectores, convocatorias abiertas o próximas registradas en los últimos 90 días, 100 convocatorias) y pulsa **Start**. Una ejecución típica tarda 1-2 minutos.

**Por API:**

```bash
curl -X POST "https://api.apify.com/v2/acts/rubenpa~spain-green-grants/run-sync-get-dataset-items?token=$APIFY_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"categories":["residuos","energia"],"beneficiaryTypes":["pymes"],"regions":["Andalucía","Cataluña"],"minBudget":50000,"maxItems":50}'
```

Prográmalo cada semana (Apify Schedules, `daysBack: 14`) para recibir un flujo fresco de convocatorias verdes nuevas.

### Entrada

| Campo | Por defecto | Descripción |
|---|---|---|
| `categories` | las 8 | `waste_circular`, `energy`, `forestry_wildfire`, `water`, `biodiversity`, `mobility`, `agriculture`, `climate_environment` (también alias en español: `residuos`, `energia`, `forestal`, `agua`, `biodiversidad`, `movilidad`, `agricultura`, `medio_ambiente`) |
| `applicationStatus` | `open_or_upcoming` | `open_or_upcoming`, `closing_soon` o `any` (incluye cerradas) |
| `closingSoonDays` | 15 | Las convocatorias con plazo dentro de N días reciben `closing_soon` |
| `deadlineBefore` | ninguna | Solo convocatorias con plazo hasta esa fecha (AAAA-MM-DD) |
| `beneficiaryTypes` | todos | `companies`, `smes`, `self_employed`, `local_entities`, `ngos`, `individuals` (alias: `empresas`, `pymes`, `autonomos`, `entidades_locales`, `ong`) |
| `regions` | toda España | Nombres de región o códigos NUTS (`Cataluña`, `ES61`...). Las convocatorias nacionales siempre pasan |
| `minBudget` | 0 | Presupuesto total mínimo en EUR (sin presupuesto publicado se descarta si se fija, salvo `includeUnknownBudget`) |
| `includeUnknownBudget` | no | Si hay `minBudget`, incluir (marcadas) las convocatorias sin presupuesto; por defecto se descartan y no se cobran en pago por evento |
| `minRelevance` | 40 | Puntuación mínima (60+ solo casos claros) |
| `includeDirectGrants` | false | Incluir concesiones directas (beneficiario nominativo, sin plazo público) |
| `daysBack` | 90 | Ventana sobre la fecha de registro en la BDNS (1-730) |
| `keywords` | ninguna | Tus propias palabras o frases, evidencia fuerte en el título (sector `custom`) |
| `excludeKeywords` | ninguna | Descarta convocatorias cuyo título o bases las contengan |
| `maxItems` | 100 | Para tras N convocatorias relevantes, las mejores primero (pagas por convocatoria entregada) |
| `maxDetailRequests` | 400 | Tope de seguridad de consultas de detalle a la API oficial |

### Cómo se puntúa la relevancia

- **Texto** (título en español y en lengua cooficial): una frase verde específica en el título (*eficiencia energética*, *incendios forestales*, *depuración*, *economía circular*, *movilidad eléctrica*) suma 60 puntos; una palabra ambigua (*agua*, *energía*, *transporte*) suma 30. Si solo aparece en el nombre de las bases reguladoras, 35 / 15.
- **Bonificaciones de contexto:** +15 si el órgano convocante es típico del sector (agencia del agua, departamento forestal, IDAE...), +10 si los metadatos oficiales coinciden (finalidad, sector CNAE, fondo europeo como FEADER), +10 si el título tiene dos frases fuertes distintas. Los metadatos o el órgano por sí solos nunca producen una coincidencia.
- **Penalizaciones** que eliminan falsos amigos: ayudas para impuestos y recibos de hogares, "movilidad" de estudiantes o personal, cooperación en el extranjero, compensaciones por incendios o sequía a empresas y explotaciones, premios y becas, convocatorias multitema de asociaciones, fiestas/deporte/turismo, sanidad animal, piscinas, pago de combustible o facturas.
- Todo se muestra en `matchReason`, así puedes auditar cada decisión.

### Legal, licencia y protección de datos

- **Fuente:** Base de Datos Nacional de Subvenciones (BDNS) / Sistema Nacional de Publicidad de Subvenciones y Ayudas Públicas (SNPSAP), gestionado por la Intervención General de la Administración del Estado (IGAE), mediante su API REST oficial (`https://www.infosubvenciones.es/bdnstrans/api/convocatorias/...`).
- **Condiciones de reutilización (aviso legal del SNPSAP, <https://www.infosubvenciones.es/bdnstrans/GE/es/avisolegal>):** la reutilización de los documentos está autorizada **con fines comerciales y no comerciales** (Ley 37/2007 y Real Decreto 1495/2011) siempre que no sea una actividad administrativa pública, con estas condiciones: no desnaturalizar el sentido de la información; citar la fuente (*"Origen de los datos: Intervención General de la Administración del Estado"*); mencionar la fecha de la última actualización cuando conste en el original; conservar los metadatos de fecha de actualización y condiciones de reutilización; no sugerir que la IGAE participa, patrocina o apoya la reutilización; y, si se disocian datos personales, indicarlo y quién lo hace. El actor lo cumple así: cada ítem lleva la atribución (`source`), la fecha de registro (`registeredDate`) y la hora de consulta (`retrievedAt`); los títulos se mantienen como se publican; la única edición es la eliminación de datos personales (declarada en `legalNotice`); y cada ítem y este README indican que el servicio no es oficial.
- **Datos personales:** el aviso legal limita la reutilización de documentos con datos personales. Por eso el actor lee **solo convocatorias**, que describen programas y órganos convocantes. Nunca pide concesiones ni la identidad de los beneficiarios (que pueden ser personas físicas). Los textos se depuran (correos, teléfonos, IBAN, DNI/NIE, nombres tras Don/Doña/D./Dña. y nombres de investigadores) y se ocultan los nombres de órgano que parecen de persona. Si algún día se añadieran concesiones, los beneficiarios personas físicas se devolverían solo como `{ naturalPerson: true }` (regla implementada y probada en `privacy.ts`).
- **Sin logotipos ni emblemas:** el icono del actor es original; no se usa ningún emblema oficial. La IGAE, el Ministerio de Hacienda y los órganos convocantes mantienen la responsabilidad de su contenido (art. 9.1 RD 130/2019). La reutilización es por cuenta y riesgo del usuario; el régimen sancionador de la Ley 37/2007 se aplica a los reutilizadores.
- **Buenas prácticas con la API:** peticiones secuenciales (sin concurrencia), al menos 0,2 s entre peticiones (el portal admite 10 por segundo y IP), consultas paginadas, espera ante HTTP 429/403/5xx y `User-Agent` identificativo. El portal puede restringir el acceso en caso de abuso.
- **Sin garantías:** los datos pueden ser incompletos, tardíos o erróneos. Prevalecen la convocatoria oficial y sus bases reguladoras.
- **Tu responsabilidad:** debes cumplir el aviso legal del SNPSAP y la normativa aplicable al reutilizar los datos (mantén la atribución en tus propios productos).

### Actores relacionados (kit de dinero público verde)

- [Radar de licitaciones verdes de España (PLACSP)](https://apify.com/rubenpa/placsp-green-radar)
- [Radar de licitaciones verdes de la UE (TED)](https://apify.com/rubenpa/ted-green-radar)
- [Radar de convocatorias verdes de la UE](https://apify.com/rubenpa/eu-green-funding-calls-radar)
- [Riesgo de incendios y focos activos en España (EFFIS)](https://apify.com/rubenpa/spain-fire-risk)

### Precio

Pago por evento: **0,003 $ por convocatoria entregada** (evento `grant-item`). Una ejecución por defecto de 100 convocatorias cuesta 0,30 $ más un uso de plataforma Apify despreciable. Puedes limitar el gasto con el ajuste estándar de Apify "maximum cost per run"; el actor se detiene limpiamente al alcanzarlo.

### Limitaciones

- Solo se buscan convocatorias registradas en la BDNS dentro de la ventana elegida (`daysBack`). Las de larga duración registradas antes no aparecerán salvo que aumentes `daysBack`.
- La búsqueda de texto de la BDNS actúa sobre el título de la convocatoria: las que solo mencionan el tema en las bases pueden perderse.
- Muchas convocatorias locales publican el plazo solo como texto ("20 días hábiles desde la publicación"): reciben `deadline_unspecified` (o `closed` si el plazo ha vencido de forma segura); revisa `deadlineText` y la convocatoria oficial.
- `beneficiaryTags` se deriva del tipo oficial de beneficiario y del texto del título y las bases: el tipo oficial siempre se devuelve.
- Las reglas de puntuación son heurísticas; ajusta con `minRelevance`, `excludeKeywords` y `matchReason`.
- Los títulos están en el idioma del órgano convocante; no se traduce para no alterar nunca el sentido.

# Actor input Schema

## `categories` (type: `array`):

Sectors to search. Default: all eight.

## `applicationStatus` (type: `string`):

'Open or upcoming' (default) keeps calls whose application window is open, opens soon or has no published end date. 'Closing soon' keeps only calls closing within the number of days below. 'Any' also returns closed calls.

## `closingSoonDays` (type: `integer`):

Calls whose deadline is within this many days get status 'closing_soon' (1-180).

## `deadlineBefore` (type: `string`):

Optional: keep only calls whose application deadline is on or before this date. Calls without a published deadline are dropped when this is set.

## `beneficiaryTypes` (type: `array`):

Keep calls open to at least one of these beneficiary types. Empty = all. Derived from the official beneficiary type plus wording in the call title and bases (the official type is always output).

## `regions` (type: `array`):

Region names or NUTS codes (e.g. Cataluña, Andalucía, Navarra, ES51, ES61). Nationwide calls are always kept because they are open to every region. Empty = all Spain.

## `minBudget` (type: `integer`):

Minimum total budget of the call. Calls without a published budget are dropped when this is set, unless includeUnknownBudget is true. 0 = no limit.

## `includeUnknownBudget` (type: `boolean`):

Off by default. When minBudget is set, calls without a published budget are dropped and not charged (pay-per-event). Turn this on only if you want them delivered, flagged as budgetUnknown.

## `minRelevance` (type: `integer`):

Only calls scoring at least this are delivered. 40 (default) balances precision and coverage; 60+ keeps only clear-cut cases.

## `includeDirectGrants` (type: `boolean`):

Direct grants (concesión directa) are awarded to a named beneficiary without a public application window, so they are not actionable for applicants. Off by default.

## `daysBack` (type: `integer`):

Look-back window on the date the call was registered in the BDNS (1-730).

## `keywords` (type: `array`):

Optional own words/phrases (Spanish). They are searched in the call title and count as strong evidence under the 'custom' sector, in addition to the sectors above.

## `excludeKeywords` (type: `array`):

Calls whose title or bases contain any of these words are dropped.

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

Best-scored first. Each delivered call is one billable event.

## `maxDetailRequests` (type: `integer`):

Safety cap on the sequential, rate-limited per-call lookups (about 0.3 s each) made to the official API.

## Actor input object example

```json
{
  "categories": [
    "waste_circular",
    "energy",
    "forestry_wildfire",
    "water",
    "biodiversity",
    "mobility",
    "agriculture",
    "climate_environment"
  ],
  "applicationStatus": "open_or_upcoming",
  "closingSoonDays": 15,
  "beneficiaryTypes": [],
  "regions": [],
  "minBudget": 0,
  "includeUnknownBudget": false,
  "minRelevance": 40,
  "includeDirectGrants": false,
  "daysBack": 14,
  "keywords": [],
  "excludeKeywords": [],
  "maxItems": 20,
  "maxDetailRequests": 60
}
```

# Actor output Schema

## `grants` (type: `string`):

No description

## `dataset` (type: `string`):

No description

## `summary` (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 = {
    "categories": [
        "waste_circular",
        "energy",
        "forestry_wildfire",
        "water",
        "biodiversity",
        "mobility",
        "agriculture",
        "climate_environment"
    ],
    "daysBack": 14,
    "maxItems": 20,
    "maxDetailRequests": 60
};

// Run the Actor and wait for it to finish
const run = await client.actor("rubenpa/spain-green-grants").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 = {
    "categories": [
        "waste_circular",
        "energy",
        "forestry_wildfire",
        "water",
        "biodiversity",
        "mobility",
        "agriculture",
        "climate_environment",
    ],
    "daysBack": 14,
    "maxItems": 20,
    "maxDetailRequests": 60,
}

# Run the Actor and wait for it to finish
run = client.actor("rubenpa/spain-green-grants").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 '{
  "categories": [
    "waste_circular",
    "energy",
    "forestry_wildfire",
    "water",
    "biodiversity",
    "mobility",
    "agriculture",
    "climate_environment"
  ],
  "daysBack": 14,
  "maxItems": 20,
  "maxDetailRequests": 60
}' |
apify call rubenpa/spain-green-grants --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,rubenpa/spain-green-grants"
        }
    }
}
```

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/kcIRK04FfcpTcheh9/builds/xcyA6ZQf4TbLWhxNi/openapi.json
