프로덕트 분석 · PA06

A/B 테스트 분석: 신뢰구간·엿보기·CUPED

실험이 끝났습니다. 공고 16건 중 8건(50%)이 통계·가설검정을 적었습니다. 이 장에서는 checkout_v2의 결과를 신뢰구간과 z검정으로 읽고, 심어 둔 정답(결제 단계 +6%p)과 비교합니다. 그리고 매일 결과를 들여다보면 거짓 양성이 5%에서 26%로 늘어나는 것, 세그먼트를 뒤지면 효과 없는 실험에서도 "유의한" 결과가 4개 나오는 것을 직접 확인합니다.


Step 1. 스크립트와 결과

"""A/B 테스트 분석: 전환율 차이와 신뢰구간, 단계 전환율, 엿보기, A/A 모의실험, CUPED, 세그먼트 뒤지기.

    python pa/pa06_analysis.py
"""
import json
import sys
import duckdb
import numpy as np
import pandas as pd
from scipy.stats import norm
from statsmodels.stats.proportion import proportions_ztest, confint_proportions_2indep
sys.path.insert(0, 'common')
from plotstyle import *

con = duckdb.connect()
con.execute("ATTACH 'data/shop.duckdb' AS shop (READ_ONLY)")
TRUE = json.load(open('data/truth.json', encoding='utf-8'))['experiment_checkout_v2']['absolute_lift_in_step_rate']
END = '2026-09-29'

# 0. 먼저 확인: 배정 시각(assigned_at)과 그날 세션의 앞뒤가 맞는가
q = con.sql("""
select count(*) users, sum((s.t0 < a.assigned_at)::int) session_before_assign
from shop.exp_assign a join (select user_id, cast(ts as date) d, min(ts) t0 from shop.events group by 1, 2) s
  on s.user_id = a.user_id and s.d = cast(a.assigned_at as date)
where a.experiment = 'checkout_v2'""").fetchall()[0]
print(f'== 0. 배정 로그 점검: 배정된 {q[0]:,}명 중 {q[1]:,}명({100 * q[1] / q[0]:.0f}%)은 배정 시각보다 앞선 같은 날 세션이 있다')
print('   → 이 데이터의 assigned_at은 시각이 정확하지 않다. 아래 분석은 "배정된 날짜부터"로 자른다.')

# 유저별 결과: 배정된 날부터 실험 종료 전까지 주문했나, 얼마 결제했나, 처음 주문한 날짜
con.execute(f"""
create table r as
select a.user_id, a.variant, cast(a.assigned_at as date) d0, u.platform, u.age_band, u.gender,
       count(o.order_id) orders, coalesce(sum(o.pay_amount), 0) revenue, min(cast(o.order_ts as date)) first_order
from shop.exp_assign a join shop.users u using (user_id)
left join shop.orders o on o.user_id = a.user_id and o.order_ts >= cast(a.assigned_at as date) and o.order_ts < '{END}'
where a.experiment = 'checkout_v2' group by all""")


def ztest(df, col='conv'):
    g = df.groupby('variant')[col].agg(['sum', 'count']).loc[['treatment', 'control']]
    z, p = proportions_ztest(g['sum'].values, g['count'].values)
    lo, hi = confint_proportions_2indep(g['sum'].iloc[0], g['count'].iloc[0], g['sum'].iloc[1], g['count'].iloc[1], method='wald')
    return g, z, p, lo, hi


r = con.sql("select *, (orders > 0)::int conv from r").df()
r['d0'] = pd.to_datetime(r.d0); r['first_order'] = pd.to_datetime(r.first_order)
g, z, p, lo, hi = ztest(r)
pt, pc = g['sum'] / g['count']
print('== 1. 주 지표: 유저 기준 구매 전환율 (배정 뒤 실험 기간 안에 주문한 유저 비율)')
print(f"   대조군 {int(g['count']['control']):,}명 중 {int(g['sum']['control']):,}명 = {100 * pc:.2f}%")
print(f"   처리군 {int(g['count']['treatment']):,}명 중 {int(g['sum']['treatment']):,}명 = {100 * pt:.2f}%")
print(f'   차이 +{100 * (pt - pc):.2f}%p (상대 +{100 * (pt / pc - 1):.1f}%), 95% 신뢰구간 [{100 * lo:+.2f}, {100 * hi:+.2f}]%p, z = {z:.2f}, p = {p:.4f}')

