HKUDS/Vibe-Trading · error · ValueError

var must be 1-D or scalar, got shape {var_values.shape}

Error message

var must be 1-D or scalar, got shape {var_values.shape}

What it means

_align accepts var as either a scalar (broadcast across all returns) or a 1-D array. A var with ndim > 1 — a DataFrame, a (n,1) column, or a (n,k) matrix of quantiles — raises ValueError with its shape, because there is no unambiguous mapping to the single returns vector.

Source

Thrown at agent/src/quantlib/var_backtest.py:282

            raise ValueError(
                "returns and var must cover exactly the same labels; "
                f"{len(only_ret)} label(s) only in returns and "
                f"{len(only_var)} only in var. Align them explicitly -- a "
                "partial join silently compares each day against another day's "
                "forecast."
            )

    ret_values = np.asarray(returns, dtype=float)
    if ret_values.ndim > 1:
        raise ValueError(f"returns must be 1-D, got shape {ret_values.shape}")
    ret_values = ret_values.ravel()

    var_values = np.asarray(var, dtype=float)
    if var_values.ndim == 0:
        var_values = np.full(ret_values.shape, float(var_values))
    else:
        if var_values.ndim > 1:
            raise ValueError(f"var must be 1-D or scalar, got shape {var_values.shape}")
        var_values = var_values.ravel()

    if ret_values.size != var_values.size:
        raise ValueError(
            f"returns and var must be the same length, got {ret_values.size} "
            f"and {var_values.size}"
        )
    if ret_values.size == 0:
        raise ValueError("returns is empty")

    keep = np.isfinite(ret_values) & np.isfinite(var_values)
    dropped = int((~keep).sum())
    if not keep.any():
        raise ValueError("no observation has a finite return and a finite var")

    index = ret_index if ret_index is not None else var_index
    kept_index = index[keep] if index is not None else None
    return ret_values[keep], var_values[keep], kept_index, dropped

View on GitHub (pinned to 80ffdda44c)

Solutions

  1. Extract one level: var_df['var_99'] or var_arr[:, 0] / var_arr.ravel().
  2. Call var_backtest once per confidence level rather than passing all columns.
  3. Convert model output with np.asarray(var).ravel() before passing.

Example fix

# before
var_backtest(rets, var_matrix)  # shape (500, 2)
# after
for col in var_matrix.columns:
    var_backtest(rets, var_matrix[col])
Defensive patterns

Strategy: type-guard

Validate before calling

import numpy as np
v = np.asarray(var)
assert v.ndim == 0 or v.ndim == 1

Type guard

def var_is_scalar_or_1d(var) -> bool:
    import numpy as np
    n = np.asarray(var).ndim
    return n <= 1

Try / catch

except ValueError as e:
    if 'var must be 1-D or scalar' in str(e): var = np.asarray(var)[:, 0]

Prevention

When it happens

Trigger: Passing VaR as a DataFrame column pair (e.g. 1% and 5% quantiles side by side), a numpy (n,1) array from a GARCH forecast's .reshape(-1,1), or selecting with double brackets var_df[['var_99']].

Common situations: GARCH/EWMA libraries whose .forecast() returns 2-D arrays; VaR reported at multiple confidence levels in one frame; batch model outputs stacked column-wise.

Related errors


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