← Blog/Data-Driven Attribution, Step by Step: A B2B Budget Example
AttributionMarketing AnalyticsPythonBudgetingCausal Inference
Marketing Analytics · 20 min read

Data-Driven Attribution, Step by Step: A B2B Budget Example

A data-driven attribution example in Python: seven models on 20,000 B2B journeys, checked against what each channel really caused.

· Martin Guzman

This is a business case for marketing attribution. A made-up software company has to decide whether to move budget between channels, and its attribution report seems to give a clear answer. We build seven attribution models on its data in Python, from last touch to Markov chains and Shapley values, and then check every one against what each channel really caused. The report's clear answer turns out to be wrong.

For how the models work and the math behind them, read How Marketing Attribution Works first or alongside. Every number, table and chart below is real output from code you can download and run. The company and its data are invented, so nothing here belongs to a client.

The application: a quarterly budget review

Northpine Software sells a business software subscription. Its marketing team spends $210,000 a quarter across seven paid channels, and its main conversion is a demo request. At the quarterly review, the attribution report in its analytics tool, which uses last touch, shows this:

  • Brand search, ads on searches for "Northpine", costs $85 per demo.
  • LinkedIn ads cost $1,622 per demo, nineteen times as much.

The proposal on the table: move $20,000 a quarter from LinkedIn to brand search. On the report's numbers, that buys about 222 more demos.

What teams usually do

Most teams take the default report at face value, or switch to a "data-driven" model in their tool and take that at face value instead. Both are reasonable first steps. Both answer the question "which channels were present before demos?" when the budget question is "which channels cause demos?".

What this case does

It builds every common model on the same journeys and compares them: last touch, first touch, linear, time decay, position-based, Markov and Shapley. Then, because the data is simulated, it compares them with the truth. That shows which errors data-driven models fix and which they keep, and what Northpine should do before moving a dollar.

TeamDecisionWhat they need from this
Marketing leadershipWhere next quarter's budget goesWhich numbers can support the move, and which cannot
Paid mediaBids and budgets within each channelHow much each report overstates its own channel
AnalyticsWhat to report, and what to testWhich model to show, with what caveats, and which experiment to run first

Attribution in one minute

How every attribution model works
Step 1
Collect the touches
Every ad click, visit and email tied to one buyer
Step 2
Build journeys
Put each buyer's touches in order, ending in a demo or nothing
Step 3
Split the credit
A rule, or a model, divides each demo between its touches
Step 4
Add it up
Credit per channel, then cost per credited demo
The models differ only in step 3: the rule that splits each conversion between the touches before it.

Every model takes each demo, looks at the touches before it, and splits one unit of credit between them. Rules such as last touch split it by position. Markov chains and Shapley values learn the split from journeys that did and did not convert. None of them asks what would have happened without a channel. How Marketing Attribution Works covers each one with the math.

The data: Northpine's journeys

Two tables. northpine_journeys.csv has one row per marketing touch: 56,519 touches on 20,000 buyer journeys over 90 days, each ending in a demo request or not. northpine_channels.csv has one row per channel, with its spend for the quarter and, unusually, the number of demos it really caused.

That last column is something real data never has. It exists here because the data is simulated from known rules: each channel has a true effect on the chance of a demo, and buyers' prior interest, which no tracking can see, drives both whether they convert and which channels they touch. Interested buyers search for Northpine by name, for example, whether or not an ad shows. The rules are in the dataset script you can download.

ColumnWhat it is
journey_idOne buyer's journey
touch_numberOrder of the touch in the journey, from 1
channelLinkedIn ads, display, content syndication, organic search, paid search, brand search, email or webinar
days_before_endDays between the touch and the end of the journey
convertedThe journey ended in a demo request (1) or not (0)
What Northpine's journeys look like
Try it
0%10%20%30%12345678+touches in the journeydemo rate
Hover a bar.
20,000 journeys over 90 days, 807 of them ending in a demo request.

Journeys with more touches convert far more often: 1.5 percent with one touch, 10 percent with five. That is not proof that touches cause demos. Interested buyers both touch more and convert more, which is exactly the trap this case is about.

The journeys that produce the most demos
Try it
  1. Brand search21 demos769 journeys · 2.7%
  2. Paid search→Brand search13 demos202 journeys · 6.4%
  3. LinkedIn→Brand search11 demos274 journeys · 4.0%
  4. Email9 demos562 journeys · 1.6%
  5. Display→Brand search8 demos225 journeys · 3.6%
  6. Organic→Email8 demos145 journeys · 5.5%
  7. Organic7 demos626 journeys · 1.1%
  8. Paid search7 demos721 journeys · 1.0%
  9. LinkedIn→Email6 demos177 journeys · 3.4%
  10. Paid search→Email6 demos122 journeys · 4.9%
  11. Syndication→Paid search5 demos175 journeys · 2.9%
  12. LinkedIn5 demos327 journeys · 1.5%
