Skip to content

trading.indicators.calculations.rsi

trading.indicators.calculations.rsi

RSI

RSI(period: days = 14)

Bases: Indicator[float | None]

Relative Strength Index (RSI).

Uses Wilder's Moving Average to smooth average gains and losses over the given period. Returns None until both averages are seeded.

Initializes RSI.

Parameters:

Name Type Description Default
period days

Lookback period for the Wilder averages.

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

    Args:
        period: Lookback period for the Wilder averages.
    """
    self._period = period
    self._avg_gain = WilderAverage(period)
    self._avg_loss = WilderAverage(period)
    self._prev_price: float | None = None

update

update(price: USD) -> float | None

Takes in a new price and returns the current RSI.

Parameters:

Name Type Description Default
price USD

The price for the current bar.

required

Returns:

Type Description
float | None

RSI in the range [0, 100], or None if the period has not been reached.

Source code in src\contango\trading\indicators\calculations\rsi.py
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
def update(self, price: USD) -> float | None:
    """
    Takes in a new price and returns the current RSI.

    Args:
        price: The price for the current bar.

    Returns:
        RSI in the range [0, 100], or None if the period has not been reached.
    """
    if self._prev_price is None:
        self._prev_price = price
        return None

    delta = price - self._prev_price
    self._prev_price = price

    gain = max(delta, 0.0)
    loss = max(-delta, 0.0)

    avg_gain = self._avg_gain.update(gain)
    avg_loss = self._avg_loss.update(loss)

    if avg_gain is None or avg_loss is None:
        return None

    if avg_loss == 0.0:
        return 100.0

    rs = avg_gain / avg_loss
    return 100 - (100 / (1 + rs))