{"record":{"id":"817b5769d37affdc","repo":"HKUDS/Vibe-Trading","slug":"find-hedge-ratio-needs-at-least-3-aligned-observat","errorCode":null,"errorMessage":"find_hedge_ratio needs at least 3 aligned observations, got {len(frame)}","messagePattern":"find_hedge_ratio needs at least 3 aligned observations, got (.+?)","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"agent/src/quantlib/timeseries.py","lineNumber":362,"sourceCode":"        ``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\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``.","sourceCodeStart":344,"sourceCodeEnd":380,"githubUrl":"https://github.com/HKUDS/Vibe-Trading/blob/80ffdda44c5c4db0dd84d70e051cca591cea67df/agent/src/quantlib/timeseries.py#L344-L380","documentation":"After aligning y and x and dropping NaN rows, fewer than 3 complete observations remain — not enough to fit the two-parameter OLS hedge regression. The library enforces a minimum sample size rather than emitting an unstable beta.","triggerScenarios":"Passing very short series (<3 points), series whose overlap after index alignment is under 3 rows, or series with many NaNs that leave <3 complete pairs after dropna.","commonSituations":"Mismatched date ranges where only 1-2 dates overlap, series with heavy missing data, or unit tests built from tiny hand-made arrays.","solutions":["Check the aligned, NaN-dropped overlap length before calling","Extend the shared date range of the two inputs","Drop or impute NaNs upstream so more complete pairs survive"],"exampleFix":"# before\nratio = find_hedge_ratio(y_short, x_short)\n# after\nframe = pd.concat({'y': y, 'x': x}, axis=1).dropna()\nassert len(frame) >= 3, f\"only {len(frame)} aligned observations\"\nratio = find_hedge_ratio(y, x)","handlingStrategy":"validation","validationCode":"frame = pd.concat({'y': pd.Series(y, dtype=float), 'x': pd.Series(x, dtype=float)}, axis=1).dropna()\nif len(frame) < 3:\n    raise ValueError(f'insufficient overlap: {len(frame)} rows')","typeGuard":"def has_enough_overlap(y, x, minimum: int = 3) -> bool:\n    frame = pd.concat({'y': pd.Series(y, dtype=float), 'x': pd.Series(x, dtype=float)}, axis=1)\n    return len(frame.dropna()) >= minimum","tryCatchPattern":"try:\n    find_hedge_ratio(y, x)\nexcept ValueError as e:\n    if 'at least 3 aligned' in str(e):\n        # widen date range or fetch more data\n        raise\n    raise","preventionTips":["Check aligned row count before regressing","Use at least 60+ overlapping observations for stable hedge ratios","Drop NaNs upstream and assert the resulting length"],"tags":["python","pandas","insufficient-data","regression"],"backgroundTag":"insufficient-samples-for-regression","analyzedSha":"80ffdda44c5c4db0dd84d70e051cca591cea67df","analyzedAt":"2026-08-28T12:46:38.989Z","schemaVersion":2},"datasetVersion":"2026-08-28T16:17:29.566Z"}