The twelve paths with the most demo requests, in touch order.

The single most common route to a demo is a brand search alone: 21 demos from 769 journeys. Four of the top five paths end in a brand search.

Step by step in Python

The code uses pandas and numpy only. Every block below is a cell in the downloadable notebook, and every output shown is what it printed.

Step 1: load the data

from math import factorial
 
import numpy as np
import pandas as pd
 
touches = pd.read_csv("northpine_journeys.csv")
channels = pd.read_csv("northpine_channels.csv")
print(f"{touches.journey_id.nunique():,} journeys, {len(touches):,} touches")
touches.head(8)
20,000 journeys, 56,519 touches
journey_idtouch_numberchanneldays_before_endconverted
J-000011Content syndication40
J-000012Content syndication40
J-000013Organic search40
J-000014Paid search40
J-000015Email40
J-000016Webinar30
J-000017LinkedIn ads00
J-000021Content syndication00

Each row is one touch. Journey J-00001 had seven touches over four days and did not convert.

Step 2: build the journeys

journeys = (touches.sort_values(["journey_id", "touch_number"])
            .groupby("journey_id")
            .agg(path=("channel", list), days=("days_before_end", list),
                 converted=("converted", "first")))
journeys["touches"] = journeys["path"].str.len()
 
print(f"{journeys.converted.sum()} demos from {len(journeys):,} journeys "
      f"({journeys.converted.mean():.2%})")
journeys.groupby("touches")["converted"].agg(journeys="size", demo_rate="mean").head(8).round(3)
807 demos from 20,000 journeys (4.04%)
 
         journeys  demo_rate
touches                     
1            3722      0.015
2            5788      0.024
3            4899      0.030
4            3042      0.052
5            1514      0.100
6             644      0.123
7             262      0.145
8              87      0.218

This groups the touches into one row per journey, with the channels in order, the days before the end, and the outcome. 807 of 20,000 journeys ended in a demo, 4.04 percent. The demo rate rises steeply with the number of touches.

Step 3: the rule-based models

def add(credit, channel, share):
    credit[channel] = credit.get(channel, 0) + share
 
 
def last_touch(path, days):
    return {path[-1]: 1.0}
 
 
def first_touch(path, days):
    return {path[0]: 1.0}
 
 
def linear(path, days):
    credit = {}
    for ch in path:
        add(credit, ch, 1 / len(path))
    return credit
 
 
def time_decay(path, days, half_life=7):
    weights = [0.5 ** (d / half_life) for d in days]
    credit = {}
    for ch, w in zip(path, weights):
        add(credit, ch, w / sum(weights))
    return credit
 
 
def position_based(path, days):
    n = len(path)
    if n == 1:
        shares = [1.0]
    elif n == 2:
        shares = [0.5, 0.5]
    else:
        shares = [0.4] + [0.2 / (n - 2)] * (n - 2) + [0.4]
    credit = {}
    for ch, s in zip(path, shares):
        add(credit, ch, s)
    return credit
 
 
def attribute(rule, data):
    total = {}
    won = data[data.converted == 1]
    for path, days in zip(won["path"], won["days"]):
        for ch, share in rule(path, days).items():
            add(total, ch, share)
    return pd.Series(total)
 
 
rules = {"Last touch": last_touch, "First touch": first_touch, "Linear": linear,
         "Time decay": time_decay, "Position-based": position_based}
credit = pd.DataFrame({name: attribute(rule, journeys) for name, rule in rules.items()}).fillna(0)
credit.round(1)
                     Last touch  First touch  Linear  Time decay  \
Brand search              351.0        114.0   217.4       273.8   
Content syndication        19.0         82.0    49.8        36.6   
Display                    22.0         89.0    53.3        38.2   
Email                     109.0         64.0    94.6       102.1   
LinkedIn ads               37.0        123.0    78.6        59.5   
Organic search             93.0        143.0   118.9       109.3   
Paid search               121.0        145.0   137.8       129.8   
Webinar                    55.0         47.0    56.7        57.8   
 
                     Position-based  
