{"record":{"id":"3d21b78ace33b934","repo":"TheAlgorithms/Python","slug":"window-size-must-be-a-positive-integer","errorCode":null,"errorMessage":"Window size must be a positive integer","messagePattern":"Window size must be a positive integer","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"financial/simple_moving_average.py","lineNumber":35,"sourceCode":"    Calculate the simple moving average (SMA) for some given time series data.\n\n    :param data: A list of numerical data points.\n    :param window_size: An integer representing the size of the SMA window.\n    :return: A list of SMA values with the same length as the input data.\n\n    Examples:\n    >>> sma = simple_moving_average([10, 12, 15, 13, 14, 16, 18, 17, 19, 21], 3)\n    >>> [round(value, 2) if value is not None else None for value in sma]\n    [None, None, 12.33, 13.33, 14.0, 14.33, 16.0, 17.0, 18.0, 19.0]\n    >>> simple_moving_average([10, 12, 15], 5)\n    [None, None, None]\n    >>> simple_moving_average([10, 12, 15, 13, 14, 16, 18, 17, 19, 21], 0)\n    Traceback (most recent call last):\n    ...\n    ValueError: Window size must be a positive integer\n    \"\"\"\n    if window_size < 1:\n        raise ValueError(\"Window size must be a positive integer\")\n\n    sma: list[float | None] = []\n\n    for i in range(len(data)):\n        if i < window_size - 1:\n            sma.append(None)  # SMA not available for early data points\n        else:\n            window = data[i - window_size + 1 : i + 1]\n            sma_value = sum(window) / window_size\n            sma.append(sma_value)\n    return sma\n\n\nif __name__ == \"__main__\":\n    import doctest\n\n    doctest.testmod()\n","sourceCodeStart":17,"sourceCodeEnd":53,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/financial/simple_moving_average.py#L17-L53","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Pass a window_size >= 1; for tiny datasets use max(1, min(window, len(data))).","Compute windows defensively: window = max(1, int(window_size)).","If the window exceeds len(data), expect [None]*len(data) output — that is valid behavior, not an error."],"exampleFix":"# before\nwindow = int(len(data) * 0.05)  # 0 when len(data) < 20\nsma = simple_moving_average(data, window)\n\n# after\nwindow = max(1, int(len(data) * 0.05))\nsma = simple_moving_average(data, window)","handlingStrategy":"validation","validationCode":"window = int(window_size)\nif window < 1:\n    raise ValueError(f'window must be >= 1, got {window_size}')\nsimple_moving_average(data, window)","typeGuard":"def is_valid_window(w: object) -> bool:\n    return isinstance(w, int) and not isinstance(w, bool) and w >= 1","tryCatchPattern":"try:\n    sma = simple_moving_average(data, w)\nexcept ValueError as exc:\n    if 'Window size' in str(exc):\n        sma = [None] * len(data)\n    else:\n        raise","preventionTips":["Coerce window sizes to int once at the call site — the library does not.","Watch the adjacent silent bug: fractional windows pass the check but corrupt the math."],"tags":["finance","input-validation","valueerror"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}