import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from scipy import stats
import warnings
warnings.filterwarnings('ignore')
# =============================================================================
# CHANNEL CONFLICT ANALYTICS DASHBOARD
# =============================================================================
# This script builds a comprehensive analytics tool for channel conflict,
# including:
# 1. Margin analysis per channel (KPIs, bars, trends).
# 2. Cannibalization checks:
# - Pairwise correlation matrix (negative corr indicates potential cannibalization).
# - Linear regression coefficients (negative slope = cannibalization signal).
# - Cannibalization Score: (1 - R^2 of positive model) * |negative_coef| * significance.
# 3. Visual dashboard with interactive Plotly charts.
# 4. Alerts for high-risk conflicts (e.g., low-margin channel cannibalizing high-margin).
#
# Assumptions:
# - Sample data generated for demo (50 periods, 4 channels: Retail (high margin), Online (low),
# Wholesale (med), Direct (high).
# - Real usage: Replace generate_sample_data() with pd.read_csv('your_data.csv').
# - Data schema: 'period', 'channel', 'revenue', 'cost', 'units_sold'.
# =============================================================================
def generate_sample_data(n_periods=50, random_seed=42):
"""
Generate realistic sample data with built-in channel dynamics.
- Retail: High margin, stable but cannibalized by Online.
- Online: Low margin, aggressive growth.
- Wholesale: Medium margin, steady.
- Direct: High margin, volatile.
- Total market grows 2% per period; channels compete.
"""
np.random.seed(random_seed)
periods = pd.date_range('2023-01-01', periods=n_periods, freq='W')
channels = ['Retail', 'Online', 'Wholesale', 'Direct']
# Base margins (%)
margins = {'Retail': 0.42, 'Online': 0.22, 'Wholesale': 0.35, 'Direct': 0.48}
data = []
total_market = 10000 # Starting total market size
for period in periods:
total_market *= 1.02 # Organic market growth
channel_revenues = np.random.lognormal(9, 0.3, len(channels)) # Base rev per channel
channel_revenues = channel_revenues / channel_revenues.sum() * total_market
# Simulate cannibalization: Online growth hurts Retail
online_boost = np.random.normal(1.1, 0.2)
channel_revenues[1] *= online_boost # Boost Online
channel_revenues[0] *= (1 - 0.08 * online_boost) # Hurt Retail
for i, ch in enumerate(channels):
revenue = max(channel_revenues[i], 1000) # Min revenue
units = np.random.poisson(revenue / np.random.uniform(20, 50))
cost = revenue * (1 - margins[ch]) * (1 + np.random.normal(0, 0.05))
data.append({'period': period, 'channel': ch, 'revenue': revenue, 'cost': cost, 'units_sold': units})
df = pd.DataFrame(data)
return df
# Load data (use your own CSV for production)
df = generate_sample_data()
print("Sample Data Shape:", df.shape)
print(df.head())
# =============================================================================
# STEP 1: MARGIN ANALYSIS
# =============================================================================
df['gross_profit'] = df['revenue'] - df['cost']
df['margin_pct'] = df['gross_profit'] / df['revenue']
df['margin_per_unit'] = df['gross_profit'] / df['units_sold']
# Aggregates
agg_df = df.groupby('channel').agg({
'revenue': ['sum', 'mean'],
'gross_profit': 'sum',
'margin_pct': 'mean',
'units_sold': 'sum'
}).round(2)
agg_df.columns = ['_'.join(col).strip() for col in agg_df.columns]
agg_df['total_margin_pct'] = (agg_df['gross_profit_sum'] / agg_df['revenue_sum'] * 100).round(1)
agg_df = agg_df.reset_index()
print("\n=== CHANNEL MARGIN SUMMARY ===")
print(agg_df)
# High/Low margin channels for conflict checks
high_margin_channels = agg_df.nlargest(2, 'total_margin_pct')['channel'].tolist()
low_margin_channels = agg_df.nsmallest(2, 'total_margin_pct')['channel'].tolist()
print(f"\nHigh Margin Channels: {high_margin_channels}")
print(f"Low Margin Channels: {low_margin_channels}")
# =============================================================================
# STEP 2: TIME SERIES AGGREGATES FOR TRENDS & CONFLICT
# =============================================================================
ts_df = df.groupby(['period', 'channel']).agg({
'revenue': 'sum',
'margin_pct': 'mean'
}).reset_index()
pivot_rev = ts_df.pivot(index='period', columns='channel', values='revenue').fillna(0)
pivot_margin = ts_df.pivot(index='period', columns='channel', values='margin_pct').fillna(method='ffill')
# =============================================================================
# STEP 3: CANNIBALIZATION CHECKS
# =============================================================================
def cannibalization_analysis(pivot_df):
"""
Compute:
- Correlation matrix (negative = potential cannibalization).
- Regression: For each pair (high vs low margin), fit sales_low ~ sales_high.
- Negative coef + p<0.05 = cannibalization signal.
- Cannibalization Score: |coef| * (1 - R^2) * significance_factor (higher = worse).
"""
corr_matrix = pivot_df.corr()
# Pairwise regressions (focus on low vs high margin pairs)
results = []
for low_ch in low_margin_channels:
for high_ch in high_margin_channels:
if low_ch == high_ch: continue
y = pivot_df[high_ch].values # High margin sales (affected?)
x = pivot_df[low_ch].values # Low margin sales (cannibalizer?)
slope, intercept, r_value, p_value = stats.linregress(x, y)
r2 = r_value**2
score = abs(slope) * (1 - r2) * (1 if p_value < 0.05 else 0.1) # Weighted score
results.append({
'cannibalizer': low_ch,
'victim': high_ch,
'corr': corr_matrix.loc[low_ch, high_ch],
'regression_coef': slope,
'p_value': p_value,
'r_squared': r2,
'cannib_score': round(score, 3),
'risk_level': 'HIGH' if score > 0.1 and slope < 0 else 'MEDIUM' if slope < 0 else 'LOW'
})
cann_df = pd.DataFrame(results).sort_values('cannib_score', ascending=False)
return corr_matrix, cann_df
corr_matrix, cann_df = cannibalization_analysis(pivot_rev)
print("\n=== CANNIBALIZATION SUMMARY ===")
print(cann_df)
# Alerts
high_risk = cann_df[cann_df['risk_level'] == 'HIGH']
if not high_risk.empty:
print("\n🚨 HIGH-RISK CONFLICTS:")
print(high_risk)
# =============================================================================
# STEP 4: INTERACTIVE DASHBOARD WITH PLOTLY
# =============================================================================
# Subplots: 2x2 grid
fig = make_subplots(
rows=2, cols=2,
subplot_titles=('Revenue by Channel (Trend)', 'Margin % by Channel',
'Channel Revenue Share (Latest)', 'Cannibalization Heatmap'),
specs=[[{"secondary_y": False}, {"secondary_y": False}],
[{"type": "pie"}, {"type": "heatmap"}]]
)
# 1. Revenue Trends
for ch in pivot_rev.columns:
fig.add_trace(
go.Scatter(x=pivot_rev.index, y=pivot_rev[ch], name=ch, mode='lines'),
row=1, col=1
)
# 2. Margin Trends
for ch in pivot_margin.columns:
fig.add_trace(
go.Scatter(x=pivot_margin.index, y=pivot_margin[ch]*100, name=ch, mode='lines'),
row=1, col=2
)
# 3. Latest Revenue Pie
latest_rev = pivot_rev.iloc[-1]
fig.add_trace(
go.Pie(labels=latest_rev.index, values=latest_rev.values, name="Latest Share"),
row=2, col=1
)
# 4. Cannibalization Heatmap (using corr_matrix)
fig.add_trace(
go.Heatmap(
z=corr_matrix.values,
x=corr_matrix.columns,
y=corr_matrix.index,
colorscale='RdYlBu_r', # Red=negative (conflict), Blue=positive
zmid=0,
hoverongaps=False
),
row=2, col=2
)
fig.update_layout(height=800, title_text="🕵️ Channel Conflict Analytics: Margins & Cannibalization", showlegend=True)
fig.update_yaxes(title_text="Margin %", secondary_y=False, row=1, col=2)
fig.show()
# Bonus: Margin Bar Chart
fig_margin = px.bar(agg_df, x='channel', y='total_margin_pct',
title='Average Margin % by Channel',
color='total_margin_pct', color_continuous_scale='viridis')
fig_margin.show()
# Bonus: Cannibalization Table (Interactive)
fig_cann = go.Figure(data=[go.Table(
header=dict(values=list(cann_df.columns),
fill_color='paleturquoise',
align='left'),
cells=dict(values=[cann_df[col] for col in cann_df.columns],
fill_color='lavender',
align='left'))
])
fig_cann.update_layout(title="Cannibalization Risk Table")
fig_cann.show()
# =============================================================================
# USAGE INSTRUCTIONS
# =============================================================================
print("""
✅ Analytics Complete!
KEY INSIGHTS:
- Review margin summary for profitability.
- Check cannibalization table: High scores + negative coef = ACTION NEEDED.
- Use Plotly charts (open in browser for interactivity).
PRODUCTION TIPS:
1. Load real data: df = pd.read_csv('sales_data.csv')
2. Add geo/product dimensions: groupby(['region', 'channel'])
3. Export: fig.write_html('dashboard.html')
4. Schedule via Airflow/Databricks for alerts.
Questions? Provide your data for custom tuning!
""")
Quick Run Guide
- Install deps:
pip install pandas numpy seaborn matplotlib plotly scipy
- Copy-paste into Jupyter/Colab or run as
.py script.
- Outputs:
- Console tables for margins & cannibalization.
- Interactive Plotly dashboard (revenue trends, margins, shares, conflict heatmap).
- Alerts for high-risk pairs (e.g., Online hurting Retail).
This tool detects channel conflicts where low-margin channels (e.g., Online) negatively impact high-margin ones (e.g., Retail) via stats-backed checks. Customize with your data! 🕵️