Brand search                  226.5  
Content syndication            49.8  
Display                        54.6  
Email                          89.6  
LinkedIn ads                   79.5  
Organic search                119.0  
Paid search                   134.8  
Webinar                        53.1

Each rule is a function that takes one journey and returns how it splits one demo between channels; attribute adds those splits up over every journey that converted. The rules disagree on almost every channel. Brand search gets 351 demos under last touch and 114 under first touch; LinkedIn gets 37 and 123. Time decay uses a 7-day half-life here, and the main guide shows how much that choice matters.

Step 4: the Markov model

def transition_counts(data):
    counts = {}
    for path, converted in zip(data["path"], data["converted"]):
        states = ["start"] + path + ["demo" if converted else "null"]
        for a, b in zip(states[:-1], states[1:]):
            counts[(a, b)] = counts.get((a, b), 0) + 1
    return counts
 
 
def p_demo(counts, removed=None):
    """Probability that a journey starting at 'start' ends in a demo.
    A removed channel sends everyone who reaches it to 'null'."""
    states = sorted({a for a, _ in counts})            # start and every channel
    idx = {s: i for i, s in enumerate(states)}
    Q = np.zeros((len(states), len(states)))             # moves between transient states
    r = np.zeros(len(states))                            # one-step chance of a demo
    for s in states:
        out = {b: n for (a, b), n in counts.items() if a == s}
        total = sum(out.values())
        if s == removed:
            continue
        for b, n in out.items():
            if b == "demo":
                r[idx[s]] += n / total
            elif b in idx and b != removed:
                Q[idx[s], idx[b]] += n / total
    x = np.linalg.solve(np.eye(len(states)) - Q, r)    # x = r + Q x
    return x[idx["start"]]
 
 
def markov_credit(data):
    counts = transition_counts(data)
    base = p_demo(counts)
    chans = sorted({c for p in data["path"] for c in p})
    removal = pd.Series({c: 1 - p_demo(counts, removed=c) / base for c in chans})
    return removal / removal.sum() * data["converted"].sum(), removal, base
 
 
credit["Markov"], removal, base_p = markov_credit(journeys)
print(f"chance of a demo, from the chain: {base_p:.4f}")
removal.sort_values(ascending=False).round(3)
chance of a demo, from the chain: 0.0404
 
Brand search           0.527
Paid search            0.357
Organic search         0.343
LinkedIn ads           0.282
Email                  0.268
Display                0.229
Content syndication    0.196
Webinar                0.155
dtype: float64

transition_counts counts every move between states, including the start and the two endings. p_demo turns the counts into probabilities and solves for the chance that a journey reaches a demo, with or without one channel. The chain's chance of a demo, 0.0404, matches the real rate, a useful check that the code is right.

The removal effects say that without brand search, 53 percent of demos would be lost; without webinars, about 16 percent. Scaled to share out all 807 demos, they become Markov credit.

Step 5: the Shapley model

def shapley_credit(data):
    chans = sorted({c for p in data["path"] for c in p})
    n = len(chans)
    bit = {c: 1 << i for i, c in enumerate(chans)}
 
    # demos from journeys that touched exactly each set of channels
    exact = np.zeros(1 << n)
    for path, converted in zip(data["path"], data["converted"]):
        exact[sum(bit[c] for c in set(path))] += converted
 
    # v(S): demos from journeys whose channels all lie inside S
    v = exact.copy()
    for i in range(n):
        for mask in range(1 << n):
            if mask & (1 << i):
                v[mask] += v[mask ^ (1 << i)]
 
    phi = {}
    for c in chans:
        total = 0.0
        for mask in range(1 << n):
            if mask & bit[c]:
                continue
            s = bin(mask).count("1")
            weight = factorial(s) * factorial(n - s - 1) / factorial(n)
            total += weight * (v[mask | bit[c]] - v[mask])
        phi[c] = total
    return pd.Series(phi)
 
 
credit["Shapley"] = shapley_credit(journeys)
credit[["Last touch", "Markov", "Shapley"]].round(1)
                     Last touch  Markov  Shapley
Brand search              351.0   180.3    182.6
Content syndication        19.0    67.2     54.7
Display                    22.0    78.6     59.1
Email                     109.0    91.8    102.2
LinkedIn ads               37.0    96.7     85.0
Organic search             93.0   117.3    119.1
Paid search               121.0   122.1    141.4
Webinar                    55.0    52.9     62.8

exact counts the demos from journeys that touched exactly each combination of channels, 256 combinations for eight channels. The loop after it turns those into v(S)v(S), the demos from journeys whose channels all lie inside a set SS. The final loop applies the Shapley formula. Markov and Shapley agree closely, and both take about half of last touch's credit away from brand search.

