Skip to content

Commit 77e43f4

Browse files
committed
fix: handle EMA window size of one
1 parent ef2ecc4 commit 77e43f4

1 file changed

Lines changed: 8 additions & 2 deletions

File tree

‎financial/exponential_moving_average.py‎

Lines changed: 8 additions & 2 deletions
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, 20, 30]), 1))
23+
(10, 20, 30)
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,10 +51,14 @@ 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 == 0:
55+
moving_average = stock_price
56+
elif window_size == 1:
57+
moving_average = stock_price
58+
elif i <= window_size:
5359
# Assigning simple moving average till the window_size for the first time
5460
# is reached
55-
moving_average = (moving_average + stock_price) * 0.5 if i else stock_price
61+
moving_average = (moving_average + stock_price) * 0.5
5662
else:
5763
# Calculating exponential moving average based on current timestamp data
5864
# point and previous exponential average value

0 commit comments

Comments
 (0)