A return needs yesterday's close, a moving average needs the last 50, a drawdown needs the highest close so far. Each row has to look at other rows. Window functions do that in one query, and they are why a quant can compute returns in SQL without a loop or a self-join.
The idea in plain words
Where we are. Topic 2 grouped rows into fewer rows; topic 4 combined two tables. A window function does neither: every input row stays, and a new column is computed from rows around it. The next topic, CTEs and subqueries, lets you name an intermediate result such as a set of returns and build on it.
The set of rows a window function looks at for the current row, defined by PARTITION BY (which rows belong together), ORDER BY (their order) and an optional frame such as ROWS BETWEEN 2 PRECEDING AND CURRENT ROW.
lag: the previous row
# lag reads the previous row's close; the return is today over yesterday, minus 1print(con.sql(""" SELECT date, close, lag(close) OVER (ORDER BY date) AS prev_close,1 round(close / lag(close) OVER (ORDER BY date) - 1, 4) AS ret FROM bars WHERE symbol = 'KO' ORDER BY date DESC LIMIT 3"""))
┌────────────┬────────┬────────────┬────────┐ │ date │ close │ prev_close │ ret │ │ date │ double │ double │ double │ ├────────────┼────────┼────────────┼────────┤ │ 2026-08-21 │ 91.1 │ 90.5 │ 0.0066 │ │ 2026-08-20 │ 90.5 │ 90.35 │ 0.0017 │ │ 2026-08-19 │ 90.35 │ 88.82 │ 0.0172 │ └────────────┴────────┴────────────┴────────┘
- 1The
OVER (ORDER BY date)is the window: all KO rows in date order.
Frames, partitions and QUALIFY
Adding ROWS BETWEEN n-1 PRECEDING AND CURRENT ROW limits the window to the last n rows, which makes avg a moving average. PARTITION BY symbol restarts the window for each symbol so one query handles all five. And QUALIFY filters on a window function's result, because WHERE runs too early to see it.
# A 3-day average, once with WHERE (history cut off) and once filtered after the windowprint(con.sql(""" SELECT date, round(avg(close) OVER (ORDER BY date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW), 2) AS ma3 FROM bars WHERE symbol = 'KO' AND date >= '2026-08-17' ORDER BY date LIMIT 21"""))print(con.sql(""" SELECT * FROM ( SELECT date, round(avg(close) OVER (ORDER BY date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW), 2) AS ma3 FROM bars WHERE symbol = 'KO'2 ) WHERE date >= '2026-08-17' ORDER BY date LIMIT 2"""))
┌────────────┬────────┐ │ date │ ma3 │ │ date │ double │ ├────────────┼────────┤ │ 2026-08-17 │ 86.98 │ │ 2026-08-18 │ 87.9 │ └────────────┴────────┘ ┌────────────┬────────┐ │ date │ ma3 │ │ date │ double │ ├────────────┼────────┤ │ 2026-08-17 │ 87.37 │ │ 2026-08-18 │ 87.84 │ └────────────┴────────┘
- 1
WHEREremoved the earlier days first, so Monday averages only itself. - 2Filtering outside the window keeps the real history: a different number.
# PARTITION BY restarts the ranking each day; QUALIFY keeps the busiest symbolprint(con.sql(""" SELECT date, symbol, volume FROM bars WHERE date >= '2026-08-19' QUALIFY row_number() OVER (PARTITION BY date ORDER BY volume DESC, symbol) = 1 ORDER BY date"""))
┌────────────┬─────────┬──────────┐ │ date │ symbol │ volume │ │ date │ varchar │ int64 │ ├────────────┼─────────┼──────────┤ │ 2026-08-19 │ AAPL │ 50505646 │ │ 2026-08-20 │ AAPL │ 40959184 │ │ 2026-08-21 │ AAPL │ 46766281 │ └────────────┴─────────┴──────────┘
# A running peak per symbol, then the worst drawdown of eachprint(con.sql(""" SELECT symbol, round(min(dd), 3) AS worst_drawdown FROM (SELECT symbol, close / max(close) OVER (PARTITION BY symbol ORDER BY date) - 1 AS dd FROM bars)1 GROUP BY symbol ORDER BY worst_drawdown"""))
┌─────────┬────────────────┐ │ symbol │ worst_drawdown │ │ varchar │ double │ ├─────────┼────────────────┤ │ AAPL │ -0.818 │ │ JPM │ -0.758 │ │ XOM │ -0.621 │ │ KO │ -0.446 │ │ JNJ │ -0.361 │ └─────────┴────────────────┘
- 1A window result cannot sit inside
min()directly, so it goes in a subquery first.
Without ORDER BY inside OVER, lag and running totals have no defined order, and without a tie-breaker row_number() picks arbitrarily among equal volumes. Write the order out, and add a second sort key (here the symbol) wherever two rows can tie.
What the tasks ask
- 1`daily_returns` and `running_high`
lagfor the previous close,max(...) OVER (ORDER BY date)for the peak so far. - 2`moving_average`A frame of
nrows, and NULL until the frame is full. - 3`top_symbol_each_day`
row_number()over a partition per day, kept withQUALIFY.
row_number() OVER (PARTITION BY date ORDER BY volume DESC) = 1 and no second sort key, what happens?Lab · what's graded
4 tasks · 100 ptslag:daily_returns25 pts- A frame of rows:
moving_average25 pts PARTITION BYandQUALIFY:top_symbol_each_day25 pts- Running totals:
running_high25 pts