Skip to content

trading.indicators.calculations.sma

trading.indicators.calculations.sma

SMA

SMA(period: days)

Bases: Indicator[float | None]

Simple Moving Average.

Maintains a window of prices and tracks their sum incrementally. Returns None until the window is full.

Initializes SMA.

Parameters:

Name Type Description Default
period days

The number of days (period) for the rolling window.

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

    Args:
        period: The number of days (period) for the rolling window.
    """
    self._period = period
    self._window: deque[float] = deque(maxlen=period)
    self._sum = 0.0

update

update(price: USD) -> float | None

Takes in a new price and returns the current SMA, or None if the window is not yet full.

Parameters:

Name Type Description Default
price USD

The price for the current bar.

required

Returns:

Type Description
float | None

The SMA over the current window, or None if period amount of days have not passed.

Source code in src\contango\trading\indicators\calculations\sma.py
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
def update(self, price: USD) -> float | None:
    """
    Takes in a new price and returns the current SMA, or None if the window is not yet full.

    Args:
        price: The price for the current bar.

    Returns:
        The SMA over the current window, or `None` if `period` amount of days have not passed.
    """
    if len(self._window) == self._period:
        self._sum -= self._window[0]

    self._window.append(price)
    self._sum += price

    if len(self._window) < self._period:
        return None

    return self._sum / self._period