diff --git a/data_sources/infonieve_historical.py b/data_sources/infonieve_historical.py index 7182357..719e6e0 100644 --- a/data_sources/infonieve_historical.py +++ b/data_sources/infonieve_historical.py @@ -17,6 +17,7 @@ and stores the combined raw history in SQLite. import io import logging import time +from datetime import date, timedelta from pathlib import Path import pandas as pd @@ -47,6 +48,49 @@ _USER_AGENT = ( ) +def _normalise_history_dates( + df: pd.DataFrame, + *, + cutoff_date: date | None = None, +) -> pd.DataFrame: + """Parse Infonieve ISO dates strictly and drop future placeholder rows. + + Infonieve's historical TSV currently emits ISO-formatted dates + (``YYYY-MM-DD``), but it also includes future rows for the active season. + Those future rows are not valid training labels and must be excluded. + + Parameters + ---------- + df: + Raw DataFrame containing a ``date`` column from the TSV endpoint. + cutoff_date: + Maximum date to keep. Defaults to yesterday so the historical station + table stays aligned with the weather archive range. + """ + payload = df.copy() + payload["date"] = pd.to_datetime( + payload["date"], + format="%Y-%m-%d", + errors="raise", + ) + + if cutoff_date is None: + cutoff_date = date.today() - timedelta(days=1) + + cutoff_ts = pd.Timestamp(cutoff_date) + original_len = len(payload) + payload = payload[payload["date"] <= cutoff_ts].copy() + dropped = original_len - len(payload) + if dropped > 0: + logger.info( + "Dropped %d future station rows after %s from Infonieve history.", + dropped, + cutoff_ts.date().isoformat(), + ) + + return payload + + def download_season( station_id: str, infonieve_id: int, year: int, session: requests.Session ) -> pd.DataFrame | None: @@ -138,9 +182,9 @@ def download_all_history(store: SQLiteStore | None = None) -> pd.DataFrame: combined = pd.concat(all_frames, ignore_index=True) - # Normalize the date column - if "date" in combined.columns: - combined["date"] = pd.to_datetime(combined["date"], format="mixed", dayfirst=True) + # Infonieve currently returns ISO dates, but also emits future rows for + # the active season. Keep only complete historical days. + combined = _normalise_history_dates(combined) # Sort combined = combined.sort_values(["station_id", "date"]).reset_index(drop=True) diff --git a/scripts/build_full_dataset.py b/scripts/build_full_dataset.py index 3c022f1..cb9332f 100644 --- a/scripts/build_full_dataset.py +++ b/scripts/build_full_dataset.py @@ -84,8 +84,26 @@ def load_station_data(store: SQLiteStore) -> pd.DataFrame: else: logger.info("Loaded %d historical station rows from SQLite.", len(df)) - # Parse dates with mixed formats (ISO and day-first variants) - df["date"] = pd.to_datetime(df["date"], format="mixed", dayfirst=True) + # Historical station data is stored in SQLite as ISO dates. + if not pd.api.types.is_datetime64_any_dtype(df["date"]): + df["date"] = pd.to_datetime( + df["date"], + format="%Y-%m-%d", + errors="raise", + ) + + # Keep station history aligned with the weather archive, which is fetched + # only up to the last complete day. + cutoff_ts = pd.Timestamp(date.today() - timedelta(days=1)) + original_len = len(df) + df = df[df["date"] <= cutoff_ts].copy() + dropped = original_len - len(df) + if dropped > 0: + logger.info( + "Dropped %d station rows after %s while building the dataset.", + dropped, + cutoff_ts.date().isoformat(), + ) # ---------- open_status ---------- # idestado=1: open (normal operation) diff --git a/tests/test_infonieve_historical.py b/tests/test_infonieve_historical.py new file mode 100644 index 0000000..973713a --- /dev/null +++ b/tests/test_infonieve_historical.py @@ -0,0 +1,48 @@ +"""Regression tests for Infonieve historical date normalization.""" + +from __future__ import annotations + +from datetime import date + +import pandas as pd + +from data_sources.infonieve_historical import _normalise_history_dates + + +def test_normalise_history_dates_keeps_iso_dates_in_place(): + """ISO dates must not be reinterpreted as day-first variants.""" + df = pd.DataFrame( + { + "date": ["2026-04-10", "2026-04-11", "2026-04-12", "2026-05-09"], + "station_id": ["pajares"] * 4, + } + ) + + normalised = _normalise_history_dates( + df, + cutoff_date=date(2026, 5, 9), + ) + + assert normalised["date"].dt.strftime("%Y-%m-%d").tolist() == [ + "2026-04-10", + "2026-04-11", + "2026-04-12", + "2026-05-09", + ] + + +def test_normalise_history_dates_drops_future_rows(): + """Rows after the cutoff must be excluded from the historical dataset.""" + df = pd.DataFrame( + { + "date": ["2026-03-12", "2026-03-13", "2026-03-14", "2026-05-09"], + "station_id": ["sanisidro"] * 4, + } + ) + + normalised = _normalise_history_dates( + df, + cutoff_date=date(2026, 3, 12), + ) + + assert normalised["date"].dt.strftime("%Y-%m-%d").tolist() == ["2026-03-12"]