From cbd04e911f42cc8f3a538aa4235439f89131a47c Mon Sep 17 00:00:00 2001 From: Aashish <145881415+aashish254@users.noreply.github.com> Date: Mon, 28 Sep 2026 02:43:41 +0545 Subject: [PATCH] fix financial/exponential_moving_average: seed uses window_size values, not window_size+1 The initialization branch guarded with `if i <= window_size`, so it ran the SMA-seed branch for window_size+1 iterations before switching to the EMA recurrence. With window_size=1 (alpha=1) the documented recurrence should echo each input unchanged, but the seed branch averaged the first two prices into 15.0 instead of yielding 20.0, so exponential_moving_average(iter([10,20,30]), 1) returned [10, 15, 30]. Change the guard to `i < window_size`. The existing window_size=3 doctest is unchanged because alpha=0.5 makes the seed and EMA branches arithmetically identical at that specific index; add a window_size=1 doctest as the witness. Fixes #15449 --- financial/exponential_moving_average.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/financial/exponential_moving_average.py b/financial/exponential_moving_average.py index b56eb2712415..6c8b5d676c0c 100644 --- a/financial/exponential_moving_average.py +++ b/financial/exponential_moving_average.py @@ -19,6 +19,8 @@ def exponential_moving_average( Yields exponential moving averages of the given stock prices. >>> tuple(exponential_moving_average(iter([2, 5, 3, 8.2, 6, 9, 10]), 3)) (2, 3.5, 3.25, 5.725, 5.8625, 7.43125, 8.715625) + >>> tuple(exponential_moving_average(iter([10.0, 20.0, 30.0]), 1)) + (10.0, 20.0, 30.0) :param stock_prices: A stream of stock prices :param window_size: The number of stock prices that will trigger a new calculation @@ -49,7 +51,7 @@ def exponential_moving_average( moving_average = 0.0 for i, stock_price in enumerate(stock_prices): - if i <= window_size: + 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