TheAlgorithms/Python · error · ValueError

window_size must be > 0

Error message

window_size must be > 0

What it means

Raised by exponential_moving_average() in financial/exponential_moving_average.py when window_size <= 0. The window size determines the smoothing factor alpha = 2/(1 + window_size); a non-positive window makes alpha undefined or >= 2, which destroys the exponential smoothing recurrence, so it is rejected before any price is processed.

Source

Thrown at financial/exponential_moving_average.py:43

                        of the exponential average (window_size > 0)
    :return: Yields a sequence of exponential moving averages

    Formula:

    st = alpha * xt + (1 - alpha) * st_prev

    Where,
    st : Exponential moving average at timestamp t
    xt : stock price in from the stock prices at timestamp t
    st_prev : Exponential moving average at timestamp t-1
    alpha : 2/(1 + window_size) - smoothing factor

    Exponential moving average (EMA) is a rule of thumb technique for
    smoothing time series data using an exponential window function.
    """

    if window_size <= 0:
        raise ValueError("window_size must be > 0")

    # Calculating smoothing factor
    alpha = 2 / (1 + window_size)

    # Exponential average at timestamp t
    moving_average = 0.0

    for i, stock_price in enumerate(stock_prices):
        if i <= window_size:
            # Assigning simple moving average till the window_size for the first time
            # is reached
            moving_average = (moving_average + stock_price) * 0.5 if i else stock_price
        else:
            # Calculating exponential moving average based on current timestamp data
            # point and previous exponential average value
            moving_average = (alpha * stock_price) + ((1 - alpha) * moving_average)
        yield moving_average

View on GitHub (pinned to f5988cc097)

Solutions

  1. Pass a positive integer window, e.g. exponential_moving_average(prices, 12).
  2. Default the window to a sane value (12 or 26 are common for EMA) instead of 0 in your own CLI/config.
  3. Validate `window_size >= 1` at the option-parsing layer so users get an argparse-style error, not a traceback.

Example fix

# before
ema = exponential_moving_average(stock_prices, 0)  # ValueError

# after
ema = exponential_moving_average(stock_prices, 12)
Defensive patterns

Strategy: validation

Validate before calling

if not isinstance(window_size, int) or window_size < 1:
    raise InputError("window_size must be a positive integer (e.g. 12)")

Type guard

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

Try / catch

try:
    ema = exponential_moving_average(stock_prices, window_size)
except ValueError as exc:
    ema = exponential_moving_average(stock_prices, 12)  # deliberate fallback default
    logger.warning("%s; fell back to window 12", exc)

Prevention

When it happens

Trigger: exponential_moving_average([], 0), a window_size of -1, or a window computed from a parameter that defaulted to 0; passing a window larger than the data length is allowed (the loop simply never reaches steady state), only <= 0 raises.

Common situations: CLI flags where the window option was not provided and defaults to 0; dividing user input (e.g. span in days) by a scale factor that yields 0; confusing argument order and passing a price list length as the window.

Related errors


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