# 2. 바꾼 단계 자체: 결제 시작 → 구매 (세션 기준)
s = con.sql(f"""
with ss as (select e.session_id, any_value(a.variant) variant,
                   max((event_name = 'begin_checkout')::int) chk, max((event_name = 'purchase')::int) buy
            from shop.events e join shop.exp_assign a on a.user_id = e.user_id and a.experiment = 'checkout_v2'
            where e.ts >= cast(a.assigned_at as date) and e.ts < '{END}' group by 1)
select variant, sum(chk) checkout_sessions, sum(buy) purchases, round(100.0 * sum(buy) / sum(chk), 2) step_rate from ss group by 1 order by 1""").df()
print('\n== 2. 바꾼 단계: 결제 시작 → 구매 (세션 기준)')
print(s.to_string(index=False))
d = s.step_rate.iloc[1] - s.step_rate.iloc[0]
se = np.sqrt(sum(q * (100 - q) / n for q, n in zip(s.step_rate, s.checkout_sessions)))
print(f'   차이 +{d:.2f}%p (95% 신뢰구간 대략 [{d - 1.96 * se:+.2f}, {d + 1.96 * se:+.2f}]%p).  심어 둔 정답 +{100 * TRUE:.1f}%p')

# 3. 엿보기: 매일 그날까지의 데이터로 p값을 다시 계산하면
days = pd.date_range('2026-09-01', '2026-09-28')
peek = []
for day in days:
    x = r[r.d0 <= day].copy()
    x['c'] = (x.first_order.notna() & (x.first_order <= day)).astype(int)
    gg, zz, pp, l, h = ztest(x, 'c')
    peek.append((day, pp, 100 * (gg['sum'] / gg['count']).diff().iloc[-1] * -1, int(gg['count'].sum())))
peek = pd.DataFrame(peek, columns=['day', 'p', 'diff', 'n'])
first = peek[peek.p < 0.05]
print('\n== 3. 날짜별 누적 p값 (매일 들여다봤다면)')
print(peek.iloc[[0, 2, 4, 6, 9, 13, 20, 27]].assign(day=lambda t: t.day.dt.strftime('%m-%d')).round({'p': 4, 'diff': 2})
      .rename(columns={'day': '날짜', 'p': 'p값', 'diff': '차이 %p', 'n': '누적 유저'}).to_string(index=False))
print(f"   p < 0.05가 처음 나온 날: {first.day.iloc[0].strftime('%m-%d') if len(first) else '없음'}, 28일 중 p < 0.05인 날 {len(first)}일, "
      f"그 뒤 다시 0.05를 넘은 날 {int((peek.p[first.index[0]:] >= 0.05).sum()) if len(first) else 0}일")

fig, ax = plt.subplots(figsize=(7.5, 3.2))
ax.plot(peek.day, peek.p, color=ACCENT, marker='o', ms=3)
ax.axhline(0.05, color=INK, lw=0.8, ls='--'); ax.text(peek.day.iloc[-1], 0.06, 'p = 0.05', ha='right', fontsize=8)
ax.set_yscale('log'); ax.set_ylabel('누적 p값 (로그 눈금)'); ax.set_title('checkout_v2: 매일 다시 계산한 p값 (가상 데이터)')
save(fig, 'pa06_peeking')

# 4. A/A 모의실험: 효과가 0인 실험을 2,000번, 매일 들여다보고 p < 0.05면 멈춘다면
rng = np.random.default_rng(7)
SIM, DAYS, NDAY, P0 = 2000, 28, int(len(r) / 2 / 28), float(pc)
a = rng.binomial(NDAY, P0, (SIM, DAYS)).cumsum(1); b = rng.binomial(NDAY, P0, (SIM, DAYS)).cumsum(1)
n = NDAY * np.arange(1, DAYS + 1)
pool = (a + b) / (2 * n)
zz = (a / n - b / n) / np.sqrt(pool * (1 - pool) * 2 / n)
pv = 2 * (1 - norm.cdf(np.abs(zz)))
print(f'\n== 4. A/A 모의실험 {SIM:,}번 (두 군 모두 전환율 {100 * P0:.1f}%, 하루 군당 {NDAY}명, 28일)')
print(f'   마지막 날 한 번만 본 경우 거짓 양성: {100 * (pv[:, -1] < 0.05).mean():.1f}%')
print(f'   매일 보고 한 번이라도 p < 0.05면 멈춘 경우: {100 * (pv < 0.05).any(1).mean():.1f}%')
print(f'   매주(7·14·21·28일) 본 경우: {100 * (pv[:, [6, 13, 20, 27]] < 0.05).any(1).mean():.1f}%')

