Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file addedsrc/data/cenace/__init__.py
Empty file.
48 changes: 48 additions & 0 deletions src/data/cenace/aggregate/core.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
from __future__ import annotations

import pandas as pd

from src.data.cenace.config import PROCESSED_CSV, PROCESSED_EVENTS_HOURLY_DIR

INPUT_CSV = PROCESSED_CSV
OUTPUT_ROOT = PROCESSED_EVENTS_HOURLY_DIR


def build_hourly_partitions() -> int:
df = pd.read_csv(INPUT_CSV)

df["ds"] = pd.to_datetime(df["ds"], errors="coerce")
df["y"] = pd.to_numeric(df["y"], errors="coerce")

df = df.dropna(subset=["unique_id", "ds", "y"]).copy()
df = df.sort_values(["unique_id", "ds"]).drop_duplicates(["unique_id", "ds"])

df["year"] = df["ds"].dt.year
df["month"] = df["ds"].dt.month
df["day"] = df["ds"].dt.day

OUTPUT_ROOT.mkdir(parents=True, exist_ok=True)

n_written = 0
for (year, month, day), part in df.groupby(["year", "month", "day"], sort=True):
part_dir = (
OUTPUT_ROOT / f"year={year:04d}" / f"month={month:02d}" / f"day={day:02d}"
)
part_dir.mkdir(parents=True, exist_ok=True)

out_path = part_dir / "series.parquet"
part[["unique_id", "ds", "y"]].to_parquet(out_path, index=False)

print(f"Saved: {out_path}")
n_written += 1

return n_written


def main() -> None:
n_written = build_hourly_partitions()
print(f"\nDone. Wrote {n_written} daily partitions.")


if __name__ == "__main__":
main()
15 changes: 15 additions & 0 deletions src/data/cenace/config.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
from __future__ import annotations

from pathlib import Path

ROOT = Path(__file__).resolve().parents[3]

DATA_ROOT = ROOT / "data" / "cenace"

TMP_DIR = DATA_ROOT / "tmp"
PROCESSED_DIR = DATA_ROOT / "processed"
PROCESSED_CSV = PROCESSED_DIR / "cenace.csv"

PROCESSED_EVENTS_HOURLY_DIR = DATA_ROOT / "processed-events" / "hourly"
FORECASTS_HOURLY_DIR = DATA_ROOT / "forecasts" / "hourly"
EVALUATIONS_HOURLY_DIR = DATA_ROOT / "evaluations" / "hourly"
169 changes: 169 additions & 0 deletions src/data/cenace/extract/core.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
from __future__ import annotations

import argparse
from datetime import datetime, timedelta
from pathlib import Path
import zipfile

import requests
from bs4 import BeautifulSoup

URL = "https://www.cenace.gob.mx/Paginas/SIM/Reportes/PreEnerServConMTR.aspx"

session = requests.Session()

HEADERS = {
"User-Agent": "Mozilla/5.0",
"Referer": URL,
"Origin": "https://www.cenace.gob.mx",
"Content-Type": "application/x-www-form-urlencoded",
}

# repo root = impermanent/
ROOT_DIR = Path(__file__).resolve().parents[4]
DEFAULT_BASE_DIR = ROOT_DIR / "data" / "cenace"


def target_date_for_execution(execution_date: datetime) -> datetime:
return execution_date + timedelta(days=1)


def raw_zip_path(date: datetime, raw_dir: Path) -> Path:
return raw_dir / f"{date.strftime('%Y%m%d')}.zip"


def get_form_state() -> dict[str, str]:
r = session.get(URL, headers=HEADERS)
r.raise_for_status()
soup = BeautifulSoup(r.text, "html.parser")

def get_value(name: str) -> str:
el = soup.find("input", {"name": name})
return el.get("value") if el else ""

return {
"__VIEWSTATE": get_value("__VIEWSTATE"),
"__VIEWSTATEGENERATOR": get_value("__VIEWSTATEGENERATOR"),
"__VIEWSTATEENCRYPTED": get_value("__VIEWSTATEENCRYPTED"),
"__EVENTVALIDATION": get_value("__EVENTVALIDATION"),
}


def download_and_extract(date: datetime, raw_dir: Path, tmp_dir: Path) -> bool:
date_str = date.strftime("%d/%m/%Y")
period_str = f"{date_str} - {date_str}"

state = get_form_state()

payload = {
"ctl00$ContentPlaceHolder1$ddlReporte": "362,325",
"ctl00$ContentPlaceHolder1$ddlPeriodicidad": "D",
"ctl00$ContentPlaceHolder1$ddlSistema": "SIN",
"ctl00$ContentPlaceHolder1$txtPeriodo": period_str,
"ctl00$ContentPlaceHolder1$hdfStartDateSelected": date_str,
"ctl00$ContentPlaceHolder1$hdfEndDateSelected": date_str,
"ctl00$ContentPlaceHolder1$btnDescargarZIP": "Descargar ZIP",
"__VIEWSTATE": state["__VIEWSTATE"],
"__VIEWSTATEGENERATOR": state["__VIEWSTATEGENERATOR"],
"__VIEWSTATEENCRYPTED": state["__VIEWSTATEENCRYPTED"],
"__EVENTVALIDATION": state["__EVENTVALIDATION"],
"__EVENTTARGET": "",
"__EVENTARGUMENT": "",
}

r = session.post(URL, data=payload, headers=HEADERS)
r.raise_for_status()

size = len(r.content)
print(f"{date_str} | {size} bytes")

if size < 10000:
print(f"Skipping {date_str}: file not published or response too small")
return False

raw_dir.mkdir(parents=True, exist_ok=True)
tmp_dir.mkdir(parents=True, exist_ok=True)

zip_path = raw_zip_path(date, raw_dir)

with open(zip_path, "wb") as f:
f.write(r.content)

with zipfile.ZipFile(zip_path, "r") as z:
z.extractall(tmp_dir)

return True


def backfill_missing(start_date: datetime, end_date: datetime, base_dir: Path) -> None:
raw_dir = base_dir / "raw"
tmp_dir = base_dir / "tmp"

current = start_date
while current <= end_date:
zip_path = raw_zip_path(current, raw_dir)
if zip_path.exists():
print(f"Already have {current.strftime('%Y-%m-%d')}, skipping")
else:
try:
ok = download_and_extract(current, raw_dir, tmp_dir)
if not ok:
print(f"Stopping at {current.strftime('%Y-%m-%d')}")
break
except Exception as e:
print(f"Error on {current.strftime('%Y-%m-%d')}: {e}")
break
current += timedelta(days=1)


def run_execution_date(execution_date: datetime, base_dir: Path) -> bool:
raw_dir = base_dir / "raw"
tmp_dir = base_dir / "tmp"
target_date = target_date_for_execution(execution_date)

zip_path = raw_zip_path(target_date, raw_dir)
if zip_path.exists():
print(f"Already have {target_date.strftime('%Y-%m-%d')}, skipping")
return True

return download_and_extract(target_date, raw_dir, tmp_dir)


def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument("--execution-date", default=None)
parser.add_argument("--start-date", default=None)
parser.add_argument("--end-date", default=None)
parser.add_argument("--out", default=str(DEFAULT_BASE_DIR))
return parser.parse_args()


def main() -> None:
args = parse_args()
base_dir = Path(args.out).resolve()

if args.start_date:
start_date = datetime.strptime(args.start_date, "%Y-%m-%d")
if args.end_date:
end_date = datetime.strptime(args.end_date, "%Y-%m-%d")
elif args.execution_date:
end_date = target_date_for_execution(
datetime.strptime(args.execution_date, "%Y-%m-%d")
)
else:
end_date = datetime.today()
backfill_missing(start_date=start_date, end_date=end_date, base_dir=base_dir)
return

if args.execution_date:
execution_date = datetime.strptime(args.execution_date, "%Y-%m-%d")
ok = run_execution_date(execution_date=execution_date, base_dir=base_dir)
if not ok:
print("No new CENACE publication detected; stopping cleanly")
return

raise ValueError("Provide either --start-date or --execution-date")


if __name__ == "__main__":
main()
Empty file.
88 changes: 88 additions & 0 deletions src/data/cenace/utils/cenace_data.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import duckdb
import pandas as pd


@dataclass
class CENACEData:
base_path: Path
freq: str = "hourly"
h: int = 24
max_window_size: int = 24 * 90

def __post_init__(self) -> None:
self.base_path = Path(self.base_path)

def _date_to_partition(self, d: pd.Timestamp) -> Path:
return (
self.base_path
/ f"year={d.year:04d}"
/ f"month={d.month:02d}"
/ f"day={d.day:02d}"
/ "series.parquet"
)

def _paths_for_range(self, start: pd.Timestamp, end: pd.Timestamp) -> list[str]:
days = pd.date_range(start.normalize(), end.normalize(), freq="D")
paths = [self._date_to_partition(d) for d in days]
existing = [str(p) for p in paths if p.exists()]
if not existing:
raise FileNotFoundError(
f"No parquet files found between {start} and \
{end} under {self.base_path}"
Comment on lines +35 to +36

CopilotAIApr 15, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The FileNotFoundError message uses a line-continuation backslash inside the f-string, which will embed a newline and indentation spaces into the exception text. Format this as a single-line f-string (or use textwrap.dedent) so the error message is stable and readable.

Suggested change
f"No parquet files found between {start} and \
{end} under {self.base_path}"
f"No parquet files found between {start} and {end} under {self.base_path}"

Copilot uses AI. Check for mistakes.
)
return existing

def get_df(
self,
cutoff: str | pd.Timestamp,
max_window_size: int | None = None,
sort: bool = True,
) -> pd.DataFrame:
cutoff = pd.Timestamp(cutoff)
window = max_window_size or self.max_window_size
start = cutoff - pd.Timedelta(hours=window - 1)

paths = self._paths_for_range(start, cutoff)

query = f"""
SELECT unique_id, ds, y
FROM read_parquet({paths})
WHERE ds >= TIMESTAMP '{start}'
AND ds <= TIMESTAMP '{cutoff}'
"""

df = duckdb.sql(query).df()
df["ds"] = pd.to_datetime(df["ds"])
Comment on lines +50 to +60

CopilotAIApr 15, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DuckDB parquet reads are built via duckdb.sql(query) with read_parquet({paths}), where {paths} is a Python list repr. This is brittle (path escaping/backslashes on Windows, quoting, and no explicit INSTALL/LOAD parquet like other modules) and can break unexpectedly. Build a connection (duckdb.connect(':memory:')), INSTALL/LOAD parquet, and pass an explicit SQL list of Path(...).as_posix() strings (as done in GH Archive code) to make reads robust.

Copilot uses AI. Check for mistakes.

if sort:
df = df.sort_values(["unique_id", "ds"]).reset_index(drop=True)

return df

def get_actuals(
self, cutoff: str | pd.Timestamp, h: int | None = None
) -> pd.DataFrame:
cutoff = pd.Timestamp(cutoff)
horizon = h or self.h

start = cutoff + pd.Timedelta(hours=1)
end = cutoff + pd.Timedelta(hours=horizon)

paths = self._paths_for_range(start, end)

query = f"""
SELECT unique_id, ds, y
FROM read_parquet({paths})
WHERE ds >= TIMESTAMP '{start}'
AND ds <= TIMESTAMP '{end}'
"""

df = duckdb.sql(query).df()
df["ds"] = pd.to_datetime(df["ds"])
df = df.sort_values(["unique_id", "ds"]).reset_index(drop=True)
return df
Empty file.
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file addedsrc/data/cenace/__init__.py
Empty file.
48 changes: 48 additions & 0 deletions src/data/cenace/aggregate/core.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
from __future__ import annotations

