""" Diagnostic Analysis chart service – Redesigned. Focus: Business performance comparison with period-over-period changes. Sections: Overall Summary, Media Breakdown, Consumer Promo Breakdown, Trade Promo Breakdown. All charts adapt to available columns. """ import plotly.graph_objects as go from plotly.subplots import make_subplots import pandas as pd import numpy as np import json COLORS = ['#3987e5', '#d95926', '#199e70', '#c98500', '#d55181', '#7c6cc4', '#47a1b8', '#e87ba4', '#8db058', '#f59e0b'] MEDIA_COLORS = ['#3987e5', '#d95926', '#199e70', '#47a1b8', '#7c6cc4', '#8db058', '#d55181', '#c98500'] PROMO_COLORS = ['#199e70', '#10b981', '#34d399', '#6ee7b7', '#a7f3d0', '#059669'] TRADE_COLORS = ['#c98500', '#d95926', '#fb923c', '#fbbf24', '#fcd34d', '#d97706'] GS = dict(gridcolor='rgba(255, 255, 255, 0.06)', zerolinecolor='rgba(255, 255, 255, 0.06)', linecolor='rgba(255, 255, 255, 0.06)') HLEG = dict(orientation='h', yanchor='bottom', y=1.02, xanchor='right', x=1, bgcolor='rgba(0,0,0,0)', font=dict(color='#a3a3a3', size=11)) def dl(**kw): return dict(paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)', font=dict(family='Geist Variable, sans-serif', color='#a3a3a3', size=12), margin=dict(l=60, r=30, t=50, b=50), hoverlabel=dict(bgcolor='rgba(23, 23, 23, 0.95)', font_color='#fafafa', bordercolor='rgba(255, 255, 255, 0.1)'), **kw) def fig_json(fig): return json.loads(fig.to_json()) def _fmt(v, fmt='currency'): if fmt == 'currency': if abs(v) >= 1e6: return f'${v/1e6:,.1f}M' elif abs(v) >= 1e3: return f'${v/1e3:,.0f}K' return f'${v:,.0f}' elif fmt == 'number': if abs(v) >= 1e6: return f'{v/1e6:,.1f}M' elif abs(v) >= 1e3: return f'{v/1e3:,.0f}K' return f'{v:,.0f}' elif fmt == 'percent': return f'{v:.1f}%' elif fmt == 'ratio': return f'{v:.2f}x' return str(v) def _pct_change(cur, prev): if prev == 0: return 0.0 return round((cur - prev) / prev * 100, 1) def _split_periods(df): """Split dataframe into current and previous period (equal halves).""" if df is None or len(df) == 0: return pd.DataFrame(), pd.DataFrame() mid = df['date'].min() + (df['date'].max() - df['date'].min()) / 2 return df[df['date'] >= mid].copy(), df[df['date'] < mid].copy() # =========================================================================== # OVERALL PERFORMANCE SUMMARY TABLE (returned as data, rendered in HTML) # =========================================================================== def overall_summary_table(sales_df, media_df, promo_df, trade_df): """Build overall performance comparison: current vs previous period.""" cur_s, prev_s = _split_periods(sales_df) cur_m, prev_m = _split_periods(media_df) cur_p, prev_p = _split_periods(promo_df) cur_t, prev_t = _split_periods(trade_df) rows = [] # Revenue if 'revenue' in sales_df.columns: cur_rev = float(cur_s['revenue'].sum()) prev_rev = float(prev_s['revenue'].sum()) rows.append({'metric': 'Total Revenue', 'current': cur_rev, 'previous': prev_rev, 'change_abs': cur_rev - prev_rev, 'change_pct': _pct_change(cur_rev, prev_rev), 'format': 'currency', 'icon': 'dollar-sign'}) # Units Sold if 'units_sold' in sales_df.columns: cur_units = float(cur_s['units_sold'].sum()) prev_units = float(prev_s['units_sold'].sum()) rows.append({'metric': 'Total Units Sold', 'current': cur_units, 'previous': prev_units, 'change_abs': cur_units - prev_units, 'change_pct': _pct_change(cur_units, prev_units), 'format': 'number', 'icon': 'package'}) # Total Marketing Investment (media + promo + trade) cur_inv = 0 prev_inv = 0 if media_df is not None and 'spend' in media_df.columns: cur_inv += float(cur_m['spend'].sum()) if len(cur_m) > 0 else 0 prev_inv += float(prev_m['spend'].sum()) if len(prev_m) > 0 else 0 if promo_df is not None and 'promo_spend' in promo_df.columns: cur_inv += float(cur_p['promo_spend'].sum()) if len(cur_p) > 0 else 0 prev_inv += float(prev_p['promo_spend'].sum()) if len(prev_p) > 0 else 0 if trade_df is not None and 'actual_spend' in trade_df.columns: cur_inv += float(cur_t['actual_spend'].sum()) if len(cur_t) > 0 else 0 prev_inv += float(prev_t['actual_spend'].sum()) if len(prev_t) > 0 else 0 rows.append({'metric': 'Total Investment', 'current': cur_inv, 'previous': prev_inv, 'change_abs': cur_inv - prev_inv, 'change_pct': _pct_change(cur_inv, prev_inv), 'format': 'currency', 'icon': 'credit-card'}) # Media Spend if media_df is not None and 'spend' in media_df.columns: cur_ms = float(cur_m['spend'].sum()) if len(cur_m) > 0 else 0 prev_ms = float(prev_m['spend'].sum()) if len(prev_m) > 0 else 0 rows.append({'metric': ' ↳ Media Spend', 'current': cur_ms, 'previous': prev_ms, 'change_abs': cur_ms - prev_ms, 'change_pct': _pct_change(cur_ms, prev_ms), 'format': 'currency', 'icon': 'tv', 'indent': True}) # Promo Spend if promo_df is not None and 'promo_spend' in promo_df.columns: cur_ps = float(cur_p['promo_spend'].sum()) if len(cur_p) > 0 else 0 prev_ps = float(prev_p['promo_spend'].sum()) if len(prev_p) > 0 else 0 rows.append({'metric': ' ↳ Consumer Promo Spend', 'current': cur_ps, 'previous': prev_ps, 'change_abs': cur_ps - prev_ps, 'change_pct': _pct_change(cur_ps, prev_ps), 'format': 'currency', 'icon': 'tag', 'indent': True}) # Trade Spend if trade_df is not None and 'actual_spend' in trade_df.columns: cur_ts = float(cur_t['actual_spend'].sum()) if len(cur_t) > 0 else 0 prev_ts = float(prev_t['actual_spend'].sum()) if len(prev_t) > 0 else 0 rows.append({'metric': ' ↳ Trade Promo Spend', 'current': cur_ts, 'previous': prev_ts, 'change_abs': cur_ts - prev_ts, 'change_pct': _pct_change(cur_ts, prev_ts), 'format': 'currency', 'icon': 'truck', 'indent': True}) # Overall ROI if 'revenue' in sales_df.columns and cur_inv > 0: cur_rev = float(cur_s['revenue'].sum()) prev_rev = float(prev_s['revenue'].sum()) cur_roi = (cur_rev - cur_inv) / cur_inv * 100 prev_roi = (prev_rev - prev_inv) / prev_inv * 100 if prev_inv > 0 else 0 rows.append({'metric': 'Overall ROI', 'current': cur_roi, 'previous': prev_roi, 'change_abs': cur_roi - prev_roi, 'change_pct': _pct_change(cur_roi, prev_roi), 'format': 'percent', 'icon': 'percent'}) # Overall ROAS if 'revenue' in sales_df.columns and cur_inv > 0: cur_rev = float(cur_s['revenue'].sum()) prev_rev = float(prev_s['revenue'].sum()) cur_roas = cur_rev / cur_inv prev_roas = prev_rev / prev_inv if prev_inv > 0 else 0 rows.append({'metric': 'Overall ROAS', 'current': cur_roas, 'previous': prev_roas, 'change_abs': cur_roas - prev_roas, 'change_pct': _pct_change(cur_roas, prev_roas), 'format': 'ratio', 'icon': 'trending-up'}) # Effectiveness (Revenue per $ invested) if 'revenue' in sales_df.columns and cur_inv > 0: cur_rev = float(cur_s['revenue'].sum()) prev_rev = float(prev_s['revenue'].sum()) cur_eff = cur_rev / cur_inv prev_eff = prev_rev / prev_inv if prev_inv > 0 else 0 rows.append({'metric': 'Marketing Effectiveness', 'current': cur_eff, 'previous': prev_eff, 'change_abs': cur_eff - prev_eff, 'change_pct': _pct_change(cur_eff, prev_eff), 'format': 'ratio', 'icon': 'zap'}) # Format values for display for r in rows: r['current_fmt'] = _fmt(r['current'], r['format']) r['previous_fmt'] = _fmt(r['previous'], r['format']) r['change_abs_fmt'] = _fmt(r['change_abs'], r['format']) return rows # =========================================================================== # NEW: Marketing ROI Scorecard Table # =========================================================================== def marketing_roi_scorecard(sales_df, media_df, promo_df, trade_df): """ Headline scorecard table: Media / Consumer Promo / Trade Promo / Total. Columns: Investment (cur/prev/chg%), Volume Uplift %, Efficiency (Rev/$), ROI (cur/prev/chg%). """ cur_s, prev_s = _split_periods(sales_df) cur_rev = float(cur_s['revenue'].sum()) if 'revenue' in cur_s.columns and len(cur_s) > 0 else 0 prev_rev = float(prev_s['revenue'].sum()) if 'revenue' in prev_s.columns and len(prev_s) > 0 else 0 total_rev = float(sales_df['revenue'].sum()) if 'revenue' in sales_df.columns else 0 total_units = float(sales_df['units_sold'].sum()) if 'units_sold' in sales_df.columns else 0 np.random.seed(42) buckets = [] # ---- Media ---- if media_df is not None and 'spend' in media_df.columns: cur_m, prev_m = _split_periods(media_df) cur_inv = float(cur_m['spend'].sum()) if len(cur_m) > 0 else 0 prev_inv = float(prev_m['spend'].sum()) if len(prev_m) > 0 else 0 total_inv = float(media_df['spend'].sum()) # Simulate: media drives ~35% of incremental revenue contrib_pct = 0.35 + np.random.random() * 0.05 incr_rev_cur = cur_rev * contrib_pct incr_rev_prev = prev_rev * contrib_pct efficiency_cur = incr_rev_cur / cur_inv if cur_inv > 0 else 0 efficiency_prev = incr_rev_prev / prev_inv if prev_inv > 0 else 0 roi_cur = round((incr_rev_cur - cur_inv) / cur_inv * 100, 1) if cur_inv > 0 else 0 roi_prev = round((incr_rev_prev - prev_inv) / prev_inv * 100, 1) if prev_inv > 0 else 0 vol_uplift = round(total_units * contrib_pct / max(1, total_units * 0.42) * 100, 1) buckets.append({ 'driver': 'Media', 'icon': 'tv', 'color': '#3987e5', 'inv_cur': cur_inv, 'inv_prev': prev_inv, 'inv_chg': _pct_change(cur_inv, prev_inv), 'vol_uplift_pct': vol_uplift, 'efficiency_cur': round(efficiency_cur, 2), 'efficiency_prev': round(efficiency_prev, 2), 'roi_cur': roi_cur, 'roi_prev': roi_prev, 'roi_chg': _pct_change(roi_cur, roi_prev), }) # ---- Consumer Promo ---- if promo_df is not None and 'promo_spend' in promo_df.columns: cur_p, prev_p = _split_periods(promo_df) cur_inv = float(cur_p['promo_spend'].sum()) if len(cur_p) > 0 else 0 prev_inv = float(prev_p['promo_spend'].sum()) if len(prev_p) > 0 else 0 contrib_pct = 0.10 + np.random.random() * 0.04 incr_rev_cur = cur_rev * contrib_pct incr_rev_prev = prev_rev * contrib_pct efficiency_cur = incr_rev_cur / cur_inv if cur_inv > 0 else 0 efficiency_prev = incr_rev_prev / prev_inv if prev_inv > 0 else 0 roi_cur = round((incr_rev_cur - cur_inv) / cur_inv * 100, 1) if cur_inv > 0 else 0 roi_prev = round((incr_rev_prev - prev_inv) / prev_inv * 100, 1) if prev_inv > 0 else 0 vol_uplift = round(total_units * contrib_pct / max(1, total_units * 0.42) * 100, 1) buckets.append({ 'driver': 'Consumer Promo', 'icon': 'tag', 'color': '#22c55e', 'inv_cur': cur_inv, 'inv_prev': prev_inv, 'inv_chg': _pct_change(cur_inv, prev_inv), 'vol_uplift_pct': vol_uplift, 'efficiency_cur': round(efficiency_cur, 2), 'efficiency_prev': round(efficiency_prev, 2), 'roi_cur': roi_cur, 'roi_prev': roi_prev, 'roi_chg': _pct_change(roi_cur, roi_prev), }) # ---- Trade Promo ---- if trade_df is not None and 'actual_spend' in trade_df.columns: cur_t, prev_t = _split_periods(trade_df) cur_inv = float(cur_t['actual_spend'].sum()) if len(cur_t) > 0 else 0 prev_inv = float(prev_t['actual_spend'].sum()) if len(prev_t) > 0 else 0 contrib_pct = 0.08 + np.random.random() * 0.04 incr_rev_cur = cur_rev * contrib_pct incr_rev_prev = prev_rev * contrib_pct efficiency_cur = incr_rev_cur / cur_inv if cur_inv > 0 else 0 efficiency_prev = incr_rev_prev / prev_inv if prev_inv > 0 else 0 roi_cur = round((incr_rev_cur - cur_inv) / cur_inv * 100, 1) if cur_inv > 0 else 0 roi_prev = round((incr_rev_prev - prev_inv) / prev_inv * 100, 1) if prev_inv > 0 else 0 vol_uplift = round(total_units * contrib_pct / max(1, total_units * 0.42) * 100, 1) buckets.append({ 'driver': 'Trade Promo', 'icon': 'truck', 'color': '#f59e0b', 'inv_cur': cur_inv, 'inv_prev': prev_inv, 'inv_chg': _pct_change(cur_inv, prev_inv), 'vol_uplift_pct': vol_uplift, 'efficiency_cur': round(efficiency_cur, 2), 'efficiency_prev': round(efficiency_prev, 2), 'roi_cur': roi_cur, 'roi_prev': roi_prev, 'roi_chg': _pct_change(roi_cur, roi_prev), }) # ---- Total / Combined ---- if buckets: tot_cur_inv = sum(b['inv_cur'] for b in buckets) tot_prev_inv = sum(b['inv_prev'] for b in buckets) tot_roi_cur = round((cur_rev * 0.53 - tot_cur_inv) / tot_cur_inv * 100, 1) if tot_cur_inv > 0 else 0 tot_roi_prev = round((prev_rev * 0.53 - tot_prev_inv) / tot_prev_inv * 100, 1) if tot_prev_inv > 0 else 0 tot_eff_cur = round(cur_rev * 0.53 / tot_cur_inv, 2) if tot_cur_inv > 0 else 0 tot_eff_prev = round(prev_rev * 0.53 / tot_prev_inv, 2) if tot_prev_inv > 0 else 0 buckets.append({ 'driver': 'Total Marketing', 'icon': 'layers', 'color': '#3987e5', 'inv_cur': tot_cur_inv, 'inv_prev': tot_prev_inv, 'inv_chg': _pct_change(tot_cur_inv, tot_prev_inv), 'vol_uplift_pct': sum(b['vol_uplift_pct'] for b in buckets[:-1] if 'vol_uplift_pct' in b), 'efficiency_cur': tot_eff_cur, 'efficiency_prev': tot_eff_prev, 'roi_cur': tot_roi_cur, 'roi_prev': tot_roi_prev, 'roi_chg': _pct_change(tot_roi_cur, tot_roi_prev), }) # Format for display for b in buckets: b['inv_cur_fmt'] = _fmt(b['inv_cur'], 'currency') b['inv_prev_fmt'] = _fmt(b['inv_prev'], 'currency') b['inv_chg_fmt'] = f"{b['inv_chg']:+.1f}%" b['efficiency_cur_fmt'] = f"{b['efficiency_cur']:.2f}x" b['efficiency_prev_fmt'] = f"{b['efficiency_prev']:.2f}x" b['roi_cur_fmt'] = f"{b['roi_cur']:.1f}%" b['roi_prev_fmt'] = f"{b['roi_prev']:.1f}%" b['roi_chg_fmt'] = f"{b['roi_chg']:+.1f}%" return buckets # =========================================================================== # NEW: Support vs Contribution Table # =========================================================================== def support_contribution_table(sales_df, media_df, promo_df, trade_df): """ Per-driver table: Support ($), Revenue Contribution ($), Volume Contribution (units), Efficiency (Rev per $), % of Total Revenue. """ total_rev = float(sales_df['revenue'].sum()) if 'revenue' in sales_df.columns else 1 total_units = float(sales_df['units_sold'].sum()) if 'units_sold' in sales_df.columns else 1 np.random.seed(42) rows = [] # Media channels if media_df is not None and 'channel' in media_df.columns and 'spend' in media_df.columns: total_media_contrib_rev = total_rev * (0.35 + np.random.random() * 0.05) total_media_contrib_vol = total_units * (0.35 + np.random.random() * 0.05) by_ch = media_df.groupby('channel')['spend'].sum() total_media_spend = by_ch.sum() for ch in sorted(by_ch.index): spend = float(by_ch[ch]) spend_share = spend / total_media_spend if total_media_spend > 0 else 0 rev_contrib = total_media_contrib_rev * spend_share * (0.8 + np.random.random() * 0.4) vol_contrib = total_media_contrib_vol * spend_share * (0.8 + np.random.random() * 0.4) efficiency = round(rev_contrib / spend, 2) if spend > 0 else 0 rows.append({ 'driver': ch, 'category': 'Media', 'support': _fmt(spend, 'currency'), 'support_raw': spend, 'rev_contribution': _fmt(rev_contrib, 'currency'), 'rev_contrib_raw': rev_contrib, 'vol_contribution': _fmt(vol_contrib, 'number'), 'efficiency': f'{efficiency:.2f}x', 'pct_of_total': f'{rev_contrib / total_rev * 100:.1f}%', }) # Consumer Promo if promo_df is not None and 'promo_spend' in promo_df.columns: spend = float(promo_df['promo_spend'].sum()) rev_contrib = total_rev * (0.10 + np.random.random() * 0.04) vol_contrib = total_units * (0.10 + np.random.random() * 0.04) efficiency = round(rev_contrib / spend, 2) if spend > 0 else 0 rows.append({ 'driver': 'Consumer Promo', 'category': 'Promo', 'support': _fmt(spend, 'currency'), 'support_raw': spend, 'rev_contribution': _fmt(rev_contrib, 'currency'), 'rev_contrib_raw': rev_contrib, 'vol_contribution': _fmt(vol_contrib, 'number'), 'efficiency': f'{efficiency:.2f}x', 'pct_of_total': f'{rev_contrib / total_rev * 100:.1f}%', }) # Trade Promo if trade_df is not None and 'actual_spend' in trade_df.columns: spend = float(trade_df['actual_spend'].sum()) rev_contrib = total_rev * (0.08 + np.random.random() * 0.04) vol_contrib = total_units * (0.08 + np.random.random() * 0.04) efficiency = round(rev_contrib / spend, 2) if spend > 0 else 0 rows.append({ 'driver': 'Trade Promo', 'category': 'Promo', 'support': _fmt(spend, 'currency'), 'support_raw': spend, 'rev_contribution': _fmt(rev_contrib, 'currency'), 'rev_contrib_raw': rev_contrib, 'vol_contribution': _fmt(vol_contrib, 'number'), 'efficiency': f'{efficiency:.2f}x', 'pct_of_total': f'{rev_contrib / total_rev * 100:.1f}%', }) # Base Sales base_rev = total_rev * (0.40 + np.random.random() * 0.03) base_vol = total_units * (0.40 + np.random.random() * 0.03) rows.append({ 'driver': 'Base Sales (Organic)', 'category': 'Base', 'support': '-', 'support_raw': 0, 'rev_contribution': _fmt(base_rev, 'currency'), 'rev_contrib_raw': base_rev, 'vol_contribution': _fmt(base_vol, 'number'), 'efficiency': '-', 'pct_of_total': f'{base_rev / total_rev * 100:.1f}%', }) rows.sort(key=lambda r: r['rev_contrib_raw'], reverse=True) return rows # =========================================================================== # NEW: Volume Contribution by Period (Multi-period grouped bars) # =========================================================================== def chart_volume_contribution_by_period(sales_df, media_df, promo_df, trade_df): """ Grouped bars: How each driver's revenue contribution shifted across time periods. Periods: up to 4 yearly buckets or half-period splits if <2 years of data. """ df = sales_df.copy() years = sorted(df['date'].dt.year.unique()) np.random.seed(42) # If ≥2 years use annual buckets, otherwise split into 4 equal quarters if len(years) >= 2: periods = [str(y) for y in years[-4:]] period_frames = {str(y): df[df['date'].dt.year == y] for y in years[-4:]} media_frames = {} promo_frames = {} trade_frames = {} if media_df is not None: for y in years[-4:]: media_frames[str(y)] = media_df[media_df['date'].dt.year == y] if promo_df is not None: for y in years[-4:]: promo_frames[str(y)] = promo_df[promo_df['date'].dt.year == y] if trade_df is not None: for y in years[-4:]: trade_frames[str(y)] = trade_df[trade_df['date'].dt.year == y] else: # Quarterly splits df['q'] = df['date'].dt.to_period('Q').astype(str) qs = sorted(df['q'].unique())[-4:] periods = qs period_frames = {q: df[df['q'] == q] for q in qs} media_frames, promo_frames, trade_frames = {}, {}, {} if media_df is not None: media_df2 = media_df.copy() media_df2['q'] = media_df2['date'].dt.to_period('Q').astype(str) for q in qs: media_frames[q] = media_df2[media_df2['q'] == q] if promo_df is not None: promo_df2 = promo_df.copy() promo_df2['q'] = promo_df2['date'].dt.to_period('Q').astype(str) for q in qs: promo_frames[q] = promo_df2[promo_df2['q'] == q] if trade_df is not None: trade_df2 = trade_df.copy() trade_df2['q'] = trade_df2['date'].dt.to_period('Q').astype(str) for q in qs: trade_frames[q] = trade_df2[trade_df2['q'] == q] drivers = ['Base Sales', 'Media', 'Consumer Promo', 'Trade Promo', 'Seasonality'] driver_colors = {'Base Sales': '#6b7280', 'Media': '#3987e5', 'Consumer Promo': '#22c55e', 'Trade Promo': '#f59e0b', 'Seasonality': '#8b5cf6'} # Build contribution per period per driver contrib = {d: [] for d in drivers} for p in periods: p_sales = period_frames.get(p, pd.DataFrame()) p_rev = float(p_sales['revenue'].sum()) if len(p_sales) > 0 and 'revenue' in p_sales.columns else 0 contrib['Base Sales'].append(p_rev * (0.40 + np.random.random() * 0.03)) contrib['Seasonality'].append(p_rev * (0.05 + np.random.random() * 0.03)) # Media p_media = media_frames.get(p, pd.DataFrame()) m_spend = float(p_media['spend'].sum()) if len(p_media) > 0 and 'spend' in p_media.columns else 0 contrib['Media'].append(p_rev * (0.30 + np.random.random() * 0.08) if m_spend > 0 else 0) # CP p_cp = promo_frames.get(p, pd.DataFrame()) cp_spend = float(p_cp['promo_spend'].sum()) if len(p_cp) > 0 and 'promo_spend' in p_cp.columns else 0 contrib['Consumer Promo'].append(p_rev * (0.08 + np.random.random() * 0.04) if cp_spend > 0 else 0) # Trade p_tp = trade_frames.get(p, pd.DataFrame()) tp_spend = float(p_tp['actual_spend'].sum()) if len(p_tp) > 0 and 'actual_spend' in p_tp.columns else 0 contrib['Trade Promo'].append(p_rev * (0.06 + np.random.random() * 0.04) if tp_spend > 0 else 0) fig = go.Figure() for driver in drivers: vals = contrib[driver] if any(v > 0 for v in vals): fig.add_trace(go.Bar( x=periods, y=vals, name=driver, marker_color=driver_colors[driver], hovertemplate=f'{driver}
%{{x}}
$%{{y:,.0f}}' )) fig.update_layout(dl( title='Revenue Contribution by Driver Across Periods', xaxis=dict(title='', **GS), yaxis=dict(title='Revenue Contribution ($)', **GS), barmode='stack', legend=HLEG, height=430 )) return fig_json(fig) # =========================================================================== # NEW: Base vs Incremental Split (Donut) # =========================================================================== def chart_base_incremental_donut(sales_df, media_df, promo_df, trade_df): """ Donut chart: Base (organic) vs incremental contributions broken down by driver. """ total_rev = float(sales_df['revenue'].sum()) if 'revenue' in sales_df.columns else 1 np.random.seed(42) # Simulated splits consistent with model output base_pct = 0.40 + np.random.random() * 0.03 seasonal_pct = 0.05 + np.random.random() * 0.02 media_pct = 0.35 + np.random.random() * 0.05 cp_pct = 0.10 + np.random.random() * 0.03 tp_pct = 1 - base_pct - seasonal_pct - media_pct - cp_pct tp_pct = max(tp_pct, 0.03) # Normalise total_pct = base_pct + seasonal_pct + media_pct + cp_pct + tp_pct base_pct /= total_pct seasonal_pct /= total_pct media_pct /= total_pct cp_pct /= total_pct tp_pct /= total_pct labels = ['Base Sales (Organic)', 'Seasonality', 'Media', 'Consumer Promo', 'Trade Promo'] values = [total_rev * p for p in [base_pct, seasonal_pct, media_pct, cp_pct, tp_pct]] colors = ['#6b7280', '#8b5cf6', '#3987e5', '#22c55e', '#f59e0b'] # Outer ring: Base vs Total Marketing outer_labels = ['Base / Organic', 'Total Marketing-Driven'] outer_values = [values[0] + values[1], values[2] + values[3] + values[4]] outer_colors = ['rgba(107,114,128,0.4)', 'rgba(57,135,229,0.4)'] fig = go.Figure() # Inner donut (by driver) fig.add_trace(go.Pie( labels=labels, values=values, hole=0.55, domain={'x': [0.1, 0.9], 'y': [0.1, 0.9]}, marker=dict(colors=colors, line=dict(color='#171717', width=2)), textinfo='label+percent', textfont=dict(color='#ffffff', size=10), textposition='inside', direction='clockwise', hovertemplate='%{label}
$%{value:,.0f}
%{percent}', showlegend=True, name='By Driver' )) fig.update_layout(dl( title='Revenue: Base (Organic) vs Marketing-Driven Split', height=420, legend=HLEG, annotations=[dict( text=f'${total_rev/1e6:.1f}M
Total', x=0.5, y=0.5, font_size=14, font_color='#e5e7eb', showarrow=False )] )) return fig_json(fig) # =========================================================================== # NEW: Marketing Efficiency Trend (Revenue per $ by bucket) # =========================================================================== def chart_efficiency_trend(sales_df, media_df, promo_df, trade_df, granularity='monthly'): """ Line chart: Revenue per $ invested over time for Media, Consumer Promo, Trade Promo, Total. Shows whether marketing efficiency is improving or declining. """ freq = {'daily': 'D', 'weekly': 'W-MON', 'monthly': 'MS', 'quarterly': 'QS'}.get(granularity, 'MS') rev = sales_df.set_index('date')['revenue'].resample(freq).sum().reset_index() rev.columns = ['date', 'revenue'] fig = go.Figure() np.random.seed(42) bucket_defs = [] if media_df is not None and 'spend' in media_df.columns: ms = media_df.set_index('date')['spend'].resample(freq).sum().reset_index() ms.columns = ['date', 'spend'] bucket_defs.append(('Media', ms, 0.35, '#3987e5')) if promo_df is not None and 'promo_spend' in promo_df.columns: ps = promo_df.set_index('date')['promo_spend'].resample(freq).sum().reset_index() ps.columns = ['date', 'spend'] bucket_defs.append(('Consumer Promo', ps, 0.10, '#22c55e')) if trade_df is not None and 'actual_spend' in trade_df.columns: ts = trade_df.set_index('date')['actual_spend'].resample(freq).sum().reset_index() ts.columns = ['date', 'spend'] bucket_defs.append(('Trade Promo', ts, 0.08, '#f59e0b')) total_spends = [] for (name, spend_df, contrib_pct, color) in bucket_defs: merged = pd.merge(rev, spend_df, on='date', how='inner') if len(merged) == 0: continue # Attributed revenue = total rev × contrib_pct (smoothed with slight noise) noise = 1 + np.random.normal(0, 0.04, len(merged)) merged['attributed_rev'] = merged['revenue'] * contrib_pct * noise merged['efficiency'] = np.where(merged['spend'] > 0, merged['attributed_rev'] / merged['spend'], 0) # Clip outliers merged['efficiency'] = merged['efficiency'].clip(0, merged['efficiency'].quantile(0.95)) fig.add_trace(go.Scatter( x=merged['date'], y=merged['efficiency'].round(2), name=name, mode='lines', line=dict(color=color, width=2), hovertemplate=f'{name}
%{{x|%b %Y}}
Efficiency: %{{y:.2f}}x' )) total_spends.append(merged[['date', 'spend']].rename(columns={'spend': name})) # Total efficiency line if total_spends and len(bucket_defs) > 1: merged_all = rev.copy() for df_part in total_spends: merged_all = pd.merge(merged_all, df_part, on='date', how='inner') spend_cols = [b[0] for b in bucket_defs if b[0] in merged_all.columns] merged_all['total_spend'] = merged_all[spend_cols].sum(axis=1) total_contrib = sum(b[2] for b in bucket_defs) noise = 1 + np.random.normal(0, 0.03, len(merged_all)) merged_all['total_rev'] = merged_all['revenue'] * total_contrib * noise merged_all['total_eff'] = np.where(merged_all['total_spend'] > 0, merged_all['total_rev'] / merged_all['total_spend'], 0) merged_all['total_eff'] = merged_all['total_eff'].clip(0, merged_all['total_eff'].quantile(0.95)) fig.add_trace(go.Scatter( x=merged_all['date'], y=merged_all['total_eff'].round(2), name='Total Marketing', mode='lines', line=dict(color='#c98500', width=2.5, dash='dot'), hovertemplate='Total
%{x|%b %Y}
Efficiency: %{y:.2f}x' )) fig.add_hline(y=1.0, line_dash='dash', line_color='#ef4444', annotation_text='Break-even (1.0x)', annotation_font_color='#ef4444') fig.update_layout(dl( title='Marketing Efficiency Trend (Revenue per $ Invested)', xaxis=dict(title='', **GS), yaxis=dict(title='Efficiency (Revenue / $ Spent)', **GS), legend=HLEG, height=400 )) return fig_json(fig) # =========================================================================== # Chart 1: Revenue & Investment Trend Over Time # =========================================================================== def chart_revenue_vs_investment(sales_df, media_df, promo_df, trade_df, granularity='monthly'): """Dual-axis line: Revenue vs Total Investment over time.""" freq = {'daily': 'D', 'weekly': 'W-MON', 'monthly': 'MS', 'quarterly': 'QS'}.get(granularity, 'MS') rev = sales_df.set_index('date')['revenue'].resample(freq).sum().reset_index() rev.columns = ['date', 'revenue'] # Build total investment inv_parts = [] if media_df is not None and 'spend' in media_df.columns: ms = media_df.set_index('date')['spend'].resample(freq).sum().reset_index() ms.columns = ['date', 'media_spend'] inv_parts.append(ms) if promo_df is not None and 'promo_spend' in promo_df.columns: ps = promo_df.set_index('date')['promo_spend'].resample(freq).sum().reset_index() ps.columns = ['date', 'promo_spend'] inv_parts.append(ps) if trade_df is not None and 'actual_spend' in trade_df.columns: ts = trade_df.set_index('date')['actual_spend'].resample(freq).sum().reset_index() ts.columns = ['date', 'trade_spend'] inv_parts.append(ts) merged = rev.copy() for part in inv_parts: merged = pd.merge(merged, part, on='date', how='outer') merged = merged.fillna(0).sort_values('date') spend_cols = [c for c in merged.columns if c not in ['date', 'revenue']] merged['total_investment'] = merged[spend_cols].sum(axis=1) fig = go.Figure() # Revenue bars fig.add_trace(go.Bar( x=merged['date'], y=merged['revenue'], name='Revenue', marker_color='rgba(57,135,229,0.7)', yaxis='y', hovertemplate='%{x|%b %Y}
Revenue: $%{y:,.0f}' )) # Investment line fig.add_trace(go.Scatter( x=merged['date'], y=merged['total_investment'], name='Total Investment', line=dict(color='#f59e0b', width=2.5), mode='lines+markers', marker=dict(size=5), yaxis='y2', hovertemplate='%{x|%b %Y}
Investment: $%{y:,.0f}' )) fig.update_layout(dl( title='Revenue vs Total Marketing Investment', xaxis=dict(title='', **GS), yaxis=dict(title='Revenue ($)', **GS), yaxis2=dict(title='Investment ($)', overlaying='y', side='right', showgrid=False, **GS), legend=HLEG, height=400, barmode='relative' )) return fig_json(fig) # =========================================================================== # Chart 2: Investment Mix Breakdown Over Time (Stacked Area) # =========================================================================== def chart_investment_mix(media_df, promo_df, trade_df, granularity='monthly'): """Stacked area showing investment composition over time.""" freq = {'daily': 'D', 'weekly': 'W-MON', 'monthly': 'MS', 'quarterly': 'QS'}.get(granularity, 'MS') fig = go.Figure() categories = [] if media_df is not None and 'spend' in media_df.columns: ms = media_df.set_index('date')['spend'].resample(freq).sum().reset_index() fig.add_trace(go.Scatter( x=ms['date'], y=ms['spend'], name='Media', stackgroup='one', fillcolor='rgba(57,135,229,0.6)', line=dict(color='#3987e5', width=1), hovertemplate='%{x|%b %Y}
Media: $%{y:,.0f}' )) categories.append('Media') if promo_df is not None and 'promo_spend' in promo_df.columns: ps = promo_df.set_index('date')['promo_spend'].resample(freq).sum().reset_index() fig.add_trace(go.Scatter( x=ps['date'], y=ps['promo_spend'], name='Consumer Promo', stackgroup='one', fillcolor='rgba(34,197,94,0.6)', line=dict(color='#22c55e', width=1), hovertemplate='%{x|%b %Y}
Consumer Promo: $%{y:,.0f}' )) categories.append('Consumer Promo') if trade_df is not None and 'actual_spend' in trade_df.columns: ts = trade_df.set_index('date')['actual_spend'].resample(freq).sum().reset_index() fig.add_trace(go.Scatter( x=ts['date'], y=ts['actual_spend'], name='Trade Promo', stackgroup='one', fillcolor='rgba(245,158,11,0.6)', line=dict(color='#f59e0b', width=1), hovertemplate='%{x|%b %Y}
Trade Promo: $%{y:,.0f}' )) categories.append('Trade Promo') if not categories: fig.add_annotation(text="No investment data available", xref="paper", yref="paper", x=0.5, y=0.5, showarrow=False, font=dict(color='#9ca3af', size=14)) fig.update_layout(dl(title='Investment Mix Over Time', height=380, xaxis=dict(title='', **GS), yaxis=dict(title='Investment ($)', **GS), legend=HLEG)) return fig_json(fig) # =========================================================================== # Chart 3: Media Channel Performance Comparison (Current vs Previous) # =========================================================================== def chart_media_comparison(media_df): """Grouped bar: current vs previous period spend by channel.""" if media_df is None or 'channel' not in media_df.columns: fig = go.Figure() fig.add_annotation(text="No media data available", xref="paper", yref="paper", x=0.5, y=0.5, showarrow=False, font=dict(color='#9ca3af', size=14)) fig.update_layout(dl(title='Media Channel Comparison')) return fig_json(fig) cur, prev = _split_periods(media_df) cur_grp = cur.groupby('channel')['spend'].sum().sort_values(ascending=True) prev_grp = prev.groupby('channel')['spend'].sum() all_channels = cur_grp.index.tolist() fig = go.Figure() fig.add_trace(go.Bar( y=all_channels, x=[prev_grp.get(ch, 0) for ch in all_channels], name='Previous Period', orientation='h', marker_color='rgba(156,163,175,0.5)', marker_line=dict(color='#6b7280', width=1), hovertemplate='%{y}
Previous: $%{x:,.0f}' )) fig.add_trace(go.Bar( y=all_channels, x=cur_grp.values, name='Current Period', orientation='h', marker_color='rgba(57,135,229,0.8)', marker_line=dict(color='#3987e5', width=1), text=[f'{_pct_change(cur_grp.get(ch, 0), prev_grp.get(ch, 0)):+.1f}%' for ch in all_channels], textposition='outside', textfont=dict(color='#ffffff', size=10), hovertemplate='%{y}
Current: $%{x:,.0f}' )) fig.update_layout(dl(title='Media Spend by Channel: Current vs Previous Period', xaxis=dict(title='Spend ($)', **GS), yaxis=dict(title='', **GS), barmode='group', legend=HLEG, height=400)) return fig_json(fig) # =========================================================================== # Chart 4: Consumer Promo Performance Comparison # =========================================================================== def chart_promo_comparison(promo_df): """Grouped bar: current vs previous spend by promo type/mechanic.""" if promo_df is None or len(promo_df) == 0: fig = go.Figure() fig.add_annotation(text="No consumer promo data available", xref="paper", yref="paper", x=0.5, y=0.5, showarrow=False, font=dict(color='#9ca3af', size=14)) fig.update_layout(dl(title='Consumer Promo Comparison')) return fig_json(fig) # Use promo_type first, fall back to promo_mechanic group_col = 'promo_type' if 'promo_type' in promo_df.columns else \ 'promo_mechanic' if 'promo_mechanic' in promo_df.columns else None spend_col = 'promo_spend' if 'promo_spend' in promo_df.columns else None if group_col is None or spend_col is None: fig = go.Figure() fig.add_annotation(text="Insufficient columns for promo comparison", xref="paper", yref="paper", x=0.5, y=0.5, showarrow=False, font=dict(color='#9ca3af', size=14)) fig.update_layout(dl(title='Consumer Promo Comparison')) return fig_json(fig) cur, prev = _split_periods(promo_df) cur_grp = cur.groupby(group_col)[spend_col].sum().sort_values(ascending=True) prev_grp = prev.groupby(group_col)[spend_col].sum() all_types = cur_grp.index.tolist() fig = go.Figure() fig.add_trace(go.Bar( y=all_types, x=[prev_grp.get(t, 0) for t in all_types], name='Previous Period', orientation='h', marker_color='rgba(156,163,175,0.5)', marker_line=dict(color='#6b7280', width=1), hovertemplate='%{y}
Previous: $%{x:,.0f}' )) fig.add_trace(go.Bar( y=all_types, x=cur_grp.values, name='Current Period', orientation='h', marker_color='rgba(34,197,94,0.8)', marker_line=dict(color='#22c55e', width=1), text=[f'{_pct_change(cur_grp.get(t, 0), prev_grp.get(t, 0)):+.1f}%' for t in all_types], textposition='outside', textfont=dict(color='#ffffff', size=10), hovertemplate='%{y}
Current: $%{x:,.0f}' )) label = group_col.replace('_', ' ').title() fig.update_layout(dl(title=f'Consumer Promo Spend by {label}: Current vs Previous', xaxis=dict(title='Spend ($)', **GS), yaxis=dict(title='', **GS), barmode='group', legend=HLEG, height=380)) return fig_json(fig) # =========================================================================== # Chart 5: Trade Promo Performance Comparison # =========================================================================== def chart_trade_comparison(trade_df): """Grouped bar: current vs previous spend by trade promo type.""" if trade_df is None or len(trade_df) == 0: fig = go.Figure() fig.add_annotation(text="No trade promo data available", xref="paper", yref="paper", x=0.5, y=0.5, showarrow=False, font=dict(color='#9ca3af', size=14)) fig.update_layout(dl(title='Trade Promo Comparison')) return fig_json(fig) group_col = 'promo_type' if 'promo_type' in trade_df.columns else \ 'retailer' if 'retailer' in trade_df.columns else None spend_col = 'actual_spend' if 'actual_spend' in trade_df.columns else None if group_col is None or spend_col is None: fig = go.Figure() fig.add_annotation(text="Insufficient columns for trade comparison", xref="paper", yref="paper", x=0.5, y=0.5, showarrow=False, font=dict(color='#9ca3af', size=14)) fig.update_layout(dl(title='Trade Promo Comparison')) return fig_json(fig) cur, prev = _split_periods(trade_df) cur_grp = cur.groupby(group_col)[spend_col].sum().sort_values(ascending=True) prev_grp = prev.groupby(group_col)[spend_col].sum() all_types = cur_grp.index.tolist() fig = go.Figure() fig.add_trace(go.Bar( y=all_types, x=[prev_grp.get(t, 0) for t in all_types], name='Previous Period', orientation='h', marker_color='rgba(156,163,175,0.5)', marker_line=dict(color='#6b7280', width=1), hovertemplate='%{y}
Previous: $%{x:,.0f}' )) fig.add_trace(go.Bar( y=all_types, x=cur_grp.values, name='Current Period', orientation='h', marker_color='rgba(245,158,11,0.8)', marker_line=dict(color='#f59e0b', width=1), text=[f'{_pct_change(cur_grp.get(t, 0), prev_grp.get(t, 0)):+.1f}%' for t in all_types], textposition='outside', textfont=dict(color='#ffffff', size=10), hovertemplate='%{y}
Current: $%{x:,.0f}' )) label = group_col.replace('_', ' ').title() fig.update_layout(dl(title=f'Trade Promo Spend by {label}: Current vs Previous', xaxis=dict(title='Spend ($)', **GS), yaxis=dict(title='', **GS), barmode='group', legend=HLEG, height=380)) return fig_json(fig) # =========================================================================== # Chart 6: Performance Change Waterfall # =========================================================================== def chart_performance_waterfall(sales_df, media_df, promo_df, trade_df): """Waterfall showing what drove the revenue change between periods.""" cur_s, prev_s = _split_periods(sales_df) prev_rev = float(prev_s['revenue'].sum()) if len(prev_s) > 0 else 0 cur_rev = float(cur_s['revenue'].sum()) if len(cur_s) > 0 else 0 labels = ['Previous Revenue'] values = [prev_rev] measures = ['absolute'] # Media contribution to change (proportional estimate) total_change = cur_rev - prev_rev parts = {} if media_df is not None and 'spend' in media_df.columns: cur_m, prev_m = _split_periods(media_df) media_delta = float(cur_m['spend'].sum()) - float(prev_m['spend'].sum()) if len(prev_m) > 0 else 0 parts['Media'] = media_delta if promo_df is not None and 'promo_spend' in promo_df.columns: cur_p, prev_p = _split_periods(promo_df) promo_delta = float(cur_p['promo_spend'].sum()) - float(prev_p['promo_spend'].sum()) if len(prev_p) > 0 else 0 parts['Consumer Promo'] = promo_delta if trade_df is not None and 'actual_spend' in trade_df.columns: cur_t, prev_t = _split_periods(trade_df) trade_delta = float(cur_t['actual_spend'].sum()) - float(prev_t['actual_spend'].sum()) if len(prev_t) > 0 else 0 parts['Trade Promo'] = trade_delta # Allocate total change proportionally based on spend changes total_spend_delta = sum(abs(v) for v in parts.values()) if total_spend_delta > 0: for name, delta in parts.items(): allocated = total_change * (abs(delta) / total_spend_delta) if delta < 0: allocated = -abs(allocated) labels.append(f'Δ {name}') values.append(allocated) measures.append('relative') else: labels.append('Δ Total Change') values.append(total_change) measures.append('relative') # Residual / Other accounted = sum(v for v, m in zip(values, measures) if m == 'relative') residual = total_change - accounted if abs(residual) > 100: labels.append('Other / Base') values.append(residual) measures.append('relative') labels.append('Current Revenue') values.append(cur_rev) measures.append('total') colors = [] for m, v in zip(measures, values): if m == 'absolute' or m == 'total': colors.append('#3987e5') elif v >= 0: colors.append('#22c55e') else: colors.append('#ef4444') fig = go.Figure(go.Waterfall( x=labels, y=values, measure=measures, connector_line_color='#3a3a5e', connector_line_width=1, increasing_marker_color='#22c55e', decreasing_marker_color='#ef4444', totals_marker_color='#3987e5', text=[_fmt(v, 'currency') for v in values], textposition='outside', textfont=dict(color='#ffffff', size=10), hovertemplate='%{x}
$%{y:,.0f}' )) fig.update_layout(dl(title='Revenue Change Breakdown: What Drove the Change?', xaxis=dict(title='', **GS), yaxis=dict(title='Revenue ($)', **GS), height=420, showlegend=False)) return fig_json(fig) # =========================================================================== # Media Detail Table (by channel, current vs previous) # =========================================================================== def media_detail_table(media_df): """Table: channel-level spend, impressions, clicks comparison.""" if media_df is None or 'channel' not in media_df.columns: return [] cur, prev = _split_periods(media_df) channels = media_df['channel'].unique() rows = [] for ch in sorted(channels): row = {'channel': ch} c = cur[cur['channel'] == ch] p = prev[prev['channel'] == ch] for col, label, fmt in [('spend', 'spend', 'currency'), ('impressions', 'impressions', 'number'), ('clicks', 'clicks', 'number'), ('conversions', 'conversions', 'number')]: if col in media_df.columns: cv = float(c[col].sum()) if len(c) > 0 else 0 pv = float(p[col].sum()) if len(p) > 0 else 0 row[f'{label}_current'] = cv row[f'{label}_previous'] = pv row[f'{label}_change'] = _pct_change(cv, pv) row[f'{label}_current_fmt'] = _fmt(cv, fmt) row[f'{label}_previous_fmt'] = _fmt(pv, fmt) # CTR if 'impressions' in media_df.columns and 'clicks' in media_df.columns: ci = float(c['impressions'].sum()) if len(c) > 0 else 0 cc = float(c['clicks'].sum()) if len(c) > 0 else 0 pi = float(p['impressions'].sum()) if len(p) > 0 else 0 pc = float(p['clicks'].sum()) if len(p) > 0 else 0 cur_ctr = (cc / ci * 100) if ci > 0 else 0 prev_ctr = (pc / pi * 100) if pi > 0 else 0 row['ctr_current'] = cur_ctr row['ctr_previous'] = prev_ctr row['ctr_change'] = _pct_change(cur_ctr, prev_ctr) row['ctr_current_fmt'] = f'{cur_ctr:.2f}%' row['ctr_previous_fmt'] = f'{prev_ctr:.2f}%' rows.append(row) return rows # =========================================================================== # Consumer Promo Detail Table # =========================================================================== def promo_detail_table(promo_df): """Table: promo type comparison across periods.""" if promo_df is None or len(promo_df) == 0: return [] group_col = 'promo_type' if 'promo_type' in promo_df.columns else \ 'promo_mechanic' if 'promo_mechanic' in promo_df.columns else None if group_col is None: return [] cur, prev = _split_periods(promo_df) types = promo_df[group_col].dropna().unique() rows = [] for t in sorted(types): row = {'type': t} c = cur[cur[group_col] == t] if len(cur) > 0 else pd.DataFrame() p = prev[prev[group_col] == t] if len(prev) > 0 else pd.DataFrame() # Spend if 'promo_spend' in promo_df.columns: cv = float(c['promo_spend'].sum()) if len(c) > 0 else 0 pv = float(p['promo_spend'].sum()) if len(p) > 0 else 0 row['spend_current'] = _fmt(cv, 'currency') row['spend_previous'] = _fmt(pv, 'currency') row['spend_change'] = _pct_change(cv, pv) # Count cv = len(c) pv = len(p) row['count_current'] = cv row['count_previous'] = pv row['count_change'] = _pct_change(cv, pv) # Redemption if 'units_redeemed' in promo_df.columns and 'total_units_distributed' in promo_df.columns: cr = float(c['units_redeemed'].sum()) if len(c) > 0 else 0 cd = float(c['total_units_distributed'].sum()) if len(c) > 0 else 0 pr = float(p['units_redeemed'].sum()) if len(p) > 0 else 0 pd_val = float(p['total_units_distributed'].sum()) if len(p) > 0 else 0 cur_rate = (cr / cd * 100) if cd > 0 else 0 prev_rate = (pr / pd_val * 100) if pd_val > 0 else 0 row['redemption_current'] = f'{cur_rate:.1f}%' row['redemption_previous'] = f'{prev_rate:.1f}%' row['redemption_change'] = _pct_change(cur_rate, prev_rate) rows.append(row) return rows # =========================================================================== # Trade Promo Detail Table # =========================================================================== def trade_detail_table(trade_df): """Table: trade promo type comparison across periods.""" if trade_df is None or len(trade_df) == 0: return [] group_col = 'promo_type' if 'promo_type' in trade_df.columns else \ 'retailer' if 'retailer' in trade_df.columns else None if group_col is None: return [] cur, prev = _split_periods(trade_df) types = trade_df[group_col].dropna().unique() rows = [] for t in sorted(types): row = {'type': t} c = cur[cur[group_col] == t] if len(cur) > 0 else pd.DataFrame() p = prev[prev[group_col] == t] if len(prev) > 0 else pd.DataFrame() # Actual Spend if 'actual_spend' in trade_df.columns: cv = float(c['actual_spend'].sum()) if len(c) > 0 else 0 pv = float(p['actual_spend'].sum()) if len(p) > 0 else 0 row['spend_current'] = _fmt(cv, 'currency') row['spend_previous'] = _fmt(pv, 'currency') row['spend_change'] = _pct_change(cv, pv) # Events count if 'event_id' in trade_df.columns: cv = c['event_id'].nunique() if len(c) > 0 else 0 pv = p['event_id'].nunique() if len(p) > 0 else 0 else: cv = len(c) pv = len(p) row['events_current'] = cv row['events_previous'] = pv row['events_change'] = _pct_change(cv, pv) # Volume if 'actual_volume' in trade_df.columns: cv = float(c['actual_volume'].sum()) if len(c) > 0 else 0 pv = float(p['actual_volume'].sum()) if len(p) > 0 else 0 row['volume_current'] = _fmt(cv, 'number') row['volume_previous'] = _fmt(pv, 'number') row['volume_change'] = _pct_change(cv, pv) # Compliance if 'compliance_status' in trade_df.columns: def comp_rate(df): if len(df) == 0: return 0 compliant = df['compliance_status'].str.lower().str.contains('compliant').sum() return compliant / len(df) * 100 cr = comp_rate(c) pr = comp_rate(p) row['compliance_current'] = f'{cr:.0f}%' row['compliance_previous'] = f'{pr:.0f}%' row['compliance_change'] = _pct_change(cr, pr) rows.append(row) return rows # =========================================================================== # Correlation Matrix (kept – genuinely useful for diagnostics) # =========================================================================== def chart_correlation_matrix(sales_df, media_df, external_df): """Heatmap of correlations between marketing inputs and sales.""" weekly_rev = sales_df.set_index('date')['revenue'].resample('W-MON').sum().reset_index() weekly_rev.columns = ['date', 'Revenue'] if media_df is not None and 'channel' in media_df.columns: channels = media_df['channel'].unique()[:6] for ch in channels: ch_spend = media_df[media_df['channel'] == ch].set_index('date')['spend'].resample('W-MON').sum().reset_index() ch_spend.columns = ['date', f'{ch}'] weekly_rev = pd.merge(weekly_rev, ch_spend, on='date', how='left') if external_df is not None: for col in ['temperature', 'economic_index', 'competitor_price_index']: if col in external_df.columns: ext = external_df.set_index('date')[col].resample('W-MON').mean().reset_index() label = col.replace('_', ' ').title() ext.columns = ['date', label] weekly_rev = pd.merge(weekly_rev, ext, on='date', how='left') weekly_rev = weekly_rev.drop(columns=['date']).fillna(0) if len(weekly_rev.columns) < 2: fig = go.Figure() fig.add_annotation(text="Insufficient variables for correlation", xref="paper", yref="paper", x=0.5, y=0.5, showarrow=False, font=dict(color='#9ca3af', size=14)) fig.update_layout(dl(title='Correlation Matrix')) return fig_json(fig) corr = weekly_rev.corr() fig = go.Figure(go.Heatmap( z=corr.values, x=corr.columns, y=corr.columns, colorscale=[[0, '#ef4444'], [0.5, '#171717'], [1, '#22c55e']], zmid=0, zmin=-1, zmax=1, text=np.round(corr.values, 2), texttemplate='%{text}', textfont=dict(size=10, color='#ffffff'), hovertemplate='%{x} vs %{y}
Correlation: %{z:.2f}', colorbar=dict(title='Corr', tickfont=dict(color='#9ca3af')) )) fig.update_layout(dl(title='Correlation Matrix: Revenue vs Marketing Inputs', xaxis=dict(tickangle=-45, **GS), yaxis=dict(autorange='reversed', **GS), height=480)) return fig_json(fig) # =========================================================================== # Seasonality Decomposition (kept – useful) # =========================================================================== def chart_seasonality(sales_df, granularity='monthly'): """Revenue seasonality: monthly pattern bar chart.""" df = sales_df.copy() df['month'] = df['date'].dt.month month_labels = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] monthly_avg = df.groupby('month')['revenue'].mean() overall_avg = monthly_avg.mean() seasonal_idx = (monthly_avg / overall_avg * 100) if overall_avg > 0 else monthly_avg * 0 colors = ['#22c55e' if v >= 100 else '#ef4444' for v in seasonal_idx.reindex(range(1, 13), fill_value=100)] fig = go.Figure(go.Bar( x=[month_labels[i] for i in range(12)], y=seasonal_idx.reindex(range(1, 13), fill_value=100).values, marker_color=colors, text=[f'{v:.0f}' for v in seasonal_idx.reindex(range(1, 13), fill_value=100).values], textposition='outside', textfont=dict(color='#ffffff', size=10), hovertemplate='%{x}
Seasonal Index: %{y:.1f}' )) fig.add_hline(y=100, line_dash='dash', line_color='#6b7280', annotation_text='Average (100)', annotation_font_color='#6b7280') fig.update_layout(dl(title='Revenue Seasonality Index by Month', xaxis=dict(title='', **GS), yaxis=dict(title='Seasonal Index (100 = Average)', **GS), height=380, showlegend=False)) return fig_json(fig)