Compute White's HC0 robust standard errors for OLS by hand with NumPy
Role: Data Scientist
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `manual_hc0_se(X, y)`. The function fits an ordinary least squares regression of `y` on `Xc = sm.add_constant(X)` and returns White's HC0 standard errors, computed with `numpy` from the sandwich
$$
V = (X_c^\top X_c)^{-1} \left( X_c^\top \operatorname{diag}(e^2) \, X_c \right) (X_c^\top X_c)^{-1}
$$
where `e` is the vector of OLS residuals. The standard errors are `np.sqrt(np.diag(V))`.
Requirements:
- Apply no small-sample correction: no HC1 degrees-of-freedom factor and no HC2 or HC3 leverage adjustment.
- Return a 1-D `ndarray` of shape `(p+1,)` ordered `[se_intercept, se_b1, ..., se_bp]`.
- Match statsmodels' `results.HC0_se` to tolerance on the grader's fixed heteroskedastic dataset, where `X` has shape `(15, 1)`.
A small case you can check by hand:
```python
import numpy as np
X = np.array([[0.0], [1.0], [2.0], [3.0]])
y = np.array([0.0, 2.0, 1.0, 3.0])
manual_hc0_se(X, y) # approximately array([0.4306, 0.18])
```
```hint Shapes and column order
Check where `sm.add_constant` puts the intercept column, and keep `y` one-dimensional so the residuals stay a vector of length n.
```
```hint The meat term
Multiplying by `diag(e**2)` only rescales the rows of `Xc`. Look for a way to do that rescaling without building an n-by-n matrix.
```
### Constraints & Assumptions
- `X` has shape `(n, p)` and `y` has length `n`. The grader uses `n = 15` and `p = 1`.
- `numpy` and `statsmodels` (imported as `sm`) are available. You may use `sm.add_constant`, but the standard errors must come from your own `numpy` computation, not from a fitted statsmodels results object.
- `Xc` has full column rank, so `Xc.T @ Xc` is invertible.
### What a Strong Answer Covers
- Building the design matrix with the intercept first and fitting OLS so the residuals are correct.
- Forming the meat from the raw squared residuals with no degrees-of-freedom or leverage factor.
- Computing the meat efficiently, with the time and memory cost of each step.
- Returning a 1-D array in the required order and checking it against `results.HC0_se`.
- Handling input shapes (1-D `X`, column-vector `y`) and saying what fails when `Xc` is rank deficient.
### Follow-up Questions
- How would you extend this to HC1, HC2, or HC3?
- Why can the sandwich estimator be unreliable in small samples like $n = 15$?
Overview: Implement White's HC0 heteroskedasticity-robust standard errors for an OLS regression in NumPy, building the sandwich covariance from the residuals yourself. Tests your grasp of the bread and meat matrices, how HC0 differs from HC1 to HC3, and careful array handling that matches statsmodels.