σμ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.4·~1 hr 30 minAdvanced

Capstone: a returns and factor warehouse in SQL

Skill positionModule 3 of 3 · Topic 4 of 4
3.4 Capstone: a returns and factor warehouse in SQL
—Lab score— / 100Total XP—Streak—
Lecture0% read

3 min readCode examples: 4

  1. 01The idea in plain words
  2. 02Steps 1 and 2: returns, daily then monthly
  3. 03Step 3: exposure to the market in one query
  4. 04Step 4: the risk report
  5. 05What the tasks ask

Five stocks, 26 years, 33,493 daily prices, and a risk analyst's questions: how much does each stock move with the market, how much does it make a year, how far has it fallen from its peak? None of it needs Python. A short chain of SQL statements turns raw prices into a warehouse that answers all of them.

01

The idea in plain words

Where we are. This is the capstone of the SQL skill. It uses every earlier topic: filters and aggregates, windows for returns, date buckets for months, a join with a factor table, CTEs for the drawdown, and constraints-minded naming. There is no new syntax here, only the way the pieces fit. Each step reads the table the step before it wrote.

DefinitionWarehouse

A set of tables built from raw data in stages, each stage reading the one before: raw bars, then daily returns, then monthly returns, then reports. Each layer is simple, named, and can be checked on its own.

02

Steps 1 and 2: returns, daily then monthly

Daily returns come from lag over each symbol, and the first day of each symbol has none. A monthly return cannot be the sum of the daily ones: returns multiply, (1 + r1)(1 + r2)..., and the logarithm turns that product into a sum, so exp(sum(ln(1 + ret))) - 1 compounds them exactly.

main.pyPython
# Step 1 and 2: each statement reads the table the one before it wrotecon = connect()con.execute(build_daily_returns("daily", "bars"))con.execute(build_monthly_returns("monthly", "daily"))print(run(con, "SELECT count(*) FROM daily"))print(con.sql("SELECT symbol, month, round(ret, 4) AS ret, days FROM monthly WHERE symbol = 'KO' ORDER BY month DESC LIMIT 3"))
[(33488,)]
┌─────────┬────────────┬────────┬───────┐
│ symbol  │   month    │  ret   │ days  │
│ varchar │    date    │ double │ int64 │
├─────────┼────────────┼────────┼───────┤
│ KO      │ 2026-08-01 │ 0.0401 │    15 │
│ KO      │ 2026-07-01 │ 0.0778 │    22 │
│ KO      │ 2026-06-01 │ 0.0286 │    21 │
└─────────┴────────────┴────────┴───────┘
main.pyPython
# Adding daily returns is close but wrong; compounding them is exactprint(con.sql("""    SELECT round(sum(ret), 5) AS added, round(exp(sum(ln(1 + ret))) - 1, 5) AS compounded    FROM daily WHERE symbol = 'AAPL' AND date >= '2026-08-01'"""))
┌────────┬────────────┐
│ added  │ compounded │
│ double │   double   │
├────────┼────────────┤
│ 0.0026 │    0.00142 │
└────────┴────────────┘
03

Step 3: exposure to the market in one query

A stock's beta is the slope of its excess return against the market's excess return. The factor table already gives the market excess return mkt_rf and the risk-free rate rf, month by month, so join the monthly returns to it on the month and let regr_slope, regr_intercept and regr_r2 do the regression inside the GROUP BY. A beta near 1 moves with the market, below 1 less than it.

main.pyPython
# Beta, alpha and r2 of each stock against the market since 2015, all in one queryfor row in run(con, factor_betas("monthly", "factors", "2015-01-01")):    print(row[0], row[1], "months | beta", round(row[2], 2), "| alpha", round(row[3], 4), "| r2", round(row[4], 2))
AAPL 140 months | beta 1.13 | alpha 0.0082 | r2 0.42
JNJ 140 months | beta 0.43 | alpha 0.0034 | r2 0.16
JPM 140 months | beta 1.09 | alpha 0.0037 | r2 0.51
KO 140 months | beta 0.43 | alpha 0.0025 | r2 0.17
XOM 140 months | beta 0.74 | alpha 0.0007 | r2 0.18
04

Step 4: the risk report

Annualising turns daily numbers into yearly ones: volatility scales by sqrt(252) and the average log return by 252. The maximum drawdown needs two windows in a row: wealth is the running compounded return, and the drawdown is wealth over its running peak minus 1. The second window reads the first one's result, which is why it needs a CTE.

main.pyPython
# Annual return, volatility, worst drawdown (wealth starts at 1) and worst day, per stockfor row in run(con, risk_report("daily")):    print(row[0], "| return", f"{row[1]:.1%}", "| vol", f"{row[2]:.1%}", "| max drawdown", f"{row[3]:.1%}", "| worst day", f"{row[4]:.1%}")
AAPL | return 24.9% | vol 38.3% | max drawdown -81.8% | worst day -51.8%
JNJ | return 8.3% | vol 19.2% | max drawdown -36.1% | worst day -15.8%
JPM | return 9.2% | vol 36.7% | max drawdown -75.8% | worst day -20.7%
KO | return 6.0% | vol 20.4% | max drawdown -44.6% | worst day -10.1%
XOM | return 7.6% | vol 26.3% | max drawdown -62.1% | worst day -14.0%
A warehouse is only as good as its inputs

These numbers assume the prices are adjusted for splits and dividends and that 252 days make a year. If the bars had an unadjusted split, one day would show a return of -50% and the drawdown would be wrong. Check the worst days first: a result that looks too good or too bad is usually a data problem, not a discovery.

05

What the tasks ask

  1. 1
    `build_daily_returns` and `build_monthly_returns`CREATE TABLE ... AS statements: a window for the daily returns, a month bucket and a compounded product for the monthly ones.
  2. 2
    `factor_betas`A join on the month, then regr_slope, regr_intercept and regr_r2 of the excess return on mkt_rf.
  3. 3
    `risk_report`Two CTEs with windows for wealth and drawdown, then annualised aggregates per symbol.

Key takeaways

  • Build in layers Raw bars, daily returns, monthly returns, reports: each layer is a table you can test.
  • SQL can do the statistics Windows, regr_* and stddev_samp give returns, betas and risk without leaving the database.
  • Check the data before the result Know what the numbers assume. That finishes the SQL skill.
Quick check
A stock rises 10% one day and falls 10% the next. What is its two-day return?
Pick an answer.

Lab · what's graded

4 tasks · 100 pts
  • Step 1, daily returns: build_daily_returns25 pts
  • Step 2, monthly returns: build_monthly_returns25 pts
  • Step 3, factor exposure: factor_betas25 pts
  • Step 4, the risk report: risk_report25 pts
Explorer · lab-11-1
▾ lab-11-1
▾ data
…
bash · in-browser
learner@quantcraft:~/lab-11-1$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

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