File size: 8,713 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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
"""
preprocessing.py
----------------
Data cleaning and preparation pipeline for the Sales Forecasting Dashboard.
"""

from __future__ import annotations

from typing import Dict, Optional, Tuple

import numpy as np
import pandas as pd

from src.utils import get_frequency_alias, robust_to_datetime


class DataPreprocessor:
    """Clean, normalise, and resample raw sales data.

    Parameters
    ----------
    date_col : str
        Name of the date column in the raw dataframe.
    sales_col : str
        Name of the sales/revenue column in the raw dataframe.
    freq : str, optional
        Target frequency: ``"Daily"``, ``"Weekly"``, ``"Monthly"``, or
        ``"auto"`` (default) to detect automatically from the data.
    """

    def __init__(
        self,
        date_col: str,
        sales_col: str,
        freq: str = "auto",
    ) -> None:
        self.date_col = date_col
        self.sales_col = sales_col
        self.freq = freq

        # Populated during fit_transform
        self._col_mapping: Dict[str, str] = {}
        self._detected_freq: Optional[str] = None

    # ------------------------------------------------------------------
    # Public API
    # ------------------------------------------------------------------

    def fit_transform(
        self, df: pd.DataFrame
    ) -> Tuple[pd.DataFrame, Dict]:
        """Clean the raw dataframe and return a time-series ready dataframe.

        Steps
        -----
        1. Copy dataframe.
        2. Normalise column names (strip + lowercase), keep original mapping.
        3. Convert *date_col* to datetime; drop rows where parsing fails.
        4. Convert *sales_col* to numeric; fill bad values with column median.
        5. Remove fully-duplicate rows.
        6. Sort by date.
        7. Remove rows where sales < 0 (counted in report, not silently dropped).
        8. Aggregate: group by date, sum sales.
        9. Auto-detect frequency (if ``freq='auto'``).
        10. Reindex to a gap-free date range; fill missing sales with 0.

        Parameters
        ----------
        df : pd.DataFrame
            Raw input dataframe.

        Returns
        -------
        cleaned_df : pd.DataFrame
            Cleaned dataframe with a ``DatetimeIndex`` and a single *sales_col*
            column.
        report : dict
            Summary of all mutations applied.
        """
        report: Dict = {}

        # --- Step 1: copy -------------------------------------------------
        data = df.copy()
        report["original_rows"] = len(data)

        # --- Step 2: normalise column names --------------------------------
        self._col_mapping = {col.strip().lower(): col for col in data.columns}
        data.columns = [col.strip().lower() for col in data.columns]

        # Normalise the target column references
        norm_date = self.date_col.strip().lower()
        norm_sales = self.sales_col.strip().lower()

        # --- Step 3: parse dates -------------------------------------------
        before_date_drop = len(data)
        data[norm_date] = robust_to_datetime(data[norm_date])
        data = data.dropna(subset=[norm_date])
        date_errors_removed = before_date_drop - len(data)
        report["date_errors_removed"] = date_errors_removed

        # --- Step 4: parse sales -> clean currency symbols, commas & fill with median
        if data[norm_sales].dtype == object:
            sales_clean = (
                data[norm_sales].astype(str)
                .str.replace(r"[^\d.-]", "", regex=True)
            )
            data[norm_sales] = pd.to_numeric(sales_clean, errors="coerce")
        else:
            data[norm_sales] = pd.to_numeric(data[norm_sales], errors="coerce")
        missing_sales = int(data[norm_sales].isna().sum())
        if missing_sales > 0:
            median_val = data[norm_sales].median()
            data[norm_sales] = data[norm_sales].fillna(median_val)
        report["missing_sales_filled"] = missing_sales

        # --- Step 5: remove duplicate rows ---------------------------------
        before_dedup = len(data)
        data = data.drop_duplicates()
        duplicate_rows_removed = before_dedup - len(data)
        report["duplicate_rows_removed"] = duplicate_rows_removed

        # --- Step 6: sort by date -----------------------------------------
        data = data.sort_values(norm_date).reset_index(drop=True)

        # --- Step 7: remove negative sales ---------------------------------
        negative_mask = data[norm_sales] < 0
        negative_rows_removed = int(negative_mask.sum())
        if negative_rows_removed:
            data = data[~negative_mask].reset_index(drop=True)
        report["negative_rows_removed"] = negative_rows_removed

        # --- Step 8: aggregate (sum) by date -------------------------------
        pre_agg_rows = len(data)
        data = (
            data.groupby(norm_date, as_index=True)[norm_sales]
            .sum()
            .reset_index()
        )
        aggregation_performed = len(data) < pre_agg_rows
        report["aggregation_performed"] = aggregation_performed

        # --- Step 9: detect / confirm frequency ----------------------------
        freq_normalized = str(self.freq).strip().lower()
        if freq_normalized in ("auto", "auto-detect", "default", "none", ""):
            detected = self._detect_frequency(data[norm_date])
        elif freq_normalized in ("daily", "d"):
            detected = "Daily"
        elif freq_normalized in ("weekly", "w"):
            detected = "Weekly"
        elif freq_normalized in ("monthly", "m", "ms"):
            detected = "Monthly"
        else:
            detected = self._detect_frequency(data[norm_date])

        self._detected_freq = detected
        report["detected_frequency"] = detected

        freq_alias = get_frequency_alias(detected)

        # --- Step 10: gap-free reindex ------------------------------------
        date_min = data[norm_date].min()
        date_max = data[norm_date].max()
        full_index = pd.date_range(start=date_min, end=date_max, freq=freq_alias)

        data = data.set_index(norm_date)
        data.index = pd.DatetimeIndex(data.index)
        data = data.reindex(full_index, fill_value=0)
        data.index.name = None

        # Keep only sales column, rename back to original user-supplied name
        data = data[[norm_sales]].rename(columns={norm_sales: self.sales_col})
        data[self.date_col] = data.index

        report["cleaned_rows"] = len(data)
        report["date_range_start"] = str(date_min.date())
        report["date_range_end"] = str(date_max.date())

        return data, report

    def get_data_quality_score(self, report: Dict) -> float:
        """Compute a 0-100 data-quality score based on the cleaning report.

        A higher score means the data required fewer corrections.

        Parameters
        ----------
        report : dict
            The report dict returned by :meth:`fit_transform`.

        Returns
        -------
        float
            Quality score between 0 and 100.
        """
        original = max(report.get("original_rows", 1), 1)

        # Weight each penalty type (more severe = higher weight)
        date_errors = report.get("date_errors_removed", 0)
        missing_filled = report.get("missing_sales_filled", 0)
        duplicates = report.get("duplicate_rows_removed", 0)
        negatives = report.get("negative_rows_removed", 0)

        penalties = (
            (date_errors / original) * 40      # up to 40 pts
            + (missing_filled / original) * 25  # up to 25 pts
            + (duplicates / original) * 20      # up to 20 pts
            + (negatives / original) * 15       # up to 15 pts
        )

        score = max(0.0, 100.0 - penalties * 100)
        return round(score, 1)

    # ------------------------------------------------------------------
    # Private helpers
    # ------------------------------------------------------------------

    @staticmethod
    def _detect_frequency(date_series: pd.Series) -> str:
        """Infer 'Daily', 'Weekly', or 'Monthly' from date diffs.

        Parameters
        ----------
        date_series : pd.Series
            Sorted datetime series.

        Returns
        -------
        str
            One of ``"Daily"``, ``"Weekly"``, ``"Monthly"``.
        """
        sorted_dates = pd.to_datetime(date_series).sort_values()
        diffs = sorted_dates.diff().dropna()
        if diffs.empty:
            return "Monthly"

        median_days = diffs.dt.days.median()

        if median_days <= 1.5:
            return "Daily"
        if median_days <= 10:
            return "Weekly"
        return "Monthly"