Download src/data_validator.py from Hamza4100/sales-forecasting-dashboard: direct link, hf CLI and curl.
- Browser
- Download file 5.2 kB
-
https://huggingface.co/spaces/Hamza4100/sales-forecasting-dashboard/resolve/main/src/data_validator.py
- Command line
-
hf download hf://spaces/Hamza4100/sales-forecasting-dashboard/src/data_validator.py
-
curl -L -o data_validator.py https://huggingface.co/spaces/Hamza4100/sales-forecasting-dashboard/resolve/main/src/data_validator.py
5.2 kB
| """ | |
| data_validator.py | |
| ----------------- | |
| Validates that a loaded dataframe is suitable for sales forecasting. | |
| """ | |
| from __future__ import annotations | |
| from typing import List, Tuple | |
| import pandas as pd | |
| from src.utils import robust_to_datetime | |
| def validate_dataset( | |
| df: pd.DataFrame, | |
| date_col: str, | |
| sales_col: str, | |
| ) -> Tuple[bool, List[str], List[str]]: | |
| """Validate a dataframe for use in sales forecasting. | |
| Checks performed | |
| ---------------- | |
| 1. *date_col* exists in ``df.columns``. | |
| 2. *sales_col* exists in ``df.columns``. | |
| 3. At least 80 % of *date_col* values parse to datetime. | |
| 4. At least 80 % of *sales_col* values parse to numeric. | |
| 5. The dataframe has ≥ 20 non-null rows after dropping nulls in both | |
| *date_col* and *sales_col*. | |
| 6. At least 5 unique dates are present. | |
| 7. The sales column is not all zeros. | |
| Parameters | |
| ---------- | |
| df : pd.DataFrame | |
| Raw (or lightly pre-processed) dataframe to validate. | |
| date_col : str | |
| Name of the column to use as the date axis. | |
| sales_col : str | |
| Name of the column to use as the sales target. | |
| Returns | |
| ------- | |
| is_valid : bool | |
| ``True`` only when **no errors** were found (warnings are tolerated). | |
| errors : list[str] | |
| Fatal problems that prevent forecasting. | |
| warnings : list[str] | |
| Non-fatal issues the user should be aware of. | |
| """ | |
| errors: List[str] = [] | |
| warnings: List[str] = [] | |
| # --- 1. Date column exists -------------------------------------------- | |
| if date_col not in df.columns: | |
| errors.append( | |
| f"Date column '{date_col}' not found in the dataset. " | |
| f"Available columns: {list(df.columns)}" | |
| ) | |
| # --- 2. Sales column exists ------------------------------------------- | |
| if sales_col not in df.columns: | |
| errors.append( | |
| f"Sales column '{sales_col}' not found in the dataset. " | |
| f"Available columns: {list(df.columns)}" | |
| ) | |
| # Short-circuit: remaining checks need both columns to be present. | |
| if errors: | |
| return False, errors, warnings | |
| # --- 3. Date column parsability (>= 80 %) ------------------------------ | |
| n_total = len(df) | |
| parsed_dates = robust_to_datetime(df[date_col]) | |
| date_parse_rate = parsed_dates.notna().sum() / max(n_total, 1) | |
| if date_parse_rate < 0.8: | |
| errors.append( | |
| f"Date column '{date_col}' could only be parsed for " | |
| f"{date_parse_rate:.0%} of rows (minimum required: 80 %). " | |
| "Please ensure it contains valid date values." | |
| ) | |
| elif date_parse_rate < 0.95: | |
| warnings.append( | |
| f"Date column '{date_col}' had {(1 - date_parse_rate):.1%} " | |
| "unparseable values; those rows will be dropped." | |
| ) | |
| # --- 4. Sales column parsability (>= 80 %) ----------------------------- | |
| sales_clean = df[sales_col] | |
| if sales_clean.dtype == object: | |
| sales_clean = sales_clean.astype(str).str.replace(r"[^\d.-]", "", regex=True) | |
| parsed_sales = pd.to_numeric(sales_clean, errors="coerce") | |
| sales_parse_rate = parsed_sales.notna().sum() / max(n_total, 1) | |
| if sales_parse_rate < 0.8: | |
| errors.append( | |
| f"Sales column '{sales_col}' could only be parsed to numeric for " | |
| f"{sales_parse_rate:.0%} of rows (minimum required: 80 %). " | |
| "Please ensure it contains valid numbers." | |
| ) | |
| elif sales_parse_rate < 0.95: | |
| warnings.append( | |
| f"Sales column '{sales_col}' had {(1 - sales_parse_rate):.1%} " | |
| "non-numeric values; those will be filled with the median." | |
| ) | |
| # --- 5. Minimum row count after dropping nulls ------------------------ | |
| valid_mask = parsed_dates.notna() & parsed_sales.notna() | |
| valid_rows = int(valid_mask.sum()) | |
| if valid_rows < 20: | |
| errors.append( | |
| f"Only {valid_rows} rows remain after removing null dates/sales values. " | |
| "At least 20 rows are required for meaningful forecasting." | |
| ) | |
| elif valid_rows < 50: | |
| warnings.append( | |
| f"Dataset has only {valid_rows} valid rows. Forecasts may be unreliable " | |
| "with fewer than 50 data points." | |
| ) | |
| # --- 6. Unique date count (>= 5) --------------------------------------- | |
| unique_dates = parsed_dates[valid_mask].nunique() | |
| if unique_dates < 5: | |
| errors.append( | |
| f"Only {unique_dates} unique dates found. At least 5 unique dates are " | |
| "required to build a time-series forecast." | |
| ) | |
| # --- 7. Sales column is not all zeros --------------------------------- | |
| sales_valid = parsed_sales[valid_mask] | |
| if (sales_valid == 0).all(): | |
| errors.append( | |
| f"Sales column '{sales_col}' contains only zero values. " | |
| "Cannot build a forecast on a constant-zero series." | |
| ) | |
| elif (sales_valid <= 0).mean() > 0.5: | |
| warnings.append( | |
| f"More than 50 % of '{sales_col}' values are zero or negative. " | |
| "Consider reviewing the data before forecasting." | |
| ) | |
| is_valid = len(errors) == 0 | |
| return is_valid, errors, warnings | |