Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(quantlib): include the shared prediction-error covariance in a CAR's standard error (#1466)

Haozhe Wu5e8b5caad106
diff --git a/agent/src/quantlib/eventstudy.py b/agent/src/quantlib/eventstudy.py
index 3485179a2..518c1c57f 100644
--- a/agent/src/quantlib/eventstudy.py
+++ b/agent/src/quantlib/eventstudy.py
@@ -32,9 +32,9 @@ WHY THREE TEST STATISTICS
dominate the sample.
``patell_z``
- Standardises each daily abnormal return by the standard error the estimation
- window implies for it, including the prediction-error term that accounts for
- the market return on that day sitting far from its estimation-window mean.
+ Standardises each event's CAR by the standard error the estimation window
+ implies for it, including the prediction error of the estimated parameters
+ and the covariance that error induces across the window's days.
Corrects for cross-sectional differences in volatility, but still assumes
event-window variance equals estimation-window variance.
@@ -135,7 +135,8 @@ class EventOutcome:
day, ordered from the window's first day to its last.
car: Cumulative abnormal return over the whole event window.
car_std_error: Standard error of ``car`` implied by the estimation
- window, including the Patell prediction-error term.
+ window, including the prediction error of the estimated parameters
+ and its covariance across the window's days.
standardised_car: ``car / car_std_error``. This is the quantity BMP
takes a cross-sectional variance of.
fit: The normal-return model behind these numbers.
@@ -278,31 +279,40 @@ def estimate_market_model(
)
-def _patell_scale(fit: MarketModelFit, market_window: np.ndarray) -> np.ndarray:
- """Per-day standard error of an abnormal return, prediction error included.
+def _car_std_error(fit: MarketModelFit, market_window: np.ndarray) -> float:
+ """Standard error of a CAR, prediction error and its covariance included.
- A forecast made far from the estimation window's average market return is
- less certain than one made near it, and Patell's correction is exactly that
- term. Dropping it understates the standard error and overstates significance.
+ Every day in the window is forecast with the same estimated parameters, so
+ one estimation error moves all of them the same way: the daily abnormal
+ returns are positively correlated, and a CAR's variance is not the sum of
+ the daily ones. With ``L`` window days, ``n`` estimation observations and
+ ``d_t`` the window market return minus its estimation mean, the variance
+ in units of the residual variance is ``L + L**2 / n + (sum d_t)**2 / S_mm``
+ for the market model and ``L + L**2 / n`` for the mean-adjusted model.
+ Summing daily variances gives ``L + L / n + sum(d_t**2) / S_mm``, which
+ left z-statistics about 8% too wide at ``n=120`` and 36% at ``n=30`` under
+ the null (#1466). The market-adjusted model estimates nothing, so its
+ variance is ``L``.
Args:
fit: The fitted normal-return model.
market_window: Market returns over the event window.
Returns:
- Array of standard errors, one per event-window day.
+ The standard error of the event's CAR.
"""
+ days = market_window.size
if fit.model == "market" and fit.market_sum_squares > 0.0:
- prediction_error = (
- 1.0
- + 1.0 / fit.observations
- + (market_window - fit.market_mean) ** 2 / fit.market_sum_squares
+ units = (
+ days
+ + days**2 / fit.observations
+ + float(np.sum(market_window - fit.market_mean)) ** 2 / fit.market_sum_squares
)
elif fit.model == "mean_adjusted":
- prediction_error = np.full(market_window.shape, 1.0 + 1.0 / fit.observations)
+ units = days + days**2 / fit.observations
else: # market_adjusted has no estimated parameter to project
- prediction_error = np.ones(market_window.shape)
- return fit.residual_std * np.sqrt(prediction_error)
+ units = float(days)
+ return float(fit.residual_std * np.sqrt(units))
def event_study(
@@ -367,7 +377,6 @@ def event_study(
market_aligned = market_returns.reindex(index)
relative_days = list(range(start, end + 1))
- window_len = len(relative_days)
outcomes: list[EventOutcome] = []
dropped: list[tuple[str, object, str]] = []
@@ -417,8 +426,7 @@ def event_study(
abnormal = asset_window - expected
car = float(abnormal.sum())
- daily_se = _patell_scale(fit, market_window)
- car_se = float(np.sqrt(np.sum(daily_se**2)))
+ car_se = _car_std_error(fit, market_window)
standardised = car / car_se if car_se > 0 else float("nan")
asset_est_arr = asset_estimation.to_numpy(dtype=float)
diff --git a/agent/tests/quantlib/test_eventstudy.py b/agent/tests/quantlib/test_eventstudy.py
index 9de48c314..4185728b9 100644
--- a/agent/tests/quantlib/test_eventstudy.py
+++ b/agent/tests/quantlib/test_eventstudy.py
@@ -113,6 +113,86 @@ def test_injected_event_day_jump_is_recovered_in_caar():
assert result.t_p_value < 0.01
+def _clm_car_std_error(asset_est, market_est, market_window, model):
+ """CAR standard error from the full prediction-error covariance matrix.
+
+ Written as matrix algebra (Campbell, Lo & MacKinlay eq. 4.4.14), not the
+ closed-form sums the module uses, so it checks the formula independently:
+ ``Var(CAR) = s^2 * 1'(I + X*(X'X)^-1 X*')1`` with ``X`` the estimation
+ design matrix and ``X*`` the event-window one.
+ """
+ n, days = len(asset_est), len(market_window)
+ if model == "market":
+ design = np.column_stack([np.ones(n), market_est])
+ window = np.column_stack([np.ones(days), market_window])
+ dof = n - 2
+ elif model == "mean_adjusted":
+ design = np.ones((n, 1))
+ window = np.ones((days, 1))
+ dof = n - 1
+ else:
+ resid = asset_est - market_est
+ return float(np.sqrt(np.sum(resid**2) / n) * np.sqrt(days))
+ coef, *_ = np.linalg.lstsq(design, asset_est, rcond=None)
+ s2 = float(np.sum((asset_est - design @ coef) ** 2) / dof)
+ covariance = s2 * (np.eye(days) + window @ np.linalg.inv(design.T @ design) @ window.T)
+ return float(np.sqrt(np.ones(days) @ covariance @ np.ones(days)))
+
+
[email protected]("model", ["market", "mean_adjusted", "market_adjusted"])
+def test_car_std_error_includes_the_covariance_of_the_shared_prediction_error(model):
+ """#1466: the window's days share one estimation error, so their variances do not just add."""
+ returns, market = _panel(n_symbols=3, seed=31)
+ event_row = 300
+ result = event_study(
+ returns,
+ market,
+ [("S01", returns.index[event_row])],
+ event_window=(-5, 5),
+ estimation_window=40,
+ model=model,
+ )
+ outcome = result.events[0]
+ est_end = event_row - 5 - DEFAULT_ESTIMATION_GAP
+ expected = _clm_car_std_error(
+ returns["S01"].iloc[est_end - 40 : est_end].to_numpy(),
+ market.iloc[est_end - 40 : est_end].to_numpy(),
+ market.iloc[event_row - 5 : event_row + 6].to_numpy(),
+ model,
+ )
+ assert outcome.car_std_error == pytest.approx(expected, rel=1e-10)
+
+
[email protected]("model", ["market", "mean_adjusted"])
+def test_standardised_cars_are_unit_variance_under_the_null(model):
+ """With a short estimation window the missing covariance inflated Var(z) to ~1.4.
+
+ What remains is the t-distribution correction for an estimated residual
+ variance, (dof) / (dof - 2), about 1.08 at 30 observations.
+ """
+ rng = np.random.default_rng(1466)
+ n_rows, n_events, window = 120, 4000, 30
+ index = pd.date_range("2020-01-01", periods=n_rows, freq="B")
+ market = pd.Series(rng.normal(0.0, 0.012, n_rows), index=index)
+ returns = pd.DataFrame(
+ rng.normal(0.0, 0.01, (n_rows, n_events)),
+ index=index,
+ columns=[f"S{i}" for i in range(n_events)],
+ )
+ rows = rng.integers(window + DEFAULT_ESTIMATION_GAP + 5, n_rows - 6, n_events)
+ result = event_study(
+ returns,
+ market,
+ [(f"S{i}", index[row]) for i, row in enumerate(rows)],
+ event_window=(-5, 5),
+ estimation_window=window,
+ model=model,
+ )
+ z = np.array([o.standardised_car for o in result.events])
+ dof = window - (2 if model == "market" else 1)
+ assert np.var(z) == pytest.approx(dof / (dof - 2), abs=0.07)
+
+
def test_car_is_exactly_the_sum_of_the_abnormal_returns():
returns, market = _panel(seed=303)
events = [(s, returns.index[250]) for s in returns.columns[:5]]