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.
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.
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.
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.
# 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 │ └─────────┴────────────┴────────┴───────┘
# 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 │ └────────┴────────────┘
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.
# 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
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.
# 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%
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.
What the tasks ask
- 1`build_daily_returns` and `build_monthly_returns`
CREATE TABLE ... ASstatements: a window for the daily returns, a month bucket and a compounded product for the monthly ones. - 2`factor_betas`A join on the month, then
regr_slope,regr_interceptandregr_r2of the excess return onmkt_rf. - 3`risk_report`Two CTEs with windows for wealth and drawdown, then annualised aggregates per symbol.
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