Skip to content

Commit 32e2d50

Browse files
fix: handle EMA window size of one (#15492)
* fix: handle EMA window size of one * fix: satisfy ruff check * Update exponential_moving_average.py --------- Co-authored-by: Christian Clauss <cclauss@me.com>
1 parent f465ad7 commit 32e2d50

1 file changed

Lines changed: 7 additions & 3 deletions

File tree

‎financial/exponential_moving_average.py‎

Lines changed: 7 additions & 3 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.1, 20.02, 30.003]), 1))
23+
(10.1, 20.02, 30.003)
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,12 @@ 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 or window_size == 1:
55+
moving_average = stock_price
56+
elif i <= window_size:
5357
# Assigning simple moving average till the window_size for the first time
5458
# is reached
55-
moving_average = (moving_average + stock_price) * 0.5 if i else stock_price
59+
moving_average = (moving_average + stock_price) * 0.5
5660
else:
5761
# Calculating exponential moving average based on current timestamp data
5862
# point and previous exponential average value
@@ -67,7 +71,7 @@ def exponential_moving_average(
6771

6872
stock_prices = [2.0, 5, 3, 8.2, 6, 9, 10]
6973
window_size = 3
70-
result = tuple(exponential_moving_average(iter(stock_prices), window_size))
74+
result = tuple(exponential_moving_average(stock_prices, window_size))
7175
print(f"{stock_prices = }")
7276
print(f"{window_size = }")
7377
print(f"{result = }")

0 commit comments

Comments
 (0)