|
| 1 | +""" |
| 2 | +The Simple Moving Average (SMA) is a statistical calculation used to analyze data points |
| 3 | +by creating a constantly updated average price over a specific time period. |
| 4 | +In finance, SMA is often used in time series analysis to smooth out price data |
| 5 | +and identify trends. |
| 6 | +
|
| 7 | +Reference: https://en.wikipedia.org/wiki/Moving_average |
| 8 | +""" |
| 9 | +from collections.abc import Sequence |
| 10 | + |
| 11 | + |
| 12 | +def simple_moving_average( |
| 13 | + data: Sequence[float], window_size: int |
| 14 | +) -> list[float | None]: |
| 15 | + """ |
| 16 | + Calculate the simple moving average (SMA) for some given time series data. |
| 17 | +
|
| 18 | + :param data: A list of numerical data points. |
| 19 | + :param window_size: An integer representing the size of the SMA window. |
| 20 | + :return: A list of SMA values with the same length as the input data. |
| 21 | +
|
| 22 | + Examples: |
| 23 | + >>> sma = simple_moving_average([10, 12, 15, 13, 14, 16, 18, 17, 19, 21], 3) |
| 24 | + >>> [round(value, 2) if value is not None else None for value in sma] |
| 25 | + [None, None, 12.33, 13.33, 14.0, 14.33, 16.0, 17.0, 18.0, 19.0] |
| 26 | + >>> simple_moving_average([10, 12, 15], 5) |
| 27 | + [None, None, None] |
| 28 | + >>> simple_moving_average([10, 12, 15, 13, 14, 16, 18, 17, 19, 21], 0) |
| 29 | + Traceback (most recent call last): |
| 30 | + ... |
| 31 | + ValueError: Window size must be a positive integer |
| 32 | + """ |
| 33 | + if window_size < 1: |
| 34 | + raise ValueError("Window size must be a positive integer") |
| 35 | + |
| 36 | + sma: list[float | None] = [] |
| 37 | + |
| 38 | + for i in range(len(data)): |
| 39 | + if i < window_size - 1: |
| 40 | + sma.append(None) # SMA not available for early data points |
| 41 | + else: |
| 42 | + window = data[i - window_size + 1 : i + 1] |
| 43 | + sma_value = sum(window) / window_size |
| 44 | + sma.append(sma_value) |
| 45 | + return sma |
| 46 | + |
| 47 | + |
| 48 | +if __name__ == "__main__": |
| 49 | + import doctest |
| 50 | + |
| 51 | + doctest.testmod() |
| 52 | + |
| 53 | + # Example data (replace with your own time series data) |
| 54 | + data = [10, 12, 15, 13, 14, 16, 18, 17, 19, 21] |
| 55 | + |
| 56 | + # Specify the window size for the SMA |
| 57 | + window_size = 3 |
| 58 | + |
| 59 | + # Calculate the Simple Moving Average |
| 60 | + sma_values = simple_moving_average(data, window_size) |
| 61 | + |
| 62 | + # Print the SMA values |
| 63 | + print("Simple Moving Average (SMA) Values:") |
| 64 | + for i, value in enumerate(sma_values): |
| 65 | + if value is not None: |
| 66 | + print(f"Day {i + 1}: {value:.2f}") |
| 67 | + else: |
| 68 | + print(f"Day {i + 1}: Not enough data for SMA") |
0 commit comments