ANCOVA vs Unadjusted Standard Error Reduction
Role: Data Scientist
Category: Analytics & Experimentation
Difficulty: medium
Interview Round: Other
Implement `ancova_vs_unadjusted(df: pd.DataFrame) -> dict`. The DataFrame `df` has columns `group` (`'control'` or `'treatment'`), `y` (the outcome) and `x` (a covariate). Fit an unadjusted OLS model and an ANCOVA OLS model, and return the standard error of the treatment coefficient from each model and their ratio.
The function must:
- Set `treat` to 1 where `group == 'treatment'` and 0 otherwise.
- Fit Model U, `y ~ const + treat`, and Model A, `y ~ const + treat + x`. Both use `sm.add_constant` and OLS with the default non-robust covariance.
- Set `se_unadjusted` to `bse['treat']` from Model U and `se_adjusted` to `bse['treat']` from Model A.
- Set `se_ratio = se_adjusted / se_unadjusted`.
- Return a dict with exactly the keys `se_unadjusted`, `se_adjusted` and `se_ratio`.
Example:
```python
import pandas as pd
df = pd.DataFrame({
"group": ["control"] * 4 + ["treatment"] * 4,
"x": [1, 2, 3, 4, 2, 3, 4, 5],
"y": [2, 4, 5, 7, 6, 7, 9, 10],
})
out = ancova_vs_unadjusted(df)
# {
# 'se_unadjusted': 1.38443..., # square root of 23/12
# 'se_adjusted': 0.24494..., # square root of 0.06
# 'se_ratio': 0.17693...,
# }
```
```hint Same term in both fits
Build each design matrix from named columns on the same index as `y`, so `bse['treat']` refers to the treatment term in both models.
```
```hint Predicting the ratio
Write the SE of the `treat` coefficient as an estimated residual variance divided by a sum of squares, then check which pieces of that formula change when `x` enters the model.
```
### Constraints & Assumptions
- `group` holds only the strings `'control'` and `'treatment'`, and both groups are present.
- `y` and `x` are numeric with no missing values, and there are more than 3 rows.
- `pandas` and `statsmodels` are available.
### What a Strong Answer Covers
- Building the indicator and two design matrices that share the index of `y`.
- Reading `bse['treat']` from each model with the default covariance and computing the ratio in the stated direction.
- Why the ratio falls below 1 when `x` predicts `y` within groups.
- What can pull the ratio back toward or above 1.
### Follow-up Questions
- Why does adjusting for `x` shrink the treatment-effect SE, and by roughly how much?
- When could ANCOVA bias the treatment effect instead of only tightening it?
- How would you turn the SE ratio into a statement about sample size?
- Would you trust the comparison if the residual variance differs a lot between arms?
Overview: Implement a Python function that fits an unadjusted and a covariate-adjusted OLS model to experiment data and compares the standard errors of the treatment coefficient. It tests statsmodels regression output, how much a pre-experiment covariate can tighten an A/B test estimate, and what offsets that gain.