OGT Owl Group Trading by Dr. Ken Long
Home About Learn The Loop Code Courses Essays Store Partners FAQ
Python · Indicator Code

VWAP - Volume-Weighted Average Price in Python

The running average price weighted by traded volume, accumulated from the session start.

Concept: what VWAP means →

Verified. Python and JavaScript implementations agree to 0.00e+00 on a 60-bar reference OHLCV series (Python vs JavaScript, comparable positions).

Python

def vwap(high, low, close, volume):
    """Session VWAP.

    Running cumulative (typical_price * volume) / cumulative volume,
    accumulated from the first bar. Typical price = (H + L + C) / 3.

    Faithful port of edge-canvas calcVWAP and the inner loop of
    edge-transform CoreIndicators.calc_vwap. Bars with missing H/L/C or
    zero/falsy volume do not advance the accumulator; they carry forward
    the prior VWAP (or None until any volume has accumulated).

    Args:
        high, low, close, volume: equal-length sequences of floats.
    Returns:
        list of VWAP values (None before any volume accumulates).
    """
    n = len(close)
    out = [None] * n
    cum_tpv = 0.0   # cumulative typical-price * volume
    cum_vol = 0.0   # cumulative volume
    for i in range(n):
        h, l, c, v = high[i], low[i], close[i], volume[i]
        # Skip incomplete bars: carry forward the running VWAP.
        if h is None or l is None or c is None or not v:
            out[i] = cum_tpv / cum_vol if cum_vol > 0 else None
            continue
        tp = (h + l + c) / 3.0          # typical price
        cum_tpv += tp * v
        cum_vol += v
        out[i] = cum_tpv / cum_vol if cum_vol > 0 else None
    return out