Grok 4.1 Fast· xai
Frontier Reasoning Traces
Build a brand lift test harness: surveys, holdouts, and analysis pipeline.
- User
Build a brand lift test harness: surveys, holdouts, and analysis pipeline.
- Assistant
Build a brand lift test harness: surveys, holdouts, and analysis pipeline.
This is a complete, self-contained brand lift test harness built with Python (Flask backend), HTML/JS (frontend), and SQLite for data storage. It simulates a digital ad campaign where:
pip install flask murmurhash numpy scipy pandas matplotlib seaborn statsmodels
python app.py → Visit http://localhost:5000.app.py)Handles bucketing, ad/survey serving, data storage.
from flask import Flask, request, jsonify, render_template_string
import sqlite3
import uuid
import murmurhash3
import json
from datetime import datetime
app = Flask(__name__)
# DB Setup
def init_db():
conn = sqlite3.connect('brandlift.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS responses
(user_id TEXT, group TEXT, timestamp TEXT, q1 INT, q2 INT, q3 INT, q4 INT)''')
conn.commit()
conn.close()
init_db()
# HTML Template (embedded for simplicity)
HTML_TEMPLATE = '''
<!DOCTYPE html>
<html>
<head><title>Brand Lift Test</title></head>
<body>
<div id="ad-container" style="width:300px;height:250px;border:1px solid #ccc;margin:20px;"></div>
<button id="start-btn" onclick="startTest()">Start Campaign</button>
<div id="survey" style="display:none;">
<h3>Quick Survey: Brand X</h3>
<label>Q1. Awareness (1=Never heard, 5=Know very well):</label><select id="q1"><option>1</option><option>2</option><option>3</option><option>4</option><option>5</option></select><br>
<label>Q2. Consideration (1=Never, 5=Very likely):</label><select id="q2"><option>1</option><option>2</option><option>3</option><option>4</option><option>5</option></select><br>
<label>Q3. Favorability (1=Very negative, 5=Very positive):</label><select id="q3"><option>1</option><option>2</option><option>3</option><option>4</option><option>5</option></select><br>
<label>Q4. Purchase Intent (Yes/No):</label><select id="q4"><option>0</option><option>1</option></select><br>
<button onclick="submitSurvey()">Submit</button>
</div>
<script>
let userId = '{{ user_id }}';
let group = '{{ group }}';
function startTest() {
document.getElementById('start-btn').style.display = 'none';
if (group === 'test') {
document.getElementById('ad-container').innerHTML = '<img src="https://via.placeholder.com/300x250/FF0000/FFFFFF?text=Brand+X+Ad" onload="setTimeout(showSurvey, 3000)">';
} else {
setTimeout(showSurvey, 1000); // Holdout: shorter "exposure"
}
}
function showSurvey() { document.getElementById('survey').style.display = 'block'; }
function submitSurvey() {
fetch('/submit', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
user_id: userId,
group: group,
q1: document.getElementById('q1').value,
q2: document.getElementById('q2').value,
q3: document.getElementById('q3').value,
q4: document.getElementById('q4').value
})
}).then(r => r.json()).then(data => alert('Submitted!'));
}
</script>
</body>
</html>
'''
@app.route('/')
def index():
# Generate/simulate user ID (in prod: use device ID, fingerprint)
user_id = request.args.get('user_id', str(uuid.uuid4()))
seed = murmurhash3.hash(user_id) % 100
group = 'test' if seed < 50 else 'control' # 50/50 split
return render_template_string(HTML_TEMPLATE, user_id=user_id, group=group)
@app.route('/submit', methods=['POST'])
def submit():
data = request.json
conn = sqlite3.connect('brandlift.db')
c = conn.cursor()
c.execute("INSERT INTO responses VALUES (?, ?, ?, ?, ?, ?, ?)",
(data['user_id'], data['group'], datetime.now().isoformat(),
data['q1'], data['q2'], data['q3'], data['q4']))
conn.commit()
conn.close()
return jsonify({'status': 'ok'})
if __name__ == '__main__':
app.run(debug=True)
Pro Tip: In prod, randomize question order, add attention checks, use 3rd-party like Qualtrics.
analyze.py)Run python analyze.py after collecting data (e.g., 100+ responses/group).
import sqlite3
import pandas as pd
import numpy as np
from scipy import stats
import statsmodels.stats.api as sms
import matplotlib.pyplot as plt
import seaborn as sns
from statsmodels.stats.proportion import proportions_ztest
# Load Data
conn = sqlite3.connect('brandlift.db')
df = pd.read_sql_query("SELECT * FROM responses", conn)
conn.close()
# Prep: Mean scores per group
metrics = ['q1', 'q2', 'q3', 'q4']
test = df[df['group'] == 'test'][metrics].mean()
control = df[df['group'] == 'control'][metrics].mean()
lift = ((test - control) / control * 100).round(1)
# Sample sizes
n_test, n_control = len(df[df['group'] == 'test']), len(df[df['group'] == 'control'])
# Statistical Tests (t-test for continuous, z-test for binary Q4)
pvals = {}
ci_low, ci_high = {}, {}
for metric in metrics:
test_vals = df[df['group'] == 'test'][metric].values
ctrl_vals = df[df['group'] == 'control'][metric].values
if metric == 'q4': # Binary prop test
count_test = np.sum(test_vals)
count_ctrl = np.sum(ctrl_vals)
z_stat, pvals[metric] = proportions_ztest([count_test, count_ctrl], [n_test, n_control])
else: # t-test
t_stat, pvals[metric] = stats.ttest_ind(test_vals, ctrl_vals)
# 95% CI for lift
diff = test_vals.mean() - ctrl_vals.mean()
sem = np.sqrt((test_vals.std()**2 / n_test) + (ctrl_vals.std()**2 / n_control))
ci_low[metric], ci_high[metric] = diff - 1.96*sem, diff + 1.96*sem
# Output
print("=== BRAND LIFT RESULTS ===")
print(f"Sample Sizes: Test={n_test}, Control={n_control}")
results_df = pd.DataFrame({
'Test Mean': test.round(2),
'Control Mean': control.round(2),
'Lift %': lift,
'P-Value': [f"{p:.4f}" for p in pvals.values()],
'Sig (p<0.05)': ['***' if p < 0.05 else 'ns' for p in pvals.values()],
'95% CI Low': [f"{low:.2f}" for low in ci_low.values()],
'95% CI High': [f"{high:.2f}" for high in ci_high.values()]
}, index=metrics)
print(results_df)
# Geo-Mean Lift (overall)
geo_lift = np.exp(np.log(1 + lift/100).mean()) - 1
print(f"\nOverall Geo-Mean Lift: {geo_lift*100:.1f}%")
# Viz
fig, ax = plt.subplots(1, 2, figsize=(12, 5))
sns.barplot(data=df.melt(id_vars='group', value_vars=metrics), x='variable', y='value', hue='group', ax=ax[0])
ax[0].set_title('Metric Means by Group')
results_df['Lift %'].plot(kind='bar', ax=ax[1])
ax[1].set_title('Lift %')
plt.tight_layout()
plt.savefig('brandlift_results.png')
plt.show()
=== BRAND LIFT RESULTS ===
Sample Sizes: Test=52, Control=48
Test Mean Control Mean Lift % P-Value Sig (p<0.05) 95% CI Low 95% CI High
q1 3.42 2.83 20.8 0.0123 *** 0.12 1.06
q2 3.21 2.67 20.2 0.0234 *** 0.08 1.09
q3 3.35 2.92 14.7 0.0891 ns -0.07 0.89
q4 0.65 0.42 54.8 0.0012 *** 0.09 0.37
Overall Geo-Mean Lift: 26.2%
*(Simulated; real data varies. Stars: **=sig @ p<0.01)
Run it, collect data via multiple browser tabs (?user_id=unique1, etc.), analyze. Questions? Ping me. 🕵️