Building a Marketing Mix Model: An Introduction for Marketers

1749.io
5 min readNov 13, 2023

--

Author: Niall Oulton, Company: 1749

Introduction

In today’s data-driven marketing world, understanding the impact of different marketing channels on sales and other key performance indicators (KPIs) is crucial. This is where Marketing Mix Modeling (MMM) comes into play. MMM is a statistical analysis technique that helps marketers quantify the impact of various marketing activities and determine the optimal mix of marketing channels for maximizing ROI. In this guide, we’ll dive deep into how to build a Marketing Mix Model, tailored for marketers with a moderate understanding of coding and analytics.

What is Marketing Mix Modeling?

Marketing Mix Modeling is an analytical approach used to understand the effectiveness of different marketing channels. It involves statistical analysis to estimate the impact of various marketing activities on a company’s sales or other target metrics. MMM can help marketers make informed decisions about budget allocation, channel optimization, and forecasting future performance.

Step 1: Gather and Prepare Your Data

The first step in building an MMM is data collection and preparation. You need historical data on sales and marketing spend across different channels. This data should ideally cover a substantial time frame to capture various market conditions and seasonality.

Data Requirements:

  • Sales data (weekly or monthly).
  • Marketing spend data across channels (TV, digital, print, etc.).
  • Control variables data (e.g., economic indicators, competitor activity).

Data Preparation:

  • Clean the data by handling missing values and outliers.
  • Aggregate the data if necessary (e.g., daily to weekly).

Example Dataset

import pandas as pd
import numpy as np
import warnings
import arviz as az
import matplotlib.pyplot as plt
import pymc as pm
import seaborn as sns
import xarray as xr


from pymc_marketing.mmm.transformers import geometric_adstock, logistic_saturation
from pymc_marketing.mmm import DelayedSaturatedMMM

warnings.filterwarnings("ignore")

az.style.use("arviz-darkgrid")
plt.rcParams["figure.figsize"] = [12, 7]
plt.rcParams["figure.dpi"] = 100

%load_ext autoreload
%autoreload 2
%config InlineBackend.figure_format = "retina"
# Parameters for simulation
weeks = 104
tv_impact, digital_impact, print_impact = 0.3, 0.5, 0.2
base_sales = 15000

# Simulating weekly marketing spend
np.random.seed(42)
tv_spend = np.random.uniform(1000, 5000, weeks)
digital_spend = np.random.uniform(500, 3000, weeks)
print_spend = np.random.uniform(300, 1500, weeks)

# Simulating sales with known impacts
sales = base_sales + tv_impact * tv_spend + digital_impact * digital_spend + print_impact * print_spend

data = pd.DataFrame({
'week': pd.date_range(start='2021-01-01', periods=weeks, freq='W'),
'tv_spend': tv_spend,
'digital_spend': digital_spend,
'print_spend': print_spend,
'sales': sales
})

Step 2: Select the Right Model

Choosing the right model is critical for the accuracy of your MMM. While there are several models to choose from, Bayesian models have gained popularity for their robustness and flexibility.

Bayesian MMM:

  • Bayesian models account for uncertainty and prior knowledge, making them ideal for MMM.
  • Tools like PyMC-Marketing offer Bayesian MMM functionalities, simplifying the process.

Step 3: Model Building

Model building involves defining the relationship between marketing spend and sales or other KPIs. This includes considering carryover effects, saturation, and external factors.

Key Components:

  • Adstock Transformation: To model the carry-over effect of marketing activities.
  • Saturation Effects: To understand diminishing returns on higher spend.
  • External Factors: Like seasonality, economic conditions, etc.

Example Code:

from pymc_marketing.mmm import DelayedSaturatedMMM
mmm = DelayedSaturatedMMM(
date_column="week",
channel_columns=["tv_spend", "digital_spend","print_spend"],
adstock_max_lag= 8,
)

Step 4: Fit the Model

Fitting the model involves using your historical data to estimate the parameters of the MMM.

Process:

  • Split your data into training and testing sets.
  • Fit the model on the training set.
  • Validate the model on the test set.

Example Code:


# Splitting data (75% train, 25% test)
train_size = int(0.75 * len(data))
train_data, test_data = data[:train_size], data[train_size:]

X_train = train_data.drop('sales', axis=1)
y_train = train_data['sales']

mmm.fit(X_train, y_train)

Step 5: Analyze the Results Using PyMC-Marketing

Once the Marketing Mix Model (MMM) is fitted using the PyMC-Marketing library, we can analyze the contributions of each marketing channel accurately.

Calculating Channel Contributions

This function will calculate the contribution of each marketing channel in its original scale. The output is a DataArray that provides a clear view of how each marketing channel (TV, digital, print, etc.) contributes to overall sales.

Example Code:

# Assuming 'mmm' is your fitted DelayedSaturatedMMM model
channel_contributions = mmm.compute_channel_contribution_original_scale().mean(dim=["draw","chain"])

# Assuming 'channel_contributions' is your xarray.DataArray
# Assign a name to the DataArray
channel_contributions.name = "contributions"

# Convert it to a pandas DataFrame
df_channel_contributions = channel_contributions.to_dataframe().reset_index()

# Display the DataFrame
print(df_channel_contributions)

This code will provide the estimated contributions for each marketing channel. The contributions are typically represented as a proportion or absolute value, reflecting the impact of each channel on total sales.

Interpreting the Results

  • Quantitative Insights: The output quantifies how much each marketing channel contributes to sales. A higher value indicates a greater contribution to sales.
  • Efficiency Assessment: Compare these contributions against the spending on each channel. This will help identify which channels are delivering higher ROI.
  • Inform Future Strategies: Use these insights for strategic decision-making. If certain channels are underperforming, consider reallocating budget to more effective channels.

Step 6: Implement and Iterate

Use the insights from the MMM to adjust your marketing strategy. Allocate more budget to high-performing channels and reduce spend on underperforming ones.

Iterative Process:

  • Implement changes based on MMM insights.
  • Continuously update the model with new data.
  • Regularly reevaluate and adjust your marketing strategy.

Conclusion

Marketing Mix Modeling (MMM) stands as a formidable instrument for marketers aiming to refine their strategies with insights grounded in data. The essence of MMM lies not only in its ability to guide investment decisions across various marketing channels but also in its complexity, which extends beyond the foundational steps outlined in basic guides. A comprehensive MMM approach should incorporate intricate elements such as bias adjustments for paid search, understanding of channel synergies, and other nuanced factors that influence the marketing landscape.

Utilizing advanced tools like PyMC-Marketing can empower marketers to develop sophisticated models. These models offer deep insights, enabling informed decisions about allocating budgets and strategizing investments across different channels. It’s crucial to recognize that MMM is not a static, one-off exercise. Instead, it’s a dynamic, evolving process that should adapt continuously to align with shifting market trends and organizational objectives. Regular model updates and iterative refinements are essential to ensure that the marketing strategy remains relevant and effective in an ever-changing business environment.

In sum, MMM serves as a strategic compass for data-driven marketing, demanding ongoing attention and adaptation to harness its full potential in optimizing marketing investments and strategies.

--

--

1749.io

Marketing Analytics consultancy, specialising in campaign & channel measurement and media budget optimisation