VWAP Formula: Calculate It From Minute Bars in Python
· OkamiStocks Team · 14 min read
VWAP, the volume-weighted average price, is the average price a stock traded at over a period, where every trade counts in proportion to its size. The VWAP formula is one line: add up price times volume for every trade in the window, then divide by the total volume. The work is in everything around that line: which trades belong in the window, when the window starts, what time zone decides that, and what you do when you have bars instead of trades.
This guide gives the formula, a five-bar worked table, the typical-price shortcut charting tools use and why it differs, and two Python versions built on the OkamiStocks API: an exact session VWAP from 1-minute historical bars, and a running VWAP from the latest minute bar that works on every plan.
What VWAP is
Take every trade in a window. Multiply each trade's price by its number of shares, add those products up, and divide by the total number of shares. The result is the price per share paid across all of those trades put together. A trade of 10,000 shares moves it a hundred times more than a trade of 100 shares, which is the point: a plain average of prices treats a single odd lot the same as a block.
VWAP started as a benchmark for measuring trading costs rather than as a chart line. Berkowitz, Logue and Noser proposed the day's volume-weighted average price as the yardstick for how well an institutional order was executed in a 1988 paper in The Journal of Finance (The Total Cost of Transactions on the NYSE, Journal of Finance 43(1), 97-112). That origin fits the convention that still holds: VWAP is anchored to a trading session and starts over each day.
The VWAP formula
With trades, where p_i is the price of trade i and q_i its share count:
VWAP = sum(p_i * q_i) / sum(q_i)
The numerator is dollar volume (dollars that changed hands), the denominator is share volume. VWAP is dollars per share.
Most of us never see individual trades; we see bars. A one-minute bar is a summary of every trade in that minute, and a good bar carries its own volume-weighted average price, computed from the trades inside it. If bar j reports its VWAP as vwap_j and its volume as v_j, then vwap_j * v_j is that minute's dollar volume, and the session formula becomes:
VWAP = sum(vwap_j * v_j) / sum(v_j)
This is exact, not an approximation, because a sum of dollar volumes is the same whether you add the trades one at a time or one minute at a time. The only loss is rounding: if each bar's VWAP is rounded to the cent before you see it, each bar's dollar volume is off by at most half a cent per share, so the session VWAP you compute is within half a cent of the unrounded answer.
The typical-price shortcut
Charting tools usually don't have a per-bar VWAP and use a stand-in. TradingView's indicator documentation, for example, states the calculation as the typical price (High + Low + Close) / 3 for each bar, then VWAP = Cumulative(Typical Price x Volume) / Cumulative(Volume) (TradingView, Volume Weighted Average Price). The same page lists the anchor options that decide when the sum resets, starting with Session.
That version is an estimate. The typical price is a guess at where the minute's volume traded, and it is a different guess on every bar. The two numbers are usually close on a liquid stock with one-minute bars and drift apart on wider bars or thin trading. If your VWAP doesn't match a chart's to the cent, check which formula the chart uses before you suspect your data.
A five-bar worked example
Five consecutive one-minute bars of a hypothetical stock, each with its own VWAP and volume. The numbers are made up to keep the arithmetic readable.
| Bar | Bar VWAP | Volume | Dollar volume | Cumulative $ | Cumulative shares | Running VWAP |
|---|---|---|---|---|---|---|
| 1 | 100.00 | 1,000 | 100,000 | 100,000 | 1,000 | 100.00 |
| 2 | 100.20 | 3,000 | 300,600 | 400,600 | 4,000 | 100.15 |
| 3 | 100.10 | 2,000 | 200,200 | 600,800 | 6,000 | 100.13 |
| 4 | 99.90 | 4,000 | 399,600 | 1,000,400 | 10,000 | 100.04 |
| 5 | 100.30 | 500 | 50,150 | 1,050,550 | 10,500 | 100.05 |
The five-bar VWAP is 1,050,550 / 10,500 = 100.0524, or 100.05 to the cent. The plain average of the five bar prices is 100.10. The gap comes from bar 4: 4,000 shares at 99.90 pull the weighted number down, and 500 shares at 100.30 in bar 5 barely move it. The running column is the same formula applied after each bar, which is what a live VWAP line is: two running totals and a division, never a recomputation of the whole day.
Session anchoring in New York time
A session VWAP is defined by its window, so pin the window down before you write code.
The session. The NYSE core trading session runs 9:30 a.m. to 4:00 p.m. ET, with an opening auction at 9:30 and a closing auction at 4:00; trading also happens before and after it, and the late session on NYSE Arca, NYSE American and NYSE's other equity markets runs to 8:00 p.m. ET (NYSE, Hours and Calendars). The usual session VWAP covers 9:30 to 4:00. Pre-market and after-hours trades are thin and can sit far from the day's prices, so include them deliberately or not at all, and never by accident because your data source happened to deliver those bars.
Half days. The same NYSE page lists 1:00 p.m. early closes (in 2026: July 3, November 27 and December 24). A window hardcoded to 4:00 p.m. is wrong on each of them. The API's trading days endpoint tells you which days are half days.
Time zone. Bar timestamps in the OkamiStocks API are UTC in RFC 3339 format and mark the start of the bar (timestamps and data behavior). 9:30 a.m. New York is 13:30 UTC in summer and 14:30 UTC in winter, so a fixed UTC cutoff breaks twice a year. Convert each timestamp to New York time and compare clock times there. Python's standard library does this with zoneinfo, which supports IANA keys such as America/New_York and falls back to the tzdata package where the system has no time zone database, notably on Windows (Python, zoneinfo). pandas handles the same conversion with tz_convert.
The 4:00 p.m. bar. Because a bar's timestamp is its start, the bar stamped 16:00 covers 4:00 to 4:01 p.m., the minute in which the closing auction usually prints, and it can also hold the first after-hours trades of that minute. Keeping it or dropping it is a choice; the code below keeps it, and says so in a constant you can change.
The same "which day, in whose clock" question decides a 52-week window, and our 52 week high guide walks through it for daily bars.
Exact session VWAP from 1-minute historical bars
On the Supreme plan, POST /api/v1/quote/historical returns bars over a date range with timeframe set to 1Min, 5Min, 15Min, 1Hour or 1Day. Each bar carries open_price, high_price, low_price, close_price, volume, volume_weighted and a UTC timestamp, with prices rounded to 2 decimal places. Intraday timeframes cap the range: at most 7 days per request for 1Min (historical bars). A single request with start and end set to the session date is enough: 9:30 a.m. to 4:01 p.m. New York falls inside the same calendar date in UTC too, and the date filter in the code below keeps only that session either way.
The request takes your API key as token in the body, with ticker, start, end, adjustment and timeframe. In cURL, as the documentation shows requests:
export OKAMI_API_TOKEN='YOUR_API_TOKEN'
curl https://okamistocks.io/api/v1/quote/historical \
-d token="$OKAMI_API_TOKEN" \
-d ticker=SPY \
-d start=2026-11-17 \
-d end=2026-11-17 \
-d adjustment=raw \
-d timeframe=1Min
And the full computation in Python with pandas:
import os
from datetime import date, time
import pandas as pd
import requests
NY = "America/New_York"
SESSION_DAY = date(2026, 11, 17)
SESSION_OPEN = time(9, 30)
SESSION_CLOSE = time(16, 0) # keep the bar that starts at 16:00 (closing auction minute)
response = requests.post(
"https://okamistocks.io/api/v1/quote/historical",
headers={"Accept": "application/json"},
json={
"token": os.environ["OKAMI_API_TOKEN"],
"ticker": "SPY",
"start": SESSION_DAY.isoformat(),
"end": SESSION_DAY.isoformat(),
"adjustment": "raw",
"timeframe": "1Min",
},
timeout=30,
)
response.raise_for_status()
bars = pd.DataFrame(response.json()["data"]["bars"])
bars["start"] = pd.to_datetime(bars["timestamp"], utc=True).dt.tz_convert(NY)
bars = bars.sort_values("start").drop_duplicates("start", keep=False)
clock = bars["start"].dt.time
session = bars[
(bars["start"].dt.date == SESSION_DAY)
& (clock >= SESSION_OPEN)
& (clock <= SESSION_CLOSE)
& (bars["volume"] > 0)
].copy()
session["dollar_volume"] = session["volume_weighted"] * session["volume"]
session["running_vwap"] = session["dollar_volume"].cumsum() / session["volume"].cumsum()
session_vwap = session["dollar_volume"].sum() / session["volume"].sum()
print("bars in session", len(session))
print("session VWAP", round(session_vwap, 4))
print(session[["start", "volume_weighted", "volume", "running_vwap"]].tail())
What each step is for:
adjustmentisraw. A session VWAP gets compared with the prices that printed that day, so the bars should be the prices as traded.split,dividendandallexist for series that cross a corporate action; the documentation asks you to send the value explicitly rather than rely on a default, and the cURL sample does the same.- The timestamp is converted before the clock is read.
tz_convert(NY)turns2026-11-17T14:30:00Zinto 09:30 New York, and the same code works in July when the open is 13:30 UTC. - The date filter and the clock filter are separate. The date keeps the session on the day you asked for; the clock keeps 9:30 through the 16:00 bar. Bars delivered outside that window, whatever their reason for being there, never reach the sum.
- Zero-volume bars are dropped. They add nothing to either total, and if a bar ever arrives with a null VWAP, it becomes
NaNin pandas, andNaNtimes zero isNaN, not zero. pandas'cumsumskipsNaNby default and would hide the gap (pandas, Series.cumsum); dropping the rows first keeps the running column honest. - Duplicates are removed entirely (
keep=False), not reduced to one copy. Two bars with the same start are a sign of an upstream problem, and a doubled minute of volume is a wrong VWAP. cumsumgives the running series for free.dollar_volume.cumsum() / volume.cumsum()is the running VWAP after each bar, the right-hand column of the worked table.
Session VWAP is session_vwap, unrounded; round it to display. The result is within half a cent of the VWAP those bars give before rounding, as explained above. A VWAP published elsewhere can still differ, because it may count a different set of trades or a different window, so compare definitions before comparing numbers.
The same bars come back as a file with "format": "csv" in the request body, one row per bar in the same columns, if you'd rather load them into a spreadsheet or a notebook later (CSV output).
A running VWAP from the latest minute bar
POST /api/v1/quote/minute returns one latest one-minute bar for a ticker: minute_open_price, minute_high_price, minute_low_price, minute_close_price, minute_volume, minute_volume_weighted_price and a UTC quote_timestamp. It is available on every plan, including Free for the tickers on the Free list (SPY is one of them), and it has no range or interval parameter; it's a snapshot, not a series (latest minute bar). Poll it once a minute during the session and you get the stream of bars the formula needs.
import os
import time
import requests
URL = "https://okamistocks.io/api/v1/quote/minute"
TOKEN = os.environ["OKAMI_API_TOKEN"]
dollar_volume = 0.0
shares = 0
seen = set()
while True: # start at 9:30 a.m. New York time, stop at the close
response = requests.post(
URL,
headers={"Accept": "application/json"},
json={"token": TOKEN, "ticker": "SPY"},
timeout=30,
)
if response.status_code == 200:
bar = response.json()["data"]
stamp = bar["quote_timestamp"]
if stamp not in seen and bar["minute_volume"] > 0:
seen.add(stamp)
dollar_volume += bar["minute_volume_weighted_price"] * bar["minute_volume"]
shares += bar["minute_volume"]
print(stamp, "running VWAP", round(dollar_volume / shares, 4))
else:
print("HTTP", response.status_code, response.json())
time.sleep(60)
Three things make this loop correct rather than roughly right:
- It keys on
quote_timestamp. Two polls that land inside the same minute return the same bar with the same timestamp. Without theseenset, that minute's volume counts twice and the VWAP is wrong for the rest of the day. - It keeps two running totals, not a list of bars. The formula needs only
sum(vwap * volume)andsum(volume). Memory stays flat and each update is one multiply, one add, one divide. - It treats errors as a skipped minute, not a crash. Errors are JSON on every endpoint. The first request for a quiet ticker can return a temporary
422or a503while the feed warms up; a429means the minute's allowance is used up and carries aRetry-Afterheader (errors and recovery). On the next loop the bar is still there to collect.
Its limit is the one you'd expect: a poll that fails, or a minute with a bar you never saw, is a minute missing from the sum, so this version is an approximation whose accuracy depends on how reliably you poll. For the exact number, or for any day in the past, use the historical version above. Reset the totals at 9:30 each day, since a VWAP that runs across sessions is a different statistic from the one everybody else calls VWAP.
On the request budget: one symbol polled once a minute is 1 request per minute, against an allowance of 10 per minute on Free, 60 on Standard and 600 on Supreme, shared across all quote endpoints (rate limits). A dashboard following several symbols at once multiplies that, and the latest-minute batch endpoint on Standard and Supreme returns up to 5 symbols for the cost of 1 request.
If all you want is the day's VWAP as the feed reports it, with no arithmetic of your own, the latest daily bar carries daily_volume_weighted_price next to the day's open, high, low, close and volume. It's one request, on every plan.
Mistakes to avoid in code
- Averaging prices instead of weighting them.
mean(close)over the session is not VWAP. The worked table shows the two numbers five cents apart on five bars; over a full day the gap can be much larger. - Summing the typical price and calling it exact.
(H + L + C) / 3is an estimate of where a bar's volume traded. Use the bar's own volume-weighted price when the source provides one, and label the result as an estimate when it doesn't. - Fixing the session in UTC. The open is 13:30 UTC for part of the year and 14:30 UTC for the rest. Convert to New York time, then compare clock times.
- Forgetting half days. A few sessions a year end at 1:00 p.m. ET. Read the day's session from the trading days endpoint instead of a constant.
- Letting extended-hours bars in by accident. Filter by clock time regardless of what the source delivers. If you want pre-market in the number, say so in the field name.
- Counting a bar twice when polling. Dedupe on the bar's timestamp, not on the price.
- Mixing adjustments. A session VWAP from
rawbars and a close from asplitseries aren't comparable across a split date. Store the adjustment with the number, as you would for any historical series. - Skipping
NaNsilently. A null bar VWAP times a positive volume isNaN, and aNaNin a running sum either poisons everything after it or, withskipna, disappears without a trace. Drop or fix the bar explicitly.
The VWAP formula itself fits on an index card. Where implementations differ is the window and the inputs: trades or bars, bar VWAP or typical price, 9:30 to 4:00 in New York or something else. Write those three choices down next to the number, and your VWAP will match anyone's that made the same choices.
Ready to compute one? Get a free API key and make your first request from the quickstart; the latest minute bar works on the Free plan, and 1-minute historical bars are on Supreme ($20 a month). The plans are compared on the pricing section.