HKUDS/Vibe-Trading · error · ValueError

ts_cov window must be >= 2, got {n}

Error message

ts_cov window must be >= 2, got {n}

What it means

ts_cov requires a window of at least 2 because sample covariance needs at least two observations; n < 2 raises. Like ts_corr it inner-joins columns and uses min_periods=n, so warmup rows are NaN.

Source

Thrown at agent/src/factors/base.py:169

    on columns; columns missing from either side become NaN.
    """
    if n < 2:
        raise ValueError(f"ts_corr window must be >= 2, got {n}")
    x = _as_float(x)
    y = _as_float(y)
    cols = x.columns.union(y.columns)
    xa = x.reindex(columns=cols)
    ya = y.reindex(columns=cols)
    corr = xa.rolling(window=n, min_periods=n).corr(ya)
    # corr above can produce +/- inf when one series is constant in some
    # pandas versions; force to NaN.
    return corr.replace([np.inf, -np.inf], np.nan)


def ts_cov(x: pd.DataFrame, y: pd.DataFrame, n: int) -> pd.DataFrame:
    """Rolling sample covariance per column, min_periods=n."""
    if n < 2:
        raise ValueError(f"ts_cov window must be >= 2, got {n}")
    x = _as_float(x)
    y = _as_float(y)
    cols = x.columns.union(y.columns)
    xa = x.reindex(columns=cols)
    ya = y.reindex(columns=cols)
    cov = xa.rolling(window=n, min_periods=n).cov(ya)
    return cov.replace([np.inf, -np.inf], np.nan)


def ts_mean(df: pd.DataFrame, n: int) -> pd.DataFrame:
    """Rolling mean per column, warmup → NaN."""
    if n < 1:
        raise ValueError(f"ts_mean window must be >= 1, got {n}")
    return df.rolling(window=n, min_periods=n).mean()


def ts_std(df: pd.DataFrame, n: int) -> pd.DataFrame:
    """Rolling sample std (ddof=1) per column, warmup → NaN."""

View on GitHub (pinned to 80ffdda44c)

Solutions

  1. Pass n >= 2
  2. Enforce a minimum window of 2 in any auto-scaling logic and handle too-short inputs explicitly
  3. Unit-test factor configs against boundary windows (1, 2, len(df))

Example fix

# before
cov = ts_cov(x, y, n=1)

# after
cov = ts_cov(x, y, n=20)
Defensive patterns

Strategy: validation

Validate before calling

if not isinstance(n, int) or n < 2:
    raise ValueError(f'invalid ts_cov window: {n!r}')
cov = ts_cov(x, y, n)

Type guard

def is_valid_ts_cov_window(n) -> bool:
    return isinstance(n, int) and n >= 2

Prevention

When it happens

Trigger: ts_cov(x, y, 1), ts_cov(x, y, 0), or negative n; also a dynamically computed window collapsing to 1 on short panels. Called from compute() and tests.

Common situations: Same as ts_corr: auto-scaled windows on short series, config errors, and copy-pasted window values from min-1 operators.

Related errors


AI-assisted analysis of HKUDS/Vibe-Trading@80ffdda44c (2026-08-28). Data as JSON: /api/errors/e2f943f80629a74c. Report an issue: GitHub.