σμ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.4·~40 minIntermediate

Time bucketing

Skill positionModule 2 of 3 · Topic 4 of 4
2.4 Time bucketing
—Lab score— / 100Total XP—Streak—
Lecture0% read

3 min readCode examples: 3

  1. 01The idea in plain words
  2. 02Weekly bars
  3. 03Month-end returns
  4. 04Fixed-width buckets and the calendar spine
  5. 05What the tasks ask

Daily bars are the raw material, but most reports want weekly or monthly numbers: a weekly high and low, a monthly return, volume per 30-day block. All of them are the same move, putting each date into a bucket and grouping by the bucket.

01

The idea in plain words

Where we are. Topic 2 grouped by an existing column such as the year. Here the group key is computed from the date. The next topic leaves the query text and asks how the database finds rows fast: indexes and query plans.

DefinitionBucket

A stretch of time that a date is rounded down to: its week start, its month start, or the start of a fixed-width block. All dates in one bucket share one group.

02

Weekly bars

date_trunc('week', date) rounds a date down to the Monday of its week. Grouping by it makes the open, high, low, close and volume of the week: max(high), min(low) and sum(volume) are easy, but the open is the open of the first day and the close the close of the last. arg_min(open, date) returns open on the row with the smallest date, and arg_max(close, date) the close on the latest one.

main.pyPython
# date_trunc on a DATE returns a timestamp, so cast it back to a dateprint(run(con, "SELECT typeof(date_trunc('week', DATE '2026-08-20')), typeof(CAST(date_trunc('week', DATE '2026-08-20') AS DATE))"))print(con.sql("""    SELECT CAST(date_trunc('week', date) AS DATE) AS week,1           arg_min(open, date) AS open, max(high) AS high, min(low) AS low,           arg_max(close, date) AS close, sum(volume) AS volume    FROM bars    WHERE symbol = 'KO' AND date >= '2026-08-01'    GROUP BY 1 ORDER BY 1"""))
[('TIMESTAMP', 'DATE')]
┌────────────┬────────┬────────┬────────┬────────┬──────────┐
│    week    │  open  │  high  │  low   │ close  │  volume  │
│    date    │ double │ double │ double │ double │  int128  │
├────────────┼────────┼────────┼────────┼────────┼──────────┤
│ 2026-08-03 │  88.48 │  88.48 │  85.16 │  87.05 │ 80941531 │
│ 2026-08-10 │  87.11 │  87.97 │  85.66 │  87.71 │ 61687816 │
│ 2026-08-17 │   87.3 │ 91.865 │  86.85 │   91.1 │ 71037510 │
└────────────┴────────┴────────┴────────┴────────┴──────────┘
  1. 1First open and last close of the week, not the lowest and highest.
03

Month-end returns

A monthly return compares one month-end close with the previous month-end close. First collapse the days to one row per month with a CTE, then use lag over the months. The first month has no earlier month and stays NULL.

main.pyPython
# One row per month first, then lag over the monthsprint(con.sql("""    WITH m AS (        SELECT CAST(date_trunc('month', date) AS DATE) AS month, arg_max(close, date) AS close        FROM bars WHERE symbol = 'JPM' GROUP BY 1    )    SELECT month, round(close / lag(close) OVER (ORDER BY month) - 1, 4) AS ret    FROM m ORDER BY month DESC LIMIT 3"""))
┌────────────┬─────────┐
│   month    │   ret   │
│    date    │ double  │
├────────────┼─────────┤
│ 2026-08-01 │ -0.0006 │
│ 2026-07-01 │  0.0747 │
│ 2026-06-01 │  0.0936 │
└────────────┴─────────┘
04

Fixed-width buckets and the calendar spine

time_bucket(INTERVAL 30 DAY, date, origin) cuts time into blocks of any width counted from an origin you choose, which weeks and months cannot do. And a group-by only shows buckets that have rows: to see the days with no bar, generate every date with generate_series and LEFT JOIN the data onto it.

main.pyPython
# 30-day blocks from 1 January, then a calendar that shows the weekend as NULLprint(con.sql("""    SELECT CAST(time_bucket(INTERVAL 30 DAY, date, DATE '2026-01-01') AS DATE) AS bucket, sum(volume) AS total    FROM bars WHERE symbol = 'XOM' AND date >= '2026-06-01'    GROUP BY 1 ORDER BY 1"""))print(con.sql("""    SELECT CAST(d AS DATE) AS date, b.close    FROM generate_series(DATE '2026-08-14', DATE '2026-08-18', INTERVAL 1 DAY) AS t(d)    LEFT JOIN bars b ON b.symbol = 'AAPL' AND b.date = CAST(d AS DATE)    ORDER BY 1"""))
┌────────────┬───────────┐
│   bucket   │   total   │
│    date    │  int128   │
├────────────┼───────────┤
│ 2026-05-31 │ 352513805 │
│ 2026-06-30 │ 318315784 │
│ 2026-07-30 │ 240797799 │
└────────────┴───────────┘

┌────────────┬────────┐
│    date    │ close  │
│    date    │ double │
├────────────┼────────┤
│ 2026-08-14 │ 305.93 │
│ 2026-08-15 │   NULL │
│ 2026-08-16 │   NULL │
│ 2026-08-17 │ 305.59 │
│ 2026-08-18 │ 310.03 │
└────────────┴────────┘
Name the edge of the week

DuckDB weeks start on Monday, other systems start on Sunday, and a month bucket is dated its first day while a week bucket is dated its Monday. Say in the column name or the docs which date you used, and cast the result to DATE, so two systems that disagree are easy to spot.

05

What the tasks ask

  1. 1
    `weekly_bars` and `monthly_return`date_trunc plus arg_min and arg_max; for the second, a CTE and lag.
  2. 2
    `bucketed_volume`time_bucket with an origin, grouped and summed.
  3. 3
    `calendar_with_gaps`generate_series for the days and a LEFT JOIN to the bars.

Key takeaways

  • Round the date, then group date_trunc and time_bucket turn a date into its bucket start; GROUP BY does the rest.
  • First and last need arg_min and arg_max An open or a close is the value at one end of the bucket, not a minimum or maximum.
  • Group-by hides empty buckets Build the calendar first and LEFT JOIN the data to see gaps. Next: indexes and query plans.
Quick check
A week has bars on Monday to Friday. Which expression gives the weekly close?
Pick an answer.

Lab · what's graded

4 tasks · 100 pts
  • Weekly OHLC: weekly_bars25 pts
  • Month-end returns: monthly_return25 pts
  • time_bucket: bucketed_volume25 pts
  • A calendar spine: calendar_with_gaps25 pts
Explorer · lab-8-1
▾ lab-8-1
▾ data
…
bash · in-browser
learner@quantcraft:~/lab-8-1$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

Everything in lab-8-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