{"record":{"id":"46a10614631dd071","repo":"HKUDS/Vibe-Trading","slug":"find-hedge-ratio-needs-an-x-that-varies-this-one","errorCode":null,"errorMessage":"find_hedge_ratio needs an x that varies; this one is constant","messagePattern":"find_hedge_ratio needs an x that varies; this one is constant","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"agent/src/quantlib/timeseries.py","lineNumber":364,"sourceCode":"\n    Raises:\n        ImportError: If ``statsmodels`` is not installed.\n        ValueError: If the series differ in length, carry different indices,\n            fewer than 3 aligned non-NaN observations remain, or ``x`` is\n            constant. A flat hedging leg is refused rather than fitted:\n            ``sm.add_constant`` leaves an already-constant column alone, so the\n            design would silently collapse to one column and the β lookup would\n            be a bare ``IndexError``.\n    \"\"\"\n    sm = _require(\"statsmodels.api\", \"statsmodels\", \"find_hedge_ratio\")\n    frame = pd.concat({\"y\": pd.Series(y, dtype=float), \"x\": pd.Series(x, dtype=float)}, axis=1)\n    if len(frame) != len(pd.Series(y)) or len(frame) != len(pd.Series(x)):\n        raise ValueError(\"find_hedge_ratio needs y and x sharing one index\")\n    frame = frame.dropna()\n    if len(frame) < 3:\n        raise ValueError(f\"find_hedge_ratio needs at least 3 aligned observations, got {len(frame)}\")\n    if frame[\"x\"].std(ddof=0) == 0:\n        raise ValueError(\"find_hedge_ratio needs an x that varies; this one is constant\")\n\n    params = _ols_params(frame[\"y\"], sm.add_constant(frame[[\"x\"]]))\n    intercept, beta = float(params[0]), float(params[1])\n    spread = frame[\"y\"] - beta * frame[\"x\"]\n\n    return {\n        \"hedge_ratio\": beta,\n        \"intercept\": intercept,\n        \"spread_mean\": float(spread.mean()),\n        \"spread_std\": float(spread.std()),\n        \"half_life\": compute_half_life(spread),\n    }\n\n\ndef granger_test(data: pd.DataFrame, x_col: str, y_col: str, max_lag: int = 5) -> dict:\n    \"\"\"Test whether ``x`` Granger-causes ``y``.\n\n    Granger causality is predictive, not structural: it asks only whether past","sourceCodeStart":346,"sourceCodeEnd":382,"githubUrl":"https://github.com/HKUDS/Vibe-Trading/blob/80ffdda44c5c4db0dd84d70e051cca591cea67df/agent/src/quantlib/timeseries.py#L346-L382","documentation":"find_hedge_ratio requires the regressor x to have nonzero standard deviation; a constant x makes the OLS design matrix rank-deficient (the constant column and x collapse), so the beta lookup would fail with a bare IndexError. The library raises a descriptive error instead.","triggerScenarios":"Passing an x series of identical values, or one that becomes constant after alignment and dropna (e.g. only 3 points all equal).","commonSituations":"Placeholder/fill-forward data, a pegged currency or pinned price feed, or accidentally passing a repeated scalar as x.","solutions":["Verify x.std(ddof=0) > 0 before the call","Check data ingestion for stuck/flat feeds","If x is genuinely constant, hedging is undefined — handle as a special case rather than regressing"],"exampleFix":"# before\nratio = find_hedge_ratio(y, pd.Series([100.0] * 50))\n# after\nif x.std(ddof=0) == 0:\n    raise ValueError(\"x is constant; hedge ratio undefined\")\nratio = find_hedge_ratio(y, x)","handlingStrategy":"validation","validationCode":"x = pd.Series(x, dtype=float)\nif x.std(ddof=0) == 0:\n    raise ValueError('x is constant; hedge ratio undefined')","typeGuard":"def regressor_varies(x) -> bool:\n    return pd.Series(x, dtype=float).std(ddof=0) > 0","tryCatchPattern":"try:\n    find_hedge_ratio(y, x)\nexcept ValueError as e:\n    if 'x that varies' in str(e):\n        # constant x: hedging undefined, handle specially\n        return None\n    raise","preventionTips":["Check x.std(ddof=0) > 0 before bivariate fits","Monitor feeds for stuck values","Treat flat regressors as a data-quality incident, not a stats problem"],"tags":["python","pandas","constant-regressor","rank-deficient"],"backgroundTag":"degenerate-input-validation","analyzedSha":"80ffdda44c5c4db0dd84d70e051cca591cea67df","analyzedAt":"2026-08-28T12:46:38.989Z","schemaVersion":2},"datasetVersion":"2026-08-28T16:17:29.566Z"}