sales-dashboard / src /utils.py
Hamza4100's picture
Upload 20 files
7f5d85f verified
Raw History Blame Contribute Delete
6.27 kB
"""
utils.py
--------
Shared utility helpers for the Sales Forecasting Dashboard.
"""
from __future__ import annotations
import numpy as np
import pandas as pd
from typing import List, Optional
# ---------------------------------------------------------------------------
# Formatting helpers
# ---------------------------------------------------------------------------
def format_number(n: float) -> str:
"""Return a human-readable string with comma thousands-separators.
Parameters
----------
n : float
The numeric value to format.
Returns
-------
str
e.g. ``"1,234,567.89"``
"""
try:
return f"{float(n):,.2f}"
except (TypeError, ValueError):
return str(n)
def format_currency(n: float, symbol: str = "$") -> str:
"""Return a currency-formatted string.
Parameters
----------
n : float
The numeric value to format.
symbol : str, optional
Currency symbol prefix (default ``"$"``).
Returns
-------
str
e.g. ``"$1,234,567.89"``
"""
return f"{symbol}{format_number(n)}"
def safe_divide(a: float, b: float, default: float = 0) -> float:
"""Safely divide *a* by *b*, returning *default* when *b* is zero.
Parameters
----------
a : float
Numerator.
b : float
Denominator.
default : float, optional
Value returned when *b* == 0 (default ``0``).
Returns
-------
float
``a / b`` or *default*.
"""
if b == 0:
return default
return a / b
def get_date_range_str(series: pd.Series) -> str:
"""Return a human-readable date-range string from a date series.
Parameters
----------
series : pd.Series
A series that can be coerced to datetime.
Returns
-------
str
e.g. ``"Jan 2021 – Dec 2023"``
"""
try:
dates = pd.to_datetime(series, errors="coerce").dropna()
if dates.empty:
return "Unknown"
start = dates.min().strftime("%b %Y")
end = dates.max().strftime("%b %Y")
return f"{start} \u2013 {end}"
except Exception:
return "Unknown"
# ---------------------------------------------------------------------------
# DataFrame helpers
# ---------------------------------------------------------------------------
def detect_categorical_columns(
df: pd.DataFrame,
exclude_cols: List[str],
max_unique: int = 50,
) -> List[str]:
"""Return column names that look categorical.
A column qualifies when it has ``object`` or ``category`` dtype, is **not**
in *exclude_cols*, and has at most *max_unique* distinct values.
Parameters
----------
df : pd.DataFrame
Source dataframe.
exclude_cols : list[str]
Column names to skip regardless of dtype.
max_unique : int, optional
Maximum number of unique values to still consider a column categorical
(default ``50``).
Returns
-------
list[str]
Qualifying column names.
"""
result: List[str] = []
exclude_set = set(exclude_cols)
for col in df.columns:
if col in exclude_set:
continue
if df[col].dtype.name in ("object", "category"):
if df[col].nunique(dropna=True) <= max_unique:
result.append(col)
return result
# ---------------------------------------------------------------------------
# Date / frequency helpers
# ---------------------------------------------------------------------------
def generate_future_dates(
last_date: pd.Timestamp,
periods: int,
freq: str,
) -> pd.DatetimeIndex:
"""Generate a :class:`pd.DatetimeIndex` of *periods* future dates.
Parameters
----------
last_date : pd.Timestamp
The last known date in the historical series.
periods : int
Number of future periods to generate.
freq : str
Pandas frequency alias (e.g. ``"D"``, ``"W"``, ``"MS"``).
Returns
-------
pd.DatetimeIndex
Index starting one period after *last_date*.
"""
return pd.date_range(start=last_date, periods=periods + 1, freq=freq)[1:]
def get_frequency_alias(freq_str: str) -> str:
"""Map a human-readable frequency label to its pandas alias.
Parameters
----------
freq_str : str
One of ``"Daily"``, ``"Weekly"``, ``"Monthly"``.
Returns
-------
str
Pandas frequency string: ``"D"``, ``"W"``, or ``"MS"``.
Raises
------
ValueError
If *freq_str* is not recognised.
"""
norm = str(freq_str).strip().lower()
mapping = {
"daily": "D",
"d": "D",
"weekly": "W",
"w": "W",
"monthly": "MS",
"m": "MS",
"ms": "MS",
}
return mapping.get(norm, "D")
def robust_to_datetime(series: pd.Series) -> pd.Series:
"""Parse dates robustly across ISO, US (MM/DD/YYYY), UK/EU (DD/MM/YYYY), and mixed formats.
Tries standard datetime parsing first. If fewer than 80% parse successfully
(common when day comes first, e.g. Kaggle's Superstore data), it attempts
`dayfirst=True`, followed by `format='mixed'` where supported by pandas.
Parameters
----------
series : pd.Series
Series containing date strings or timestamps.
Returns
-------
pd.Series
Datetime-parsed series with invalid values coerced to NaT.
"""
if pd.api.types.is_datetime64_any_dtype(series):
return series
# 1. Standard parsing (fast, covers ISO 8601 like YYYY-MM-DD)
p1 = pd.to_datetime(series, errors="coerce")
rate1 = p1.notna().mean()
if rate1 >= 0.8:
return p1
# 2. Day-first parsing (covers DD/MM/YYYY common worldwide & Kaggle Superstore)
p2 = pd.to_datetime(series, dayfirst=True, errors="coerce")
rate2 = p2.notna().mean()
if rate2 >= rate1 and rate2 >= 0.8:
return p2
# 3. Mixed format parsing (pandas 2.0+)
try:
p3 = pd.to_datetime(series, format="mixed", errors="coerce")
rate3 = p3.notna().mean()
if rate3 >= rate2 and rate3 >= 0.8:
return p3
except Exception:
pass
# Return best parsed result
return p2 if rate2 > rate1 else p1