σμ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 3 · Fast and well built›Topic 3.2·~50 minIntermediate

Data modelling for market data

Skill positionModule 3 of 3 · Topic 2 of 4
3.2 Data modelling for market data
—Lab score— / 100Total XP—Streak—
Lecture0% read

3 min readCode examples: 4

  1. 01The idea in plain words
  2. 02Facts in one place
  3. 03Let the database say no
  4. 04Loads you can run twice
  5. 05Views: a saved question
  6. 06What the tasks ask

Suppose every price row also stored its stock's name and sector. Then 6,699 AAPL rows hold the same sector, a typo makes "Technology" and "Tecnology" two sectors, and changing a classification means rewriting thousands of rows. A good model removes that risk before the first row is loaded.

01

The idea in plain words

Where we are. The previous nine topics used tables someone else had designed. Here you design them. This is also the last topic before the capstone, which builds a returns and factor warehouse and needs every earlier idea: aggregation, windows, as-of joins, time buckets, plans and now keys.

DefinitionConstraint

A rule the database checks on every insert and update and enforces by refusing the row: NOT NULL, PRIMARY KEY, REFERENCES (a foreign key) and CHECK. A rule in the schema cannot be forgotten by one careless script.

02

Facts in one place

Split by what each fact depends on. A stock's name and sector depend only on the stock, so they go in securities, one row each. A close depends on the stock and the day, so it goes in prices, keyed by (symbol, date), with symbol pointing at securities. The database now knows what can repeat and what cannot.

main.pyPython
# One row per stock in securities, one row per stock per day in pricesdb = duckdb.connect()db.execute(create_securities("securities"))db.executemany("INSERT INTO securities (symbol, name, sector) VALUES (?, ?, ?)", SECURITIES)db.execute(create_prices("prices", "securities"))print(db.sql("SELECT symbol, name, sector, currency FROM securities ORDER BY symbol"))1
┌─────────┬─────────────────────────┬──────────────────┬──────────┐
│ symbol  │          name           │      sector      │ currency │
│ varchar │         varchar         │     varchar      │ varchar  │
├─────────┼─────────────────────────┼──────────────────┼──────────┤
│ AAPL    │ Apple Inc.              │ Technology       │ USD      │
│ JNJ     │ Johnson & Johnson       │ Health Care      │ USD      │
│ JPM     │ JPMorgan Chase & Co.    │ Financials       │ USD      │
│ KO      │ The Coca-Cola Company   │ Consumer Staples │ USD      │
│ XOM     │ Exxon Mobil Corporation │ Energy           │ USD      │
└─────────┴─────────────────────────┴──────────────────┴──────────┘
  1. 1The currency was never given: the default filled in USD.
03

Let the database say no

Constraints turn assumptions into checks. A high below a low, a negative close, a second bar for the same day and a bar for an unknown symbol are all errors in the data, and the database stops them at the door instead of letting them reach a back-test.

main.pyPython
# Three bad bars: each one is refused, and the table stays cleanbad = [("AAPL", "2026-08-22", 5, 1, 2, 3, 10, "high below low"),       ("ZZZ", "2026-08-22", 1, 2, 1, 1.5, 10, "unknown symbol"),       ("AAPL", "2026-08-22", 1, 2, 1, -5, 10, "negative close")]for *row, why in bad:    try:        db.execute("INSERT INTO prices VALUES (?, ?, ?, ?, ?, ?, ?)", row)    except duckdb.Error as error:        print(why, "->", type(error).__name__)print(db.sql("SELECT count(*) AS bars FROM prices"))
high below low -> ConstraintException
unknown symbol -> ConstraintException
negative close -> ConstraintException
┌───────┐
│ bars  │
│ int64 │
├───────┤
│     0 │
└───────┘
04

Loads you can run twice

A nightly job fails halfway and is run again; a vendor sends a corrected close for yesterday. With a plain INSERT the second run hits the primary key and stops. ON CONFLICT (symbol, date) DO UPDATE makes the load idempotent: a new bar is added, an existing one is replaced, and running it twice leaves the same table as running it once.

main.pyPython
# Loading everything twice changes nothing; a correction replaces the old KO barfor _ in range(2):    for symbol in SYMBOLS:        db.executemany(upsert_bars("prices"), bar_rows(symbol, 200))print(db.sql("SELECT count(*) AS bars FROM prices"))db.execute(upsert_bars("prices"), ["KO", "2026-08-21", 90.85, 91.5, 90.7, 91.25, 15534719])print(db.sql("SELECT date, close FROM prices WHERE symbol = 'KO' ORDER BY date DESC LIMIT 2"))
┌───────┐
│ bars  │
│ int64 │
├───────┤
│  1000 │
└───────┘

┌────────────┬────────┐
│    date    │ close  │
│    date    │ double │
├────────────┼────────┤
│ 2026-08-21 │  91.25 │
│ 2026-08-20 │   90.5 │
└────────────┴────────┘
05

Views: a saved question

A view stores a query, not rows. latest below is defined once, and every time you read it, it reads the current table, so a bar loaded a minute ago appears in it with no refresh. A copy made with CREATE TABLE AS would be stale the moment new data arrives.

main.pyPython
# The view follows the table: a newer KO bar appears with no refreshdb.execute(latest_view("latest", "prices"))print(db.sql("SELECT * FROM latest WHERE symbol = 'KO'"))db.execute("INSERT INTO prices VALUES ('KO', '2026-08-24', 91.2, 91.9, 91.0, 91.7, 1000)")print(db.sql("SELECT * FROM latest WHERE symbol = 'KO'"))
┌─────────┬────────────┬────────┐
│ symbol  │    date    │ close  │
│ varchar │    date    │ double │
├─────────┼────────────┼────────┤
│ KO      │ 2026-08-21 │  91.25 │
└─────────┴────────────┴────────┘

┌─────────┬────────────┬────────┐
│ symbol  │    date    │ close  │
│ varchar │    date    │ double │
├─────────┼────────────┼────────┤
│ KO      │ 2026-08-24 │   91.7 │
└─────────┴────────────┴────────┘
Quote the names you build into statements

Values go through quote(); table and column names cannot be passed as ? parameters, so they go through ident(). A name with a double quote or a space breaks a hand-built statement, and a name taken from user input is a way in for an attacker.

06

What the tasks ask

  1. 1
    `create_securities` and `create_prices`Keys, NOT NULL, a default, a foreign key and CHECK rules. The grader tries to break them with bad rows.
  2. 2
    `upsert_bars`INSERT ... ON CONFLICT (symbol, date) DO UPDATE with seven placeholders.
  3. 3
    `latest_view`CREATE VIEW with row_number() and QUALIFY, so it follows the table.

Key takeaways

  • One fact, one place Split tables by what each fact depends on and join them back with keys.
  • Constraints are tests that never get skipped Put every rule you can in the schema: keys, NOT NULL, foreign keys, CHECK.
  • Make loads idempotent ON CONFLICT DO UPDATE lets a job rerun safely. Next: the capstone.
Quick check
A vendor re-sends yesterday's bars with one corrected close. The load uses a plain INSERT into a table with PRIMARY KEY (symbol, date). What happens?
Pick an answer.

Lab · what's graded

4 tasks · 100 pts
  • Keys and defaults: create_securities25 pts
  • Constraints: create_prices25 pts
  • A repeatable load: upsert_bars25 pts
  • A view: latest_view25 pts
Explorer · lab-10-1
▾ lab-10-1
▾ data
…
bash · in-browser
learner@quantcraft:~/lab-10-1$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

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