{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "e6d720ac",
   "metadata": {},
   "source": [
    "# Marketing attribution, step by step: a B2B budget review\n",
    "\n",
    "Companion notebook to the guides at https://martinguzman.ca/blog/marketing-attribution-explained and https://martinguzman.ca/blog/data-driven-attribution-example\n",
    "\n",
    "Put `northpine_journeys.csv` and `northpine_channels.csv` in the same folder as this notebook. The data is synthetic: Northpine Software is an invented company."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "39a38436",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:17:50.773553Z",
     "iopub.status.busy": "2026-12-05T03:17:50.773427Z",
     "iopub.status.idle": "2026-12-05T03:17:50.986835Z",
     "shell.execute_reply": "2026-12-05T03:17:50.986490Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "20,000 journeys, 56,519 touches\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>journey_id</th>\n",
       "      <th>touch_number</th>\n",
       "      <th>channel</th>\n",
       "      <th>days_before_end</th>\n",
       "      <th>converted</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>J-00001</td>\n",
       "      <td>1</td>\n",
       "      <td>Content syndication</td>\n",
       "      <td>4</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>J-00001</td>\n",
       "      <td>2</td>\n",
       "      <td>Content syndication</td>\n",
       "      <td>4</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>J-00001</td>\n",
       "      <td>3</td>\n",
       "      <td>Organic search</td>\n",
       "      <td>4</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>J-00001</td>\n",
       "      <td>4</td>\n",
       "      <td>Paid search</td>\n",
       "      <td>4</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>J-00001</td>\n",
       "      <td>5</td>\n",
       "      <td>Email</td>\n",
       "      <td>4</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>J-00001</td>\n",
       "      <td>6</td>\n",
       "      <td>Webinar</td>\n",
       "      <td>3</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>J-00001</td>\n",
       "      <td>7</td>\n",
       "      <td>LinkedIn ads</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>J-00002</td>\n",
       "      <td>1</td>\n",
       "      <td>Content syndication</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "  journey_id  touch_number              channel  days_before_end  converted\n",
       "0    J-00001             1  Content syndication                4          0\n",
       "1    J-00001             2  Content syndication                4          0\n",
       "2    J-00001             3       Organic search                4          0\n",
       "3    J-00001             4          Paid search                4          0\n",
       "4    J-00001             5                Email                4          0\n",
       "5    J-00001             6              Webinar                3          0\n",
       "6    J-00001             7         LinkedIn ads                0          0\n",
       "7    J-00002             1  Content syndication                0          0"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from math import factorial\n",
    "\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "touches = pd.read_csv(\"northpine_journeys.csv\")\n",
    "channels = pd.read_csv(\"northpine_channels.csv\")\n",
    "print(f\"{touches.journey_id.nunique():,} journeys, {len(touches):,} touches\")\n",
    "touches.head(8)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "c59b42cd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:17:50.988068Z",
     "iopub.status.busy": "2026-12-05T03:17:50.987980Z",
     "iopub.status.idle": "2026-12-05T03:17:51.190348Z",
     "shell.execute_reply": "2026-12-05T03:17:51.189815Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "807 demos from 20,000 journeys (4.04%)\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>journeys</th>\n",
       "      <th>demo_rate</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>touches</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>3722</td>\n",
       "      <td>0.015</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>5788</td>\n",
       "      <td>0.024</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>4899</td>\n",
       "      <td>0.030</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>3042</td>\n",
       "      <td>0.052</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>1514</td>\n",
       "      <td>0.100</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>644</td>\n",
       "      <td>0.123</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>262</td>\n",
       "      <td>0.145</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>87</td>\n",
       "      <td>0.218</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "         journeys  demo_rate\n",
       "touches                     \n",
       "1            3722      0.015\n",
       "2            5788      0.024\n",
       "3            4899      0.030\n",
       "4            3042      0.052\n",
       "5            1514      0.100\n",
       "6             644      0.123\n",
       "7             262      0.145\n",
       "8              87      0.218"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "journeys = (touches.sort_values([\"journey_id\", \"touch_number\"])\n",
    "            .groupby(\"journey_id\")\n",
    "            .agg(path=(\"channel\", list), days=(\"days_before_end\", list),\n",
    "                 converted=(\"converted\", \"first\")))\n",
    "journeys[\"touches\"] = journeys[\"path\"].str.len()\n",
    "\n",
    "print(f\"{journeys.converted.sum()} demos from {len(journeys):,} journeys \"\n",
    "      f\"({journeys.converted.mean():.2%})\")\n",
    "journeys.groupby(\"touches\")[\"converted\"].agg(journeys=\"size\", demo_rate=\"mean\").head(8).round(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "27b86c79",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:17:51.191754Z",
     "iopub.status.busy": "2026-12-05T03:17:51.191648Z",
     "iopub.status.idle": "2026-12-05T03:17:51.202603Z",
     "shell.execute_reply": "2026-12-05T03:17:51.202067Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Last touch</th>\n",
       "      <th>First touch</th>\n",
       "      <th>Linear</th>\n",
       "      <th>Time decay</th>\n",
       "      <th>Position-based</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Brand search</th>\n",
       "      <td>351.0</td>\n",
       "      <td>114.0</td>\n",
       "      <td>217.4</td>\n",
       "      <td>273.8</td>\n",
       "      <td>226.5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Content syndication</th>\n",
       "      <td>19.0</td>\n",
       "      <td>82.0</td>\n",
       "      <td>49.8</td>\n",
       "      <td>36.6</td>\n",
       "      <td>49.8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Display</th>\n",
       "      <td>22.0</td>\n",
       "      <td>89.0</td>\n",
       "      <td>53.3</td>\n",
       "      <td>38.2</td>\n",
       "      <td>54.6</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Email</th>\n",
       "      <td>109.0</td>\n",
       "      <td>64.0</td>\n",
       "      <td>94.6</td>\n",
       "      <td>102.1</td>\n",
       "      <td>89.6</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>LinkedIn ads</th>\n",
       "      <td>37.0</td>\n",
       "      <td>123.0</td>\n",
       "      <td>78.6</td>\n",
       "      <td>59.5</td>\n",
       "      <td>79.5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Organic search</th>\n",
       "      <td>93.0</td>\n",
       "      <td>143.0</td>\n",
       "      <td>118.9</td>\n",
       "      <td>109.3</td>\n",
       "      <td>119.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Paid search</th>\n",
       "      <td>121.0</td>\n",
       "      <td>145.0</td>\n",
       "      <td>137.8</td>\n",
       "      <td>129.8</td>\n",
       "      <td>134.8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Webinar</th>\n",
       "      <td>55.0</td>\n",
       "      <td>47.0</td>\n",
       "      <td>56.7</td>\n",
       "      <td>57.8</td>\n",
       "      <td>53.1</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                     Last touch  First touch  Linear  Time decay  \\\n",
       "Brand search              351.0        114.0   217.4       273.8   \n",
       "Content syndication        19.0         82.0    49.8        36.6   \n",
       "Display                    22.0         89.0    53.3        38.2   \n",
       "Email                     109.0         64.0    94.6       102.1   \n",
       "LinkedIn ads               37.0        123.0    78.6        59.5   \n",
       "Organic search             93.0        143.0   118.9       109.3   \n",
       "Paid search               121.0        145.0   137.8       129.8   \n",
       "Webinar                    55.0         47.0    56.7        57.8   \n",
       "\n",
       "                     Position-based  \n",
       "Brand search                  226.5  \n",
       "Content syndication            49.8  \n",
       "Display                        54.6  \n",
       "Email                          89.6  \n",
       "LinkedIn ads                   79.5  \n",
       "Organic search                119.0  \n",
       "Paid search                   134.8  \n",
       "Webinar                        53.1  "
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def add(credit, channel, share):\n",
    "    credit[channel] = credit.get(channel, 0) + share\n",
    "\n",
    "\n",
    "def last_touch(path, days):\n",
    "    return {path[-1]: 1.0}\n",
    "\n",
    "\n",
    "def first_touch(path, days):\n",
    "    return {path[0]: 1.0}\n",
    "\n",
    "\n",
    "def linear(path, days):\n",
    "    credit = {}\n",
    "    for ch in path:\n",
    "        add(credit, ch, 1 / len(path))\n",
    "    return credit\n",
    "\n",
    "\n",
    "def time_decay(path, days, half_life=7):\n",
    "    weights = [0.5 ** (d / half_life) for d in days]\n",
    "    credit = {}\n",
    "    for ch, w in zip(path, weights):\n",
    "        add(credit, ch, w / sum(weights))\n",
    "    return credit\n",
    "\n",
    "\n",
    "def position_based(path, days):\n",
    "    n = len(path)\n",
    "    if n == 1:\n",
    "        shares = [1.0]\n",
    "    elif n == 2:\n",
    "        shares = [0.5, 0.5]\n",
    "    else:\n",
    "        shares = [0.4] + [0.2 / (n - 2)] * (n - 2) + [0.4]\n",
    "    credit = {}\n",
    "    for ch, s in zip(path, shares):\n",
    "        add(credit, ch, s)\n",
    "    return credit\n",
    "\n",
    "\n",
    "def attribute(rule, data):\n",
    "    total = {}\n",
    "    won = data[data.converted == 1]\n",
    "    for path, days in zip(won[\"path\"], won[\"days\"]):\n",
    "        for ch, share in rule(path, days).items():\n",
    "            add(total, ch, share)\n",
    "    return pd.Series(total)\n",
    "\n",
    "\n",
    "rules = {\"Last touch\": last_touch, \"First touch\": first_touch, \"Linear\": linear,\n",
    "         \"Time decay\": time_decay, \"Position-based\": position_based}\n",
    "credit = pd.DataFrame({name: attribute(rule, journeys) for name, rule in rules.items()}).fillna(0)\n",
    "credit.round(1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "15e0fce0",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:17:51.203611Z",
     "iopub.status.busy": "2026-12-05T03:17:51.203536Z",
     "iopub.status.idle": "2026-12-05T03:17:51.223097Z",
     "shell.execute_reply": "2026-12-05T03:17:51.222712Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "chance of a demo, from the chain: 0.0404\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "Brand search           0.527\n",
       "Paid search            0.357\n",
       "Organic search         0.343\n",
       "LinkedIn ads           0.282\n",
       "Email                  0.268\n",
       "Display                0.229\n",
       "Content syndication    0.196\n",
       "Webinar                0.155\n",
       "dtype: float64"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def transition_counts(data):\n",
    "    counts = {}\n",
    "    for path, converted in zip(data[\"path\"], data[\"converted\"]):\n",
    "        states = [\"start\"] + path + [\"demo\" if converted else \"null\"]\n",
    "        for a, b in zip(states[:-1], states[1:]):\n",
    "            counts[(a, b)] = counts.get((a, b), 0) + 1\n",
    "    return counts\n",
    "\n",
    "\n",
    "def p_demo(counts, removed=None):\n",
    "    \"\"\"Probability that a journey starting at 'start' ends in a demo.\n",
    "    A removed channel sends everyone who reaches it to 'null'.\"\"\"\n",
    "    states = sorted({a for a, _ in counts})            # start and every channel\n",
    "    idx = {s: i for i, s in enumerate(states)}\n",
    "    Q = np.zeros((len(states), len(states)))             # moves between transient states\n",
    "    r = np.zeros(len(states))                            # one-step chance of a demo\n",
    "    for s in states:\n",
    "        out = {b: n for (a, b), n in counts.items() if a == s}\n",
    "        total = sum(out.values())\n",
    "        if s == removed:\n",
    "            continue\n",
    "        for b, n in out.items():\n",
    "            if b == \"demo\":\n",
    "                r[idx[s]] += n / total\n",
    "            elif b in idx and b != removed:\n",
    "                Q[idx[s], idx[b]] += n / total\n",
    "    x = np.linalg.solve(np.eye(len(states)) - Q, r)    # x = r + Q x\n",
    "    return x[idx[\"start\"]]\n",
    "\n",
    "\n",
    "def markov_credit(data):\n",
    "    counts = transition_counts(data)\n",
    "    base = p_demo(counts)\n",
    "    chans = sorted({c for p in data[\"path\"] for c in p})\n",
    "    removal = pd.Series({c: 1 - p_demo(counts, removed=c) / base for c in chans})\n",
    "    return removal / removal.sum() * data[\"converted\"].sum(), removal, base\n",
    "\n",
    "\n",
    "credit[\"Markov\"], removal, base_p = markov_credit(journeys)\n",
    "print(f\"chance of a demo, from the chain: {base_p:.4f}\")\n",
    "removal.sort_values(ascending=False).round(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "653fb5f2",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:17:51.224238Z",
     "iopub.status.busy": "2026-12-05T03:17:51.224157Z",
     "iopub.status.idle": "2026-12-05T03:17:51.239732Z",
     "shell.execute_reply": "2026-12-05T03:17:51.239208Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Last touch</th>\n",
       "      <th>Markov</th>\n",
       "      <th>Shapley</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Brand search</th>\n",
       "      <td>351.0</td>\n",
       "      <td>180.3</td>\n",
       "      <td>182.6</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Content syndication</th>\n",
       "      <td>19.0</td>\n",
       "      <td>67.2</td>\n",
       "      <td>54.7</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Display</th>\n",
       "      <td>22.0</td>\n",
       "      <td>78.6</td>\n",
       "      <td>59.1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Email</th>\n",
       "      <td>109.0</td>\n",
       "      <td>91.8</td>\n",
       "      <td>102.2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>LinkedIn ads</th>\n",
       "      <td>37.0</td>\n",
       "      <td>96.7</td>\n",
       "      <td>85.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Organic search</th>\n",
       "      <td>93.0</td>\n",
       "      <td>117.3</td>\n",
       "      <td>119.1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Paid search</th>\n",
       "      <td>121.0</td>\n",
       "      <td>122.1</td>\n",
       "      <td>141.4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Webinar</th>\n",
       "      <td>55.0</td>\n",
       "      <td>52.9</td>\n",
       "      <td>62.8</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                     Last touch  Markov  Shapley\n",
       "Brand search              351.0   180.3    182.6\n",
       "Content syndication        19.0    67.2     54.7\n",
       "Display                    22.0    78.6     59.1\n",
       "Email                     109.0    91.8    102.2\n",
       "LinkedIn ads               37.0    96.7     85.0\n",
       "Organic search             93.0   117.3    119.1\n",
       "Paid search               121.0   122.1    141.4\n",
       "Webinar                    55.0    52.9     62.8"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def shapley_credit(data):\n",
    "    chans = sorted({c for p in data[\"path\"] for c in p})\n",
    "    n = len(chans)\n",
    "    bit = {c: 1 << i for i, c in enumerate(chans)}\n",
    "\n",
    "    # demos from journeys that touched exactly each set of channels\n",
    "    exact = np.zeros(1 << n)\n",
    "    for path, converted in zip(data[\"path\"], data[\"converted\"]):\n",
    "        exact[sum(bit[c] for c in set(path))] += converted\n",
    "\n",
    "    # v(S): demos from journeys whose channels all lie inside S\n",
    "    v = exact.copy()\n",
    "    for i in range(n):\n",
    "        for mask in range(1 << n):\n",
    "            if mask & (1 << i):\n",
    "                v[mask] += v[mask ^ (1 << i)]\n",
    "\n",
    "    phi = {}\n",
    "    for c in chans:\n",
    "        total = 0.0\n",
    "        for mask in range(1 << n):\n",
    "            if mask & bit[c]:\n",
    "                continue\n",
    "            s = bin(mask).count(\"1\")\n",
    "            weight = factorial(s) * factorial(n - s - 1) / factorial(n)\n",
    "            total += weight * (v[mask | bit[c]] - v[mask])\n",
    "        phi[c] = total\n",
    "    return pd.Series(phi)\n",
    "\n",
    "\n",
    "credit[\"Shapley\"] = shapley_credit(journeys)\n",
    "credit[[\"Last touch\", \"Markov\", \"Shapley\"]].round(1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "ca4bc908",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:17:51.240679Z",
     "iopub.status.busy": "2026-12-05T03:17:51.240603Z",
     "iopub.status.idle": "2026-12-05T03:17:51.245744Z",
     "shell.execute_reply": "2026-12-05T03:17:51.245375Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Last touch</th>\n",
       "      <th>First touch</th>\n",
       "      <th>Linear</th>\n",
       "      <th>Time decay</th>\n",
       "      <th>Position-based</th>\n",
       "      <th>Markov</th>\n",
       "      <th>Shapley</th>\n",
       "      <th>Truth</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Brand search</th>\n",
       "      <td>351.0</td>\n",
       "      <td>114.0</td>\n",
       "      <td>217.4</td>\n",
       "      <td>273.8</td>\n",
       "      <td>226.5</td>\n",
       "      <td>180.3</td>\n",
       "      <td>182.6</td>\n",
       "      <td>26.9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Content syndication</th>\n",
       "      <td>19.0</td>\n",
       "      <td>82.0</td>\n",
       "      <td>49.8</td>\n",
       "      <td>36.6</td>\n",
       "      <td>49.8</td>\n",
       "      <td>67.2</td>\n",
       "      <td>54.7</td>\n",
       "      <td>21.6</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Display</th>\n",
       "      <td>22.0</td>\n",
       "      <td>89.0</td>\n",
       "      <td>53.3</td>\n",
       "      <td>38.2</td>\n",
       "      <td>54.6</td>\n",
       "      <td>78.6</td>\n",
       "      <td>59.1</td>\n",
       "      <td>15.3</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Email</th>\n",
       "      <td>109.0</td>\n",
       "      <td>64.0</td>\n",
       "      <td>94.6</td>\n",
       "      <td>102.1</td>\n",
       "      <td>89.6</td>\n",
       "      <td>91.8</td>\n",
       "      <td>102.2</td>\n",
       "      <td>63.9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>LinkedIn ads</th>\n",
       "      <td>37.0</td>\n",
       "      <td>123.0</td>\n",
       "      <td>78.6</td>\n",
       "      <td>59.5</td>\n",
       "      <td>79.5</td>\n",
       "      <td>96.7</td>\n",
       "      <td>85.0</td>\n",
       "      <td>74.8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Organic search</th>\n",
       "      <td>93.0</td>\n",
       "      <td>143.0</td>\n",
       "      <td>118.9</td>\n",
       "      <td>109.3</td>\n",
       "      <td>119.0</td>\n",
       "      <td>117.3</td>\n",
       "      <td>119.1</td>\n",
       "      <td>88.8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Paid search</th>\n",
       "      <td>121.0</td>\n",
       "      <td>145.0</td>\n",
       "      <td>137.8</td>\n",
       "      <td>129.8</td>\n",
       "      <td>134.8</td>\n",
       "      <td>122.1</td>\n",
       "      <td>141.4</td>\n",
       "      <td>146.3</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Webinar</th>\n",
       "      <td>55.0</td>\n",
       "      <td>47.0</td>\n",
       "      <td>56.7</td>\n",
       "      <td>57.8</td>\n",
       "      <td>53.1</td>\n",
       "      <td>52.9</td>\n",
       "      <td>62.8</td>\n",
       "      <td>83.6</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Total</th>\n",
       "      <td>807.0</td>\n",
       "      <td>807.0</td>\n",
       "      <td>807.1</td>\n",
       "      <td>807.1</td>\n",
       "      <td>806.9</td>\n",
       "      <td>806.9</td>\n",
       "      <td>806.9</td>\n",
       "      <td>521.2</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                     Last touch  First touch  Linear  Time decay  \\\n",
       "Brand search              351.0        114.0   217.4       273.8   \n",
       "Content syndication        19.0         82.0    49.8        36.6   \n",
       "Display                    22.0         89.0    53.3        38.2   \n",
       "Email                     109.0         64.0    94.6       102.1   \n",
       "LinkedIn ads               37.0        123.0    78.6        59.5   \n",
       "Organic search             93.0        143.0   118.9       109.3   \n",
       "Paid search               121.0        145.0   137.8       129.8   \n",
       "Webinar                    55.0         47.0    56.7        57.8   \n",
       "Total                     807.0        807.0   807.1       807.1   \n",
       "\n",
       "                     Position-based  Markov  Shapley  Truth  \n",
       "Brand search                  226.5   180.3    182.6   26.9  \n",
       "Content syndication            49.8    67.2     54.7   21.6  \n",
       "Display                        54.6    78.6     59.1   15.3  \n",
       "Email                          89.6    91.8    102.2   63.9  \n",
       "LinkedIn ads                   79.5    96.7     85.0   74.8  \n",
       "Organic search                119.0   117.3    119.1   88.8  \n",
       "Paid search                   134.8   122.1    141.4  146.3  \n",
       "Webinar                        53.1    52.9     62.8   83.6  \n",
       "Total                         806.9   806.9    806.9  521.2  "
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "truth = channels.set_index(\"channel\")[\"true_incremental_demos\"]\n",
    "compare = credit.assign(Truth=truth).round(1)\n",
    "compare.loc[\"Total\"] = compare.sum()\n",
    "compare"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "57ac41c2",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:17:51.246773Z",
     "iopub.status.busy": "2026-12-05T03:17:51.246699Z",
     "iopub.status.idle": "2026-12-05T03:17:51.250962Z",
     "shell.execute_reply": "2026-12-05T03:17:51.250618Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Last touch</th>\n",
       "      <th>Linear</th>\n",
       "      <th>Markov</th>\n",
       "      <th>Shapley</th>\n",
       "      <th>Truth</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>channel</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>LinkedIn ads</th>\n",
       "      <td>1622.0</td>\n",
       "      <td>763.0</td>\n",
       "      <td>620.0</td>\n",
       "      <td>706.0</td>\n",
       "      <td>802.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Display</th>\n",
       "      <td>1136.0</td>\n",
       "      <td>469.0</td>\n",
       "      <td>318.0</td>\n",
       "      <td>423.0</td>\n",
       "      <td>1634.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Content syndication</th>\n",
       "      <td>1579.0</td>\n",
       "      <td>602.0</td>\n",
       "      <td>446.0</td>\n",
       "      <td>548.0</td>\n",
       "      <td>1389.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Paid search</th>\n",
       "      <td>372.0</td>\n",
       "      <td>327.0</td>\n",
       "      <td>369.0</td>\n",
       "      <td>318.0</td>\n",
       "      <td>308.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Brand search</th>\n",
       "      <td>85.0</td>\n",
       "      <td>138.0</td>\n",
       "      <td>166.0</td>\n",
       "      <td>164.0</td>\n",
       "      <td>1115.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Email</th>\n",
       "      <td>46.0</td>\n",
       "      <td>53.0</td>\n",
       "      <td>54.0</td>\n",
       "      <td>49.0</td>\n",
       "      <td>78.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Webinar</th>\n",
       "      <td>273.0</td>\n",
       "      <td>265.0</td>\n",
       "      <td>284.0</td>\n",
       "      <td>239.0</td>\n",
       "      <td>179.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                     Last touch  Linear  Markov  Shapley   Truth\n",
       "channel                                                         \n",
       "LinkedIn ads             1622.0   763.0   620.0    706.0   802.0\n",
       "Display                  1136.0   469.0   318.0    423.0  1634.0\n",
       "Content syndication      1579.0   602.0   446.0    548.0  1389.0\n",
       "Paid search               372.0   327.0   369.0    318.0   308.0\n",
       "Brand search               85.0   138.0   166.0    164.0  1115.0\n",
       "Email                      46.0    53.0    54.0     49.0    78.0\n",
       "Webinar                   273.0   265.0   284.0    239.0   179.0"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "spend = channels.set_index(\"channel\")[\"spend_90d\"]\n",
    "paid = spend[spend > 0].index\n",
    "cost_per_demo = compare.loc[paid].rdiv(spend[paid], axis=0).round(0)\n",
    "cost_per_demo[[\"Last touch\", \"Linear\", \"Markov\", \"Shapley\", \"Truth\"]]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "536213fd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:17:51.251986Z",
     "iopub.status.busy": "2026-12-05T03:17:51.251911Z",
     "iopub.status.idle": "2026-12-05T03:17:54.059775Z",
     "shell.execute_reply": "2026-12-05T03:17:54.059371Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead tr th {\n",
       "        text-align: left;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr>\n",
       "      <th></th>\n",
       "      <th colspan=\"2\" halign=\"left\">Last touch</th>\n",
       "      <th colspan=\"2\" halign=\"left\">Markov</th>\n",
       "      <th colspan=\"2\" halign=\"left\">Shapley</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th></th>\n",
       "      <th>0.05</th>\n",
       "      <th>0.95</th>\n",
       "      <th>0.05</th>\n",
       "      <th>0.95</th>\n",
       "      <th>0.05</th>\n",
       "      <th>0.95</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Brand search</th>\n",
       "      <td>323.0</td>\n",
       "      <td>381.0</td>\n",
       "      <td>168.0</td>\n",
       "      <td>191.0</td>\n",
       "      <td>170.0</td>\n",
       "      <td>194.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Content syndication</th>\n",
       "      <td>12.0</td>\n",
       "      <td>25.0</td>\n",
       "      <td>63.0</td>\n",
       "      <td>70.0</td>\n",
       "      <td>46.0</td>\n",
       "      <td>61.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Display</th>\n",
       "      <td>15.0</td>\n",
       "      <td>31.0</td>\n",
       "      <td>73.0</td>\n",
       "      <td>84.0</td>\n",
       "      <td>49.0</td>\n",
       "      <td>65.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Email</th>\n",
       "      <td>95.0</td>\n",
       "      <td>124.0</td>\n",
       "      <td>84.0</td>\n",
       "      <td>98.0</td>\n",
       "      <td>93.0</td>\n",
       "      <td>112.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>LinkedIn ads</th>\n",
       "      <td>28.0</td>\n",
       "      <td>46.0</td>\n",
       "      <td>90.0</td>\n",
       "      <td>102.0</td>\n",
       "      <td>75.0</td>\n",
       "      <td>94.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Organic search</th>\n",
       "      <td>80.0</td>\n",
       "      <td>109.0</td>\n",
       "      <td>108.0</td>\n",
       "      <td>125.0</td>\n",
       "      <td>109.0</td>\n",
       "      <td>132.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Paid search</th>\n",
       "      <td>99.0</td>\n",
       "      <td>135.0</td>\n",
       "      <td>114.0</td>\n",
       "      <td>130.0</td>\n",
       "      <td>129.0</td>\n",
       "      <td>153.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Webinar</th>\n",
       "      <td>43.0</td>\n",
       "      <td>65.0</td>\n",
       "      <td>48.0</td>\n",
       "      <td>57.0</td>\n",
       "      <td>55.0</td>\n",
       "      <td>70.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                    Last touch        Markov        Shapley       \n",
       "                          0.05   0.95   0.05   0.95    0.05   0.95\n",
       "Brand search             323.0  381.0  168.0  191.0   170.0  194.0\n",
       "Content syndication       12.0   25.0   63.0   70.0    46.0   61.0\n",
       "Display                   15.0   31.0   73.0   84.0    49.0   65.0\n",
       "Email                     95.0  124.0   84.0   98.0    93.0  112.0\n",
       "LinkedIn ads              28.0   46.0   90.0  102.0    75.0   94.0\n",
       "Organic search            80.0  109.0  108.0  125.0   109.0  132.0\n",
       "Paid search               99.0  135.0  114.0  130.0   129.0  153.0\n",
       "Webinar                   43.0   65.0   48.0   57.0    55.0   70.0"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "rng = np.random.default_rng(42)\n",
    "boot = []\n",
    "for b in range(100):\n",
    "    sample = journeys.sample(len(journeys), replace=True, random_state=int(rng.integers(1_000_000)))\n",
    "    boot.append(pd.DataFrame({\n",
    "        \"Last touch\": attribute(last_touch, sample),\n",
    "        \"Markov\": markov_credit(sample)[0],\n",
    "        \"Shapley\": shapley_credit(sample),\n",
    "    }).fillna(0))\n",
    "\n",
    "boot = pd.concat(boot, keys=range(100))\n",
    "ranges = boot.groupby(level=1).quantile([0.05, 0.95]).unstack().round(0)\n",
    "ranges"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "6efa2cea",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:17:54.061107Z",
     "iopub.status.busy": "2026-12-05T03:17:54.061012Z",
     "iopub.status.idle": "2026-12-05T03:17:54.064401Z",
     "shell.execute_reply": "2026-12-05T03:17:54.063948Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Last touch        221.7\n",
       "First touch        35.0\n",
       "Linear            118.7\n",
       "Time decay        162.7\n",
       "Position-based    124.5\n",
       "Markov             88.0\n",
       "Shapley            93.4\n",
       "Truth              -7.0\n",
       "dtype: float64"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def shift(credit, frm=\"LinkedIn ads\", to=\"Brand search\", amount=20_000):\n",
    "    \"\"\"Change in demos if `amount` moves from one channel to another,\n",
    "    assuming each dollar buys demos at the channel's average rate.\"\"\"\n",
    "    return amount * (credit[to] / spend[to] - credit[frm] / spend[frm])\n",
    "\n",
    "\n",
    "pd.Series({model: shift(compare[model]) for model in compare.columns}).round(1)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f907749f",
   "metadata": {},
   "source": [
    "## Appendix: the numbers behind the charts\n",
    "\n",
    "The guides' interactive charts are drawn from the numbers computed below. Run these cells after the ones above; the last cell saves everything to `attribution_charts.json`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "16fdd5db",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:17:54.065372Z",
     "iopub.status.busy": "2026-12-05T03:17:54.065291Z",
     "iopub.status.idle": "2026-12-05T03:17:54.070158Z",
     "shell.execute_reply": "2026-12-05T03:17:54.069748Z"
    }
   },
   "outputs": [],
   "source": [
    "import json\n",
    "\n",
    "order = list(truth.sort_values(ascending=False).index)\n",
    "charts = {\n",
    "    \"channels\": order,\n",
    "    \"spend\": {c: int(spend[c]) for c in order},\n",
    "    \"truth\": {c: float(truth[c]) for c in order},\n",
    "    \"credit\": {m: {c: round(float(credit.loc[c, m]), 1) for c in order} for m in credit.columns},\n",
    "    \"n_journeys\": int(len(journeys)), \"n_demos\": int(journeys.converted.sum()),\n",
    "    \"n_touches\": int(len(touches)), \"markov_p\": round(float(base_p), 5),\n",
    "    \"removal\": {c: round(float(removal[c]), 4) for c in order},\n",
    "}\n",
    "q = boot.groupby(level=1).quantile([0.05, 0.95])\n",
    "charts[\"boot\"] = {m: {c: [round(float(q.loc[(c, 0.05), m]), 1), round(float(q.loc[(c, 0.95), m]), 1)]\n",
    "                      for c in order} for m in [\"Last touch\", \"Markov\", \"Shapley\"]}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "6b5ad1d4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:17:54.071183Z",
     "iopub.status.busy": "2026-12-05T03:17:54.071119Z",
     "iopub.status.idle": "2026-12-05T03:17:54.088488Z",
     "shell.execute_reply": "2026-12-05T03:17:54.088038Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>size</th>\n",
       "      <th>sum</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>key</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Brand search</th>\n",
       "      <td>769</td>\n",
       "      <td>21</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Paid search &gt; Brand search</th>\n",
       "      <td>202</td>\n",
       "      <td>13</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>LinkedIn ads &gt; Brand search</th>\n",
       "      <td>274</td>\n",
       "      <td>11</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Email</th>\n",
       "      <td>562</td>\n",
       "      <td>9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Display &gt; Brand search</th>\n",
       "      <td>225</td>\n",
       "      <td>8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Organic search &gt; Email</th>\n",
       "      <td>145</td>\n",
       "      <td>8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Organic search</th>\n",
       "      <td>626</td>\n",
       "      <td>7</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Paid search</th>\n",
       "      <td>721</td>\n",
       "      <td>7</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>LinkedIn ads &gt; Email</th>\n",
       "      <td>177</td>\n",
       "      <td>6</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Paid search &gt; Email</th>\n",
       "      <td>122</td>\n",
       "      <td>6</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Content syndication &gt; Paid search</th>\n",
       "      <td>175</td>\n",
       "      <td>5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>LinkedIn ads</th>\n",
       "      <td>327</td>\n",
       "      <td>5</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                                   size  sum\n",
       "key                                         \n",
       "Brand search                        769   21\n",
       "Paid search > Brand search          202   13\n",
       "LinkedIn ads > Brand search         274   11\n",
       "Email                               562    9\n",
       "Display > Brand search              225    8\n",
       "Organic search > Email              145    8\n",
       "Organic search                      626    7\n",
       "Paid search                         721    7\n",
       "LinkedIn ads > Email                177    6\n",
       "Paid search > Email                 122    6\n",
       "Content syndication > Paid search   175    5\n",
       "LinkedIn ads                        327    5"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Journeys: length, demo rate by length, time from first touch to the end, the commonest paths\n",
    "by_len = journeys.groupby(journeys[\"touches\"].clip(upper=8))[\"converted\"].agg([\"size\", \"mean\"])\n",
    "charts[\"by_length\"] = [{\"touches\": int(k), \"journeys\": int(r[\"size\"]), \"rate\": round(float(r[\"mean\"]), 4)}\n",
    "                       for k, r in by_len.iterrows()]\n",
    "first_day = journeys[\"days\"].str[0]\n",
    "bins = [-1, 0, 7, 14, 30, 60, 90, 10_000]\n",
    "labels = [\"same day\", \"1-7\", \"8-14\", \"15-30\", \"31-60\", \"61-90\", \"90+\"]\n",
    "span = pd.cut(first_day, bins=bins, labels=labels)\n",
    "charts[\"span\"] = [{\"label\": l, \"all\": int((span == l).sum()), \"demos\": int(((span == l) & (journeys.converted == 1)).sum())}\n",
    "                  for l in labels]\n",
    "key = journeys[\"path\"].map(lambda p: \" > \".join(p))\n",
    "top = journeys.assign(key=key).groupby(\"key\")[\"converted\"].agg([\"size\", \"sum\"]).sort_values(\"sum\", ascending=False, kind=\"stable\").head(12)\n",
    "charts[\"top_paths\"] = [{\"path\": k.split(\" > \"), \"journeys\": int(r[\"size\"]), \"demos\": int(r[\"sum\"])} for k, r in top.iterrows()]\n",
    "top"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "d8e618a2",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:17:54.089497Z",
     "iopub.status.busy": "2026-12-05T03:17:54.089435Z",
     "iopub.status.idle": "2026-12-05T03:17:54.094215Z",
     "shell.execute_reply": "2026-12-05T03:17:54.093875Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>path</th>\n",
       "      <th>days</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>journey_id</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>J-12931</th>\n",
       "      <td>[Display, Organic search, Webinar, Display]</td>\n",
       "      <td>[15, 9, 8, 0]</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>J-09711</th>\n",
       "      <td>[LinkedIn ads, Brand search, Paid search]</td>\n",
       "      <td>[55, 55, 0]</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>J-15412</th>\n",
       "      <td>[Brand search, LinkedIn ads, Webinar, Brand se...</td>\n",
       "      <td>[6, 4, 4, 0]</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>J-02448</th>\n",
       "      <td>[Email, Organic search, Webinar, Brand search]</td>\n",
       "      <td>[19, 12, 9, 0]</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>J-15976</th>\n",
       "      <td>[Paid search, Brand search, Brand search]</td>\n",
       "      <td>[6, 5, 0]</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>J-00120</th>\n",
       "      <td>[Paid search, Email, Brand search, Email, Bran...</td>\n",
       "      <td>[16, 15, 13, 10, 0]</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                                                         path  \\\n",
       "journey_id                                                      \n",
       "J-12931           [Display, Organic search, Webinar, Display]   \n",
       "J-09711             [LinkedIn ads, Brand search, Paid search]   \n",
       "J-15412     [Brand search, LinkedIn ads, Webinar, Brand se...   \n",
       "J-02448        [Email, Organic search, Webinar, Brand search]   \n",
       "J-15976             [Paid search, Brand search, Brand search]   \n",
       "J-00120     [Paid search, Email, Brand search, Email, Bran...   \n",
       "\n",
       "                           days  \n",
       "journey_id                       \n",
       "J-12931           [15, 9, 8, 0]  \n",
       "J-09711             [55, 55, 0]  \n",
       "J-15412            [6, 4, 4, 0]  \n",
       "J-02448          [19, 12, 9, 0]  \n",
       "J-15976               [6, 5, 0]  \n",
       "J-00120     [16, 15, 13, 10, 0]  "
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Real converting journeys for the journey builder's presets\n",
    "won = journeys[(journeys.converted == 1) & journeys.touches.between(3, 6)]\n",
    "picks = won.sample(6, random_state=7)\n",
    "charts[\"examples\"] = [{\"id\": i, \"path\": p, \"days\": [int(d) for d in ds]} for i, p, ds in zip(picks.index, picks.path, picks.days)]\n",
    "picks[[\"path\", \"days\"]]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "79ad60b4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:17:54.095271Z",
     "iopub.status.busy": "2026-12-05T03:17:54.095203Z",
     "iopub.status.idle": "2026-12-05T03:17:54.107156Z",
     "shell.execute_reply": "2026-12-05T03:17:54.106787Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>1</th>\n",
       "      <th>3</th>\n",
       "      <th>7</th>\n",
       "      <th>14</th>\n",
       "      <th>30</th>\n",
       "      <th>60</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Paid search</th>\n",
       "      <td>120.5</td>\n",
       "      <td>125.1</td>\n",
       "      <td>129.8</td>\n",
       "      <td>133.2</td>\n",
       "      <td>135.5</td>\n",
       "      <td>136.7</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Organic search</th>\n",
       "      <td>99.2</td>\n",
       "      <td>104.4</td>\n",
       "      <td>109.3</td>\n",
       "      <td>112.9</td>\n",
       "      <td>115.6</td>\n",
       "      <td>117.1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Webinar</th>\n",
       "      <td>57.2</td>\n",
       "      <td>57.8</td>\n",
       "      <td>57.8</td>\n",
       "      <td>57.5</td>\n",
       "      <td>57.4</td>\n",
       "      <td>57.2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>LinkedIn ads</th>\n",
       "      <td>42.8</td>\n",
       "      <td>50.5</td>\n",
       "      <td>59.5</td>\n",
       "      <td>66.6</td>\n",
       "      <td>72.2</td>\n",
       "      <td>75.2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Email</th>\n",
       "      <td>107.7</td>\n",
       "      <td>106.0</td>\n",
       "      <td>102.1</td>\n",
       "      <td>99.4</td>\n",
       "      <td>97.5</td>\n",
       "      <td>96.2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Brand search</th>\n",
       "      <td>329.5</td>\n",
       "      <td>301.7</td>\n",
       "      <td>273.8</td>\n",
       "      <td>252.3</td>\n",
       "      <td>235.4</td>\n",
       "      <td>226.6</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Content syndication</th>\n",
       "      <td>23.1</td>\n",
       "      <td>29.7</td>\n",
       "      <td>36.6</td>\n",
       "      <td>41.3</td>\n",
       "      <td>45.2</td>\n",
       "      <td>47.3</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Display</th>\n",
       "      <td>27.1</td>\n",
       "      <td>31.8</td>\n",
       "      <td>38.2</td>\n",
       "      <td>43.7</td>\n",
       "      <td>48.2</td>\n",
       "      <td>50.6</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                         1      3      7     14     30     60\n",
       "Paid search          120.5  125.1  129.8  133.2  135.5  136.7\n",
       "Organic search        99.2  104.4  109.3  112.9  115.6  117.1\n",
       "Webinar               57.2   57.8   57.8   57.5   57.4   57.2\n",
       "LinkedIn ads          42.8   50.5   59.5   66.6   72.2   75.2\n",
       "Email                107.7  106.0  102.1   99.4   97.5   96.2\n",
       "Brand search         329.5  301.7  273.8  252.3  235.4  226.6\n",
       "Content syndication   23.1   29.7   36.6   41.3   45.2   47.3\n",
       "Display               27.1   31.8   38.2   43.7   48.2   50.6"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Time decay at different half-lives\n",
    "charts[\"half_life\"] = {str(h): {c: round(float(v), 1) for c, v in\n",
    "                               attribute(lambda p, d, h=h: time_decay(p, d, half_life=h), journeys).items()}\n",
    "                       for h in [1, 3, 7, 14, 30, 60]}\n",
    "pd.DataFrame(charts[\"half_life\"]).loc[order]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "f9fca037",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:17:54.108542Z",
     "iopub.status.busy": "2026-12-05T03:17:54.108437Z",
     "iopub.status.idle": "2026-12-05T03:17:55.240542Z",
     "shell.execute_reply": "2026-12-05T03:17:55.239993Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>7</th>\n",
       "      <th>14</th>\n",
       "      <th>30</th>\n",
       "      <th>60</th>\n",
       "      <th>90</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Paid search</th>\n",
       "      <td>125.1</td>\n",
       "      <td>125.2</td>\n",
       "      <td>124.1</td>\n",
       "      <td>122.5</td>\n",
       "      <td>122.2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Organic search</th>\n",
       "      <td>110.2</td>\n",
       "      <td>114.6</td>\n",
       "      <td>116.3</td>\n",
       "      <td>117.2</td>\n",
       "      <td>117.4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Webinar</th>\n",
       "      <td>54.0</td>\n",
       "      <td>53.5</td>\n",
       "      <td>53.2</td>\n",
       "      <td>52.9</td>\n",
       "      <td>53.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>LinkedIn ads</th>\n",
       "      <td>69.1</td>\n",
       "      <td>80.1</td>\n",
       "      <td>90.5</td>\n",
       "      <td>95.4</td>\n",
       "      <td>96.5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Email</th>\n",
       "      <td>100.1</td>\n",
       "      <td>96.5</td>\n",
       "      <td>94.2</td>\n",
       "      <td>92.4</td>\n",
       "      <td>91.9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Brand search</th>\n",
       "      <td>247.3</td>\n",
       "      <td>218.6</td>\n",
       "      <td>194.9</td>\n",
       "      <td>183.6</td>\n",
       "      <td>181.1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Content syndication</th>\n",
       "      <td>46.8</td>\n",
       "      <td>54.5</td>\n",
       "      <td>62.0</td>\n",
       "      <td>66.0</td>\n",
       "      <td>66.9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Display</th>\n",
       "      <td>54.4</td>\n",
       "      <td>64.0</td>\n",
       "      <td>71.8</td>\n",
       "      <td>76.9</td>\n",
       "      <td>78.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                         7     14     30     60     90\n",
       "Paid search          125.1  125.2  124.1  122.5  122.2\n",
       "Organic search       110.2  114.6  116.3  117.2  117.4\n",
       "Webinar               54.0   53.5   53.2   52.9   53.0\n",
       "LinkedIn ads          69.1   80.1   90.5   95.4   96.5\n",
       "Email                100.1   96.5   94.2   92.4   91.9\n",
       "Brand search         247.3  218.6  194.9  183.6  181.1\n",
       "Content syndication   46.8   54.5   62.0   66.0   66.9\n",
       "Display               54.4   64.0   71.8   76.9   78.0"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# The lookback window: only touches within W days of the end count\n",
    "look = {}\n",
    "for w in [7, 14, 30, 60, 90]:\n",
    "    t = touches[touches.days_before_end <= w]\n",
    "    j = (t.sort_values([\"journey_id\", \"touch_number\"]).groupby(\"journey_id\")\n",
    "         .agg(path=(\"channel\", list), days=(\"days_before_end\", list), converted=(\"converted\", \"first\")))\n",
    "    look[str(w)] = {\"Linear\": attribute(linear, j), \"Position-based\": attribute(position_based, j),\n",
    "                    \"Markov\": markov_credit(j)[0], \"Shapley\": shapley_credit(j)}\n",
    "charts[\"lookback\"] = {w: {m: {c: round(float(s.get(c, 0)), 1) for c in order} for m, s in d.items()} for w, d in look.items()}\n",
    "pd.DataFrame({w: d[\"Markov\"] for w, d in look.items()}).loc[order].round(1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "16d71945",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:17:55.241847Z",
     "iopub.status.busy": "2026-12-05T03:17:55.241744Z",
     "iopub.status.idle": "2026-12-05T03:17:56.165822Z",
     "shell.execute_reply": "2026-12-05T03:17:56.165336Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>0</th>\n",
       "      <th>0.1</th>\n",
       "      <th>0.25</th>\n",
       "      <th>0.5</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Paid search</th>\n",
       "      <td>122.1</td>\n",
       "      <td>122.8</td>\n",
       "      <td>122.9</td>\n",
       "      <td>123.2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Organic search</th>\n",
       "      <td>117.3</td>\n",
       "      <td>116.6</td>\n",
       "      <td>115.8</td>\n",
       "      <td>113.3</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Webinar</th>\n",
       "      <td>52.9</td>\n",
       "      <td>52.8</td>\n",
       "      <td>52.1</td>\n",
       "      <td>52.6</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>LinkedIn ads</th>\n",
       "      <td>96.7</td>\n",
       "      <td>94.1</td>\n",
       "      <td>91.1</td>\n",
       "      <td>81.3</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Email</th>\n",
       "      <td>91.8</td>\n",
       "      <td>92.3</td>\n",
       "      <td>93.5</td>\n",
       "      <td>96.5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Brand search</th>\n",
       "      <td>180.3</td>\n",
       "      <td>186.5</td>\n",
       "      <td>197.9</td>\n",
       "      <td>224.2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Content syndication</th>\n",
       "      <td>67.2</td>\n",
       "      <td>65.2</td>\n",
       "      <td>62.5</td>\n",
       "      <td>53.5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Display</th>\n",
       "      <td>78.6</td>\n",
       "      <td>76.6</td>\n",
       "      <td>71.3</td>\n",
       "      <td>62.4</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                         0    0.1   0.25    0.5\n",
       "Paid search          122.1  122.8  122.9  123.2\n",
       "Organic search       117.3  116.6  115.8  113.3\n",
       "Webinar               52.9   52.8   52.1   52.6\n",
       "LinkedIn ads          96.7   94.1   91.1   81.3\n",
       "Email                 91.8   92.3   93.5   96.5\n",
       "Brand search         180.3  186.5  197.9  224.2\n",
       "Content syndication   67.2   65.2   62.5   53.5\n",
       "Display               78.6   76.6   71.3   62.4"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Tracking gaps: each touch before the last one is lost with probability g\n",
    "gap_rng = np.random.default_rng(11)\n",
    "gaps = {}\n",
    "for g in [0, 0.1, 0.25, 0.5]:\n",
    "    keep = (touches.groupby(\"journey_id\")[\"touch_number\"].transform(\"max\") == touches.touch_number) | (gap_rng.random(len(touches)) >= g)\n",
    "    t = touches[keep]\n",
    "    j = (t.sort_values([\"journey_id\", \"touch_number\"]).groupby(\"journey_id\")\n",
    "         .agg(path=(\"channel\", list), days=(\"days_before_end\", list), converted=(\"converted\", \"first\")))\n",
    "    gaps[str(g)] = {\"Last touch\": attribute(last_touch, j), \"Linear\": attribute(linear, j),\n",
    "                    \"Markov\": markov_credit(j)[0], \"Shapley\": shapley_credit(j)}\n",
    "charts[\"gaps\"] = {g: {m: {c: round(float(s.get(c, 0)), 1) for c in order} for m, s in d.items()} for g, d in gaps.items()}\n",
    "pd.DataFrame({g: d[\"Markov\"] for g, d in gaps.items()}).loc[order].round(1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "84aef195",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:17:56.167021Z",
     "iopub.status.busy": "2026-12-05T03:17:56.166947Z",
     "iopub.status.idle": "2026-12-05T03:17:56.183046Z",
     "shell.execute_reply": "2026-12-05T03:17:56.182643Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Paid search            0.02596\n",
       "Organic search         0.02653\n",
       "Webinar                0.03411\n",
       "LinkedIn ads           0.02896\n",
       "Email                  0.02954\n",
       "Brand search           0.01911\n",
       "Content syndication    0.03243\n",
       "Display                0.03109\n",
       "dtype: float64"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# The Markov chain itself: transition probabilities between states\n",
    "counts = transition_counts(journeys)\n",
    "out_tot = {}\n",
    "for (a, b), n in counts.items():\n",
    "    out_tot[a] = out_tot.get(a, 0) + n\n",
    "charts[\"transitions\"] = [{\"from\": a, \"to\": b, \"p\": round(n / out_tot[a], 4), \"n\": int(n)}\n",
    "                         for (a, b), n in sorted(counts.items())]\n",
    "charts[\"removed_p\"] = {c: round(float(p_demo(counts, removed=c)), 5) for c in order}\n",
    "pd.Series(charts[\"removed_p\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "5836850b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:17:56.184172Z",
     "iopub.status.busy": "2026-12-05T03:17:56.184099Z",
     "iopub.status.idle": "2026-12-05T03:17:56.187959Z",
     "shell.execute_reply": "2026-12-05T03:17:56.187541Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'base': 0.6667, 'without': {'LinkedIn ads': 0.3333, 'Brand search': 0.0}}\n",
      "{'Brand search': 35.0, 'LinkedIn ads': 25.0}\n"
     ]
    }
   ],
   "source": [
    "# Worked examples for the math section, on tiny made-up data\n",
    "toy = pd.DataFrame({\"path\": [[\"LinkedIn ads\", \"Brand search\"], [\"LinkedIn ads\"], [\"Brand search\"]],\n",
    "                    \"days\": [[5, 0], [0], [0]], \"converted\": [1, 0, 1]})\n",
    "toy_counts = transition_counts(toy)\n",
    "toy_markov = {\"base\": round(float(p_demo(toy_counts)), 4),\n",
    "              \"without\": {c: round(float(p_demo(toy_counts, removed=c)), 4) for c in [\"LinkedIn ads\", \"Brand search\"]}}\n",
    "charts[\"toy_markov\"] = toy_markov\n",
    "toy_shapley = pd.DataFrame({\"path\": [[\"LinkedIn ads\"], [\"Brand search\"], [\"LinkedIn ads\", \"Brand search\"]],\n",
    "                            \"days\": [[0], [0], [3, 0]], \"converted\": [1, 1, 1]})\n",
    "toy_shapley = pd.concat([toy_shapley.iloc[[0]]] * 10 + [toy_shapley.iloc[[1]]] * 20 + [toy_shapley.iloc[[2]]] * 30,\n",
    "                        ignore_index=True)\n",
    "charts[\"toy_shapley\"] = {c: round(float(v), 2) for c, v in shapley_credit(toy_shapley).items()}\n",
    "print(toy_markov)\n",
    "print(charts[\"toy_shapley\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "17e72768",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-12-05T03:17:56.188861Z",
     "iopub.status.busy": "2026-12-05T03:17:56.188797Z",
     "iopub.status.idle": "2026-12-05T03:17:56.191588Z",
     "shell.execute_reply": "2026-12-05T03:17:56.191179Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "saved 21 chart datasets\n"
     ]
    }
   ],
   "source": [
    "with open(\"attribution_charts.json\", \"w\") as f:\n",
    "    json.dump(charts, f, default=lambda o: o.item() if hasattr(o, \"item\") else str(o))\n",
    "print(\"saved\", len(charts), \"chart datasets\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
