feat: initial ski predictor system

Hybrid ML + rules prediction system for 3 Asturian ski stations
(Pajares, San Isidro, Fuentes de Invierno).

- Weather data from Open-Meteo (historical + forecast)
- Station scraping from infonieve.es (live + 16 seasons historical TSV)
- Feature engineering: rolling snow, calendar, temperature/pressure trends
- ML models: RandomForest (open/close), GradientBoosting (km), LightGBM (crowd)
- Rules engine: wind closure, snow depth, rain+heat, heavy snow
- YOLOv8 webcam crowd detection (cars, people in parking/lifts)
- Telegram bot with /pajares, /sanisidro, /fuentes commands
- Daily cron pipeline for automated data collection and predictions
- Deployment guide with systemd service and cron setup
This commit is contained in:
dasemu committed 2026-03-12 14:51:32 +01:00
commit 1afe2b73e0
34 files changed
+7201

No files matched your search

+1
View File
@@ -0,0 +1 @@
"""Scripts package for ski predictor automation tasks."""
+430
View File
@@ -0,0 +1,430 @@
"""Build the full historical dataset by merging station data with weather.
Steps:
1. Load historical station CSV from infonieve.es (data/raw/station_historical_all.csv)
2. Map infonieve columns to the project schema
3. Fetch historical weather from Open-Meteo for 2009-2026 in 1-year chunks
4. Merge weather + station data on (date, station_id)
5. Run feature engineering
6. Save to data/processed/dataset_featured.csv
7. Train ML models
Column mapping from infonieve schema to project schema:
closedflag / idestado -> open_status (1=open, 0=closed)
kmopen -> km_open
pistasopen -> lifts_open (actually slopes, but matches schema)
espesormax -> snow_depth
calidadnieve -> snow_quality
pistasopen/pistastotal ratio -> crowd_level (low/medium/high)
open_status + km_open -> station_open (ML target alias)
"""
import logging
import sys
import time
from datetime import date
from pathlib import Path
import pandas as pd
# ---------------------------------------------------------------------------
# Path setup - add repo root to sys.path so project modules are importable
# ---------------------------------------------------------------------------
REPO_ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(REPO_ROOT))
from data_sources.weather_api import WeatherCollector
from pipeline.feature_engineering import FeatureEngineer
from ml.train_model import ModelTrainer
# ---------------------------------------------------------------------------
# Logging
# ---------------------------------------------------------------------------
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
)
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
STATION_CSV = REPO_ROOT / "data" / "raw" / "station_historical_all.csv"
OUTPUT_DIR = REPO_ROOT / "data" / "processed"
OUTPUT_PATH = OUTPUT_DIR / "dataset_featured.csv"
# Weather fetch range - driven by what is in the station data
WEATHER_START_YEAR = 2009
WEATHER_END_YEAR = 2026 # inclusive
# Crowd level thresholds based on pistas open / pistas total ratio
CROWD_LOW_THRESHOLD = 0.33
CROWD_HIGH_THRESHOLD = 0.67
# Station coordinates from config/stations.yaml
STATIONS = {
"fuentes": {"latitude": 43.0833, "longitude": -5.9333},
"pajares": {"latitude": 43.0500, "longitude": -5.7700},
"sanisidro": {"latitude": 43.0700, "longitude": -5.3700},
}
# Delay between API calls to avoid rate-limiting (seconds)
API_CALL_DELAY = 3.0
# Extra pause between stations (seconds)
INTER_STATION_DELAY = 10.0
# Local cache directory for per-year weather chunks
WEATHER_CACHE_DIR = REPO_ROOT / "data" / "raw" / "weather_cache"
# ---------------------------------------------------------------------------
# Step 1: Load and map station data
# ---------------------------------------------------------------------------
def load_station_data() -> pd.DataFrame:
"""Load the infonieve historical CSV and map columns to project schema."""
logger.info("Loading station data from %s", STATION_CSV)
df = pd.read_csv(STATION_CSV)
logger.info("Loaded %d rows, %d columns", len(df), len(df.columns))
# Parse dates with mixed formats (ISO and day-first variants)
df["date"] = pd.to_datetime(df["date"], format="mixed", dayfirst=True)
# ---------- open_status ----------
# idestado=1: open (normal operation)
# idestado=4: open (special/summer operation, some km data present)
# idestado=0: closed (no operation that day)
# idestado=2: off-season (not yet / no longer open)
# idestado=3: temporarily closed (weather/maintenance)
# Best signal: station is open if kmopen > 0, else use idestado
df["open_status"] = 0
has_km_data = df["kmopen"].notna() & (df["kmopen"] > 0)
df.loc[has_km_data, "open_status"] = 1
# Also mark idestado=1 rows where kmopen may be missing as open
df.loc[(df["idestado"] == 1.0) & ~has_km_data, "open_status"] = 1
# station_open is the ML binary classification target (same as open_status)
df["station_open"] = df["open_status"]
# ---------- km_open ----------
df["km_open"] = pd.to_numeric(df["kmopen"], errors="coerce")
# ---------- lifts_open (slopes in this dataset) ----------
df["lifts_open"] = pd.to_numeric(df["pistasopen"], errors="coerce")
# ---------- snow_depth ----------
df["snow_depth"] = pd.to_numeric(df["espesormax"], errors="coerce")
# ---------- snow_quality ----------
df["snow_quality"] = df["calidadnieve"].astype(str)
df.loc[df["snow_quality"] == "nan", "snow_quality"] = None
# ---------- crowd_level ----------
# Derived from fraction of slopes open vs total available
pistastotal = pd.to_numeric(df["pistastotal"], errors="coerce")
pistasopen = pd.to_numeric(df["pistasopen"], errors="coerce")
ratio = pistasopen / pistastotal.replace(0, float("nan"))
crowd = pd.Series(index=df.index, dtype="object")
crowd[ratio < CROWD_LOW_THRESHOLD] = "low"
crowd[(ratio >= CROWD_LOW_THRESHOLD) & (ratio < CROWD_HIGH_THRESHOLD)] = "medium"
crowd[ratio >= CROWD_HIGH_THRESHOLD] = "high"
# Only assign crowd_level when the station is open
df["crowd_level"] = None
df.loc[df["open_status"] == 1, "crowd_level"] = crowd[df["open_status"] == 1]
# Keep only the columns needed for merging
keep = [
"date", "station_id",
"open_status", "station_open",
"km_open", "lifts_open",
"snow_depth", "snow_quality",
"crowd_level",
]
result = df[keep].copy()
result = result.sort_values(["station_id", "date"]).reset_index(drop=True)
logger.info(
"Station data mapped. Open rows: %d / %d",
(result["open_status"] == 1).sum(),
len(result),
)
logger.info(
"crowd_level distribution:\n%s",
result["crowd_level"].value_counts(),
)
return result
# ---------------------------------------------------------------------------
# Step 2: Fetch historical weather in 1-year chunks
# ---------------------------------------------------------------------------
def _cache_path(station_id: str, year: int) -> Path:
"""Return the local cache file path for a (station, year) chunk."""
return WEATHER_CACHE_DIR / f"weather_{station_id}_{year}.csv"
def fetch_weather_all_stations() -> pd.DataFrame:
"""Fetch full historical weather for all stations in annual chunks.
Each (station, year) chunk is cached to
``data/raw/weather_cache/weather_{station_id}_{year}.csv``.
If the cache file already exists the API call is skipped, making
reruns fast and avoiding rate-limit exhaustion.
The current year's cache is always refreshed (partial year grows daily).
"""
WEATHER_CACHE_DIR.mkdir(parents=True, exist_ok=True)
collector = WeatherCollector()
all_frames: list[pd.DataFrame] = []
today = date.today()
end_year = min(WEATHER_END_YEAR, today.year)
for station_id, coords in STATIONS.items():
lat = coords["latitude"]
lon = coords["longitude"]
station_frames: list[pd.DataFrame] = []
needs_api_call = False
for year in range(WEATHER_START_YEAR, end_year + 1):
cache_file = _cache_path(station_id, year)
start_date = f"{year}-01-01"
# For the current partial year always refresh the cache
is_current_year = year == today.year
if cache_file.exists() and not is_current_year:
logger.info(
"Cache hit: %s (skipping API call)", cache_file.name
)
df = pd.read_csv(cache_file)
df["date"] = pd.to_datetime(df["date"])
station_frames.append(df)
continue
# For the current year, only fetch up to yesterday
if is_current_year:
from datetime import timedelta
yesterday = today - timedelta(days=1)
end_date = yesterday.strftime("%Y-%m-%d")
else:
end_date = f"{year}-12-31"
logger.info(
"Fetching weather for station=%s year=%d (%s to %s)",
station_id, year, start_date, end_date,
)
needs_api_call = True
try:
df = collector.get_historical(
station_id=station_id,
lat=lat,
lon=lon,
start_date=start_date,
end_date=end_date,
)
if not df.empty:
df["date"] = pd.to_datetime(df["date"])
# Save to per-year cache (not the rolling weather_X_today.csv)
df.to_csv(cache_file, index=False)
logger.info(
" -> Got %d rows; cached to %s",
len(df), cache_file.name,
)
station_frames.append(df)
except RuntimeError as exc:
logger.error(
"Weather fetch failed for station=%s year=%d: %s",
station_id, year, exc,
)
# Be polite to the API between calls
time.sleep(API_CALL_DELAY)
if station_frames:
combined = pd.concat(station_frames, ignore_index=True)
combined["date"] = pd.to_datetime(combined["date"])
combined.drop_duplicates(subset=["date", "station_id"], inplace=True)
combined.sort_values("date", inplace=True)
all_frames.append(combined)
logger.info(
"Total weather rows for %s: %d", station_id, len(combined)
)
if needs_api_call:
# Only pause if we actually made API calls for this station
logger.info("Pausing %ds before next station.", INTER_STATION_DELAY)
time.sleep(INTER_STATION_DELAY)
if not all_frames:
raise RuntimeError("No weather data fetched for any station.")
weather = pd.concat(all_frames, ignore_index=True)
weather["date"] = pd.to_datetime(weather["date"])
logger.info("Total weather rows across all stations: %d", len(weather))
return weather
# ---------------------------------------------------------------------------
# Step 3: Merge weather + station data
# ---------------------------------------------------------------------------
def merge_datasets(
weather_df: pd.DataFrame,
station_df: pd.DataFrame,
) -> pd.DataFrame:
"""Outer-merge weather and station frames on (date, station_id)."""
logger.info(
"Merging weather (%d rows) with station (%d rows).",
len(weather_df), len(station_df),
)
# Normalise date type for both frames before merging
weather_df = weather_df.copy()
station_df = station_df.copy()
weather_df["date"] = pd.to_datetime(weather_df["date"])
station_df["date"] = pd.to_datetime(station_df["date"])
merged = pd.merge(
weather_df,
station_df,
on=["date", "station_id"],
how="outer",
)
merged = merged.sort_values(["station_id", "date"]).reset_index(drop=True)
logger.info("Merged dataset shape: %s", merged.shape)
return merged
# ---------------------------------------------------------------------------
# Step 4: Feature engineering
# ---------------------------------------------------------------------------
def run_feature_engineering(df: pd.DataFrame) -> pd.DataFrame:
"""Apply the standard feature engineering pipeline."""
logger.info("Running feature engineering on %d rows.", len(df))
engineer = FeatureEngineer()
featured = engineer.transform(df)
logger.info(
"Feature engineering complete. Output shape: %s", featured.shape
)
return featured
# ---------------------------------------------------------------------------
# Step 5: Save
# ---------------------------------------------------------------------------
def save_dataset(df: pd.DataFrame) -> None:
"""Persist the featured dataset to disk."""
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
df.to_csv(OUTPUT_PATH, index=False)
logger.info("Featured dataset saved to %s (%d rows)", OUTPUT_PATH, len(df))
# ---------------------------------------------------------------------------
# Step 6: Summary statistics
# ---------------------------------------------------------------------------
def print_summary(df: pd.DataFrame) -> None:
"""Print summary statistics about the final dataset."""
print("\n" + "=" * 60)
print("DATASET SUMMARY")
print("=" * 60)
print(f"Total rows: {len(df):,}")
print(f"Total columns: {len(df.columns)}")
print(f"Date range: {df['date'].min().date()} to {df['date'].max().date()}")
print(f"Stations: {sorted(df['station_id'].unique())}")
print()
print("Rows per station:")
for sid, count in df.groupby("station_id").size().items():
print(f" {sid}: {count:,}")
print()
if "station_open" in df.columns:
open_rows = df["station_open"].notna()
total_labeled = open_rows.sum()
open_count = (df.loc[open_rows, "station_open"] == 1).sum()
closed_count = (df.loc[open_rows, "station_open"] == 0).sum()
print(f"station_open labels: {total_labeled:,} total")
print(f" open: {open_count:,} ({100*open_count/total_labeled:.1f}%)")
print(f" closed: {closed_count:,} ({100*closed_count/total_labeled:.1f}%)")
print()
if "crowd_level" in df.columns:
crowd_dist = df["crowd_level"].value_counts()
print("crowd_level distribution:")
for level, cnt in crowd_dist.items():
print(f" {level}: {cnt:,}")
print()
if "km_open" in df.columns:
km = df["km_open"].dropna()
print(f"km_open stats (non-null, n={len(km):,}):")
print(f" mean={km.mean():.2f} median={km.median():.2f} "
f"min={km.min():.2f} max={km.max():.2f}")
print()
if "snow_depth" in df.columns:
sd = df["snow_depth"].dropna()
print(f"snow_depth stats (non-null, n={len(sd):,}):")
print(f" mean={sd.mean():.1f}cm max={sd.max():.1f}cm")
print()
missing_pct = 100 * df.isnull().sum() / len(df)
high_missing = missing_pct[missing_pct > 20].sort_values(ascending=False)
if not high_missing.empty:
print("Columns with >20% missing values:")
for col, pct in high_missing.items():
print(f" {col}: {pct:.1f}%")
else:
print("No columns with >20% missing values.")
print("=" * 60 + "\n")
# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------
def main() -> None:
logger.info("Starting full dataset build pipeline.")
# Step 1: Load and map station data
station_df = load_station_data()
# Step 2: Fetch historical weather
weather_df = fetch_weather_all_stations()
# Step 3: Merge
merged = merge_datasets(weather_df, station_df)
# Step 4: Feature engineering
featured = run_feature_engineering(merged)
# Step 5: Save
save_dataset(featured)
# Step 6: Summary
print_summary(featured)
# Step 7: Train models
logger.info("Starting model training on the full dataset.")
trainer = ModelTrainer(dataset_path=OUTPUT_PATH)
cv_results = trainer.train_all()
print("\nCROSS-VALIDATION RESULTS")
print("=" * 60)
for target, scores in cv_results.items():
print(f"\n {target}:")
for metric, value in scores.items():
print(f" {metric}: {value:.4f}")
print("=" * 60)
logger.info("Pipeline complete.")
if __name__ == "__main__":
main()
+267
View File
@@ -0,0 +1,267 @@
"""Daily data collection pipeline for the ski predictor.
This script is designed for cron execution. It runs every day to:
1. Collect weather forecasts for all configured stations.
2. Collect current station operational status.
3. Append new rows to the processed dataset.
4. Run feature engineering on the updated dataset.
5. Generate predictions for the next day using the HybridPredictor.
6. Save the predictions to data/processed/predictions_latest.json.
Cron example (run daily at 20:00, after stations close):
0 20 * * * /path/to/.venv/bin/python /path/to/scripts/collect_daily_data.py
Exit codes:
0 - Pipeline completed (partial failures are logged but do not abort).
1 - Fatal error that prevented any useful work.
"""
import json
import logging
import sys
from datetime import date, datetime, timedelta, timezone
from pathlib import Path
import pandas as pd
# ---------------------------------------------------------------------------
# Ensure the project root is on sys.path so all project packages are
# importable when this script is executed directly (e.g. via cron or CLI).
# ---------------------------------------------------------------------------
_SCRIPT_DIR = Path(__file__).resolve().parent
_PROJECT_ROOT = _SCRIPT_DIR.parent
if str(_PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(_PROJECT_ROOT))
from data_sources.weather_api import WeatherCollector
from data_sources.station_scraper import StationScraper
from pipeline.build_dataset import DatasetBuilder
from pipeline.feature_engineering import FeatureEngineer
from predictor.hybrid_predictor import HybridPredictor
# ---------------------------------------------------------------------------
# Logging setup
# ---------------------------------------------------------------------------
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)-8s %(name)s - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# Output paths
# ---------------------------------------------------------------------------
_PROCESSED_DIR = _PROJECT_ROOT / "data" / "processed"
_DATASET_PATH = _PROCESSED_DIR / "dataset.csv"
_FEATURED_PATH = _PROCESSED_DIR / "dataset_featured.csv"
_PREDICTIONS_PATH = _PROCESSED_DIR / "predictions_latest.json"
# ---------------------------------------------------------------------------
# Pipeline steps
# ---------------------------------------------------------------------------
def collect_weather(collector: WeatherCollector) -> dict[str, pd.DataFrame]:
"""Fetch weather forecasts for all stations."""
logger.info("Step 1/5 - Collecting weather forecasts.")
results = {}
for station_id, cfg in collector.stations.items():
try:
df = collector.get_forecast(station_id, cfg["latitude"], cfg["longitude"])
results[station_id] = df
logger.info("Weather forecast: station=%s, %d rows.", station_id, len(df))
except Exception as exc:
logger.error("Weather failed for %s: %s", station_id, exc)
return results
def collect_station_status(scraper: StationScraper) -> list[dict]:
"""Scrape current operational status for all stations."""
logger.info("Step 2/5 - Collecting station status.")
records = []
for station_id in scraper._stations:
try:
record = scraper.scrape_station(station_id)
records.append(record)
logger.info(
"Station status: %s open=%s km=%s depth=%s",
station_id, record.get("open_status"),
record.get("km_open"), record.get("snow_depth"),
)
except Exception as exc:
logger.error("Scraping failed for %s: %s", station_id, exc)
return records
def append_to_dataset(
builder: DatasetBuilder,
weather_by_station: dict[str, pd.DataFrame],
station_records: list[dict],
) -> pd.DataFrame:
"""Append today's data to the processed dataset."""
logger.info("Step 3/5 - Appending data to dataset.")
station_map = {r["station_id"]: r for r in station_records}
today = date.today()
for station_id, weather_df in weather_by_station.items():
station_record = station_map.get(station_id)
if station_record is None:
logger.warning("No station record for %s, skipping.", station_id)
continue
# Use today's forecast row for the weather data
today_rows = weather_df[weather_df["date"] == today]
if today_rows.empty:
# Fallback to first available row
today_rows = weather_df.head(1)
weather_row = today_rows.iloc[0].to_dict()
try:
builder.append_daily(weather_data=weather_row, station_data=station_record)
logger.info("Dataset updated for %s.", station_id)
except Exception as exc:
logger.error("Append failed for %s: %s", station_id, exc)
# Return the current dataset
if _DATASET_PATH.exists():
df = pd.read_csv(_DATASET_PATH)
df["date"] = pd.to_datetime(df["date"])
return df
return pd.DataFrame()
def run_feature_engineering(engineer: FeatureEngineer, df: pd.DataFrame) -> pd.DataFrame:
"""Run feature engineering on the dataset."""
logger.info("Step 4/5 - Running feature engineering.")
if df.empty:
logger.warning("Empty dataset, skipping feature engineering.")
return df
featured = engineer.transform(df)
_PROCESSED_DIR.mkdir(parents=True, exist_ok=True)
featured.to_csv(_FEATURED_PATH, index=False)
logger.info("Featured dataset saved: %d rows, %d cols.", len(featured), len(featured.columns))
return featured
def generate_predictions(
predictor: HybridPredictor,
weather_by_station: dict[str, pd.DataFrame],
featured_df: pd.DataFrame,
station_records: list[dict],
) -> None:
"""Generate next-day predictions and save to disk."""
logger.info("Step 5/5 - Generating predictions.")
tomorrow = date.today() + timedelta(days=1)
predictions = {}
station_map = {r["station_id"]: r for r in station_records}
for station_id, weather_df in weather_by_station.items():
# Get tomorrow's forecast row as weather_data dict
tomorrow_rows = weather_df[weather_df["date"] == tomorrow]
if tomorrow_rows.empty:
tomorrow_rows = weather_df.iloc[1:2]
if tomorrow_rows.empty:
logger.warning("No forecast for tomorrow for %s.", station_id)
continue
weather_data = tomorrow_rows.iloc[0].to_dict()
# Build a feature row: tomorrow's weather + today's station data
# (lifts_open, snow_depth are current observations - best proxy for tomorrow)
features_df = None
if not featured_df.empty:
station_featured = featured_df[featured_df["station_id"] == station_id]
if not station_featured.empty:
# Start from the latest featured row (has rolling features)
features_df = station_featured.tail(1).copy()
# Overlay tomorrow's weather
for col in weather_data:
if col in features_df.columns and col not in ("date", "station_id"):
features_df[col] = weather_data[col]
# Overlay today's station data as best proxy
station_rec = station_map.get(station_id, {})
if station_rec.get("snow_depth") is not None:
features_df["snow_depth"] = station_rec["snow_depth"]
if station_rec.get("lifts_open") is not None:
features_df["lifts_open"] = station_rec["lifts_open"]
# Also inject snow_depth into weather_data for the rules engine
station_rec = station_map.get(station_id, {})
if station_rec.get("snow_depth") is not None:
weather_data["snow_depth"] = station_rec["snow_depth"]
try:
result = predictor.predict(station_id, weather_data, features_df)
predictions[station_id] = result
logger.info(
"Prediction for %s: open=%.2f, km=%.1f, crowd=%s, source=%s",
station_id,
result["open_probability"],
result["km_open"],
result["crowd_level"],
result["prediction_source"],
)
except Exception as exc:
logger.error("Prediction failed for %s: %s", station_id, exc)
# Save predictions
_PREDICTIONS_PATH.parent.mkdir(parents=True, exist_ok=True)
output = {
"generated_at": datetime.now(timezone.utc).isoformat(),
"prediction_date": tomorrow.isoformat(),
"stations": predictions,
}
with open(_PREDICTIONS_PATH, "w", encoding="utf-8") as fh:
json.dump(output, fh, indent=2, ensure_ascii=False, default=str)
logger.info("Predictions saved to %s.", _PREDICTIONS_PATH)
# ---------------------------------------------------------------------------
# Main entry point
# ---------------------------------------------------------------------------
def main() -> int:
"""Run the full daily data collection and prediction pipeline."""
logger.info("=== Daily pipeline started ===")
try:
weather_collector = WeatherCollector()
station_scraper = StationScraper()
dataset_builder = DatasetBuilder()
feature_engineer = FeatureEngineer()
hybrid_predictor = HybridPredictor()
except Exception as exc:
logger.critical("Failed to initialise components: %s", exc, exc_info=True)
return 1
# Steps 1-2: collect data
weather_data = collect_weather(weather_collector)
station_records = collect_station_status(station_scraper)
if not weather_data and not station_records:
logger.error("No data collected. Aborting.")
return 1
# Step 3: append to dataset
df = append_to_dataset(dataset_builder, weather_data, station_records)
# Step 4: feature engineering
featured_df = run_feature_engineering(feature_engineer, df)
# Step 5: predictions
generate_predictions(hybrid_predictor, weather_data, featured_df, station_records)
logger.info("=== Daily pipeline finished ===")
return 0
if __name__ == "__main__":
sys.exit(main())
+200
View File
@@ -0,0 +1,200 @@
"""Model retraining script for the ski predictor.
Loads the latest processed and feature-engineered dataset, trains all
configured ML models (RandomForest, GradientBoosting, LightGBM) for each
target variable, evaluates them, and logs metrics.
Usage:
python scripts/retrain_model.py
The trained models are persisted to ml/models/ by the training module.
Exit codes:
0 - Training and evaluation completed successfully.
1 - Fatal error prevented any training.
"""
import logging
import sys
from datetime import datetime
from pathlib import Path
# ---------------------------------------------------------------------------
# Ensure the project root is on sys.path so all project packages are importable
# when this script is executed directly.
# ---------------------------------------------------------------------------
_SCRIPT_DIR = Path(__file__).resolve().parent
_PROJECT_ROOT = _SCRIPT_DIR.parent
if str(_PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(_PROJECT_ROOT))
from pipeline.feature_engineering import FeatureEngineer
from ml.train_model import ModelTrainer
from ml.evaluate_model import ModelEvaluator
# ---------------------------------------------------------------------------
# Logging setup
# ---------------------------------------------------------------------------
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)-8s %(name)s - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# Dataset path
# ---------------------------------------------------------------------------
_PROCESSED_DIR = _PROJECT_ROOT / "data" / "processed"
_FEATURES_DATASET_PATH = _PROCESSED_DIR / "dataset_features.csv"
_DATASET_PATH = _PROCESSED_DIR / "dataset.csv"
# ---------------------------------------------------------------------------
# Retraining steps
# ---------------------------------------------------------------------------
def load_feature_dataset():
"""Load the feature-engineered dataset from disk.
Falls back to running feature engineering on the base dataset when the
features file does not exist yet.
Returns
-------
pandas.DataFrame
Feature-engineered dataset ready for ML training.
Raises
------
FileNotFoundError
When neither the features dataset nor the base dataset is found.
RuntimeError
When feature engineering fails unexpectedly.
"""
import pandas as pd
if _FEATURES_DATASET_PATH.exists():
logger.info("Loading features dataset from %s.", _FEATURES_DATASET_PATH)
df = pd.read_csv(_FEATURES_DATASET_PATH)
logger.info("Loaded %d rows.", len(df))
return df
logger.warning(
"Features dataset not found at %s. Running feature engineering first.",
_FEATURES_DATASET_PATH,
)
if not _DATASET_PATH.exists():
raise FileNotFoundError(
f"Base dataset not found at {_DATASET_PATH}. "
"Run collect_daily_data.py or pipeline/build_dataset.py first."
)
engineer = FeatureEngineer()
df = engineer.run()
logger.info("Feature engineering produced %d rows.", len(df))
return df
def train_models(df) -> dict:
"""Train all models on the provided feature dataset.
Parameters
----------
df:
Feature-engineered DataFrame with target columns present.
Returns
-------
dict
Mapping of target variable name to fitted model objects, as returned
by ModelTrainer.train_all().
"""
logger.info("Starting model training.")
trainer = ModelTrainer()
trained_models = trainer.train_all(df)
logger.info(
"Training complete. Models trained for targets: %s.",
list(trained_models.keys()),
)
return trained_models
def evaluate_models(trained_models: dict, df) -> dict:
"""Evaluate trained models and log per-target metrics.
Parameters
----------
trained_models:
Output of :func:`train_models`.
df:
Feature-engineered DataFrame used for evaluation (held-out split is
managed internally by ModelEvaluator).
Returns
-------
dict
Nested dict of {target: {model_name: {metric: value}}}.
"""
logger.info("Evaluating trained models.")
evaluator = ModelEvaluator()
metrics = evaluator.evaluate_all(trained_models, df)
for target, model_metrics in metrics.items():
for model_name, scores in model_metrics.items():
metric_str = " ".join(f"{k}={v:.4f}" for k, v in scores.items())
logger.info("[%s] %s -> %s", target, model_name, metric_str)
return metrics
# ---------------------------------------------------------------------------
# Main entry point
# ---------------------------------------------------------------------------
def main() -> int:
"""Run the full retraining pipeline.
Returns
-------
int
Exit code: 0 on success, 1 on fatal error.
"""
logger.info("=== Model retraining started at %s ===", datetime.utcnow().isoformat())
try:
df = load_feature_dataset()
except FileNotFoundError as exc:
logger.critical("Dataset not found: %s.", exc)
return 1
except Exception as exc:
logger.critical("Failed to load dataset: %s.", exc, exc_info=True)
return 1
if df.empty:
logger.critical("Dataset is empty. Cannot train models.")
return 1
try:
trained_models = train_models(df)
except Exception as exc:
logger.critical("Training failed: %s.", exc, exc_info=True)
return 1
try:
evaluate_models(trained_models, df)
except Exception as exc:
# Evaluation failure is non-fatal; models are already saved.
logger.error("Evaluation failed: %s. Models were still saved.", exc, exc_info=True)
logger.info("=== Model retraining finished successfully. ===")
return 0
if __name__ == "__main__":
sys.exit(main())