Step 6: compare with the truth

truth = channels.set_index("channel")["true_incremental_demos"]
compare = credit.assign(Truth=truth).round(1)
compare.loc["Total"] = compare.sum()
compare
                     Last touch  First touch  Linear  Time decay  \
Brand search              351.0        114.0   217.4       273.8   
Content syndication        19.0         82.0    49.8        36.6   
Display                    22.0         89.0    53.3        38.2   
Email                     109.0         64.0    94.6       102.1   
LinkedIn ads               37.0        123.0    78.6        59.5   
Organic search             93.0        143.0   118.9       109.3   
Paid search               121.0        145.0   137.8       129.8   
Webinar                    55.0         47.0    56.7        57.8   
Total                     807.0        807.0   807.1       807.1   
 
                     Position-based  Markov  Shapley  Truth  
Brand search                  226.5   180.3    182.6   26.9  
Content syndication            49.8    67.2     54.7   21.6  
Display                        54.6    78.6     59.1   15.3  
Email                          89.6    91.8    102.2   63.9  
LinkedIn ads                   79.5    96.7     85.0   74.8  
Organic search                119.0   117.3    119.1   88.8  
Paid search                   134.8   122.1    141.4  146.3  
Webinar                        53.1    52.9     62.8   83.6  
Total                         806.9   806.9    806.9  521.2
Credit against what each channel really caused
Try it
0100200300Paid search122Organic search117Webinar53LinkedIn ads97Email92Brand search180Content syndication67Display79
demos credited
807
by markov
Hover a channel for its numbers.
The truth is known only because the data is simulated. In real data you need an experiment to see it.

This is the step real data cannot give you. Three findings:

  • Every model hands out 807 demos; marketing caused 521. The other 286 would have happened anyway. Any cost per demo built on attribution credit is too low across the board.
  • Brand search is overcredited by every model, from 114 to 351 demos against a true 27. Its touches come from buyers who had already decided.
  • Data-driven models fix one error and make others. Markov credits display with 79 demos and content syndication with 67, against true figures of 15 and 22. Webinars, which really caused 84, get 53.

Step 7: cost per demo

spend = channels.set_index("channel")["spend_90d"]
paid = spend[spend > 0].index
cost_per_demo = compare.loc[paid].rdiv(spend[paid], axis=0).round(0)
cost_per_demo[["Last touch", "Linear", "Markov", "Shapley", "Truth"]]
                     Last touch  Linear  Markov  Shapley   Truth
channel                                                         
LinkedIn ads             1622.0   763.0   620.0    706.0   802.0
Display                  1136.0   469.0   318.0    423.0  1634.0
Content syndication      1579.0   602.0   446.0    548.0  1389.0
Paid search               372.0   327.0   369.0    318.0   308.0
Brand search               85.0   138.0   166.0    164.0  1115.0
Email                      46.0    53.0    54.0     49.0    78.0
Webinar                   273.0   265.0   284.0    239.0   179.0
Cost per demo depends on the model you ask
Try it
0500100015002000Paid search$372Webinar$273LinkedIn ads$1,622Email$46Brand search$85Content syndication$1,579Display$1,136white tick: true cost per demo caused
Hover a channel. Organic search is left out: it has no media spend.
90-day spend divided by credited demos, against spend divided by demos really caused.

Under last touch, brand search looks like the cheapest channel at 85ademo.Eachdemoitreallycausedcost85 a demo. Each demo it really caused cost 1,115. Under Markov, display looks cheap at 318;thetruecostis318; the true cost is 1,634, the worst of any channel. The two channels whose real costs are lowest are email (78)andwebinars(78) and webinars (179), and webinars look worse under every model than they are.

Step 8: how sure are the numbers?

rng = np.random.default_rng(42)
boot = []
for b in range(100):
    sample = journeys.sample(len(journeys), replace=True, random_state=int(rng.integers(1_000_000)))
    boot.append(pd.DataFrame({
        "Last touch": attribute(last_touch, sample),
        "Markov": markov_credit(sample)[0],
        "Shapley": shapley_credit(sample),
    }).fillna(0))
 
boot = pd.concat(boot, keys=range(100))
ranges = boot.groupby(level=1).quantile([0.05, 0.95]).unstack().round(0)
ranges
                    Last touch        Markov        Shapley       
                          0.05   0.95   0.05   0.95    0.05   0.95
