fix(data): normalize station history dates

This commit is contained in:
dasemu committed 2026-03-13 08:45:00 +01:00
1 parent 2a34054399
commit 04eb0fde61
3 files changed
+115 -5

No files matched your search

+47 -3
View File
@@ -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)
+20 -2
View File
@@ -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)
+48
View File
@@ -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"]