Skip to content

trading.indicators.calculations.vwap

trading.indicators.calculations.vwap

VWAP

VWAP(k: float = 1.25)

Bases: Indicator[VWAPSnapshot | None]

VWAP with standard deviation bands.

Resets at the start of each new trading session. Returns None on the first bar of each session (no deviation yet).

Parameters:

Name Type Description Default
k float

Band-width multiplier in standard deviations.

1.25
Source code in src\contango\trading\indicators\calculations\vwap.py
48
49
50
51
52
53
54
55
56
57
58
59
def __init__(self, k: float = 1.25) -> None:
    """
    Args:
        k: Band-width multiplier in standard deviations.
    """
    self._k = k

    # Intraday accumulators — reset each session
    self._cumulative_tp_volume: float = 0.0
    self._cumulative_volume: float = 0.0
    self._cumulative_tp_sq_volume: float = 0.0
    self._bar_count: int = 0

update

update(high: USD, low: USD, close: USD, volume: float) -> VWAPSnapshot | None

Takes in a new bar and returns the current VWAP snapshot. Returns None on the first bar of the session (standard deviation undefined).

Parameters:

Name Type Description Default
high USD

Bar high price.

required
low USD

Bar low price.

required
close USD

Bar close price.

required
volume float

Bar volume.

required
Source code in src\contango\trading\indicators\calculations\vwap.py
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
def update(
    self,
    high: USD,
    low: USD,
    close: USD,
    volume: float
) -> VWAPSnapshot | None:
    """
    Takes in a new bar and returns the current VWAP snapshot.
    Returns None on the first bar of the session (standard deviation undefined).

    Args:
        high: Bar high price.
        low: Bar low price.
        close: Bar close price.
        volume: Bar volume.
    """
    typical_price = (high + low + close) / 3

    self._cumulative_tp_volume += typical_price * volume
    self._cumulative_volume += volume
    self._cumulative_tp_sq_volume += (typical_price ** 2) * volume
    self._bar_count += 1

    if self._cumulative_volume == 0:
        return None

    vwap = self._cumulative_tp_volume / self._cumulative_volume

    # Volume-weighted variance
    variance = (
        self._cumulative_tp_sq_volume / self._cumulative_volume
    ) - vwap ** 2

    # Variance can be slightly negative due to floating point
    std = max(variance, 0.0) ** 0.5

    if self._bar_count < 2:
        return None

    band = self._k * std

    return VWAPSnapshot(
        vwap=vwap,
        upper=vwap + band,
        lower=vwap - band,
    )

VWAPSnapshot

Bases: NamedTuple

A single snapshot of VWAP with bands.

Attributes:

Name Type Description
vwap float

The current volume-weighted average price.

upper float

VWAP + k standard deviations.

lower float

VWAP - k standard deviations.