← Blog/How Marketing Attribution Works: Rules, Markov Chains and Shapley Values
AttributionMarketing AnalyticsPythonStatisticsCausal Inference
Marketing Analytics · 25 min read

How Marketing Attribution Works: Rules, Markov Chains and Shapley Values

Marketing attribution models explained: last touch, linear, time decay, Markov chains and Shapley values, with the math, interactive charts and Python.

· Martin Guzman

Marketing attribution splits the credit for each sale or lead between the ads, emails and visits that came before it. This guide explains how it works from the ground up: the rule-based models, the two data-driven ones, Markov chains and Shapley values, the math behind each, and how far any of them can be trusted.

The business cases that apply it are separate guides, so this one can focus on the models. The first is a B2B budget review. Every example on this page comes from that case: an invented software company, Northpine, with 20,000 buyer journeys and 807 demo requests. Because the data is simulated, we also know what each channel really caused, which lets this guide show something real data never can: how far each model is from the truth.

How attribution works

Every attribution model does the same thing: it takes each conversion, looks at the marketing touches that came before it, and divides one unit of credit between them. Add up the credit by channel and you get each channel's share of the results.

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.

The models differ only in the rule that divides the credit. That has two consequences you will meet throughout this guide:

  • Every model hands out all the credit. If 807 demos were requested, every model credits 807 demos to channels, even if many of those buyers would have asked for a demo anyway.
  • Attribution describes; it does not test. It records who touched what before converting. Whether a touch changed anything is a different question, and the one budgets depend on.

The math behind attribution

The notation is light. Once it is in place, every model is one line.

A journey is a sequence

Write journey jj as its touches in order, (cj1,cj2,…,cjnj)(c_{j1}, c_{j2}, \ldots, c_{jn_j}), where cjkc_{jk} is the channel of the kk-th touch and njn_j the number of touches. Each touch also has tjkt_{jk}, the days between it and the end of the journey. The outcome yjy_j is 1 if the journey ended in a demo request and 0 if not.

A model gives each touch a weight wjkw_{jk}, with the weights of a journey adding up to 1:

wjk≥0,∑k=1njwjk=1w_{jk} \ge 0, \qquad \sum_{k=1}^{n_j} w_{jk} = 1

The credit for channel cc is the sum of its weights over all journeys that converted:

Ac=∑jyj∑k=1njwjk 1(cjk=c)A_c = \sum_{j} y_j \sum_{k=1}^{n_j} w_{jk} \, \mathbb{1}(c_{jk} = c)

where 1(⋅)\mathbb{1}(\cdot) is 1 when the condition holds and 0 otherwise. Because each converting journey hands out exactly 1, the credits always add up to the number of conversions: ∑cAc=∑jyj\sum_c A_c = \sum_j y_j.

The rule-based models

Five common rules, each a different choice of wjkw_{jk}:

ModelWeight of touch kk in a journey of nn touchesThe idea
Last touchwk=1w_k = 1 if k=nk = n, else 0The touch that closed it
First touchwk=1w_k = 1 if k=1k = 1, else 0The touch that started it
Linearwk=1/nw_k = 1/nEvery touch counts the same
Time decaywk∝2−tk/hw_k \propto 2^{-t_k / h}Recent touches count more
Position-based0.4 first, 0.4 last, 0.2 shared by the middleOpening and closing matter most

Position-based gives a two-touch journey 0.5 each and a one-touch journey 1. "∝\propto" means "in proportion to": time decay computes 2−tk/h2^{-t_k/h} for every touch and then divides by their sum, so the weights add up to 1.

Applied to Northpine's 807 demos, the rules disagree sharply. Pick a model to see its split:

The same 807 demos, seven ways
Try it
0100200300Paid search121Organic search93Webinar55LinkedIn ads37Email109Brand search351Content syndication19Display22
demos credited
807
by last touch
Hover a channel for its numbers.
Credit by channel under each model, from 20,000 Northpine journeys. Real output from the notebook.

Brand search, paid ads on searches for Northpine's own name, gets 351 demos under last touch and 114 under first touch. LinkedIn gets 37 under last touch and 123 under first touch. Nothing about the journeys changed; only the rule did. The reason is position. Brand search tends to come at the end, when a buyer who already knows Northpine searches for it. LinkedIn and display tend to come at the start.

Time decay and its half-life