import pandas as pd

from src.data.cenace.config import PROCESSED_CSV, PROCESSED_EVENTS_HOURLY_DIR

INPUT_CSV = PROCESSED_CSV
OUTPUT_ROOT = PROCESSED_EVENTS_HOURLY_DIR


def build_hourly_partitions() -> int:
df = pd.read_csv(INPUT_CSV)

df["ds"] = pd.to_datetime(df["ds"], errors="coerce")
df["y"] = pd.to_numeric(df["y"], errors="coerce")

df = df.dropna(subset=["unique_id", "ds", "y"]).copy()
df = df.sort_values(["unique_id", "ds"]).drop_duplicates(["unique_id", "ds"])

df["year"] = df["ds"].dt.year
df["month"] = df["ds"].dt.month
df["day"] = df["ds"].dt.day

OUTPUT_ROOT.mkdir(parents=True, exist_ok=True)

n_written = 0
for (year, month, day), part in df.groupby(["year", "month", "day"], sort=True):
part_dir = (
OUTPUT_ROOT / f"year={year:04d}" / f"month={month:02d}" / f"day={day:02d}"
)
part_dir.mkdir(parents=True, exist_ok=True)

out_path = part_dir / "series.parquet"
part[["unique_id", "ds", "y"]].to_parquet(out_path, index=False)

print(f"Saved: {out_path}")
n_written += 1

return n_written


def main() -> None:
n_written = build_hourly_partitions()
print(f"\nDone. Wrote {n_written} daily partitions.")


if __name__ == "__main__":
main()
15 changes: 15 additions & 0 deletions src/data/cenace/config.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
from __future__ import annotations

from pathlib import Path

ROOT = Path(__file__).resolve().parents[3]

DATA_ROOT = ROOT / "data" / "cenace"

TMP_DIR = DATA_ROOT / "tmp"
PROCESSED_DIR = DATA_ROOT / "processed"
PROCESSED_CSV = PROCESSED_DIR / "cenace.csv"

PROCESSED_EVENTS_HOURLY_DIR = DATA_ROOT / "processed-events" / "hourly"
FORECASTS_HOURLY_DIR = DATA_ROOT / "forecasts" / "hourly"
EVALUATIONS_HOURLY_DIR = DATA_ROOT / "evaluations" / "hourly"
169 changes: 169 additions & 0 deletions src/data/cenace/extract/core.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
from __future__ import annotations

import argparse
from datetime import datetime, timedelta
from pathlib import Path
import zipfile

import requests
from bs4 import BeautifulSoup

URL = "https://www.cenace.gob.mx/Paginas/SIM/Reportes/PreEnerServConMTR.aspx"

session = requests.Session()

HEADERS = {
"User-Agent": "Mozilla/5.0",
"Referer": URL,
"Origin": "https://www.cenace.gob.mx",
"Content-Type": "application/x-www-form-urlencoded",
}

# repo root = impermanent/
ROOT_DIR = Path(__file__).resolve().parents[4]
DEFAULT_BASE_DIR = ROOT_DIR / "data" / "cenace"


def target_date_for_execution(execution_date: datetime) -> datetime:
return execution_date + timedelta(days=1)


def raw_zip_path(date: datetime, raw_dir: Path) -> Path:
return raw_dir / f"{date.strftime('%Y%m%d')}.zip"


def get_form_state() -> dict[str, str]:
r = session.get(URL, headers=HEADERS)
r.raise_for_status()
soup = BeautifulSoup(r.text, "html.parser")

def get_value(name: str) -> str:
el = soup.find("input", {"name": name})
return el.get("value") if el else ""

return {
"__VIEWSTATE": get_value("__VIEWSTATE"),
"__VIEWSTATEGENERATOR": get_value("__VIEWSTATEGENERATOR"),
"__VIEWSTATEENCRYPTED": get_value("__VIEWSTATEENCRYPTED"),
"__EVENTVALIDATION": get_value("__EVENTVALIDATION"),
}


def download_and_extract(date: datetime, raw_dir: Path, tmp_dir: Path) -> bool:
date_str = date.strftime("%d/%m/%Y")
period_str = f"{date_str} - {date_str}"

state = get_form_state()

payload = {
"ctl00$ContentPlaceHolder1$ddlReporte": "362,325",
"ctl00$ContentPlaceHolder1$ddlPeriodicidad": "D",
"ctl00$ContentPlaceHolder1$ddlSistema": "SIN",
"ctl00$ContentPlaceHolder1$txtPeriodo": period_str,
"ctl00$ContentPlaceHolder1$hdfStartDateSelected": date_str,
"ctl00$ContentPlaceHolder1$hdfEndDateSelected": date_str,
"ctl00$ContentPlaceHolder1$btnDescargarZIP": "Descargar ZIP",
"__VIEWSTATE": state["__VIEWSTATE"],
"__VIEWSTATEGENERATOR": state["__VIEWSTATEGENERATOR"],
"__VIEWSTATEENCRYPTED": state["__VIEWSTATEENCRYPTED"],
"__EVENTVALIDATION": state["__EVENTVALIDATION"],
"__EVENTTARGET": "",
"__EVENTARGUMENT": "",
}

r = session.post(URL, data=payload, headers=HEADERS)
r.raise_for_status()

size = len(r.content)
print(f"{date_str} | {size} bytes")

if size < 10000:
print(f"Skipping {date_str}: file not published or response too small")
return False

raw_dir.mkdir(parents=True, exist_ok=True)
tmp_dir.mkdir(parents=True, exist_ok=True)

zip_path = raw_zip_path(date, raw_dir)

with open(zip_path, "wb") as f:
f.write(r.content)

with zipfile.ZipFile(zip_path, "r") as z:
z.extractall(tmp_dir)

return True


def backfill_missing(start_date: datetime, end_date: datetime, base_dir: Path) -> None:
raw_dir = base_dir / "raw"
tmp_dir = base_dir / "tmp"

current = start_date
while current <= end_date:
zip_path = raw_zip_path(current, raw_dir)
if zip_path.exists():
print(f"Already have {current.strftime('%Y-%m-%d')}, skipping")
else:
try:
ok = download_and_extract(current, raw_dir, tmp_dir)
if not ok:
print(f"Stopping at {current.strftime('%Y-%m-%d')}")
break
except Exception as e:
print(f"Error on {current.strftime('%Y-%m-%d')}: {e}")
break
current += timedelta(days=1)


def run_execution_date(execution_date: datetime, base_dir: Path) -> bool:
raw_dir = base_dir / "raw"
tmp_dir = base_dir / "tmp"
target_date = target_date_for_execution(execution_date)

zip_path = raw_zip_path(target_date, raw_dir)
if zip_path.exists():
print(f"Already have {target_date.strftime('%Y-%m-%d')}, skipping")
return True

return download_and_extract(target_date, raw_dir, tmp_dir)


def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument("--execution-date", default=None)
parser.add_argument("--start-date", default=None)
parser.add_argument("--end-date", default=None)
parser.add_argument("--out", default=str(DEFAULT_BASE_DIR))
return parser.parse_args()


def main() -> None:
args = parse_args()
base_dir = Path(args.out).resolve()

if args.start_date:
start_date = datetime.strptime(args.start_date, "%Y-%m-%d")
if args.end_date:
end_date = datetime.strptime(args.end_date, "%Y-%m-%d")
elif args.execution_date:
end_date = target_date_for_execution(
datetime.strptime(args.execution_date, "%Y-%m-%d")
)
else:
end_date = datetime.today()
backfill_missing(start_date=start_date, end_date=end_date, base_dir=base_dir)
return

if args.execution_date:
execution_date = datetime.strptime(args.execution_date, "%Y-%m-%d")
ok = run_execution_date(execution_date=execution_date, base_dir=base_dir)
if not ok:
print("No new CENACE publication detected; stopping cleanly")
return

raise ValueError("Provide either --start-date or --execution-date")


if __name__ == "__main__":
main()
Empty file.
88 changes: 88 additions & 0 deletions src/data/cenace/utils/cenace_data.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import duckdb
import pandas as pd


@dataclass
class CENACEData:
base_path: Path
freq: str = "hourly"
h: int = 24
max_window_size: int = 24 * 90

def __post_init__(self) -> None:
self.base_path = Path(self.base_path)

def _date_to_partition(self, d: pd.Timestamp) -> Path:
return (
self.base_path
/ f"year={d.year:04d}"
/ f"month={d.month:02d}"
/ f"day={d.day:02d}"
/ "series.parquet"
)

def _paths_for_range(self, start: pd.Timestamp, end: pd.Timestamp) -> list[str]:
days = pd.date_range(start.normalize(), end.normalize(), freq="D")
paths = [self._date_to_partition(d) for d in days]
existing = [str(p) for p in paths if p.exists()]
if not existing:
raise FileNotFoundError(
f"No parquet files found between {start} and \
{end} under {self.base_path}"
Comment on lines +35 to +36

CopilotAIApr 15, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The FileNotFoundError message uses a line-continuation backslash inside the f-string, which will embed a newline and indentation spaces into the exception text. Format this as a single-line f-string (or use textwrap.dedent) so the error message is stable and readable.

Suggested change
f"No parquet files found between {start} and \
{end} under {self.base_path}"
f"No parquet files found between {start} and {end} under {self.base_path}"

Copilot uses AI. Check for mistakes.
)
return existing

def get_df(
self,
cutoff: str | pd.Timestamp,
max_window_size: int | None = None,
sort: bool = True,
) -> pd.DataFrame:
cutoff = pd.Timestamp(cutoff)
window = max_window_size or self.max_window_size
start = cutoff - pd.Timedelta(hours=window - 1)

paths = self._paths_for_range(start, cutoff)

query = f"""
SELECT unique_id, ds, y
FROM read_parquet({paths})
WHERE ds >= TIMESTAMP '{start}'
AND ds <= TIMESTAMP '{cutoff}'
"""

df = duckdb.sql(query).df()
df["ds"] = pd.to_datetime(df["ds"])
Comment on lines +50 to +60

CopilotAIApr 15, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DuckDB parquet reads are built via duckdb.sql(query) with read_parquet({paths}), where {paths} is a Python list repr. This is brittle (path escaping/backslashes on Windows, quoting, and no explicit INSTALL/LOAD parquet like other modules) and can break unexpectedly. Build a connection (duckdb.connect(':memory:')), INSTALL/LOAD parquet, and pass an explicit SQL list of Path(...).as_posix() strings (as done in GH Archive code) to make reads robust.

Copilot uses AI. Check for mistakes.

if sort:
df = df.sort_values(["unique_id", "ds"]).reset_index(drop=True)

return df

def get_actuals(
self, cutoff: str | pd.Timestamp, h: int | None = None
) -> pd.DataFrame:
cutoff = pd.Timestamp(cutoff)
horizon = h or self.h

start = cutoff + pd.Timedelta(hours=1)
end = cutoff + pd.Timedelta(hours=horizon)

paths = self._paths_for_range(start, end)

query = f"""
SELECT unique_id, ds, y
FROM read_parquet({paths})
WHERE ds >= TIMESTAMP '{start}'
AND ds <= TIMESTAMP '{end}'
"""

df = duckdb.sql(query).df()
df["ds"] = pd.to_datetime(df["ds"])
df = df.sort_values(["unique_id", "ds"]).reset_index(drop=True)
return df
Empty file.
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file addedsrc/data/cenace/__init__.py
Empty file.
48 changes: 48 additions & 0 deletions src/data/cenace/aggregate/core.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
from __future__ import annotations

