import plotly.graph_objects as go
import pandas as pd
import numpy as np
import json
COLORS = ['#3987e5', '#d95926', '#199e70', '#c98500', '#d55181', '#7c6cc4', '#47a1b8', '#e87ba4', '#8db058', '#f59e0b']
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_to_json(fig):
return json.loads(fig.to_json())
def freq_map(g):
return {'daily': 'D', 'weekly': 'W-MON', 'monthly': 'MS', 'quarterly': 'QS', 'yearly': 'YS'}.get(g, 'MS')
# ---- SCREEN 1 ----
def chart_revenue_vs_spend(sales_df, media_df, granularity='monthly'):
f = freq_map(granularity)
rev = sales_df.set_index('date')['revenue'].resample(f).sum().reset_index()
spd = media_df.set_index('date')['spend'].resample(f).sum().reset_index()
m = pd.merge(rev, spd, on='date', how='outer').fillna(0).sort_values('date')
fig = go.Figure()
fig.add_trace(go.Scatter(x=m['date'], y=m['revenue'], name='Revenue', line=dict(color=COLORS[0], width=2.5), fill='tozeroy', fillcolor='rgba(57,135,229,0.08)'))
fig.add_trace(go.Scatter(x=m['date'], y=m['spend'], name='Marketing Spend', line=dict(color=COLORS[1], width=2.5, dash='dot'), yaxis='y2'))
fig.update_layout(dl(title='Revenue vs Total Marketing Spend',
xaxis=dict(**GS), yaxis=dict(title='Revenue ($)', **GS),
yaxis2=dict(title='Spend ($)', overlaying='y', side='right', **GS), legend=HLEG))
return fig_to_json(fig)
def chart_spend_allocation(media_df, promo_df, trade_df):
ms = media_df.groupby('channel')['spend'].sum()
cp = promo_df['promo_spend'].sum() if len(promo_df) > 0 else 0
tp = trade_df['actual_spend'].sum() if len(trade_df) > 0 else 0
labels = list(ms.index) + ['Consumer Promo', 'Trade Promo']
values = list(ms.values) + [cp, tp]
fig = go.Figure(data=[go.Pie(labels=labels, values=values, hole=0.55,
marker=dict(colors=COLORS[:len(labels)]), textinfo='percent+label',
textfont=dict(size=11, color='#ffffff'),
hovertemplate='%{label}
$%{value:,.0f}
%{percent}')])
total = sum(values)
fig.update_layout(dl(title='Spend Allocation Breakdown',
annotations=[dict(text=f'${total:,.0f}', x=0.5, y=0.5, font_size=18, font_color='#ffffff', showarrow=False)]))
return fig_to_json(fig)
def chart_category_volume_trend(sales_df, granularity='monthly'):
"""Category volume trend over time by product — shows how category has changed."""
f = freq_map(granularity)
if 'product' in sales_df.columns:
grouped = sales_df.set_index('date').groupby('product')['units_sold'].resample(f).sum().reset_index()
fig = go.Figure()
products = sorted(grouped['product'].unique())
for i, prod in enumerate(products[:8]):
cd = grouped[grouped['product'] == prod]
fig.add_trace(go.Bar(x=cd['date'], y=cd['units_sold'], name=prod,
marker_color=COLORS[i % len(COLORS)]))
fig.update_layout(dl(title='Category Volume Trend by Product',
barmode='stack', xaxis=dict(**GS),
yaxis=dict(title='Units Sold', **GS), legend=HLEG))
else:
agg = sales_df.set_index('date')['units_sold'].resample(f).sum().reset_index()
fig = go.Figure()
fig.add_trace(go.Bar(x=agg['date'], y=agg['units_sold'], name='Total Volume',
marker_color=COLORS[0]))
fig.update_layout(dl(title='Category Volume Trend',
xaxis=dict(**GS), yaxis=dict(title='Units Sold', **GS), legend=HLEG))
return fig_to_json(fig)
def chart_revenue_price_trend(sales_df, granularity='monthly'):
"""Revenue vs Average Selling Price trend — shows pricing dynamics."""
f = freq_map(granularity)
agg = sales_df.set_index('date').resample(f).agg({'revenue': 'sum', 'units_sold': 'sum'}).reset_index()
agg['avg_price'] = np.where(agg['units_sold'] > 0, agg['revenue'] / agg['units_sold'], 0)
fig = go.Figure()
fig.add_trace(go.Scatter(x=agg['date'], y=agg['revenue'], name='Revenue',
line=dict(color=COLORS[0], width=2.5), fill='tozeroy', fillcolor='rgba(57,135,229,0.08)'))
fig.add_trace(go.Scatter(x=agg['date'], y=agg['avg_price'], name='Avg Selling Price',
line=dict(color=COLORS[5], width=2.5, dash='dot'), yaxis='y2'))
fig.update_layout(dl(title='Revenue & Avg Selling Price Trend',
xaxis=dict(**GS), yaxis=dict(title='Revenue ($)', **GS),
yaxis2=dict(title='Avg Price ($)', overlaying='y', side='right', **GS), legend=HLEG))
return fig_to_json(fig)
def chart_marketing_efficiency(sales_df, media_df, granularity='monthly'):
f = freq_map(granularity)
rev = sales_df.set_index('date')['revenue'].resample(f).sum().reset_index()
spd = media_df.set_index('date')['spend'].resample(f).sum().reset_index()
m = pd.merge(rev, spd, on='date', how='outer').fillna(0).sort_values('date')
m['eff'] = np.where(m['spend'] > 0, m['revenue'] / m['spend'], 0)
by_ch = media_df.set_index('date').groupby('channel')['spend'].resample(f).sum().reset_index()
rev_idx = rev.set_index('date')['revenue']
fig = go.Figure()
fig.add_trace(go.Scatter(x=m['date'], y=m['eff'], name='Overall', line=dict(color=COLORS[0], width=3)))
for i, ch in enumerate(media_df['channel'].unique()[:4]):
cd = by_ch[by_ch['channel'] == ch].set_index('date')['spend']
cm = pd.DataFrame({'spend': cd}).join(pd.DataFrame({'revenue': rev_idx}), how='inner')
cm['eff'] = np.where(cm['spend'] > 0, cm['revenue'] / cm['spend'], 0)
cm = cm.reset_index()
fig.add_trace(go.Scatter(x=cm['date'], y=cm['eff'], name=ch, line=dict(color=COLORS[i+1], width=1.5, dash='dot')))
fig.update_layout(dl(title='Marketing Efficiency Trend', xaxis=dict(**GS),
yaxis=dict(title='Revenue per $ Spent', **GS), legend=HLEG))
return fig_to_json(fig)
def category_performance_table(sales_df):
"""Category performance by product — revenue, volume, price, share."""
if 'product' not in sales_df.columns:
return []
total_rev = sales_df['revenue'].sum()
total_units = sales_df['units_sold'].sum()
by_prod = sales_df.groupby('product').agg({
'revenue': 'sum', 'units_sold': 'sum', 'price': 'mean',
}).reset_index()
by_prod['avg_price'] = np.where(by_prod['units_sold'] > 0, by_prod['revenue'] / by_prod['units_sold'], 0)
by_prod['revenue_share'] = by_prod['revenue'] / total_rev * 100
by_prod['volume_share'] = by_prod['units_sold'] / total_units * 100
by_prod = by_prod.sort_values('revenue', ascending=False)
return [{'product': r['product'], 'revenue': round(r['revenue'], 0),
'units': int(r['units_sold']), 'avg_price': round(r['avg_price'], 2),
'revenue_share': round(r['revenue_share'], 1),
'volume_share': round(r['volume_share'], 1)}
for _, r in by_prod.iterrows()]
# ---- SCREEN 2 ----
def chart_media_spend_by_channel(media_df, granularity='monthly'):
f = freq_map(granularity)
grouped = media_df.set_index('date').groupby('channel')['spend'].resample(f).sum().reset_index()
fig = go.Figure()
for i, ch in enumerate(sorted(grouped['channel'].unique())):
cd = grouped[grouped['channel'] == ch]
fig.add_trace(go.Bar(x=cd['date'], y=cd['spend'], name=ch, marker_color=COLORS[i % len(COLORS)]))
fig.update_layout(dl(barmode='stack', title='Media Spend Over Time by Channel',
xaxis=dict(**GS), yaxis=dict(title='Spend ($)', **GS), legend=HLEG))
return fig_to_json(fig)
def chart_impressions_clicks(media_df, granularity='monthly'):
f = freq_map(granularity)
agg = media_df.set_index('date')[['impressions', 'clicks']].resample(f).sum().reset_index()
fig = go.Figure()
fig.add_trace(go.Scatter(x=agg['date'], y=agg['impressions'], name='Impressions', line=dict(color=COLORS[0], width=2.5)))
fig.add_trace(go.Scatter(x=agg['date'], y=agg['clicks'], name='Clicks', line=dict(color=COLORS[2], width=2.5), yaxis='y2'))
fig.update_layout(dl(title='Impressions & Clicks Trend', xaxis=dict(**GS),
yaxis=dict(title='Impressions', **GS), yaxis2=dict(title='Clicks', overlaying='y', side='right', **GS), legend=HLEG))
return fig_to_json(fig)
def chart_ctr_cpm(media_df, granularity='monthly'):
f = freq_map(granularity)
agg = media_df.set_index('date')[['impressions', 'clicks', 'spend']].resample(f).sum().reset_index()
agg['ctr'] = np.where(agg['impressions'] > 0, agg['clicks'] / agg['impressions'] * 100, 0)
agg['cpm'] = np.where(agg['impressions'] > 0, agg['spend'] / agg['impressions'] * 1000, 0)
fig = go.Figure()
fig.add_trace(go.Scatter(x=agg['date'], y=agg['ctr'], name='CTR (%)', line=dict(color=COLORS[0], width=2.5)))
fig.add_trace(go.Scatter(x=agg['date'], y=agg['cpm'], name='CPM ($)', line=dict(color=COLORS[1], width=2.5), yaxis='y2'))
fig.update_layout(dl(title='CTR & CPM Trend', xaxis=dict(**GS),
yaxis=dict(title='CTR (%)', **GS), yaxis2=dict(title='CPM ($)', overlaying='y', side='right', **GS), legend=HLEG))
return fig_to_json(fig)
def chart_campaign_funnel(media_df):
vals = {'Impressions': int(media_df['impressions'].sum()), 'Clicks': int(media_df['clicks'].sum()),
'Leads': int(media_df['leads'].sum()), 'Conversions': int(media_df['conversions'].sum())}
fig = go.Figure(go.Funnel(y=list(vals.keys()), x=list(vals.values()),
textinfo='value+percent initial', textfont=dict(color='#ffffff', size=13),
marker=dict(color=COLORS[:4]), connector=dict(line=dict(color='#262626', width=1))))
fig.update_layout(dl(title='Campaign Funnel', xaxis=dict(**GS), yaxis=dict(**GS)))
return fig_to_json(fig)
def chart_share_of_voice(media_df):
by_ch = media_df.groupby('channel').agg({'spend': 'sum'}).reset_index()
fig = go.Figure(go.Treemap(labels=by_ch['channel'], values=by_ch['spend'],
parents=['' for _ in by_ch['channel']],
marker=dict(colors=COLORS[:len(by_ch)], line=dict(color='#171717', width=2)),
textinfo='label+value+percent root', textfont=dict(color='#ffffff', size=13),
hovertemplate='%{label}
Spend: $%{value:,.0f}
Share: %{percentRoot:.1%}'))
fig.update_layout(dl(title='Channel Share of Voice'))
return fig_to_json(fig)
def chart_spend_vs_performance(media_df):
by_c = media_df.groupby(['campaign_name', 'channel']).agg(
{'spend': 'sum', 'conversions': 'sum', 'impressions': 'sum'}).reset_index()
by_c = by_c.nlargest(50, 'spend')
cmap = {ch: COLORS[i % len(COLORS)] for i, ch in enumerate(by_c['channel'].unique())}
fig = go.Figure()
for ch in by_c['channel'].unique():
s = by_c[by_c['channel'] == ch]
fig.add_trace(go.Scatter(x=s['spend'], y=s['conversions'], mode='markers', name=ch,
marker=dict(size=np.clip(s['impressions'] / s['impressions'].max() * 30, 5, 40),
color=cmap[ch], opacity=0.7, line=dict(color='#262626', width=1)),
text=s['campaign_name'],
hovertemplate='%{text}
Spend: $%{x:,.0f}
Conversions: %{y:,}'))
fig.add_hline(y=by_c['conversions'].mean(), line_dash='dash', line_color='rgba(107,114,128,0.6)')
fig.add_vline(x=by_c['spend'].mean(), line_dash='dash', line_color='rgba(107,114,128,0.6)')
fig.update_layout(dl(title='Spend vs Performance', xaxis=dict(title='Spend ($)', **GS),
yaxis=dict(title='Conversions', **GS), legend=HLEG))
return fig_to_json(fig)
def campaign_detail_table(media_df):
by_c = media_df.groupby(['campaign_name', 'channel']).agg(
{'spend': 'sum', 'impressions': 'sum', 'clicks': 'sum', 'conversions': 'sum',
'date': ['min', 'max']}).reset_index()
by_c.columns = ['campaign_name', 'channel', 'spend', 'impressions', 'clicks', 'conversions', 'start_date', 'end_date']
by_c['ctr'] = np.where(by_c['impressions'] > 0, by_c['clicks'] / by_c['impressions'] * 100, 0)
by_c['cpm'] = np.where(by_c['impressions'] > 0, by_c['spend'] / by_c['impressions'] * 1000, 0)
by_c['cpc'] = np.where(by_c['clicks'] > 0, by_c['spend'] / by_c['clicks'], 0)
by_c['cpa'] = np.where(by_c['conversions'] > 0, by_c['spend'] / by_c['conversions'], 0)
by_c['roas'] = np.where(by_c['spend'] > 0, by_c['conversions'] * 50 / by_c['spend'], 0)
by_c = by_c.sort_values('spend', ascending=False).head(100)
return [{'campaign': r['campaign_name'], 'channel': r['channel'],
'start': str(r['start_date'].date()), 'end': str(r['end_date'].date()),
'spend': round(r['spend'], 0), 'impressions': int(r['impressions']),
'clicks': int(r['clicks']), 'ctr': round(r['ctr'], 2), 'cpm': round(r['cpm'], 2),
'cpc': round(r['cpc'], 2), 'conversions': int(r['conversions']),
'cpa': round(r['cpa'], 2), 'roas': round(r['roas'], 2)}
for _, r in by_c.iterrows()]