Brand search             323.0  381.0  168.0  191.0   170.0  194.0
Content syndication       12.0   25.0   63.0   70.0    46.0   61.0
Display                   15.0   31.0   73.0   84.0    49.0   65.0
Email                     95.0  124.0   84.0   98.0    93.0  112.0
LinkedIn ads              28.0   46.0   90.0  102.0    75.0   94.0
Organic search            80.0  109.0  108.0  125.0   109.0  132.0
Paid search               99.0  135.0  114.0  130.0   129.0  153.0
Webinar                   43.0   65.0   48.0   57.0    55.0   70.0

This resamples the 20,000 journeys 100 times with replacement and rebuilds three of the models each time. The 5th and 95th percentiles give a range for each channel's credit.

How sure is the credit?
Try it
0100200300Paid search122Organic search117Webinar53LinkedIn ads97Email92Brand search180Content syndication67Display79bracket: 90% range · tick: truth
Hover a channel. The bracket is how much the credit moves when the journeys are resampled.
100 bootstrap resamples of the 20,000 journeys. The bracket holds 90% of them.

The ranges are narrow. With 807 demos, Markov puts brand search between 168 and 191 in 90 percent of resamples. That is the trap: the models are precise, and precisely wrong about cause. A tight interval measures how stable the credit is, not whether the credit is deserved.

Step 9: the budget question

def shift(credit, frm="LinkedIn ads", to="Brand search", amount=20_000):
    """Change in demos if `amount` moves from one channel to another,
    assuming each dollar buys demos at the channel's average rate."""
    return amount * (credit[to] / spend[to] - credit[frm] / spend[frm])
 
 
pd.Series({model: shift(compare[model]) for model in compare.columns}).round(1)
Last touch        221.7
First touch        35.0
Linear            118.7
Time decay        162.7
Position-based    124.5
Markov             88.0
Shapley            93.4
Truth              -7.0
dtype: float64

shift estimates the change in demos from moving $20,000 from LinkedIn to brand search, assuming every dollar buys demos at the channel's average rate. Every attribution model predicts a gain, from 35 demos under first touch to 222 under last touch. The truth is a loss of 7 demos a quarter. Try other moves:

Move budget, and see what each model predicts
Try it
$20,000
LinkedIn: demos caused per $1k
1.25
Brand search: demos caused per $1k
0.90
Each line assumes every extra dollar buys demos at the channel's average rate. Real channels saturate, so treat these as directions, not forecasts.
Expected change in demos per quarter at each channel's average rate, by model, and from the true effects.

The average-rate assumption is generous to brand search in particular. Brand search can only buy clicks from people already searching for Northpine, so extra budget mostly raises the price of the same clicks. The real loss from this move would likely be larger.

What Northpine should do

  1. Do not move the $20,000 on the strength of any attribution report. Every model points the same way, and every model is wrong about brand search.
  2. Test brand search directly. Pause brand search ads in some regions for four to six weeks, keep them on in similar regions, and compare demo requests. Organic results for the company's own name often catch many of those searches. This is a geo test, and incrementality explains the idea.
  3. Look harder at display and webinars. Display is overcredited by the data-driven models and webinars undercredited by all of them. A holdout on display, and a test of more webinar promotion, would each settle more budget than another attribution model.
  4. Keep attribution for what it does well. Use it to understand journeys and to compare campaigns within a channel, where the selection problem is smaller. For splitting budget between channels, pair experiments with a marketing mix model.

Mistakes to avoid

  • Treating credit as cause. Credit shows who was present. Budget decisions need what would have happened otherwise.
  • Switching models to get a better answer. Moving from last touch to Markov changed brand search's credit from 351 to 180. Both are far from 27. A different split of the same data does not remove selection.
  • Trusting a narrow interval. Bootstrap ranges measure noise, not bias. The Markov range for brand search is 168 to 191; the truth is outside it by a factor of six.
  • Ignoring the settings. Lookback windows and half-lives move credit between channels. Report them with every number.
  • Forgetting tracking gaps. Lost earlier touches push credit to the end of the journey, towards brand search and email.
  • Cost per credited conversion as a target. Bidding systems that optimise to it will keep buying the cheap end-of-journey clicks that buyers would have made anyway.

Download the data and the notebook

All three files are free to use. The notebook runs every step of this case in order and already contains the outputs shown above.

To run it: install Python, then run pip install pandas numpy jupyter, put the files in one folder, and open the notebook with Jupyter.

Want this on your own data?

If you would like your own attribution reports checked against a test, or a test designed for the channel your budget depends on most, get in touch and we can talk it through on a short call.