import pandas as pd

from src.data.cenace.config import PROCESSED_CSV, PROCESSED_EVENTS_HOURLY_DIR

INPUT_CSV = PROCESSED_CSV
OUTPUT_ROOT = PROCESSED_EVENTS_HOURLY_DIR


def build_hourly_partitions() -> int:
df = pd.read_csv(INPUT_CSV)

df["ds"] = pd.to_datetime(df["ds"], errors="coerce")
df["y"] = pd.to_numeric(df["y"], errors="coerce")

df = df.dropna(subset=["unique_id", "ds", "y"]).copy()
df = df.sort_values(["unique_id", "ds"]).drop_duplicates(["unique_id", "ds"])

df["year"] = df["ds"].dt.year
df["month"] = df["ds"].dt.month
df["day"] = df["ds"].dt.day

OUTPUT_ROOT.mkdir(parents=True, exist_ok=True)

n_written = 0
for (year, month, day), part in df.groupby(["year", "month", "day"], sort=True):
part_dir = (
OUTPUT_ROOT / f"year={year:04d}" / f"month={month:02d}" / f"day={day:02d}"
)
part_dir.mkdir(parents=True, exist_ok=True)

out_path = part_dir / "series.parquet"
part[["unique_id", "ds", "y"]].to_parquet(out_path, index=False)

print(f"Saved: {out_path}")
n_written += 1

return n_written


def main() -> None:
n_written = build_hourly_partitions()
print(f"\nDone. Wrote {n_written} daily partitions.")


if __name__ == "__main__":
main()
15 changes: 15 additions & 0 deletions src/data/cenace/config.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
from __future__ import annotations

from pathlib import Path

ROOT = Path(__file__).resolve().parents[3]

DATA_ROOT = ROOT / "data" / "cenace"

TMP_DIR = DATA_ROOT / "tmp"
PROCESSED_DIR = DATA_ROOT / "processed"
PROCESSED_CSV = PROCESSED_DIR / "cenace.csv"

PROCESSED_EVENTS_HOURLY_DIR = DATA_ROOT / "processed-events" / "hourly"
FORECASTS_HOURLY_DIR = DATA_ROOT / "forecasts" / "hourly"
EVALUATIONS_HOURLY_DIR = DATA_ROOT / "evaluations" / "hourly"
169 changes: 169 additions & 0 deletions src/data/cenace/extract/core.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
from __future__ import annotations

import argparse
from datetime import datetime, timedelta
from pathlib import Path
import zipfile

import requests
from bs4 import BeautifulSoup

URL = "https://www.cenace.gob.mx/Paginas/SIM/Reportes/PreEnerServConMTR.aspx"

session = requests.Session()

HEADERS = {
"User-Agent": "Mozilla/5.0",
"Referer": URL,
"Origin": "https://www.cenace.gob.mx",
"Content-Type": "application/x-www-form-urlencoded",
}

# repo root = impermanent/
ROOT_DIR = Path(__file__).resolve().parents[4]
DEFAULT_BASE_DIR = ROOT_DIR / "data" / "cenace"


def target_date_for_execution(execution_date: datetime) -> datetime:
return execution_date + timedelta(days=1)


def raw_zip_path(date: datetime, raw_dir: Path) -> Path:
return raw_dir / f"{date.strftime('%Y%m%d')}.zip"


def get_form_state() -> dict[str, str]:
r = session.get(URL, headers=HEADERS)
r.raise_for_status()
soup = BeautifulSoup(r.text, "html.parser")

def get_value(name: str) -> str:
el = soup.find("input", {"name": name})
return el.get("value") if el else ""

return {
"__VIEWSTATE": get_value("__VIEWSTATE"),
"__VIEWSTATEGENERATOR": get_value("__VIEWSTATEGENERATOR"),
"__VIEWSTATEENCRYPTED": get_value("__VIEWSTATEENCRYPTED"),
"__EVENTVALIDATION": get_value("__EVENTVALIDATION"),
}


def download_and_extract(date: datetime, raw_dir: Path, tmp_dir: Path) -> bool:
date_str = date.strftime("%d/%m/%Y")
period_str = f"{date_str} - {date_str}"

state = get_form_state()

payload = {
"ctl00$ContentPlaceHolder1$ddlReporte": "362,325",
"ctl00$ContentPlaceHolder1$ddlPeriodicidad": "D",
"ctl00$ContentPlaceHolder1$ddlSistema": "SIN",
"ctl00$ContentPlaceHolder1$txtPeriodo": period_str,
"ctl00$ContentPlaceHolder1$hdfStartDateSelected": date_str,
"ctl00$ContentPlaceHolder1$hdfEndDateSelected": date_str,
"ctl00$ContentPlaceHolder1$btnDescargarZIP": "Descargar ZIP",
"__VIEWSTATE": state["__VIEWSTATE"],
"__VIEWSTATEGENERATOR": state["__VIEWSTATEGENERATOR"],
"__VIEWSTATEENCRYPTED": state["__VIEWSTATEENCRYPTED"],
"__EVENTVALIDATION": state["__EVENTVALIDATION"],
"__EVENTTARGET": "",
"__EVENTARGUMENT": "",
}

r = session.post(URL, data=payload, headers=HEADERS)
r.raise_for_status()

size = len(r.content)
print(f"{date_str} | {size} bytes")

if size < 10000:
print(f"Skipping {date_str}: file not published or response too small")
return False

raw_dir.mkdir(parents=True, exist_ok=True)
tmp_dir.mkdir(parents=True, exist_ok=True)

zip_path = raw_zip_path(date, raw_dir)

with open(zip_path, "wb") as f:
f.write(r.content)

with zipfile.ZipFile(zip_path, "r") as z:
z.extractall(tmp_dir)

return True


def backfill_missing(start_date: datetime, end_date: datetime, base_dir: Path) -> None:
raw_dir = base_dir / "raw"
tmp_dir = base_dir / "tmp"

current = start_date
while current <= end_date:
zip_path = raw_zip_path(current, raw_dir)
if zip_path.exists():
print(f"Already have {current.strftime('%Y-%m-%d')}, skipping")
else:
try:
ok = download_and_extract(current, raw_dir, tmp_dir)
if not ok:
print(f"Stopping at {current.strftime('%Y-%m-%d')}")
break
except Exception as e:
print(f"Error on {current.strftime('%Y-%m-%d')}: {e}")
break
current += timedelta(days=1)


def run_execution_date(execution_date: datetime, base_dir: Path) -> bool:
raw_dir = base_dir / "raw"
tmp_dir = base_dir / "tmp"
target_date = target_date_for_execution(execution_date)

zip_path = raw_zip_path(target_date, raw_dir)
if zip_path.exists():
print(f"Already have {target_date.strftime('%Y-%m-%d')}, skipping")
return True

return download_and_extract(target_date, raw_dir, tmp_dir)


def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument("--execution-date", default=None)
parser.add_argument("--start-date", default=None)
parser.add_argument("--end-date", default=None)
parser.add_argument("--out", default=str(DEFAULT_BASE_DIR))
return parser.parse_args()


def main() -> None:
args = parse_args()
base_dir = Path(args.out).resolve()

if args.start_date:
start_date = datetime.strptime(args.start_date, "%Y-%m-%d")
if args.end_date:
end_date = datetime.strptime(args.end_date, "%Y-%m-%d")
elif args.execution_date:
end_date = target_date_for_execution(
datetime.strptime(args.execution_date, "%Y-%m-%d")
)
else:
end_date = datetime.today()
backfill_missing(start_date=start_date, end_date=end_date, base_dir=base_dir)
return

if args.execution_date:
execution_date = datetime.strptime(args.execution_date, "%Y-%m-%d")
ok = run_execution_date(execution_date=execution_date, base_dir=base_dir)
if not ok:
print("No new CENACE publication detected; stopping cleanly")
return

raise ValueError("Provide either --start-date or --execution-date")


if __name__ == "__main__":
main()
Empty file.
88 changes: 88 additions & 0 deletions src/data/cenace/utils/cenace_data.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import duckdb
import pandas as pd


@dataclass
class CENACEData:
base_path: Path
freq: str = "hourly"
h: int = 24
max_window_size: int = 24 * 90

def __post_init__(self) -> None:
self.base_path = Path(self.base_path)

def _date_to_partition(self, d: pd.Timestamp) -> Path:
return (
self.base_path
/ f"year={d.year:04d}"
/ f"month={d.month:02d}"
/ f"day={d.day:02d}"
/ "series.parquet"
)

def _paths_for_range(self, start: pd.Timestamp, end: pd.Timestamp) -> list[str]:
days = pd.date_range(start.normalize(), end.normalize(), freq="D")
paths = [self._date_to_partition(d) for d in days]
existing = [str(p) for p in paths if p.exists()]
if not existing:
raise FileNotFoundError(
f"No parquet files found between {start} and \
{end} under {self.base_path}"
Comment on lines +35 to +36

CopilotAIApr 15, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The FileNotFoundError message uses a line-continuation backslash inside the f-string, which will embed a newline and indentation spaces into the exception text. Format this as a single-line f-string (or use textwrap.dedent) so the error message is stable and readable.

Suggested change
f"No parquet files found between {start} and \
{end} under {self.base_path}"
f"No parquet files found between {start} and {end} under {self.base_path}"

Copilot uses AI. Check for mistakes.
)
return existing

def get_df(
self,
cutoff: str | pd.Timestamp,
max_window_size: int | None = None,
sort: bool = True,
) -> pd.DataFrame:
cutoff = pd.Timestamp(cutoff)
window = max_window_size or self.max_window_size
start = cutoff - pd.Timedelta(hours=window - 1)

paths = self._paths_for_range(start, cutoff)

query = f"""
SELECT unique_id, ds, y
FROM read_parquet({paths})
WHERE ds >= TIMESTAMP '{start}'
AND ds <= TIMESTAMP '{cutoff}'
"""

df = duckdb.sql(query).df()
df["ds"] = pd.to_datetime(df["ds"])
Comment on lines +50 to +60

CopilotAIApr 15, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DuckDB parquet reads are built via duckdb.sql(query) with read_parquet({paths}), where {paths} is a Python list repr. This is brittle (path escaping/backslashes on Windows, quoting, and no explicit INSTALL/LOAD parquet like other modules) and can break unexpectedly. Build a connection (duckdb.connect(':memory:')), INSTALL/LOAD parquet, and pass an explicit SQL list of Path(...).as_posix() strings (as done in GH Archive code) to make reads robust.

Copilot uses AI. Check for mistakes.

if sort:
df = df.sort_values(["unique_id", "ds"]).reset_index(drop=True)

return df

def get_actuals(
self, cutoff: str | pd.Timestamp, h: int | None = None
) -> pd.DataFrame:
cutoff = pd.Timestamp(cutoff)
horizon = h or self.h

start = cutoff + pd.Timedelta(hours=1)
end = cutoff + pd.Timedelta(hours=horizon)

paths = self._paths_for_range(start, end)

query = f"""
SELECT unique_id, ds, y
FROM read_parquet({paths})
WHERE ds >= TIMESTAMP '{start}'
AND ds <= TIMESTAMP '{end}'
"""

df = duckdb.sql(query).df()
df["ds"] = pd.to_datetime(df["ds"])
df = df.sort_values(["unique_id", "ds"]).reset_index(drop=True)
return df
Empty file.
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file addedsrc/data/cenace/__init__.py
Empty file.
48 changes: 48 additions & 0 deletions src/data/cenace/aggregate/core.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
from __future__ import annotations