# 5. CUPED: 실험 전 60일의 행동으로 결과의 흩어짐을 줄인다
pre = con.sql("""
select a.user_id, count(distinct cast(e.ts as date)) pre_days,
       count(*) filter (where e.event_name = 'purchase') pre_orders
from shop.exp_assign a left join shop.events e on e.user_id = a.user_id and e.ts >= '2026-07-03' and e.ts < '2026-09-01'
where a.experiment = 'checkout_v2' group by 1""").df()
vis = con.sql(f"""
select a.user_id, count(distinct cast(e.ts as date)) visit_days
from shop.exp_assign a join shop.events e on e.user_id = a.user_id and e.ts >= cast(a.assigned_at as date) and e.ts < '{END}'
where a.experiment = 'checkout_v2' group by 1""").df()
x = r.merge(pre, on='user_id').merge(vis, on='user_id')
print('\n== 5. CUPED (공변량: 실험 전 60일의 활동일 수와 주문 수)')
rows = []
for ycol, yname in [('conv', '구매 전환(0/1)'), ('orders', '주문 수'), ('revenue', '결제액'), ('visit_days', '방문일 수(참고)')]:
    y = x[ycol].astype(float).values
    X = x[['pre_days', 'pre_orders']].astype(float).values
    Xc = X - X.mean(0)
    theta = np.linalg.lstsq(Xc, y - y.mean(), rcond=None)[0]       # 두 군을 합쳐서 구한다
    yc = y - Xc @ theta
    t = (x.variant == 'treatment').values
    for label, v in [('원래', y), ('CUPED', yc)]:
        diff = v[t].mean() - v[~t].mean(); se = np.sqrt(v[t].var(ddof=1) / t.sum() + v[~t].var(ddof=1) / (~t).sum())
        rows.append((yname, label, diff, se, 2 * (1 - norm.cdf(abs(diff / se))), 100 * (1 - yc.var() / y.var()) if label == 'CUPED' else 0))
print(pd.DataFrame(rows, columns=['지표', '방법', '차이', '표준오차', 'p값', '분산 감소 %']).to_string(index=False, float_format=lambda v: f'{v:.4g}'))
print('   결과와 공변량의 상관계수(실험 전 활동일 수): ' + ', '.join(f"{c} {np.corrcoef(x[c], x.pre_days)[0, 1]:.2f}" for c in ['conv', 'orders', 'revenue', 'visit_days']))
print(f"   실험 전 기록이 있는 유저: {100 * (x.pre_days > 0).mean():.1f}% (나머지는 실험 기간에 가입한 신규 유저라 공변량이 0)")

# 6. 세그먼트 뒤지기: 효과가 없는 실험(home_banner)을 30개 세그먼트로 쪼개면
hb = con.sql("""
select a.user_id, a.variant, u.platform, u.age_band, u.gender,
       (exists (select 1 from shop.orders o where o.user_id = a.user_id and o.order_ts >= cast(a.assigned_at as date) and o.order_ts < '2026-10-19'))::int conv
from shop.exp_assign a join shop.users u using (user_id) where a.experiment = 'home_banner'""").df()
gg, zz, pp, l, h = ztest(hb)
print(f"\n== 6. home_banner (심어 둔 효과 0) 전체: 차이 {100 * (gg['sum'] / gg['count']).diff().iloc[-1] * -1:+.2f}%p, p = {pp:.3f}")
seg = []
for keys, df in hb.groupby(['platform', 'age_band', 'gender']):
    try:
        g2, z2, p2, l2, h2 = ztest(df)
        seg.append((*keys, len(df), 100 * (g2['sum'] / g2['count']).diff().iloc[-1] * -1, p2))
    except Exception:
        pass
