σμimplied vol · KKmax(S−K,0)udβρᵢⱼfat tailsPnL · drawdownyield · TdSₜ = μSₜ dt + σSₜ dWₜC = S·N(d₁) − K·e⁻ʳᵀ·N(d₂)σₚ² = wᵀΣwd₁ = [ln(S/K) + (r + σ²⁄2)T] ⁄ σ√T∂V/∂t + ½σ²S²·∂²V/∂S² + rS·∂V/∂S − rV = 0Sharpe = (Rₚ − R_f) ⁄ σₚVaR₉₉ = μ − 2.33σρ = Cov(X,Y) ⁄ σₓσᵧE[Rₚ] = Σ wᵢ·E[Rᵢ]φ(x) = e^(−x²/2) ⁄ √2πE[Rᵢ] = R_f + βᵢ(E[Rₘ] − R_f)dXₜ = θ(μ − Xₜ)dt + σ dWₜσ²ₜ = ω + α·ε²ₜ₋₁ + β·σ²ₜ₋₁C − P = S − K·e⁻ʳᵀΔ = ∂V/∂S Γ = ∂²V/∂S²p = (e^(rΔt) − d) ⁄ (u − d)rₜ = ln(Pₜ ⁄ Pₜ₋₁)E[Xₜ₊₁ | ℱₜ] = Xₜf* = (bp − q) ⁄ bz = (x − μ) ⁄ σP(N=k) = λᵏe^(−λ) ⁄ k!Θ = −∂V/∂Tν = S·φ(d₁)·√Tmin wᵀΣw s.t. wᵀμ = μ*∫Σ∂∞λ
uantCraft AcademyRoadmapsSkills
Ctrl K
AO
+1.2k Learners
LoginJoin ↗
RoadmapsSkills
AO
+1.2k Learners
Login
  • English
  • Français
  • Español
  • العربية
  • Português
  • Deutsch
  • 日本語
  • 中文
σμimplied vol · KKmax(S−K,0)udβρᵢⱼfat tailsPnL · drawdownyield · TdSₜ = μSₜ dt + σSₜ dWₜC = S·N(d₁) − K·e⁻ʳᵀ·N(d₂)σₚ² = wᵀΣwd₁ = [ln(S/K) + (r + σ²⁄2)T] ⁄ σ√T∂V/∂t + ½σ²S²·∂²V/∂S² + rS·∂V/∂S − rV = 0Sharpe = (Rₚ − R_f) ⁄ σₚVaR₉₉ = μ − 2.33σρ = Cov(X,Y) ⁄ σₓσᵧE[Rₚ] = Σ wᵢ·E[Rᵢ]φ(x) = e^(−x²/2) ⁄ √2πE[Rᵢ] = R_f + βᵢ(E[Rₘ] − R_f)dXₜ = θ(μ − Xₜ)dt + σ dWₜσ²ₜ = ω + α·ε²ₜ₋₁ + β·σ²ₜ₋₁C − P = S − K·e⁻ʳᵀΔ = ∂V/∂S Γ = ∂²V/∂S²p = (e^(rΔt) − d) ⁄ (u − d)rₜ = ln(Pₜ ⁄ Pₜ₋₁)E[Xₜ₊₁ | ℱₜ] = Xₜf* = (bp − q) ⁄ bz = (x − μ) ⁄ σP(N=k) = λᵏe^(−λ) ⁄ k!Θ = −∂V/∂Tν = S·φ(d₁)·√Tmin wᵀΣw s.t. wᵀμ = μ*∫Σ∂∞λ
uantCraft AcademyRoadmapsSkills
Ctrl K
AO
+1.2k Learners
LoginJoin ↗
RoadmapsSkills
AO
+1.2k Learners
Login
  • English
  • Français
  • Español
  • العربية
  • Português
  • Deutsch
  • 日本語
  • 中文
SQL skill›Module 2 · Prices over time›Topic 2.1·~55 minIntermediate

Window functions

Skill positionModule 2 of 3 · Topic 1 of 4
2.1 Window functions
—Lab score— / 100Total XP—Streak—
Lecture0% read

2 min readCode examples: 4

  1. 01The idea in plain words
  2. 02lag: the previous row
  3. 03Frames, partitions and QUALIFY
  4. 04What the tasks ask

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.

01

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.

DefinitionWindow

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.

02

lag: the previous row

main.pyPython
# 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 │
└────────────┴────────┴────────────┴────────┘
  1. 1The OVER (ORDER BY date) is the window: all KO rows in date order.
03

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.

main.pyPython
# 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. 1WHERE removed the earlier days first, so Monday averages only itself.
  2. 2Filtering outside the window keeps the real history: a different number.
main.pyPython
# 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 │
└────────────┴─────────┴──────────┘
main.pyPython
# 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 │
└─────────┴────────────────┘
  1. 1A window result cannot sit inside min() directly, so it goes in a subquery first.
Order inside the window matters

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.

04

What the tasks ask

  1. 1
    `daily_returns` and `running_high`lag for the previous close, max(...) OVER (ORDER BY date) for the peak so far.
  2. 2
    `moving_average`A frame of n rows, and NULL until the frame is full.
  3. 3
    `top_symbol_each_day`row_number() over a partition per day, kept with QUALIFY.

Key takeaways

  • Windows add columns, they do not remove rows OVER computes per row from related rows; PARTITION BY splits, ORDER BY orders, a frame limits.
  • Windows run after WHERE Filtering rows first can starve the window of history; filter on the result with a subquery or QUALIFY.
  • Always order, always break ties Results must not depend on arbitrary row order. Next: CTEs and subqueries.
Quick check
Two symbols tie for the highest volume on one day. With row_number() OVER (PARTITION BY date ORDER BY volume DESC) = 1 and no second sort key, what happens?
Pick an answer.

Lab · what's graded

4 tasks · 100 pts
  • lag: daily_returns25 pts
  • A frame of rows: moving_average25 pts
  • PARTITION BY and QUALIFY: top_symbol_each_day25 pts
  • Running totals: running_high25 pts
Explorer · lab-5-1
▾ lab-5-1
▾ data
…
bash · in-browser
learner@quantcraft:~/lab-5-1$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

Everything in lab-5-1 goes back to the starter files and the terminal is cleared. Your current solution will be lost — this can't be undone.

Will be reset
  • main.py → starter code
  • Terminal history and test output
  • Unsubmitted changes
Will be kept
  • Best lab score
  • Your XP and streak
  • Lecture progress and notes