import pandas as pd

from src.data.cenace.config import PROCESSED_CSV, PROCESSED_EVENTS_HOURLY_DIR

INPUT_CSV = PROCESSED_CSV
OUTPUT_ROOT = PROCESSED_EVENTS_HOURLY_DIR


def build_hourly_partitions() -> int:
df = pd.read_csv(INPUT_CSV)

df["ds"] = pd.to_datetime(df["ds"], errors="coerce")
df["y"] = pd.to_numeric(df["y"], errors="coerce")

df = df.dropna(subset=["unique_id", "ds", "y"]).copy()
df = df.sort_values(["unique_id", "ds"]).drop_duplicates(["unique_id", "ds"])

df["year"] = df["ds"].dt.year
df["month"] = df["ds"].dt.month
df["day"] = df["ds"].dt.day

OUTPUT_ROOT.mkdir(parents=True, exist_ok=True)

n_written = 0
for (year, month, day), part in df.groupby(["year", "month", "day"], sort=True):
part_dir = (
OUTPUT_ROOT / f"year={year:04d}" / f"month={month:02d}" / f"day={day:02d}"
)
part_dir.mkdir(parents=True, exist_ok=True)

out_path = part_dir / "series.parquet"
part[["unique_id", "ds", "y"]].to_parquet(out_path, index=False)

print(f"Saved: {out_path}")
n_written += 1

return n_written


def main() -> None:
n_written = build_hourly_partitions()
print(f"\nDone. Wrote {n_written} daily partitions.")


if __name__ == "__main__":
main()
15 changes: 15 additions & 0 deletions src/data/cenace/config.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
from __future__ import annotations

from pathlib import Path

ROOT = Path(__file__).resolve().parents[3]

DATA_ROOT = ROOT / "data" / "cenace"

TMP_DIR = DATA_ROOT / "tmp"
PROCESSED_DIR = DATA_ROOT / "processed"
PROCESSED_CSV = PROCESSED_DIR / "cenace.csv"

PROCESSED_EVENTS_HOURLY_DIR = DATA_ROOT / "processed-events" / "hourly"
FORECASTS_HOURLY_DIR = DATA_ROOT / "forecasts" / "hourly"
EVALUATIONS_HOURLY_DIR = DATA_ROOT / "evaluations" / "hourly"
169 changes: 169 additions & 0 deletions src/data/cenace/extract/core.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
from __future__ import annotations

import argparse
from datetime import datetime, timedelta
from pathlib import Path
import zipfile

import requests
from bs4 import BeautifulSoup

URL = "https://www.cenace.gob.mx/Paginas/SIM/Reportes/PreEnerServConMTR.aspx"

session = requests.Session()

HEADERS = {
"User-Agent": "Mozilla/5.0",
"Referer": URL,
"Origin": "https://www.cenace.gob.mx",
"Content-Type": "application/x-www-form-urlencoded",
}

# repo root = impermanent/
ROOT_DIR = Path(__file__).resolve().parents[4]
DEFAULT_BASE_DIR = ROOT_DIR / "data" / "cenace"


def target_date_for_execution(execution_date: datetime) -> datetime:
return execution_date + timedelta(days=1)


def raw_zip_path(date: datetime, raw_dir: Path) -> Path:
return raw_dir / f"{date.strftime('%Y%m%d')}.zip"


def get_form_state() -> dict[str, str]:
r = session.get(URL, headers=HEADERS)
r.raise_for_status()
soup = BeautifulSoup(r.text, "html.parser")

def get_value(name: str) -> str:
el = soup.find("input", {"name": name})
return el.get("value") if el else ""

return {
"__VIEWSTATE": get_value("__VIEWSTATE"),
"__VIEWSTATEGENERATOR": get_value("__VIEWSTATEGENERATOR"),
"__VIEWSTATEENCRYPTED": get_value("__VIEWSTATEENCRYPTED"),
"__EVENTVALIDATION": get_value("__EVENTVALIDATION"),
}


def download_and_extract(date: datetime, raw_dir: Path, tmp_dir: Path) -> bool:
date_str = date.strftime("%d/%m/%Y")
period_str = f"{date_str} - {date_str}"

state = get_form_state()

payload = {
"ctl00$ContentPlaceHolder1$ddlReporte": "362,325",
"ctl00$ContentPlaceHolder1$ddlPeriodicidad": "D",
"ctl00$ContentPlaceHolder1$ddlSistema": "SIN",
"ctl00$ContentPlaceHolder1$txtPeriodo": period_str,
"ctl00$ContentPlaceHolder1$hdfStartDateSelected": date_str,
"ctl00$ContentPlaceHolder1$hdfEndDateSelected": date_str,
"ctl00$ContentPlaceHolder1$btnDescargarZIP": "Descargar ZIP",
"__VIEWSTATE": state["__VIEWSTATE"],
"__VIEWSTATEGENERATOR": state["__VIEWSTATEGENERATOR"],
"__VIEWSTATEENCRYPTED": state["__VIEWSTATEENCRYPTED"],
"__EVENTVALIDATION": state["__EVENTVALIDATION"],
"__EVENTTARGET": "",
"__EVENTARGUMENT": "",
}

r = session.post(URL, data=payload, headers=HEADERS)
r.raise_for_status()

size = len(r.content)
print(f"{date_str} | {size} bytes")

if size < 10000:
print(f"Skipping {date_str}: file not published or response too small")
return False

raw_dir.mkdir(parents=True, exist_ok=True)
tmp_dir.mkdir(parents=True, exist_ok=True)

zip_path = raw_zip_path(date, raw_dir)

with open(zip_path, "wb") as f:
f.write(r.content)

with zipfile.ZipFile(zip_path, "r") as z:
z.extractall(tmp_dir)

return True


def backfill_missing(start_date: datetime, end_date: datetime, base_dir: Path) -> None:
raw_dir = base_dir / "raw"
tmp_dir = base_dir / "tmp"

current = start_date
while current <= end_date:
zip_path = raw_zip_path(current, raw_dir)
if zip_path.exists():
print(f"Already have {current.strftime('%Y-%m-%d')}, skipping")
else:
try:
ok = download_and_extract(current, raw_dir, tmp_dir)
if not ok:
print(f"Stopping at {current.strftime('%Y-%m-%d')}")
break
except Exception as e:
print(f"Error on {current.strftime('%Y-%m-%d')}: {e}")
break
current += timedelta(days=1)


def run_execution_date(execution_date: datetime, base_dir: Path) -> bool:
raw_dir = base_dir / "raw"
tmp_dir = base_dir / "tmp"
target_date = target_date_for_execution(execution_date)

zip_path = raw_zip_path(target_date, raw_dir)
if zip_path.exists():
print(f"Already have {target_date.strftime('%Y-%m-%d')}, skipping")
return True

return download_and_extract(target_date, raw_dir, tmp_dir)


def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument("--execution-date", default=None)
parser.add_argument("--start-date", default=None)
parser.add_argument("--end-date", default=None)
parser.add_argument("--out", default=str(DEFAULT_BASE_DIR))
return parser.parse_args()


def main() -> None:
args = parse_args()
base_dir = Path(args.out).resolve()

if args.start_date:
start_date = datetime.strptime(args.start_date, "%Y-%m-%d")
if args.end_date:
end_date = datetime.strptime(args.end_date, "%Y-%m-%d")
elif args.execution_date:
end_date = target_date_for_execution(
datetime.strptime(args.execution_date, "%Y-%m-%d")
)
else:
end_date = datetime.today()
backfill_missing(start_date=start_date, end_date=end_date, base_dir=base_dir)
return

if args.execution_date:
execution_date = datetime.strptime(args.execution_date, "%Y-%m-%d")
ok = run_execution_date(execution_date=execution_date, base_dir=base_dir)
if not ok:
print("No new CENACE publication detected; stopping cleanly")
return

raise ValueError("Provide either --start-date or --execution-date")


if __name__ == "__main__":
main()
Empty file.
88 changes: 88 additions & 0 deletions src/data/cenace/utils/cenace_data.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import duckdb
import pandas as pd


@dataclass
class CENACEData:
base_path: Path
freq: str = "hourly"
h: int = 24
max_window_size: int = 24 * 90

def __post_init__(self) -> None:
self.base_path = Path(self.base_path)

def _date_to_partition(self, d: pd.Timestamp) -> Path:
return (
self.base_path
/ f"year={d.year:04d}"
/ f"month={d.month:02d}"
/ f"day={d.day:02d}"
/ "series.parquet"
)

def _paths_for_range(self, start: pd.Timestamp, end: pd.Timestamp) -> list[str]:
days = pd.date_range(start.normalize(), end.normalize(), freq="D")
paths = [self._date_to_partition(d) for d in days]
existing = [str(p) for p in paths if p.exists()]
if not existing:
raise FileNotFoundError(
f"No parquet files found between {start} and \
{end} under {self.base_path}"
Comment on lines +35 to +36

CopilotAIApr 15, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The FileNotFoundError message uses a line-continuation backslash inside the f-string, which will embed a newline and indentation spaces into the exception text. Format this as a single-line f-string (or use textwrap.dedent) so the error message is stable and readable.

Suggested change
f"No parquet files found between {start} and \
{end} under {self.base_path}"
f"No parquet files found between {start} and {end} under {self.base_path}"

Copilot uses AI. Check for mistakes.
)
return existing

def get_df(
self,
cutoff: str | pd.Timestamp,
max_window_size: int | None = None,
sort: bool = True,
) -> pd.DataFrame:
cutoff = pd.Timestamp(cutoff)
window = max_window_size or self.max_window_size
start = cutoff - pd.Timedelta(hours=window - 1)

paths = self._paths_for_range(start, cutoff)

query = f"""
SELECT unique_id, ds, y
FROM read_parquet({paths})
WHERE ds >= TIMESTAMP '{start}'
AND ds <= TIMESTAMP '{cutoff}'
"""

df = duckdb.sql(query).df()
df["ds"] = pd.to_datetime(df["ds"])
Comment on lines +50 to +60

CopilotAIApr 15, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DuckDB parquet reads are built via duckdb.sql(query) with read_parquet({paths}), where {paths} is a Python list repr. This is brittle (path escaping/backslashes on Windows, quoting, and no explicit INSTALL/LOAD parquet like other modules) and can break unexpectedly. Build a connection (duckdb.connect(':memory:')), INSTALL/LOAD parquet, and pass an explicit SQL list of Path(...).as_posix() strings (as done in GH Archive code) to make reads robust.

Copilot uses AI. Check for mistakes.

if sort:
df = df.sort_values(["unique_id", "ds"]).reset_index(drop=True)

return df

def get_actuals(
self, cutoff: str | pd.Timestamp, h: int | None = None
) -> pd.DataFrame:
cutoff = pd.Timestamp(cutoff)
horizon = h or self.h

start = cutoff + pd.Timedelta(hours=1)
end = cutoff + pd.Timedelta(hours=horizon)

paths = self._paths_for_range(start, end)

query = f"""
SELECT unique_id, ds, y
FROM read_parquet({paths})
WHERE ds >= TIMESTAMP '{start}'
AND ds <= TIMESTAMP '{end}'
"""

df = duckdb.sql(query).df()
df["ds"] = pd.to_datetime(df["ds"])
df = df.sort_values(["unique_id", "ds"]).reset_index(drop=True)
return df
Empty file.
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file addedsrc/data/cenace/__init__.py
Empty file.
48 changes: 48 additions & 0 deletions src/data/cenace/aggregate/core.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
from __future__ import annotations