seg = pd.DataFrame(seg, columns=['platform', 'age_band', 'gender', 'n', 'diff_pp', 'p']).sort_values('p')
print(f'   세그먼트 {len(seg)}개 중 p < 0.05: {(seg.p < 0.05).sum()}개,  본페로니 기준(p < {0.05 / len(seg):.4f}): {(seg.p < 0.05 / len(seg)).sum()}개')
print(seg.head(4).round({'diff_pp': 2, 'p': 4}).to_string(index=False))
python pa/pa06_analysis.py
== 0. 배정 로그 점검: 배정된 35,999명 중 12,973명(36%)은 배정 시각보다 앞선 같은 날 세션이 있다
   → 이 데이터의 assigned_at은 시각이 정확하지 않다. 아래 분석은 "배정된 날짜부터"로 자른다.
== 1. 주 지표: 유저 기준 구매 전환율 (배정 뒤 실험 기간 안에 주문한 유저 비율)
   대조군 17,996명 중 2,982명 = 16.57%
   처리군 18,003명 중 3,234명 = 17.96%
   차이 +1.39%p (상대 +8.4%), 95% 신뢰구간 [+0.61, +2.17]%p, z = 3.50, p = 0.0005

== 2. 바꾼 단계: 결제 시작 → 구매 (세션 기준)
  variant  checkout_sessions  purchases  step_rate
  control             5618.0     3429.0      61.04
treatment             5656.0     3714.0      65.66
   차이 +4.62%p (95% 신뢰구간 대략 [+2.84, +6.40]%p).  심어 둔 정답 +6.0%p

== 3. 날짜별 누적 p값 (매일 들여다봤다면)
   날짜     p값  차이 %p  누적 유저
09-01 0.2587   1.28   2639
09-03 0.3410   0.69   6934
09-05 0.2485   0.69  10681
09-07 0.0255   1.22  13908
09-10 0.0272   1.09  18148
09-14 0.0008   1.54  22985
09-21 0.0002   1.55  30048
09-28 0.0005   1.39  35999
   p < 0.05가 처음 나온 날: 09-07, 28일 중 p < 0.05인 날 22일, 그 뒤 다시 0.05를 넘은 날 0일
[차트 저장] out/img/pa06_peeking.png

== 4. A/A 모의실험 2,000번 (두 군 모두 전환율 16.6%, 하루 군당 642명, 28일)
   마지막 날 한 번만 본 경우 거짓 양성: 4.1%
   매일 보고 한 번이라도 p < 0.05면 멈춘 경우: 26.2%
   매주(7·14·21·28일) 본 경우: 11.5%

== 5. CUPED (공변량: 실험 전 60일의 활동일 수와 주문 수)
        지표    방법      차이     표준오차        p값  분산 감소 %
구매 전환(0/1)    원래 0.01393 0.003984 0.0004693        0
구매 전환(0/1) CUPED 0.01396 0.003969 0.0004375   0.7345
      주문 수    원래 0.01576 0.004955  0.001472        0
      주문 수 CUPED 0.01579 0.004933  0.001373    0.882
       결제액    원래    1043    352.1  0.003058        0
       결제액 CUPED    1044    351.1  0.002935    0.552
 방문일 수(참고)    원래 0.01317  0.01791    0.4623        0
 방문일 수(참고) CUPED 0.01328  0.01777    0.4549    1.555
   결과와 공변량의 상관계수(실험 전 활동일 수): conv 0.08, orders 0.09, revenue 0.07, visit_days 0.12
   실험 전 기록이 있는 유저: 70.3% (나머지는 실험 기간에 가입한 신규 유저라 공변량이 0)

== 6. home_banner (심어 둔 효과 0) 전체: 차이 -0.24%p, p = 0.575
   세그먼트 30개 중 p < 0.05: 4개,  본페로니 기준(p < 0.0017): 0개
platform age_band gender    n  diff_pp      p
     web     50대+      M  262    12.29 0.0033
 android      30대      F 2128    -3.68 0.0114
 android      40대      F 1216    -4.65 0.0190
     ios     50대+      M  260     8.79 0.0440

