Skip to content

trading.indicators.calculations.ema

trading.indicators.calculations.ema

EMA

EMA(period: days)

Bases: Indicator[float]

Exponential Moving Average.

Uses alpha = 2 / (period + 1) and seeds the first value directly from the first price to avoid bias (towards 0).

Initializes Ema.

Parameters:

Name Type Description Default
period days

Lookback period to derive the smoothing factor. Larger values -> slower to react to price changes.

required
Source code in src\contango\trading\indicators\calculations\ema.py
33
34
35
36
37
38
39
40
41
42
def __init__(self, period: days) -> None:
    """
    Initializes `Ema`.

    Args:
        period: Lookback period to derive the smoothing factor. Larger values -> slower to react to price changes.
    """
    self._alpha = 2 / (period + 1)
    self._value: float | None = None
    self._period = period

update

update(price: USD) -> float

Takes in a new price and returns the current EMA.

Parameters:

Name Type Description Default
price USD

The price for the current bar.

required

Returns:

Type Description
float

The current EMA. The first call returns price unsmoothed.

Source code in src\contango\trading\indicators\calculations\ema.py
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
def update(self, price: USD) -> float:
    """
    Takes in a new price and returns the current EMA.

    Args:
        price: The price for the current bar.

    Returns:
        The current EMA. The first call returns `price` unsmoothed.
    """
    if self._value is None:
        self._value = price
    else:
        self._value = price * self._alpha + self._value * (1 - self._alpha)
    return self._value