import pandas as pd

from src.data.cenace.config import PROCESSED_CSV, PROCESSED_EVENTS_HOURLY_DIR

INPUT_CSV = PROCESSED_CSV
OUTPUT_ROOT = PROCESSED_EVENTS_HOURLY_DIR


def build_hourly_partitions() -> int:
df = pd.read_csv(INPUT_CSV)

df["ds"] = pd.to_datetime(df["ds"], errors="coerce")
df["y"] = pd.to_numeric(df["y"], errors="coerce")

df = df.dropna(subset=["unique_id", "ds", "y"]).copy()
df = df.sort_values(["unique_id", "ds"]).drop_duplicates(["unique_id", "ds"])

df["year"] = df["ds"].dt.year
df["month"] = df["ds"].dt.month
df["day"] = df["ds"].dt.day

OUTPUT_ROOT.mkdir(parents=True, exist_ok=True)

n_written = 0
for (year, month, day), part in df.groupby(["year", "month", "day"], sort=True):
part_dir = (
OUTPUT_ROOT / f"year={year:04d}" / f"month={month:02d}" / f"day={day:02d}"
)
part_dir.mkdir(parents=True, exist_ok=True)

out_path = part_dir / "series.parquet"
part[["unique_id", "ds", "y"]].to_parquet(out_path, index=False)

print(f"Saved: {out_path}")
n_written += 1

return n_written


def main() -> None:
n_written = build_hourly_partitions()
print(f"\nDone. Wrote {n_written} daily partitions.")


if __name__ == "__main__":
main()
15 changes: 15 additions & 0 deletions src/data/cenace/config.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
from __future__ import annotations

from pathlib import Path

ROOT = Path(__file__).resolve().parents[3]

DATA_ROOT = ROOT / "data" / "cenace"

TMP_DIR = DATA_ROOT / "tmp"
PROCESSED_DIR = DATA_ROOT / "processed"
PROCESSED_CSV = PROCESSED_DIR / "cenace.csv"

PROCESSED_EVENTS_HOURLY_DIR = DATA_ROOT / "processed-events" / "hourly"
FORECASTS_HOURLY_DIR = DATA_ROOT / "forecasts" / "hourly"
EVALUATIONS_HOURLY_DIR = DATA_ROOT / "evaluations" / "hourly"
169 changes: 169 additions & 0 deletions src/data/cenace/extract/core.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
from __future__ import annotations

import argparse
from datetime import datetime, timedelta
from pathlib import Path
import zipfile

import requests
from bs4 import BeautifulSoup

URL = "https://www.cenace.gob.mx/Paginas/SIM/Reportes/PreEnerServConMTR.aspx"

session = requests.Session()

HEADERS = {
"User-Agent": "Mozilla/5.0",
"Referer": URL,
"Origin": "https://www.cenace.gob.mx",
"Content-Type": "application/x-www-form-urlencoded",
}

# repo root = impermanent/
ROOT_DIR = Path(__file__).resolve().parents[4]
DEFAULT_BASE_DIR = ROOT_DIR / "data" / "cenace"


def target_date_for_execution(execution_date: datetime) -> datetime:
return execution_date + timedelta(days=1)


def raw_zip_path(date: datetime, raw_dir: Path) -> Path:
return raw_dir / f"{date.strftime('%Y%m%d')}.zip"


def get_form_state() -> dict[str, str]:
r = session.get(URL, headers=HEADERS)
r.raise_for_status()
soup = BeautifulSoup(r.text, "html.parser")

def get_value(name: str) -> str:
el = soup.find("input", {"name": name})
return el.get("value") if el else ""

return {
"__VIEWSTATE": get_value("__VIEWSTATE"),
"__VIEWSTATEGENERATOR": get_value("__VIEWSTATEGENERATOR"),
"__VIEWSTATEENCRYPTED": get_value("__VIEWSTATEENCRYPTED"),
"__EVENTVALIDATION": get_value("__EVENTVALIDATION"),
}


def download_and_extract(date: datetime, raw_dir: Path, tmp_dir: Path) -> bool:
date_str = date.strftime("%d/%m/%Y")
period_str = f"{date_str} - {date_str}"

state = get_form_state()

payload = {
"ctl00$ContentPlaceHolder1$ddlReporte": "362,325",
"ctl00$ContentPlaceHolder1$ddlPeriodicidad": "D",
"ctl00$ContentPlaceHolder1$ddlSistema": "SIN",
"ctl00$ContentPlaceHolder1$txtPeriodo": period_str,
"ctl00$ContentPlaceHolder1$hdfStartDateSelected": date_str,
"ctl00$ContentPlaceHolder1$hdfEndDateSelected": date_str,
"ctl00$ContentPlaceHolder1$btnDescargarZIP": "Descargar ZIP",
"__VIEWSTATE": state["__VIEWSTATE"],
"__VIEWSTATEGENERATOR": state["__VIEWSTATEGENERATOR"],
"__VIEWSTATEENCRYPTED": state["__VIEWSTATEENCRYPTED"],
"__EVENTVALIDATION": state["__EVENTVALIDATION"],
"__EVENTTARGET": "",
"__EVENTARGUMENT": "",
}

r = session.post(URL, data=payload, headers=HEADERS)
r.raise_for_status()

size = len(r.content)
print(f"{date_str} | {size} bytes")

if size < 10000:
print(f"Skipping {date_str}: file not published or response too small")
return False

raw_dir.mkdir(parents=True, exist_ok=True)
tmp_dir.mkdir(parents=True, exist_ok=True)

zip_path = raw_zip_path(date, raw_dir)

with open(zip_path, "wb") as f:
f.write(r.content)

with zipfile.ZipFile(zip_path, "r") as z:
z.extractall(tmp_dir)

return True


def backfill_missing(start_date: datetime, end_date: datetime, base_dir: Path) -> None:
raw_dir = base_dir / "raw"
tmp_dir = base_dir / "tmp"

current = start_date
while current <= end_date:
zip_path = raw_zip_path(current, raw_dir)
if zip_path.exists():
print(f"Already have {current.strftime('%Y-%m-%d')}, skipping")
else:
try:
ok = download_and_extract(current, raw_dir, tmp_dir)
if not ok:
print(f"Stopping at {current.strftime('%Y-%m-%d')}")
break
except Exception as e:
print(f"Error on {current.strftime('%Y-%m-%d')}: {e}")
break
current += timedelta(days=1)


def run_execution_date(execution_date: datetime, base_dir: Path) -> bool:
raw_dir = base_dir / "raw"
tmp_dir = base_dir / "tmp"
target_date = target_date_for_execution(execution_date)

zip_path = raw_zip_path(target_date, raw_dir)
if zip_path.exists():
print(f"Already have {target_date.strftime('%Y-%m-%d')}, skipping")
return True

return download_and_extract(target_date, raw_dir, tmp_dir)


def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument("--execution-date", default=None)
parser.add_argument("--start-date", default=None)
parser.add_argument("--end-date", default=None)
parser.add_argument("--out", default=str(DEFAULT_BASE_DIR))
return parser.parse_args()


def main() -> None:
args = parse_args()
base_dir = Path(args.out).resolve()

if args.start_date:
start_date = datetime.strptime(args.start_date, "%Y-%m-%d")
if args.end_date:
end_date = datetime.strptime(args.end_date, "%Y-%m-%d")
elif args.execution_date:
end_date = target_date_for_execution(
datetime.strptime(args.execution_date, "%Y-%m-%d")
)
else:
end_date = datetime.today()
backfill_missing(start_date=start_date, end_date=end_date, base_dir=base_dir)
return

if args.execution_date:
execution_date = datetime.strptime(args.execution_date, "%Y-%m-%d")
ok = run_execution_date(execution_date=execution_date, base_dir=base_dir)
if not ok:
print("No new CENACE publication detected; stopping cleanly")
return

raise ValueError("Provide either --start-date or --execution-date")


if __name__ == "__main__":
main()
Empty file.
88 changes: 88 additions & 0 deletions src/data/cenace/utils/cenace_data.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import duckdb
import pandas as pd


@dataclass
class CENACEData:
base_path: Path
freq: str = "hourly"
h: int = 24
max_window_size: int = 24 * 90

def __post_init__(self) -> None:
self.base_path = Path(self.base_path)

def _date_to_partition(self, d: pd.Timestamp) -> Path:
return (
self.base_path
/ f"year={d.year:04d}"
/ f"month={d.month:02d}"
/ f"day={d.day:02d}"
/ "series.parquet"
)

def _paths_for_range(self, start: pd.Timestamp, end: pd.Timestamp) -> list[str]:
days = pd.date_range(start.normalize(), end.normalize(), freq="D")
paths = [self._date_to_partition(d) for d in days]
existing = [str(p) for p in paths if p.exists()]
if not existing:
raise FileNotFoundError(
f"No parquet files found between {start} and \
{end} under {self.base_path}"
Comment on lines +35 to +36

CopilotAIApr 15, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The FileNotFoundError message uses a line-continuation backslash inside the f-string, which will embed a newline and indentation spaces into the exception text. Format this as a single-line f-string (or use textwrap.dedent) so the error message is stable and readable.

Suggested change
f"No parquet files found between {start} and \
{end} under {self.base_path}"
f"No parquet files found between {start} and {end} under {self.base_path}"

Copilot uses AI. Check for mistakes.
)
return existing

def get_df(
self,
cutoff: str | pd.Timestamp,
max_window_size: int | None = None,
sort: bool = True,
) -> pd.DataFrame:
cutoff = pd.Timestamp(cutoff)
window = max_window_size or self.max_window_size
start = cutoff - pd.Timedelta(hours=window - 1)

paths = self._paths_for_range(start, cutoff)

query = f"""
SELECT unique_id, ds, y
FROM read_parquet({paths})
WHERE ds >= TIMESTAMP '{start}'
AND ds <= TIMESTAMP '{cutoff}'
"""

df = duckdb.sql(query).df()
df["ds"] = pd.to_datetime(df["ds"])
Comment on lines +50 to +60

CopilotAIApr 15, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DuckDB parquet reads are built via duckdb.sql(query) with read_parquet({paths}), where {paths} is a Python list repr. This is brittle (path escaping/backslashes on Windows, quoting, and no explicit INSTALL/LOAD parquet like other modules) and can break unexpectedly. Build a connection (duckdb.connect(':memory:')), INSTALL/LOAD parquet, and pass an explicit SQL list of Path(...).as_posix() strings (as done in GH Archive code) to make reads robust.

Copilot uses AI. Check for mistakes.

if sort:
df = df.sort_values(["unique_id", "ds"]).reset_index(drop=True)

return df

def get_actuals(
self, cutoff: str | pd.Timestamp, h: int | None = None
) -> pd.DataFrame:
cutoff = pd.Timestamp(cutoff)
horizon = h or self.h

start = cutoff + pd.Timedelta(hours=1)
end = cutoff + pd.Timedelta(hours=horizon)

paths = self._paths_for_range(start, end)

query = f"""
SELECT unique_id, ds, y
FROM read_parquet({paths})
WHERE ds >= TIMESTAMP '{start}'
AND ds <= TIMESTAMP '{end}'
"""

df = duckdb.sql(query).df()
df["ds"] = pd.to_datetime(df["ds"])
df = df.sort_values(["unique_id", "ds"]).reset_index(drop=True)
return df
Empty file.
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file addedsrc/data/cenace/__init__.py
Empty file.
48 changes: 48 additions & 0 deletions src/data/cenace/aggregate/core.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
from __future__ import annotations

