Answer the question
In order to leave comments, you need to log in
Why is there an error in the code?
Hello. In search of speeding up the calculation of the exponential moving average, I decided to write a recursive algorithm for this. I love recursion and try to use it more often.
Here is the actual code:
def get_ema(array, N: int, prev_ema: float = None):
alpha = 2 / (1 + N)
if len(array) == 1:
ema = []
ema.append(array[0] * alpha + (1 - alpha) * prev_ema)
return ema
if not prev_ema:
for_sma = array[:N]
sma = sum(for_sma) / len(for_sma)
return get_ema(array[N:], N, prev_ema=sma).append(sma)
else:
new_ema = array[0] * alpha + (1 - alpha) * prev_ema
return get_ema(array[1:], N, prev_ema=new_ema).append(new_ema)
Answer the question
In order to leave comments, you need to log in
append()
returns None. So any return
(except return ema
) will return None. Well, at the next iteration, the code will crumble.
You can quickly check by replacing the first if block
tmp = get_ema(array[N:], N, prev_ema=sma)
print(type(tmp))
return tmp.append(sma)
tmp = get_ema(array[1:], N, prev_ema=new_ema)
print(type(tmp))
return tmp.append(new_ema)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question