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:
(
data: Sequence[float], window_size: int
)
| 11 | |
| 12 | |
| 13 | def simple_moving_average( |
| 14 | data: Sequence[float], window_size: int |
| 15 | ) -> list[float | None]: |
| 16 | """ |
| 17 | Calculate the simple moving average (SMA) for some given time series data. |
| 18 | |
| 19 | :param data: A list of numerical data points. |
| 20 | :param window_size: An integer representing the size of the SMA window. |
| 21 | :return: A list of SMA values with the same length as the input data. |
| 22 | |
| 23 | Examples: |
| 24 | >>> sma = simple_moving_average([10, 12, 15, 13, 14, 16, 18, 17, 19, 21], 3) |
| 25 | >>> [round(value, 2) if value is not None else None for value in sma] |
| 26 | [None, None, 12.33, 13.33, 14.0, 14.33, 16.0, 17.0, 18.0, 19.0] |
| 27 | >>> simple_moving_average([10, 12, 15], 5) |
| 28 | [None, None, None] |
| 29 | >>> simple_moving_average([10, 12, 15, 13, 14, 16, 18, 17, 19, 21], 0) |
| 30 | Traceback (most recent call last): |
| 31 | ... |
| 32 | ValueError: Window size must be a positive integer |
| 33 | """ |
| 34 | if window_size < 1: |
| 35 | raise ValueError("Window size must be a positive integer") |
| 36 | |
| 37 | sma: list[float | None] = [] |
| 38 | |
| 39 | for i in range(len(data)): |
| 40 | if i < window_size - 1: |
| 41 | sma.append(None) # SMA not available for early data points |
| 42 | else: |
| 43 | window = data[i - window_size + 1 : i + 1] |
| 44 | sma_value = sum(window) / window_size |
| 45 | sma.append(sma_value) |
| 46 | return sma |
| 47 | |
| 48 | |
| 49 | if __name__ == "__main__": |
no test coverage detected