import pandas as pd

from src.data.cenace.config import PROCESSED_CSV, PROCESSED_EVENTS_HOURLY_DIR

INPUT_CSV = PROCESSED_CSV
OUTPUT_ROOT = PROCESSED_EVENTS_HOURLY_DIR


def build_hourly_partitions() -> int:
df = pd.read_csv(INPUT_CSV)

df["ds"] = pd.to_datetime(df["ds"], errors="coerce")
df["y"] = pd.to_numeric(df["y"], errors="coerce")

df = df.dropna(subset=["unique_id", "ds", "y"]).copy()
df = df.sort_values(["unique_id", "ds"]).drop_duplicates(["unique_id", "ds"])

df["year"] = df["ds"].dt.year
df["month"] = df["ds"].dt.month
df["day"] = df["ds"].dt.day

OUTPUT_ROOT.mkdir(parents=True, exist_ok=True)

n_written = 0
for (year, month, day), part in df.groupby(["year", "month", "day"], sort=True):
part_dir = (
OUTPUT_ROOT / f"year={year:04d}" / f"month={month:02d}" / f"day={day:02d}"
)
part_dir.mkdir(parents=True, exist_ok=True)

out_path = part_dir / "series.parquet"
part[["unique_id", "ds", "y"]].to_parquet(out_path, index=False)

print(f"Saved: {out_path}")
n_written += 1

return n_written


def main() -> None:
n_written = build_hourly_partitions()
print(f"\nDone. Wrote {n_written} daily partitions.")


if __name__ == "__main__":
main()
15 changes: 15 additions & 0 deletions src/data/cenace/config.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
from __future__ import annotations

from pathlib import Path

ROOT = Path(__file__).resolve().parents[3]

DATA_ROOT = ROOT / "data" / "cenace"

TMP_DIR = DATA_ROOT / "tmp"
PROCESSED_DIR = DATA_ROOT / "processed"
PROCESSED_CSV = PROCESSED_DIR / "cenace.csv"

PROCESSED_EVENTS_HOURLY_DIR = DATA_ROOT / "processed-events" / "hourly"
FORECASTS_HOURLY_DIR = DATA_ROOT / "forecasts" / "hourly"
EVALUATIONS_HOURLY_DIR = DATA_ROOT / "evaluations" / "hourly"
169 changes: 169 additions & 0 deletions src/data/cenace/extract/core.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
from __future__ import annotations

import argparse
from datetime import datetime, timedelta
from pathlib import Path
import zipfile

import requests
from bs4 import BeautifulSoup

URL = "https://www.cenace.gob.mx/Paginas/SIM/Reportes/PreEnerServConMTR.aspx"

session = requests.Session()

HEADERS = {
"User-Agent": "Mozilla/5.0",
"Referer": URL,
"Origin": "https://www.cenace.gob.mx",
"Content-Type": "application/x-www-form-urlencoded",
}

# repo root = impermanent/
ROOT_DIR = Path(__file__).resolve().parents[4]
DEFAULT_BASE_DIR = ROOT_DIR / "data" / "cenace"


def target_date_for_execution(execution_date: datetime) -> datetime:
return execution_date + timedelta(days=1)


def raw_zip_path(date: datetime, raw_dir: Path) -> Path:
return raw_dir / f"{date.strftime('%Y%m%d')}.zip"


def get_form_state() -> dict[str, str]:
r = session.get(URL, headers=HEADERS)
r.raise_for_status()
soup = BeautifulSoup(r.text, "html.parser")

def get_value(name: str) -> str:
el = soup.find("input", {"name": name})
return el.get("value") if el else ""

return {
"__VIEWSTATE": get_value("__VIEWSTATE"),
"__VIEWSTATEGENERATOR": get_value("__VIEWSTATEGENERATOR"),
"__VIEWSTATEENCRYPTED": get_value("__VIEWSTATEENCRYPTED"),
"__EVENTVALIDATION": get_value("__EVENTVALIDATION"),
}


def download_and_extract(date: datetime, raw_dir: Path, tmp_dir: Path) -> bool:
date_str = date.strftime("%d/%m/%Y")
period_str = f"{date_str} - {date_str}"

state = get_form_state()

payload = {
"ctl00$ContentPlaceHolder1$ddlReporte": "362,325",
"ctl00$ContentPlaceHolder1$ddlPeriodicidad": "D",
"ctl00$ContentPlaceHolder1$ddlSistema": "SIN",
"ctl00$ContentPlaceHolder1$txtPeriodo": period_str,
"ctl00$ContentPlaceHolder1$hdfStartDateSelected": date_str,
"ctl00$ContentPlaceHolder1$hdfEndDateSelected": date_str,
"ctl00$ContentPlaceHolder1$btnDescargarZIP": "Descargar ZIP",
"__VIEWSTATE": state["__VIEWSTATE"],
"__VIEWSTATEGENERATOR": state["__VIEWSTATEGENERATOR"],
"__VIEWSTATEENCRYPTED": state["__VIEWSTATEENCRYPTED"],
"__EVENTVALIDATION": state["__EVENTVALIDATION"],
"__EVENTTARGET": "",
"__EVENTARGUMENT": "",
}

r = session.post(URL, data=payload, headers=HEADERS)
r.raise_for_status()

size = len(r.content)
print(f"{date_str} | {size} bytes")

if size < 10000:
print(f"Skipping {date_str}: file not published or response too small")
return False

raw_dir.mkdir(parents=True, exist_ok=True)
tmp_dir.mkdir(parents=True, exist_ok=True)

zip_path = raw_zip_path(date, raw_dir)

with open(zip_path, "wb") as f:
f.write(r.content)

with zipfile.ZipFile(zip_path, "r") as z:
z.extractall(tmp_dir)

return True


def backfill_missing(start_date: datetime, end_date: datetime, base_dir: Path) -> None:
raw_dir = base_dir / "raw"
tmp_dir = base_dir / "tmp"

current = start_date
while current <= end_date:
zip_path = raw_zip_path(current, raw_dir)
if zip_path.exists():
print(f"Already have {current.strftime('%Y-%m-%d')}, skipping")
else:
try:
ok = download_and_extract(current, raw_dir, tmp_dir)
if not ok:
print(f"Stopping at {current.strftime('%Y-%m-%d')}")
break
except Exception as e:
print(f"Error on {current.strftime('%Y-%m-%d')}: {e}")
break
current += timedelta(days=1)


def run_execution_date(execution_date: datetime, base_dir: Path) -> bool:
raw_dir = base_dir / "raw"
tmp_dir = base_dir / "tmp"
target_date = target_date_for_execution(execution_date)

zip_path = raw_zip_path(target_date, raw_dir)
if zip_path.exists():
print(f"Already have {target_date.strftime('%Y-%m-%d')}, skipping")
return True

return download_and_extract(target_date, raw_dir, tmp_dir)


def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument("--execution-date", default=None)
parser.add_argument("--start-date", default=None)
parser.add_argument("--end-date", default=None)
parser.add_argument("--out", default=str(DEFAULT_BASE_DIR))
return parser.parse_args()


def main() -> None:
args = parse_args()
base_dir = Path(args.out).resolve()

if args.start_date:
start_date = datetime.strptime(args.start_date, "%Y-%m-%d")
if args.end_date:
end_date = datetime.strptime(args.end_date, "%Y-%m-%d")
elif args.execution_date:
end_date = target_date_for_execution(
datetime.strptime(args.execution_date, "%Y-%m-%d")
)
else:
end_date = datetime.today()
backfill_missing(start_date=start_date, end_date=end_date, base_dir=base_dir)
return

if args.execution_date:
execution_date = datetime.strptime(args.execution_date, "%Y-%m-%d")
ok = run_execution_date(execution_date=execution_date, base_dir=base_dir)
if not ok:
print("No new CENACE publication detected; stopping cleanly")
return

raise ValueError("Provide either --start-date or --execution-date")


if __name__ == "__main__":
main()
Empty file.
88 changes: 88 additions & 0 deletions src/data/cenace/utils/cenace_data.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import duckdb
import pandas as pd


@dataclass
class CENACEData:
base_path: Path
freq: str = "hourly"
h: int = 24
max_window_size: int = 24 * 90

def __post_init__(self) -> None:
self.base_path = Path(self.base_path)

def _date_to_partition(self, d: pd.Timestamp) -> Path:
return (
self.base_path
/ f"year={d.year:04d}"
/ f"month={d.month:02d}"
/ f"day={d.day:02d}"
/ "series.parquet"
)

def _paths_for_range(self, start: pd.Timestamp, end: pd.Timestamp) -> list[str]:
days = pd.date_range(start.normalize(), end.normalize(), freq="D")
paths = [self._date_to_partition(d) for d in days]
existing = [str(p) for p in paths if p.exists()]
if not existing:
raise FileNotFoundError(
f"No parquet files found between {start} and \
{end} under {self.base_path}"
Comment on lines +35 to +36

CopilotAIApr 15, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The FileNotFoundError message uses a line-continuation backslash inside the f-string, which will embed a newline and indentation spaces into the exception text. Format this as a single-line f-string (or use textwrap.dedent) so the error message is stable and readable.

Suggested change
f"No parquet files found between {start} and \
{end} under {self.base_path}"
f"No parquet files found between {start} and {end} under {self.base_path}"

Copilot uses AI. Check for mistakes.
)
return existing

def get_df(
self,
cutoff: str | pd.Timestamp,
max_window_size: int | None = None,
sort: bool = True,
) -> pd.DataFrame:
cutoff = pd.Timestamp(cutoff)
window = max_window_size or self.max_window_size
start = cutoff - pd.Timedelta(hours=window - 1)

paths = self._paths_for_range(start, cutoff)

query = f"""
SELECT unique_id, ds, y
FROM read_parquet({paths})
WHERE ds >= TIMESTAMP '{start}'
AND ds <= TIMESTAMP '{cutoff}'
"""

df = duckdb.sql(query).df()
df["ds"] = pd.to_datetime(df["ds"])
Comment on lines +50 to +60

CopilotAIApr 15, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DuckDB parquet reads are built via duckdb.sql(query) with read_parquet({paths}), where {paths} is a Python list repr. This is brittle (path escaping/backslashes on Windows, quoting, and no explicit INSTALL/LOAD parquet like other modules) and can break unexpectedly. Build a connection (duckdb.connect(':memory:')), INSTALL/LOAD parquet, and pass an explicit SQL list of Path(...).as_posix() strings (as done in GH Archive code) to make reads robust.

Copilot uses AI. Check for mistakes.

if sort:
df = df.sort_values(["unique_id", "ds"]).reset_index(drop=True)

return df

def get_actuals(
self, cutoff: str | pd.Timestamp, h: int | None = None
) -> pd.DataFrame:
cutoff = pd.Timestamp(cutoff)
horizon = h or self.h

start = cutoff + pd.Timedelta(hours=1)
end = cutoff + pd.Timedelta(hours=horizon)

paths = self._paths_for_range(start, end)

query = f"""
SELECT unique_id, ds, y
FROM read_parquet({paths})
WHERE ds >= TIMESTAMP '{start}'
AND ds <= TIMESTAMP '{end}'
"""

df = duckdb.sql(query).df()
df["ds"] = pd.to_datetime(df["ds"])
df = df.sort_values(["unique_id", "ds"]).reset_index(drop=True)
return df
Empty file.
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file addedsrc/data/cenace/__init__.py
Empty file.
48 changes: 48 additions & 0 deletions src/data/cenace/aggregate/core.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
from __future__ import annotations

