ANCOVA Covariate-Adjusted Treatment Effect
Role: Data Scientist
Category: Analytics & Experimentation
Difficulty: medium
Interview Round: Other
Implement `ancova_effect(df: pd.DataFrame) -> float`. The DataFrame `df` has columns `group` (`'control'` or `'treatment'`), `y` (the outcome) and `x` (a pre-experiment covariate). Fit an ANCOVA, that is, an OLS regression of `y` on a treatment indicator and `x`, and return the treatment coefficient.
The function must:
- Build an indicator `treat` that is 1 for `'treatment'` and 0 otherwise.
- Regress `y` on `treat` and `x`, with an intercept added by `statsmodels.api.add_constant`.
- Fit with `sm.OLS(y, X).fit()`, keeping the default non-robust covariance.
- Return only `results.params['treat']`, as a plain Python `float`.
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],
})
ancova_effect(df) # 2.0, up to floating-point rounding
# the unadjusted difference in group means is 3.5
```
```hint Name the column
Build the 0/1 indicator as a column called `treat` before you add the constant, so the fitted parameter can be looked up by name.
```
```hint Sanity check
Compare your result with the raw difference in group means. If they differ, look at how the average `x` differs between the two groups.
```
### Constraints & Assumptions
- `group` holds only the strings `'control'` and `'treatment'`, and both groups are present.
- `y` and `x` are numeric and have no missing values.
- `pandas` and `statsmodels` are available.
### What a Strong Answer Covers
- Building the treatment indicator from the group labels with the correct reference level.
- Adding the intercept and fitting OLS of `y` on `treat` and `x` with the default covariance.
- Returning the `treat` coefficient by name as a plain `float`.
- What the coefficient means compared with the raw difference in means.
- Why adjusting for a pre-experiment covariate reduces the variance of the estimate.
### Follow-up Questions
- Why does ANCOVA typically reduce the variance of the effect estimate compared with a raw difference in means?
- When would you switch to `cov_type='HC3'` robust standard errors, and what does that change in the output?
- How does this estimate relate to CUPED using the same covariate?
- What goes wrong if `x` is measured after the treatment starts?
Overview: Implement a Python function that fits an ANCOVA regression of an experiment outcome on a treatment indicator and a pre-experiment covariate, then returns the adjusted treatment coefficient. It tests regression adjustment with statsmodels, reading OLS output by name, and why covariate adjustment reduces variance in A/B tests.