|
| 1 | +# src/eda/eda_tools.py |
| 2 | +import os |
| 3 | +import pandas as pd |
| 4 | +import numpy as np |
| 5 | +import matplotlib.pyplot as plt |
| 6 | +import seaborn as sns |
| 7 | +from typing import Tuple |
| 8 | + |
| 9 | +sns.set(style="whitegrid", rc={"figure.dpi": 150}) |
| 10 | + |
| 11 | +def ensure_dir(path: str): |
| 12 | + os.makedirs(path, exist_ok=True) |
| 13 | + |
| 14 | +# ---------- Summaries ---------- |
| 15 | +def data_structure(df: pd.DataFrame) -> pd.DataFrame: |
| 16 | + """Return dtypes and non-null counts.""" |
| 17 | + info = pd.DataFrame({ |
| 18 | + "dtype": df.dtypes.astype(str), |
| 19 | + "non_null_count": df.count(), |
| 20 | + "null_count": df.isna().sum(), |
| 21 | + "unique": df.nunique(dropna=False) |
| 22 | + }) |
| 23 | + return info |
| 24 | + |
| 25 | +def descriptive_stats(df: pd.DataFrame, cols: list) -> pd.DataFrame: |
| 26 | + return df[cols].describe().T |
| 27 | + |
| 28 | +# ---------- Business Metric: Loss Ratio ---------- |
| 29 | +def overall_loss_ratio(df: pd.DataFrame) -> float: |
| 30 | + total_claims = df["TotalClaims"].sum(skipna=True) |
| 31 | + total_premium = df["TotalPremium"].sum(skipna=True) |
| 32 | + if total_premium == 0: |
| 33 | + return np.nan |
| 34 | + return total_claims / total_premium |
| 35 | + |
| 36 | +def loss_ratio_by_group(df: pd.DataFrame, group_col: str) -> pd.DataFrame: |
| 37 | + grp = df.groupby(group_col)[["TotalPremium","TotalClaims"]].sum() |
| 38 | + grp = grp.assign(LossRatio = grp["TotalClaims"] / grp["TotalPremium"]) |
| 39 | + grp = grp.sort_values("LossRatio", ascending=False) |
| 40 | + return grp |
| 41 | + |
| 42 | +# ---------- Time series ---------- |
| 43 | +def monthly_claims_premiums(df: pd.DataFrame, date_col: str = "TransactionMonth") -> pd.DataFrame: |
| 44 | + df = df.copy() |
| 45 | + df[date_col] = pd.to_datetime(df[date_col], errors="coerce") |
| 46 | + df = df.dropna(subset=[date_col]) |
| 47 | + monthly = df.groupby(pd.Grouper(key=date_col, freq="MS"))[["TotalClaims","TotalPremium"]].sum() |
| 48 | + monthly["ClaimFrequency"] = df.groupby(pd.Grouper(key=date_col, freq="MS"))["TotalClaims"].apply(lambda s: (s>0).sum()) |
| 49 | + # severity: average claim amount per claim (avoid div by zero) |
| 50 | + monthly["ClaimSeverity"] = monthly.apply(lambda r: r["TotalClaims"] / max(r["ClaimFrequency"], 1), axis=1) |
| 51 | + return monthly |
| 52 | + |
| 53 | +# ---------- Outlier detection ---------- |
| 54 | +def outlier_summary(df: pd.DataFrame, col: str) -> dict: |
| 55 | + s = df[col].dropna() |
| 56 | + q1, q3 = s.quantile([0.25, 0.75]) |
| 57 | + iqr = q3 - q1 |
| 58 | + lower = q1 - 1.5 * iqr |
| 59 | + upper = q3 + 1.5 * iqr |
| 60 | + return {"q1": q1, "q3": q3, "iqr": iqr, "lower": lower, "upper": upper, |
| 61 | + "n_outliers": ((s < lower) | (s > upper)).sum()} |
| 62 | + |
| 63 | +# ---------- Plots (3 required polished plots) ---------- |
| 64 | +def plot_loss_ratio_by_province(df: pd.DataFrame, outdir: str): |
| 65 | + ensure_dir(outdir) |
| 66 | + grp = loss_ratio_by_group(df, "Province") |
| 67 | + plt.figure(figsize=(10,6)) |
| 68 | + sns.barplot(x=grp.index, y=grp["LossRatio"]) |
| 69 | + plt.xticks(rotation=45, ha="right") |
| 70 | + plt.ylabel("Loss Ratio (TotalClaims / TotalPremium)") |
| 71 | + plt.title("Loss Ratio by Province") |
| 72 | + plt.tight_layout() |
| 73 | + path = os.path.join(outdir, "loss_ratio_by_province.png") |
| 74 | + plt.savefig(path) |
| 75 | + plt.close() |
| 76 | + return path |
| 77 | + |
| 78 | +def plot_totalclaims_distribution(df: pd.DataFrame, outdir: str): |
| 79 | + ensure_dir(outdir) |
| 80 | + plt.figure(figsize=(8,5)) |
| 81 | + # log scale helps when heavy skew/outliers |
| 82 | + sns.histplot(df["TotalClaims"].dropna(), bins=100, kde=True) |
| 83 | + plt.xscale('symlog') # symmetric log to keep zeros visible |
| 84 | + plt.xlabel("TotalClaims (symlog scale)") |
| 85 | + plt.title("Distribution of TotalClaims (log-friendly)") |
| 86 | + plt.tight_layout() |
| 87 | + path = os.path.join(outdir, "totalclaims_distribution.png") |
| 88 | + plt.savefig(path) |
| 89 | + plt.close() |
| 90 | + return path |
| 91 | + |
| 92 | +def plot_claims_premium_time_series(df: pd.DataFrame, outdir: str, date_col="TransactionMonth"): |
| 93 | + ensure_dir(outdir) |
| 94 | + monthly = monthly_claims_premiums(df, date_col=date_col) |
| 95 | + plt.figure(figsize=(10,6)) |
| 96 | + ax = monthly[["TotalClaims","TotalPremium"]].plot(title="Monthly TotalClaims vs TotalPremium") |
| 97 | + ax.set_ylabel("Amount (local currency)") |
| 98 | + plt.tight_layout() |
| 99 | + path = os.path.join(outdir, "monthly_claims_premium.png") |
| 100 | + plt.savefig(path) |
| 101 | + plt.close() |
| 102 | + return path |
| 103 | + |
| 104 | +# ---------- Bivariate exploration ---------- |
| 105 | +def scatter_premium_vs_claims(df: pd.DataFrame, outdir: str, sample=10000): |
| 106 | + ensure_dir(outdir) |
| 107 | + n = min(len(df), sample) |
| 108 | + sample_df = df.sample(n=n, random_state=42) |
| 109 | + plt.figure(figsize=(8,6)) |
| 110 | + sns.scatterplot(x=sample_df["TotalPremium"], y=sample_df["TotalClaims"], alpha=0.6) |
| 111 | + plt.xscale("symlog") |
| 112 | + plt.yscale("symlog") |
| 113 | + plt.xlabel("TotalPremium (symlog)") |
| 114 | + plt.ylabel("TotalClaims (symlog)") |
| 115 | + plt.title(f"Scatter: TotalPremium vs TotalClaims (sample n={n})") |
| 116 | + plt.tight_layout() |
| 117 | + path = os.path.join(outdir, "scatter_premium_vs_claims.png") |
| 118 | + plt.savefig(path) |
| 119 | + plt.close() |
| 120 | + return path |
0 commit comments