import pandas as pd

from src.data.cenace.config import PROCESSED_CSV, PROCESSED_EVENTS_HOURLY_DIR

INPUT_CSV = PROCESSED_CSV
OUTPUT_ROOT = PROCESSED_EVENTS_HOURLY_DIR


def build_hourly_partitions() -> int:
df = pd.read_csv(INPUT_CSV)

df["ds"] = pd.to_datetime(df["ds"], errors="coerce")
df["y"] = pd.to_numeric(df["y"], errors="coerce")

df = df.dropna(subset=["unique_id", "ds", "y"]).copy()
df = df.sort_values(["unique_id", "ds"]).drop_duplicates(["unique_id", "ds"])

df["year"] = df["ds"].dt.year
df["month"] = df["ds"].dt.month
df["day"] = df["ds"].dt.day

OUTPUT_ROOT.mkdir(parents=True, exist_ok=True)

n_written = 0
for (year, month, day), part in df.groupby(["year", "month", "day"], sort=True):
part_dir = (
OUTPUT_ROOT / f"year={year:04d}" / f"month={month:02d}" / f"day={day:02d}"
)
part_dir.mkdir(parents=True, exist_ok=True)

out_path = part_dir / "series.parquet"
part[["unique_id", "ds", "y"]].to_parquet(out_path, index=False)

print(f"Saved: {out_path}")
n_written += 1

return n_written


def main() -> None:
n_written = build_hourly_partitions()
print(f"\nDone. Wrote {n_written} daily partitions.")


if __name__ == "__main__":
main()
15 changes: 15 additions & 0 deletions src/data/cenace/config.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
from __future__ import annotations

from pathlib import Path

ROOT = Path(__file__).resolve().parents[3]

DATA_ROOT = ROOT / "data" / "cenace"

TMP_DIR = DATA_ROOT / "tmp"
PROCESSED_DIR = DATA_ROOT / "processed"
PROCESSED_CSV = PROCESSED_DIR / "cenace.csv"

PROCESSED_EVENTS_HOURLY_DIR = DATA_ROOT / "processed-events" / "hourly"
FORECASTS_HOURLY_DIR = DATA_ROOT / "forecasts" / "hourly"
EVALUATIONS_HOURLY_DIR = DATA_ROOT / "evaluations" / "hourly"
169 changes: 169 additions & 0 deletions src/data/cenace/extract/core.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
from __future__ import annotations

import argparse
from datetime import datetime, timedelta
from pathlib import Path
import zipfile

import requests
from bs4 import BeautifulSoup

URL = "https://www.cenace.gob.mx/Paginas/SIM/Reportes/PreEnerServConMTR.aspx"

session = requests.Session()

HEADERS = {
"User-Agent": "Mozilla/5.0",
"Referer": URL,
"Origin": "https://www.cenace.gob.mx",
"Content-Type": "application/x-www-form-urlencoded",
}

# repo root = impermanent/
ROOT_DIR = Path(__file__).resolve().parents[4]
DEFAULT_BASE_DIR = ROOT_DIR / "data" / "cenace"


def target_date_for_execution(execution_date: datetime) -> datetime:
return execution_date + timedelta(days=1)


def raw_zip_path(date: datetime, raw_dir: Path) -> Path:
return raw_dir / f"{date.strftime('%Y%m%d')}.zip"


def get_form_state() -> dict[str, str]:
r = session.get(URL, headers=HEADERS)
r.raise_for_status()
soup = BeautifulSoup(r.text, "html.parser")

def get_value(name: str) -> str:
el = soup.find("input", {"name": name})
return el.get("value") if el else ""

return {
"__VIEWSTATE": get_value("__VIEWSTATE"),
"__VIEWSTATEGENERATOR": get_value("__VIEWSTATEGENERATOR"),
"__VIEWSTATEENCRYPTED": get_value("__VIEWSTATEENCRYPTED"),
"__EVENTVALIDATION": get_value("__EVENTVALIDATION"),
}


def download_and_extract(date: datetime, raw_dir: Path, tmp_dir: Path) -> bool:
date_str = date.strftime("%d/%m/%Y")
period_str = f"{date_str} - {date_str}"

state = get_form_state()

payload = {
"ctl00$ContentPlaceHolder1$ddlReporte": "362,325",
"ctl00$ContentPlaceHolder1$ddlPeriodicidad": "D",
"ctl00$ContentPlaceHolder1$ddlSistema": "SIN",
"ctl00$ContentPlaceHolder1$txtPeriodo": period_str,
"ctl00$ContentPlaceHolder1$hdfStartDateSelected": date_str,
"ctl00$ContentPlaceHolder1$hdfEndDateSelected": date_str,
"ctl00$ContentPlaceHolder1$btnDescargarZIP": "Descargar ZIP",
"__VIEWSTATE": state["__VIEWSTATE"],
"__VIEWSTATEGENERATOR": state["__VIEWSTATEGENERATOR"],
"__VIEWSTATEENCRYPTED": state["__VIEWSTATEENCRYPTED"],
"__EVENTVALIDATION": state["__EVENTVALIDATION"],
"__EVENTTARGET": "",
"__EVENTARGUMENT": "",
}

r = session.post(URL, data=payload, headers=HEADERS)
r.raise_for_status()

size = len(r.content)
print(f"{date_str} | {size} bytes")

if size < 10000:
print(f"Skipping {date_str}: file not published or response too small")
return False

raw_dir.mkdir(parents=True, exist_ok=True)
tmp_dir.mkdir(parents=True, exist_ok=True)

zip_path = raw_zip_path(date, raw_dir)

with open(zip_path, "wb") as f:
f.write(r.content)

with zipfile.ZipFile(zip_path, "r") as z:
z.extractall(tmp_dir)

return True


def backfill_missing(start_date: datetime, end_date: datetime, base_dir: Path) -> None:
raw_dir = base_dir / "raw"
tmp_dir = base_dir / "tmp"

current = start_date
while current <= end_date:
zip_path = raw_zip_path(current, raw_dir)
if zip_path.exists():
print(f"Already have {current.strftime('%Y-%m-%d')}, skipping")
else:
try:
ok = download_and_extract(current, raw_dir, tmp_dir)
if not ok:
print(f"Stopping at {current.strftime('%Y-%m-%d')}")
break
except Exception as e:
print(f"Error on {current.strftime('%Y-%m-%d')}: {e}")
break
current += timedelta(days=1)


def run_execution_date(execution_date: datetime, base_dir: Path) -> bool:
raw_dir = base_dir / "raw"
tmp_dir = base_dir / "tmp"
target_date = target_date_for_execution(execution_date)

zip_path = raw_zip_path(target_date, raw_dir)
if zip_path.exists():
print(f"Already have {target_date.strftime('%Y-%m-%d')}, skipping")
return True

return download_and_extract(target_date, raw_dir, tmp_dir)


def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument("--execution-date", default=None)
parser.add_argument("--start-date", default=None)
parser.add_argument("--end-date", default=None)
parser.add_argument("--out", default=str(DEFAULT_BASE_DIR))
return parser.parse_args()


def main() -> None:
args = parse_args()
base_dir = Path(args.out).resolve()

if args.start_date:
start_date = datetime.strptime(args.start_date, "%Y-%m-%d")
if args.end_date:
end_date = datetime.strptime(args.end_date, "%Y-%m-%d")
elif args.execution_date:
end_date = target_date_for_execution(
datetime.strptime(args.execution_date, "%Y-%m-%d")
)
else:
end_date = datetime.today()
backfill_missing(start_date=start_date, end_date=end_date, base_dir=base_dir)
return

if args.execution_date:
execution_date = datetime.strptime(args.execution_date, "%Y-%m-%d")
ok = run_execution_date(execution_date=execution_date, base_dir=base_dir)
if not ok:
print("No new CENACE publication detected; stopping cleanly")
return

raise ValueError("Provide either --start-date or --execution-date")


if __name__ == "__main__":
main()
Empty file.
88 changes: 88 additions & 0 deletions src/data/cenace/utils/cenace_data.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import duckdb
import pandas as pd


@dataclass
class CENACEData:
base_path: Path
freq: str = "hourly"
h: int = 24
max_window_size: int = 24 * 90

def __post_init__(self) -> None:
self.base_path = Path(self.base_path)

def _date_to_partition(self, d: pd.Timestamp) -> Path:
return (
self.base_path
/ f"year={d.year:04d}"
/ f"month={d.month:02d}"
/ f"day={d.day:02d}"
/ "series.parquet"
)

def _paths_for_range(self, start: pd.Timestamp, end: pd.Timestamp) -> list[str]:
days = pd.date_range(start.normalize(), end.normalize(), freq="D")
paths = [self._date_to_partition(d) for d in days]
existing = [str(p) for p in paths if p.exists()]
if not existing:
raise FileNotFoundError(
f"No parquet files found between {start} and \
{end} under {self.base_path}"
Comment on lines +35 to +36

CopilotAIApr 15, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The FileNotFoundError message uses a line-continuation backslash inside the f-string, which will embed a newline and indentation spaces into the exception text. Format this as a single-line f-string (or use textwrap.dedent) so the error message is stable and readable.

Suggested change
f"No parquet files found between {start} and \
{end} under {self.base_path}"
f"No parquet files found between {start} and {end} under {self.base_path}"

Copilot uses AI. Check for mistakes.
)
return existing

def get_df(
self,
cutoff: str | pd.Timestamp,
max_window_size: int | None = None,
sort: bool = True,
) -> pd.DataFrame:
cutoff = pd.Timestamp(cutoff)
window = max_window_size or self.max_window_size
start = cutoff - pd.Timedelta(hours=window - 1)

paths = self._paths_for_range(start, cutoff)

query = f"""
SELECT unique_id, ds, y
FROM read_parquet({paths})
WHERE ds >= TIMESTAMP '{start}'
AND ds <= TIMESTAMP '{cutoff}'
"""

df = duckdb.sql(query).df()
df["ds"] = pd.to_datetime(df["ds"])
Comment on lines +50 to +60

CopilotAIApr 15, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DuckDB parquet reads are built via duckdb.sql(query) with read_parquet({paths}), where {paths} is a Python list repr. This is brittle (path escaping/backslashes on Windows, quoting, and no explicit INSTALL/LOAD parquet like other modules) and can break unexpectedly. Build a connection (duckdb.connect(':memory:')), INSTALL/LOAD parquet, and pass an explicit SQL list of Path(...).as_posix() strings (as done in GH Archive code) to make reads robust.

Copilot uses AI. Check for mistakes.

if sort:
df = df.sort_values(["unique_id", "ds"]).reset_index(drop=True)

return df

def get_actuals(
self, cutoff: str | pd.Timestamp, h: int | None = None
) -> pd.DataFrame:
cutoff = pd.Timestamp(cutoff)
horizon = h or self.h

start = cutoff + pd.Timedelta(hours=1)
end = cutoff + pd.Timedelta(hours=horizon)

paths = self._paths_for_range(start, end)

query = f"""
SELECT unique_id, ds, y
FROM read_parquet({paths})
WHERE ds >= TIMESTAMP '{start}'
AND ds <= TIMESTAMP '{end}'
"""

df = duckdb.sql(query).df()
df["ds"] = pd.to_datetime(df["ds"])
df = df.sort_values(["unique_id", "ds"]).reset_index(drop=True)
return df
Empty file.
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file addedsrc/data/cenace/__init__.py
Empty file.
48 changes: 48 additions & 0 deletions src/data/cenace/aggregate/core.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
from __future__ import annotations

