TheAlgorithms/Python · error · ValueError

Window size must be a positive integer

Error message

Window size must be a positive integer

What it means

Raised by simple_moving_average() in financial/simple_moving_average.py when window_size < 1. The function slices data[i - window_size + 1 : i + 1] and divides by window_size; a window of 0 or less would divide by zero or slice nonsense, so it fails fast. Note the guard only checks < 1 — it does not verify the value is an integer, so 2.5 passes validation and produces subtly wrong output.

Source

Thrown at financial/simple_moving_average.py:35

    Calculate the simple moving average (SMA) for some given time series data.

    :param data: A list of numerical data points.
    :param window_size: An integer representing the size of the SMA window.
    :return: A list of SMA values with the same length as the input data.

    Examples:
    >>> sma = simple_moving_average([10, 12, 15, 13, 14, 16, 18, 17, 19, 21], 3)
    >>> [round(value, 2) if value is not None else None for value in sma]
    [None, None, 12.33, 13.33, 14.0, 14.33, 16.0, 17.0, 18.0, 19.0]
    >>> simple_moving_average([10, 12, 15], 5)
    [None, None, None]
    >>> simple_moving_average([10, 12, 15, 13, 14, 16, 18, 17, 19, 21], 0)
    Traceback (most recent call last):
    ...
    ValueError: Window size must be a positive integer
    """
    if window_size < 1:
        raise ValueError("Window size must be a positive integer")

    sma: list[float | None] = []

    for i in range(len(data)):
        if i < window_size - 1:
            sma.append(None)  # SMA not available for early data points
        else:
            window = data[i - window_size + 1 : i + 1]
            sma_value = sum(window) / window_size
            sma.append(sma_value)
    return sma


if __name__ == "__main__":
    import doctest

    doctest.testmod()

View on GitHub (pinned to f5988cc097)

Solutions

  1. Pass a window_size >= 1; for tiny datasets use max(1, min(window, len(data))).
  2. Compute windows defensively: window = max(1, int(window_size)).
  3. If the window exceeds len(data), expect [None]*len(data) output — that is valid behavior, not an error.

Example fix

# before
window = int(len(data) * 0.05)  # 0 when len(data) < 20
sma = simple_moving_average(data, window)

# after
window = max(1, int(len(data) * 0.05))
sma = simple_moving_average(data, window)
Defensive patterns

Strategy: validation

Validate before calling

window = int(window_size)
if window < 1:
    raise ValueError(f'window must be >= 1, got {window_size}')
simple_moving_average(data, window)

Type guard

def is_valid_window(w: object) -> bool:
    return isinstance(w, int) and not isinstance(w, bool) and w >= 1

Try / catch

try:
    sma = simple_moving_average(data, w)
except ValueError as exc:
    if 'Window size' in str(exc):
        sma = [None] * len(data)
    else:
        raise

Prevention

When it happens

Trigger: Calling simple_moving_average(data, 0), with a negative window, or with a computed window that underflowed. A float like 2.5 will NOT trigger this error but yields incorrect averages — a silent hazard next to it.

Common situations: window_size derived from a percentage of data length that rounds to 0 on tiny datasets, config defaults of 0 meaning 'off', or non-integer windows passed from UI spinboxes.

Related errors


AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14). Data as JSON: /api/errors/3d21b78ace33b934. Report an issue: GitHub.