-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalgorithms.py
More file actions
39 lines (32 loc) · 1.18 KB
/
algorithms.py
File metadata and controls
39 lines (32 loc) · 1.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
from __future__ import annotations
import abc
from datetime import timedelta
class SmoothingAlgorithm(abc.ABC):
@abc.abstractmethod
def __init__(self, **kwargs):
raise NotImplementedError
@abc.abstractmethod
def update(self, new_value: float, elapsed: timedelta) -> float:
"""Updates the algorithm with a new value and returns the smoothed
value.
"""
pass
class ExponentialMovingAverage(SmoothingAlgorithm):
"""
The Exponential Moving Average (EMA) is an exponentially weighted moving
average that reduces the lag that's typically associated with a simple
moving average. It's more responsive to recent changes in data.
"""
def __init__(self, alpha: float=0.5) -> None:
self.alpha = alpha
self.value = 0
class DoubleExponentialMovingAverage(SmoothingAlgorithm):
"""
The Double Exponential Moving Average (DEMA) is essentially an EMA of an
EMA, which reduces the lag that's typically associated with a simple EMA.
It's more responsive to recent changes in data.
"""
def __init__(self, alpha: float=0.5) -> None:
self.alpha = alpha
self.ema1 = 0
self.ema2 = 0