import pandas as pd

from src.data.cenace.config import PROCESSED_CSV, PROCESSED_EVENTS_HOURLY_DIR

INPUT_CSV = PROCESSED_CSV
OUTPUT_ROOT = PROCESSED_EVENTS_HOURLY_DIR


def build_hourly_partitions() -> int:
df = pd.read_csv(INPUT_CSV)

df["ds"] = pd.to_datetime(df["ds"], errors="coerce")
df["y"] = pd.to_numeric(df["y"], errors="coerce")

df = df.dropna(subset=["unique_id", "ds", "y"]).copy()
df = df.sort_values(["unique_id", "ds"]).drop_duplicates(["unique_id", "ds"])

df["year"] = df["ds"].dt.year
df["month"] = df["ds"].dt.month
df["day"] = df["ds"].dt.day

OUTPUT_ROOT.mkdir(parents=True, exist_ok=True)

n_written = 0
for (year, month, day), part in df.groupby(["year", "month", "day"], sort=True):
part_dir = (
OUTPUT_ROOT / f"year={year:04d}" / f"month={month:02d}" / f"day={day:02d}"
)
part_dir.mkdir(parents=True, exist_ok=True)

out_path = part_dir / "series.parquet"
part[["unique_id", "ds", "y"]].to_parquet(out_path, index=False)

print(f"Saved: {out_path}")
n_written += 1

return n_written


def main() -> None:
n_written = build_hourly_partitions()
print(f"\nDone. Wrote {n_written} daily partitions.")


if __name__ == "__main__":
main()
15 changes: 15 additions & 0 deletions src/data/cenace/config.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
from __future__ import annotations

from pathlib import Path

ROOT = Path(__file__).resolve().parents[3]

DATA_ROOT = ROOT / "data" / "cenace"

TMP_DIR = DATA_ROOT / "tmp"
PROCESSED_DIR = DATA_ROOT / "processed"
PROCESSED_CSV = PROCESSED_DIR / "cenace.csv"

PROCESSED_EVENTS_HOURLY_DIR = DATA_ROOT / "processed-events" / "hourly"
FORECASTS_HOURLY_DIR = DATA_ROOT / "forecasts" / "hourly"
EVALUATIONS_HOURLY_DIR = DATA_ROOT / "evaluations" / "hourly"
169 changes: 169 additions & 0 deletions src/data/cenace/extract/core.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
from __future__ import annotations

import argparse
from datetime import datetime, timedelta
from pathlib import Path
import zipfile

import requests
from bs4 import BeautifulSoup

URL = "https://www.cenace.gob.mx/Paginas/SIM/Reportes/PreEnerServConMTR.aspx"

session = requests.Session()

HEADERS = {
"User-Agent": "Mozilla/5.0",
"Referer": URL,
"Origin": "https://www.cenace.gob.mx",
"Content-Type": "application/x-www-form-urlencoded",
}

# repo root = impermanent/
ROOT_DIR = Path(__file__).resolve().parents[4]
DEFAULT_BASE_DIR = ROOT_DIR / "data" / "cenace"


def target_date_for_execution(execution_date: datetime) -> datetime:
return execution_date + timedelta(days=1)


def raw_zip_path(date: datetime, raw_dir: Path) -> Path:
return raw_dir / f"{date.strftime('%Y%m%d')}.zip"


def get_form_state() -> dict[str, str]:
r = session.get(URL, headers=HEADERS)
r.raise_for_status()
soup = BeautifulSoup(r.text, "html.parser")

def get_value(name: str) -> str:
el = soup.find("input", {"name": name})
return el.get("value") if el else ""

return {
"__VIEWSTATE": get_value("__VIEWSTATE"),
"__VIEWSTATEGENERATOR": get_value("__VIEWSTATEGENERATOR"),
"__VIEWSTATEENCRYPTED": get_value("__VIEWSTATEENCRYPTED"),
"__EVENTVALIDATION": get_value("__EVENTVALIDATION"),
}


def download_and_extract(date: datetime, raw_dir: Path, tmp_dir: Path) -> bool:
date_str = date.strftime("%d/%m/%Y")
period_str = f"{date_str} - {date_str}"

state = get_form_state()

payload = {
"ctl00$ContentPlaceHolder1$ddlReporte": "362,325",
"ctl00$ContentPlaceHolder1$ddlPeriodicidad": "D",
"ctl00$ContentPlaceHolder1$ddlSistema": "SIN",
"ctl00$ContentPlaceHolder1$txtPeriodo": period_str,
"ctl00$ContentPlaceHolder1$hdfStartDateSelected": date_str,
"ctl00$ContentPlaceHolder1$hdfEndDateSelected": date_str,
"ctl00$ContentPlaceHolder1$btnDescargarZIP": "Descargar ZIP",
"__VIEWSTATE": state["__VIEWSTATE"],
"__VIEWSTATEGENERATOR": state["__VIEWSTATEGENERATOR"],
"__VIEWSTATEENCRYPTED": state["__VIEWSTATEENCRYPTED"],
"__EVENTVALIDATION": state["__EVENTVALIDATION"],
"__EVENTTARGET": "",
"__EVENTARGUMENT": "",
}

r = session.post(URL, data=payload, headers=HEADERS)
r.raise_for_status()

size = len(r.content)
print(f"{date_str} | {size} bytes")

if size < 10000:
print(f"Skipping {date_str}: file not published or response too small")
return False

raw_dir.mkdir(parents=True, exist_ok=True)
tmp_dir.mkdir(parents=True, exist_ok=True)

zip_path = raw_zip_path(date, raw_dir)

with open(zip_path, "wb") as f:
f.write(r.content)

with zipfile.ZipFile(zip_path, "r") as z:
z.extractall(tmp_dir)

return True


def backfill_missing(start_date: datetime, end_date: datetime, base_dir: Path) -> None:
raw_dir = base_dir / "raw"
tmp_dir = base_dir / "tmp"

current = start_date
while current <= end_date:
zip_path = raw_zip_path(current, raw_dir)
if zip_path.exists():
print(f"Already have {current.strftime('%Y-%m-%d')}, skipping")
else:
try:
ok = download_and_extract(current, raw_dir, tmp_dir)
if not ok:
print(f"Stopping at {current.strftime('%Y-%m-%d')}")
break
except Exception as e:
print(f"Error on {current.strftime('%Y-%m-%d')}: {e}")
break
current += timedelta(days=1)


def run_execution_date(execution_date: datetime, base_dir: Path) -> bool:
raw_dir = base_dir / "raw"
tmp_dir = base_dir / "tmp"
target_date = target_date_for_execution(execution_date)

zip_path = raw_zip_path(target_date, raw_dir)
if zip_path.exists():
print(f"Already have {target_date.strftime('%Y-%m-%d')}, skipping")
return True

return download_and_extract(target_date, raw_dir, tmp_dir)


def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument("--execution-date", default=None)
parser.add_argument("--start-date", default=None)
parser.add_argument("--end-date", default=None)
parser.add_argument("--out", default=str(DEFAULT_BASE_DIR))
return parser.parse_args()


def main() -> None:
args = parse_args()
base_dir = Path(args.out).resolve()

if args.start_date:
start_date = datetime.strptime(args.start_date, "%Y-%m-%d")
if args.end_date:
end_date = datetime.strptime(args.end_date, "%Y-%m-%d")
elif args.execution_date:
end_date = target_date_for_execution(
datetime.strptime(args.execution_date, "%Y-%m-%d")
)
else:
end_date = datetime.today()
backfill_missing(start_date=start_date, end_date=end_date, base_dir=base_dir)
return

if args.execution_date:
execution_date = datetime.strptime(args.execution_date, "%Y-%m-%d")
ok = run_execution_date(execution_date=execution_date, base_dir=base_dir)
if not ok:
print("No new CENACE publication detected; stopping cleanly")
return

raise ValueError("Provide either --start-date or --execution-date")


if __name__ == "__main__":
main()
Empty file.
88 changes: 88 additions & 0 deletions src/data/cenace/utils/cenace_data.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import duckdb
import pandas as pd


@dataclass
class CENACEData:
base_path: Path
freq: str = "hourly"
h: int = 24
max_window_size: int = 24 * 90

def __post_init__(self) -> None:
self.base_path = Path(self.base_path)

def _date_to_partition(self, d: pd.Timestamp) -> Path:
return (
self.base_path
/ f"year={d.year:04d}"
/ f"month={d.month:02d}"
/ f"day={d.day:02d}"
/ "series.parquet"
)

def _paths_for_range(self, start: pd.Timestamp, end: pd.Timestamp) -> list[str]:
days = pd.date_range(start.normalize(), end.normalize(), freq="D")
paths = [self._date_to_partition(d) for d in days]
existing = [str(p) for p in paths if p.exists()]
if not existing:
raise FileNotFoundError(
f"No parquet files found between {start} and \
{end} under {self.base_path}"
Comment on lines +35 to +36

CopilotAIApr 15, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The FileNotFoundError message uses a line-continuation backslash inside the f-string, which will embed a newline and indentation spaces into the exception text. Format this as a single-line f-string (or use textwrap.dedent) so the error message is stable and readable.

Suggested change
f"No parquet files found between {start} and \
{end} under {self.base_path}"
f"No parquet files found between {start} and {end} under {self.base_path}"

Copilot uses AI. Check for mistakes.
)
return existing

def get_df(
self,
cutoff: str | pd.Timestamp,
max_window_size: int | None = None,
sort: bool = True,
) -> pd.DataFrame:
cutoff = pd.Timestamp(cutoff)
window = max_window_size or self.max_window_size
start = cutoff - pd.Timedelta(hours=window - 1)

paths = self._paths_for_range(start, cutoff)

query = f"""
SELECT unique_id, ds, y
FROM read_parquet({paths})
WHERE ds >= TIMESTAMP '{start}'
AND ds <= TIMESTAMP '{cutoff}'
"""

df = duckdb.sql(query).df()
df["ds"] = pd.to_datetime(df["ds"])
Comment on lines +50 to +60

CopilotAIApr 15, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DuckDB parquet reads are built via duckdb.sql(query) with read_parquet({paths}), where {paths} is a Python list repr. This is brittle (path escaping/backslashes on Windows, quoting, and no explicit INSTALL/LOAD parquet like other modules) and can break unexpectedly. Build a connection (duckdb.connect(':memory:')), INSTALL/LOAD parquet, and pass an explicit SQL list of Path(...).as_posix() strings (as done in GH Archive code) to make reads robust.

Copilot uses AI. Check for mistakes.

if sort:
df = df.sort_values(["unique_id", "ds"]).reset_index(drop=True)

return df

def get_actuals(
self, cutoff: str | pd.Timestamp, h: int | None = None
) -> pd.DataFrame:
cutoff = pd.Timestamp(cutoff)
horizon = h or self.h

start = cutoff + pd.Timedelta(hours=1)
end = cutoff + pd.Timedelta(hours=horizon)

paths = self._paths_for_range(start, end)

query = f"""
SELECT unique_id, ds, y
FROM read_parquet({paths})
WHERE ds >= TIMESTAMP '{start}'
AND ds <= TIMESTAMP '{end}'
"""

df = duckdb.sql(query).df()
df["ds"] = pd.to_datetime(df["ds"])
df = df.sort_values(["unique_id", "ds"]).reset_index(drop=True)
return df
Empty file.
Loading
Loading