Skip to content

Commit 4e5e989

Browse files
Fix exponential_moving_average for window_size=1
The warmup branch used `i <= window_size`, so with window_size=1 the second price was averaged ((10+20)*0.5=15) instead of applying the documented smoothing factor alpha=2/(1+1)=1, which must return each input unchanged. Narrowing the warmup to `i < window_size` applies the exponential recurrence from the second value onward, and adds a doctest pinning the window_size=1 behavior.
1 parent 7f81fcd commit 4e5e989

1 file changed

Lines changed: 3 additions & 1 deletion

File tree

‎financial/exponential_moving_average.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ def exponential_moving_average(
1919
Yields exponential moving averages of the given stock prices.
2020
>>> tuple(exponential_moving_average(iter([2, 5, 3, 8.2, 6, 9, 10]), 3))
2121
(2, 3.5, 3.25, 5.725, 5.8625, 7.43125, 8.715625)
22+
>>> tuple(exponential_moving_average(iter([10.0, 20.0, 30.0]), 1))
23+
(10.0, 20.0, 30.0)
2224
2325
:param stock_prices: A stream of stock prices
2426
:param window_size: The number of stock prices that will trigger a new calculation
@@ -49,7 +51,7 @@ def exponential_moving_average(
4951
moving_average = 0.0
5052

5153
for i, stock_price in enumerate(stock_prices):
52-
if i <= window_size:
54+
if i < window_size:
5355
# Assigning simple moving average till the window_size for the first time
5456
# is reached
5557
moving_average = (moving_average + stock_price) * 0.5 if i else stock_price

0 commit comments

Comments
 (0)