# ETL salud: EPH + prepagas (SSSalud) (`tinchoars/etl-salud`) Actor

Limpia la EPH del INDEC y la oferta de prepagas de SSSalud, valida cada fila con Pydantic, genera el perfilado (EDA) y guarda las tablas limpias como CSV en el key-value store.

- **URL**: https://apify.com/tinchoars/etl-salud.md
- **Developed by:** [Martin Fradejas Soria](https://apify.com/tinchoars) (community)
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

Pay per usage

This Actor is paid per platform usage. The Actor is free to use, and you only pay for the Apify platform usage, which gets cheaper the higher subscription plan you have.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-usage

## 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

## ETL salud (actor de Apify)

ETL que une los notebooks del proyecto (`limpieza.ipynb`, `EDA.ipynb`,
`EDA_salud.ipynb`) en un solo proceso que corre como actor de Apify:

1. **Extraer**: lee la EPH del INDEC (ZIP o los dos `.txt`) y la base de salud ya limpia
   (`base_limpia.csv`: precios de SSSalud + prestaciones por plan) desde URLs o links públicos
   de Google Drive.
2. **Transformar**: EPH: la limpieza de `limpieza.ipynb` (personas ocupadas, códigos de no
   respuesta, región por aglomerado). Salud: `base_limpia.csv` ya viene limpia; se verifican sus
   columnas, se tipan las booleanas y se acota al período. Se usan todas sus prepagas.
3. **Validar**: cada fila de salida se valida con un esquema Pydantic (la misma validación que
   usa FastAPI). Si algo no cumple, el actor falla y dice qué campo y en cuántas filas.
4. **Perfilar**: el EDA de los notebooks como estadísticas en JSON (sin gráficos).
5. **Cargar**: tablas limpias como CSV y perfilado como JSON en el key-value store, más una fila
   de resumen por tabla en el dataset.

No entrena ningún modelo: es solo el ETL de los datasets.

### Input

| campo | descripción |
|---|---|
| `eph_zip` | URL del ZIP de la EPH (con `usu_hogar` y `usu_individual`) |
| `eph_hogar`, `eph_individual` | alternativa al ZIP: URL de cada `.txt` |
| `base_salud` | `base_limpia.csv`: oferta de prepagas ya limpia, con las mismas 32 columnas que `salud_limpia.csv` |
| `procesar_eph`, `procesar_salud` | qué partes correr (default: ambas) |
| `periodo` | mes de precios AAAAMM (default `202608`) |
| `muestra_filas` | modo prueba: N personas de la EPH y N filas de precios del período (repartidas entre las prepagas); 0 o vacío = todo |

Las URLs de Google Drive se aceptan tal como se copian del navegador (`/file/d/<id>/view`);
el archivo tiene que estar compartido como "cualquier persona con el enlace".

### Prepagas incluidas

Se usan todas las prepagas que trae `base_limpia.csv`; el actor no filtra ninguna. La versión
actual trae las **10 con más cápitas** en SSSalud (202608, planes integrales):

| rnemp | prepaga |
|---|---|
| 614081 | OSDE |
| 311371 | Sancor Salud |
| 113328 | Swiss Medical |
| 412258 | Medifé |
| 211947 | Avalian |
| 116792 | Prevención Salud |
| 120177 | Nobis Medical |
| 311586 | Federada Cobertura Médica |
| 112172 | Premedic |
| 110077 | Medicina Esencial |

Galeno no está: no informó precios a SSSalud desde agosto 2026. Para sumar o sacar prepagas, se
cambia `base_limpia.csv`. La EPH no se filtra: no identifica la prepaga de cada persona, solo el
tipo de cobertura.

### Salida

| dónde | clave | contenido |
|---|---|---|
| key-value store | `eph_limpia.csv` | personas ocupadas con cobertura, ingresos y región |
| key-value store | `salud_limpia.csv` | precio por plan × región × rango etario, con prestaciones |
| key-value store | `eda_eph`, `eda_salud` | perfilado en JSON |
| dataset | vista `resumen` | filas leídas / limpias, columnas, tamaño de cada CSV |

Leer un resultado desde Python:

```python
import pandas as pd
url = "https://api.apify.com/v2/key-value-stores/<STORE_ID>/records/salud_limpia.csv"
salud = pd.read_csv(url)
```

### Estructura

```
.actor/            actor.json + esquemas de input, dataset y output
my_actor/
  main.py          orquesta: valida el input y llama a cada etapa
  etapas.py        etapa EPH y etapa salud (extraer → transformar → validar → perfilar → cargar)
  esquemas.py      esquemas Pydantic (input y filas de salida)
  validacion.py    validación de un DataFrame fila por fila
  constantes.py    mapas y listas de columnas
  extraer/         descarga y lectura de fuentes (URL, Drive, ZIP, gz, xlsx)
  transformar/     limpieza EPH y preparación de base_limpia, una función por paso
  perfilar/        estadísticas del EDA (Cramér, Spearman, razón de correlación, etc.)
  cargar/          escritura en el key-value store y el dataset de Apify
tests/             pytest sobre tablas sintéticas
```

### Correr localmente

```bash
py -3.11 -m venv .venv
.venv\Scripts\python -m pip install -r requirements.txt -r requirements-dev.txt
.venv\Scripts\python -m pytest
```

Poner el input en `storage/key_value_stores/default/INPUT.json` (acepta rutas locales) y:

```bash
.venv\Scripts\python -m my_actor
```

Los resultados quedan en `storage/`.

### Notas

- La EPH 2022 no trae `EMPLEO` ni `V5_01` (los notebooks usan la EPH 2026); si faltan, se omiten
  con un aviso y el resto del ETL sigue.
- Dependencias mínimas: `apify`, `pandas`, `pydantic`, `openpyxl` (solo para `.xlsx`). Sin scipy,
  matplotlib, seaborn ni joblib.

# Actor input Schema

## `eph_zip` (type: `string`):

URL (o link público de Google Drive) del ZIP de la EPH con usu_hogar y usu_individual. Alternativa: completar los dos campos siguientes.

## `eph_hogar` (type: `string`):

URL del usu_hogar (.txt, separado por ;). Se usa si no hay ZIP.

## `eph_individual` (type: `string`):

URL del usu_individual (.txt, separado por ;). Se usa si no hay ZIP.

## `base_salud` (type: `string`):

URL (o link público de Google Drive) de base_limpia.csv: la oferta de prepagas ya limpia (precios de SSSalud + prestaciones por plan). Se usan todas las prepagas que trae.

## `procesar_eph` (type: `boolean`):

Limpia la EPH y genera eph_limpia.csv y eda_eph.

## `procesar_salud` (type: `boolean`):

Prepara base_limpia y genera salud_limpia.csv y eda_salud.

## `periodo` (type: `integer`):

Mes de los precios de SSSalud (AAAAMM).

## `muestra_filas` (type: `integer`):

Si se completa, procesa solo N personas de la EPH y N filas de precios del período elegido (repartidas entre las prepagas). 0 o vacío = todo.

## Actor input object example

```json
{
  "procesar_eph": true,
  "procesar_salud": true,
  "periodo": 202608
}
```

# Actor output Schema

## `resumen` (type: `string`):

No description

## `eph_csv` (type: `string`):

No description

## `salud_csv` (type: `string`):

No description

## `eda_eph` (type: `string`):

No description

## `eda_salud` (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("tinchoars/etl-salud").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("tinchoars/etl-salud").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 tinchoars/etl-salud --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,tinchoars/etl-salud"
        }
    }
}
```

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/6QBvWYvxxwKujOCNC/builds/ktcHrjiqyGahlYfPf/openapi.json