Step 0(실제로 막힌 곳). 배정 시각을 믿을 수 있나

처음에는 "배정 시각(assigned_at) 이후의 주문"으로 전환을 셌습니다. 그랬더니 대조군 전환율이 14.0%로 나와, PA05에서 같은 정의로 잰 실험 전 기준 전환율 17.3%보다 3%p나 낮았습니다. 대조군은 아무것도 안 바꾼 군이라 기준과 비슷해야 합니다. 원인을 찾아보니 배정된 35,999명 중 12,973명(36%)에게 배정 시각보다 앞선 같은 날 세션이 있었습니다. 이 가상 데이터의 assigned_at은 날짜만 맞고 시각은 그날 안의 임의 시각이라, 시각으로 자르면 배정 당일 주문의 일부가 빠집니다.

Step 2. 주 지표 읽기

Step 3. 바꾼 단계와 정답 비교

지표대조군처리군차이심어 둔 정답
결제시작→구매(세션 기준)61.04%65.66%+4.62%p (대략 [+2.84, +6.40])+6.0%p
유저 기준 구매 전환율16.57%17.96%+1.39%p [+0.61, +2.17](단계 효과가 희석된 값)

Step 4. 엿보기(peeking)

날짜별 누적 p값
checkout_v2에서 매일 그날까지의 데이터로 다시 계산한 p값(로그 눈금). 9월 7일에 처음 0.05 아래로 내려갑니다. 가상 데이터.

Step 5. CUPED: 실험 전 데이터로 흔들림 줄이기

CUPED는 실험 전 행동(공변량)으로 설명되는 부분을 결과에서 빼서 분산을 줄이는 방법입니다. 무작위 배정 덕분에 실험 전 행동은 두 군에서 평균이 같으므로, 빼도 차이의 추정은 치우치지 않고 흔들림만 줄어듭니다. 줄어드는 분산의 비율은 결과와 공변량의 상관계수의 제곱입니다.

Step 6. 세그먼트 뒤지기와 다중 비교

결과 보고서에 들어갈 것

1

점검: SRM 통과 여부, 대조군 값이 실험 전 기준과 비슷한지, 실험 기간과 표본 수

2

주 지표: 두 군의 값, 차이, 95% 신뢰구간. p값은 그 뒤에

3

보조·가드레일: 단계 전환율로 왜 움직였는지, 가드레일이 나빠지지 않았는지

4

결정: 출시 / 폐기 / 재실험 중 하나와 그 이유. 신뢰구간 아래쪽 끝 기준으로 본 기대 효과

5

한계: 못 본 것(장기 효과, 표본이 작았던 세그먼트)과 다음 실험 제안

AI에게 시킬 때

A/B 테스트 결과를 분석해 줘. 테이블은 exp_assign(user_id, variant, assigned_at), orders(user_id, order_ts, pay_amount), events(user_id, session_id, ts, event_name). 순서대로 해 줘. (1) SRM 검사(카이제곱, p<0.001이면 중단하고 플랫폼별 비율 출력) (2) 대조군 전환율이 실험 전 4주 기준 전환율과 비슷한지 확인 (3) 주 지표인 유저 기준 구매 전환율의 차이, 95% 신뢰구간, p값(statsmodels proportions_ztest, confint_proportions_2indep) (4) 보조 지표인 결제시작→구매 단계 전환율. 세그먼트별 분석은 내가 미리 정한 platform 하나만 하고, 여러 번 검정한 만큼 본페로니 보정을 적용해 줘. 결과는 p값보다 신뢰구간 중심으로, 출시 여부 판단에 쓸 수 있게 5줄로 요약해 줘.

이것만 기억하세요

결과는 신뢰구간으로 말합니다. 추정 +4.6%p의 구간 안에 정답 +6.0%p가 있었습니다. 매일 들여다보고 멈추면 거짓 양성이 5%에서 26%가 되고, 세그먼트 30개를 뒤지면 효과 없는 실험에서도 4개가 유의하게 나옵니다. 종료일과 볼 세그먼트는 실험 전에 정합니다.

다음
PA07. 실험을 못 할 때
이어보기 →