Time decay needs one setting, the half-life hh: the number of days after which a touch counts half as much. With h=7h = 7, a touch on the day of the demo request has weight 1 before scaling, a touch a week earlier 0.5, and a touch two weeks earlier 0.25.

wk=2−tk/h∑i=1n2−ti/hw_k = \frac{2^{-t_k / h}}{\sum_{i=1}^{n} 2^{-t_i / h}}

A short half-life makes time decay behave like last touch; a long one makes it behave like linear. The half-life is a choice, not a finding, and it moves the answer:

Time decay: how fast should credit fade?
Try it
7 days
0100200300Paid search130Organic search109Webinar58LinkedIn ads60Email102Brand search274Content syndication37Display38white tick: linear model
Half-life 7 days: brand search gets 274 demos (last touch gives 351, linear 217).
Time decay credit at six half-lives, all 807 demos.

With a one-day half-life, brand search gets 330 demos. With 60 days it gets 227. Any model with a setting like this should be reported with the setting.

Markov chains

The rules above are fixed in advance. Data-driven models instead learn from the journeys that did not convert as well as the ones that did. The first treats journeys as a Markov chain: a set of states with a probability of moving from each state to each other one.

The states are a start, one state per channel, and two endings, "demo" and "null" (no demo). From the journeys, count how often each move happens, and turn the counts into probabilities:

P(a→b)=na→b∑b′na→b′P(a \to b) = \frac{n_{a \to b}}{\sum_{b'} n_{a \to b'}}

where na→bn_{a \to b} is the number of times a journey moved from state aa straight to state bb. A "first-order" chain assumes the next step depends only on the current state, not on how the buyer got there.

From those probabilities you can compute the chance that a journey starting at "start" ends at "demo". Call xsx_s the chance of eventually reaching a demo from state ss. It is the chance of going straight to a demo, plus the chance of moving to another channel and reaching a demo from there:

xs=P(s→demo)+∑s′P(s→s′) xs′x_s = P(s \to \text{demo}) + \sum_{s'} P(s \to s') \, x_{s'}

That is one equation per state, solved together as a small linear system. For Northpine's journeys, xstart=0.0404x_{\text{start}} = 0.0404, which matches the real demo rate of 4.04 percent.

Now the key step, the removal effect. Delete channel cc from the chain, so that anyone who reaches it goes to "null", and solve again. The removal effect is the share of demos lost:

REc=1−xstart(−c)xstart\text{RE}_c = 1 - \frac{x_{\text{start}}^{(-c)}}{x_{\text{start}}}

Removal effects add up to more than 1, because some demos need several channels. Markov credit scales them so they share out all the demos:

Ac=REc∑c′REc′×∑jyjA_c = \frac{\text{RE}_c}{\sum_{c'} \text{RE}_{c'}} \times \sum_j y_j

A worked example. Three journeys: LinkedIn then brand search, ending in a demo; LinkedIn alone, ending in nothing; brand search alone, ending in a demo. From "start", two of three journeys go to LinkedIn and one to brand search. From LinkedIn, one goes on to brand search and one to null. From brand search, both go to a demo. So:

xstart=23×12×1+13×1=23x_{\text{start}} = \tfrac{2}{3} \times \tfrac{1}{2} \times 1 + \tfrac{1}{3} \times 1 = \tfrac{2}{3}

Remove LinkedIn and only the direct brand search route is left, x=13x = \tfrac{1}{3}, a removal effect of 0.5. Remove brand search and no route reaches a demo, a removal effect of 1. Scaled to the 2 demos, LinkedIn gets 2×0.5/1.5=0.672 \times 0.5 / 1.5 = 0.67 and brand search 1.33. Last touch would have given brand search both.

Here is the chain for all 20,000 Northpine journeys. Click a channel to remove it:

The journeys as a Markov chain
Try it
Click a channel to remove it from every journey. Hover to see where its visitors go next.
Paid search36%Organic34%Webinar15%LinkedIn28%Email27%Brand search53%Syndication20%Display23%startdemono demo
chance of a demo
4.04%
all channels in place
removal effect
–
click a channel
Markov credit
–
Numbers in the circles are each channel's removal effect.
Transition probabilities estimated from all 20,000 journeys. Only common moves are drawn; hover a channel to see all of its own.

Removing brand search cuts the chance of a demo from 4.04 to 1.91 percent, a removal effect of 53 percent, the largest of any channel. That is the chain saying "most journeys that reached a demo went through brand search". It is not saying brand search caused them, a distinction this guide returns to below.

Shapley values

The second data-driven model comes from game theory. Treat the channels as players in a team, and the demos as the team's payout. The Shapley value gives each player its average contribution over every order in which the team could have been assembled.

Let NN be the set of all channels, with ∣N∣=n|N| = n, and let v(S)v(S) be the value of a set of channels SS: here, the demos from journeys that touched only channels inside SS. The Shapley value of channel cc is:

ϕc=∑S⊆N∖{c}∣S∣! (n−∣S∣−1)!n![v(S∪{c})−v(S)]\phi_c = \sum_{S \subseteq N \setminus \{c\}} \frac{|S|! \, (n - |S| - 1)!}{n!} \Big[ v(S \cup \{c\}) - v(S) \Big]

In words: for every set SS of other channels, measure how much adding cc raises the value, v(S∪{c})−v(S)v(S \cup \{c\}) - v(S). Then average those gains, weighting each set by the share of orderings in which cc joins right after exactly the channels in SS. The values always add up to v(N)v(N), all the demos.

A worked example. Two channels. 10 demos came from journeys that touched only LinkedIn, 20 from brand search only, and 30 from journeys that touched both. So v({LinkedIn})=10v(\{\text{LinkedIn}\}) = 10, v({Brand})=20v(\{\text{Brand}\}) = 20, and v({LinkedIn,Brand})=60v(\{\text{LinkedIn}, \text{Brand}\}) = 60. There are two orders:

  • LinkedIn joins first and adds 10; brand search joins second and adds 60−10=5060 - 10 = 50.
  • Brand search joins first and adds 20; LinkedIn joins second and adds 60−20=4060 - 20 = 40.

Averaging, ϕLinkedIn=(10+40)/2=25\phi_{\text{LinkedIn}} = (10 + 40)/2 = 25 and ϕBrand=(50+20)/2=35\phi_{\text{Brand}} = (50 + 20)/2 = 35. Each channel keeps its solo demos and the 30 shared ones are split evenly. Change the numbers and watch:

Shapley values with two channels, by hand
Try it
10
20
30
v(∅)
0
v({LinkedIn})
10
v({Brand})
20
v({LinkedIn, Brand})
60
Order channels joinLinkedIn getsBrand search gets
LinkedIn first, then brand10.050.0
Brand first, then LinkedIn40.020.0
Shapley value: the average25.035.0
The 30 demos that needed both are split evenly, 15.0 each; each channel keeps its own solo demos. Total 60 = v(both).
Made-up numbers you can change. The defaults match the worked example.

With eight channels there are 28=2562^8 = 256 sets, few enough to compute exactly. Past about 20 channels, exact computation becomes slow and you sample orderings instead. This simple version ignores the order of touches; variants that use order exist, at the cost of more data per combination.

Markov or Shapley?

On Northpine's journeys the two agree closely. Brand search gets 180 under Markov and 183 under Shapley, paid search 122 and 141, LinkedIn 97 and 85. Both move credit from brand search to the channels that start journeys, compared with last touch. Choose by what you need to explain: removal effects are easier to describe to a team ("without this channel, we would lose this share of demos"); Shapley values have the cleaner fairness guarantees.

Try it

Build a journey and see how each rule splits a single demo. Start with a real Northpine journey, then add a brand search at the end and watch last touch hand it everything.

Build a journey and watch each rule split the credit
Try it
Add touches in order (up to 8):
The journey, first touch to demo request
  1. 1Display
  2. 2Organic
  3. 3Webinar
  4. 4Display
7 days
Last touch100%First touch100%Linear50%25%25%Time decay59%20%22%Position-based80%10%10%
DisplayOrganicWebinar
One demo request, split by five rules. Load a real Northpine journey or build your own.

Three things to try:

  1. Add one brand search touch at the end of any journey. Last touch moves all the credit to it; linear moves only a share.
  2. Change the days on early touches. Only time decay reacts.
  3. Drag the half-life from 1 to 30 days and watch time decay slide from last touch towards linear.

How far to trust attribution

Three things move the answer without any change in what buyers did: the settings, the tracking, and chance. And one thing no model can fix: the difference between being present and making a difference.

The lookback window

Most tools only count touches within a window before the conversion, often 30 or 90 days. A short window drops early touches, and so the channels that start journeys:

The lookback window changes the answer
Try it
30 days
050100150200250Paid search124Organic search116Webinar53LinkedIn ads91Email94Brand search195Content syndication62Display72white tick: 90-day window
Markov, 30-day window: brand search 195, LinkedIn 91 demos. Nothing about the journeys changed, only what was counted.
Credit when only touches within the window count. Same journeys, same demos.

Under Markov, a 7-day window gives brand search 247 demos and LinkedIn 69. A 90-day window gives 181 and 97. Report the window with the result, and choose it from how long your buyers actually take: for Northpine, about half of demos (394 of 807) come from journeys that began more than two weeks earlier.

Lost tracking

Consent refusals, buyers switching between phone and laptop, and blocked tags all remove touches from the record. The touch that is almost never lost is the last one, because it happens on your own site, in the same session as the conversion. So lost tracking pushes credit towards the end of the journey:

What lost tracking does to the credit
Try it
25%
0100200300Paid search123Organic search116Webinar52LinkedIn ads91Email94Brand search198Content syndication63Display71white tick: nothing lost
25% lost: Markov gives brand search 198 demos (180 with full tracking).
Earlier touches removed at random, as consent refusals, cross-device journeys and blocked tags do. The last touch is always kept.

If half of the earlier touches go missing, Markov's credit for brand search rises from 180 to 224, and LinkedIn's falls from 97 to 81. The model has not learned anything new; it has seen less.

Attribution is not causation

This is the limit that matters most. Every model splits the demos that happened between the channels that were present. None asks what would have happened without a channel. Northpine's simulation knows that answer, so we can compare:

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.

All seven models hand out 807 demos. Marketing really caused 521; the other 286 came from buyers who would have asked for a demo anyway. And the gap is not spread evenly:

  • Brand search really caused about 27 demos. Last touch credits it with 351, the data-driven models about 180. People search for Northpine's name after they have decided; the ad is present at the end, not the reason for it.
  • Display really caused about 15. Markov credits it with 79. It appears early in many journeys, so removing it from the chain looks costly.
  • Webinars really caused about 84 and every model gives them 47 to 63. A webinar changes minds, but it sits in the middle of a journey where no rule puts much weight.

Data-driven models fix last touch's worst error and introduce new ones. Only an experiment, such as a holdout or a geo test, measures what a channel causes. Incrementality, explained covers how.

Attribution in Python

The rules take a few lines each. Here is linear, with the helper that adds up credit over all converting journeys:

def linear(path, days):
    credit = {}
    for ch in path:
        credit[ch] = credit.get(ch, 0) + 1 / len(path)
    return credit
 
def attribute(rule, journeys):
    total = {}
    won = journeys[journeys.converted == 1]
    for path, days in zip(won["path"], won["days"]):
        for ch, share in rule(path, days).items():
            total[ch] = total.get(ch, 0) + share
    return pd.Series(total)

Markov and Shapley take about 30 lines each with numpy and no other library. The business case builds all seven models on the full data, with every output shown.

Which model to use, and when

ModelGood forWatch out for
Last touchSeeing what closes; the default in many toolsGives the end of the journey everything
First touchSeeing what opens journeysIgnores everything after
LinearA neutral first look across the journeyTreats a glance and a demo the same
Time decayShort buying cyclesThe half-life is a guess
Position-basedFunnels where opening and closing matter40/20/40 is a convention, not a finding
MarkovExplaining each channel's role in the pathFirst-order memory; credit is not cause
ShapleyFair splitting when channels combineIgnores order in its simple form; slow with many channels

And how attribution fits with the other measurement tools:

  • Attribution describes paths. Use it to understand journeys and to tune campaigns within a channel.
  • Marketing mix modelling estimates each channel's effect on total sales from spend over time. Use it to set budgets between channels. The comparison goes further.
  • Experiments measure cause directly. Use them to check the claims the other two make.

Business cases

Each case applies attribution to one marketing decision, from the business question to the answer, with the code and data:

Download the data and the notebook

The notebook builds every model and computes every chart on this page, in its appendix.

Want this on your own data?

If you would like to know what your own attribution reports can and cannot tell you, or how to test them, get in touch and we can talk it through on a short call.