the simple moving average sma is a statistical calculation used to analyze data points by creating a constantly updated average price over a specific time period in finance sma is often used in time series analysis to smooth out price data and identify trends reference https en wikipedia orgwikimovingaverage calculate the simple moving average sma for some given time series data param data a list of numerical data points param windowsize 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 simplemovingaverage10 12 15 13 14 16 18 17 19 21 3 roundvalue 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 simplemovingaverage10 12 15 5 none none none simplemovingaverage10 12 15 13 14 16 18 17 19 21 0 traceback most recent call last valueerror window size must be a positive integer example data replace with your own time series data specify the window size for the sma calculate the simple moving average print the sma values 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 sma not available for early data points example data replace with your own time series data specify the window size for the sma calculate the simple moving average print the sma values
from collections.abc import Sequence


def simple_moving_average(
    data: Sequence[float], window_size: int
) -> list[float | None]:
    
    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)  
        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()

    
    data = [10, 12, 15, 13, 14, 16, 18, 17, 19, 21]

    
    window_size = 3

    
    sma_values = simple_moving_average(data, window_size)

    
    print("Simple Moving Average (SMA) Values:")
    for i, value in enumerate(sma_values):
        if value is not None:
            print(f"Day {i + 1}: {value:.2f}")
        else:
            print(f"Day {i + 1}: Not enough data for SMA")