{"record":{"id":"9314f0b8465e1cf1","repo":"HKUDS/Vibe-Trading","slug":"find-hedge-ratio-needs-y-and-x-sharing-one-index","errorCode":null,"errorMessage":"find_hedge_ratio needs y and x sharing one index","messagePattern":"find_hedge_ratio needs y and x sharing one index","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"agent/src/quantlib/timeseries.py","lineNumber":359,"sourceCode":"\n    Returns:\n        Dict with keys ``hedge_ratio`` (β, float), ``intercept`` (α, float),\n        ``spread_mean`` (float), ``spread_std`` (float, sample ddof=1) and\n        ``half_life`` (float, in observation periods).\n\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","sourceCodeStart":341,"sourceCodeEnd":377,"githubUrl":"https://github.com/HKUDS/Vibe-Trading/blob/80ffdda44c5c4db0dd84d70e051cca591cea67df/agent/src/quantlib/timeseries.py#L341-L377","documentation":"find_hedge_ratio aligns y and x positionally via pd.concat on their indices; if the two inputs do not share the same index, concat produces a longer union frame and the length check fails. This guard prevents silently regressing misaligned observations.","triggerScenarios":"Passing two pd.Series with different DatetimeIndexes (different dates or ranges), overlapping-but-not-identical indices, or mixing a Series with a plain list/array whose default RangeIndex differs from the other's index.","commonSituations":"Loading two price series from different sources with different trading calendars, reindexing one series but not the other, or passing y as a Series and x as a numpy array.","solutions":["Align both inputs on a common index before calling: y, x = y.align(x, join='inner')","Reset both to positional: pass .to_numpy() for both y and x","Verify with (y.index == x.index).all() before the call"],"exampleFix":"# before\nratio = find_hedge_ratio(prices_a, prices_b)  # different calendars\n# after\ncommon = prices_a.index.intersection(prices_b.index)\nratio = find_hedge_ratio(prices_a.loc[common], prices_b.loc[common])","handlingStrategy":"validation","validationCode":"if isinstance(y, pd.Series) and isinstance(x, pd.Series):\n    assert y.index.equals(x.index), 'y and x must share one index'\nelse:\n    y = pd.Series(y, dtype=float)\n    x = pd.Series(x, dtype=float)","typeGuard":"def share_index(y, x) -> bool:\n    if not (isinstance(y, pd.Series) and isinstance(x, pd.Series)):\n        return True  # positional\n    return y.index.equals(x.index)","tryCatchPattern":"try:\n    find_hedge_ratio(y, x)\nexcept ValueError as e:\n    if 'sharing one index' in str(e):\n        y, x = y.align(x, join='inner')\n        return find_hedge_ratio(y, x)\n    raise","preventionTips":["Align series with .align(join='inner') before any bivariate call","Convert both inputs to numpy arrays if you mean positional pairing","Assert index equality in data-prep tests"],"tags":["python","pandas","index-alignment","cointegration"],"backgroundTag":"pandas-index-misalignment","analyzedSha":"80ffdda44c5c4db0dd84d70e051cca591cea67df","analyzedAt":"2026-08-28T12:46:38.989Z","schemaVersion":2},"datasetVersion":"2026-08-28T16:17:29.566Z"}