File size: 5,201 Bytes
7f5d85f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
"""
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