σμ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
  • 日本語
  • 中文
Polars skill›Module 2 · Joins, time and windows›Topic 2.3·~45 minIntermediate

Rolling and cumulative expressions

Skill positionModule 2 of 3 · Topic 3 of 3
2.3 Rolling and cumulative expressions
—Lab score— / 100Total XP—Streak—
Lecture0% read

3 min readCode examples: 3

  1. 01The idea in plain words
  2. 02A window per symbol
  3. 03Volatility: the spread of recent returns
  4. 04Growth and drawdown: cumulative expressions
  5. 05What the tasks ask

A price on its own says little; a price next to its recent average, its recent wobble or its record high says a lot. Rolling and cumulative expressions build exactly those columns, and in Polars each one is a single expression that runs on the whole table at once.

01

The idea in plain words

Where we are. Topic 5 cut a series by the calendar. Here the window is a count of rows instead: the last 20 closes, everything since the start. We build four columns in turn: a moving average, a rolling volatility, the growth of one dollar and the drawdown. The one new trick is .over("symbol"), which keeps each stock's window to itself.

DefinitionRolling window

A window of the last N rows that slides forward one row at a time, so every row gets a statistic of its own recent past. Until N rows exist the result is null, because the window is not full.

02

A window per symbol

pl.col("close").rolling_mean(20) averages the last 20 rows of the column. In a table that stacks five stocks, the first rows of the second stock would borrow the last closes of the first, which is nonsense. Adding .over("symbol") runs the expression inside each symbol's rows and puts the answers back in the original order, so each stock starts its own window empty.

main.pyPython
# A 3-day average: the first two rows of each symbol are null because its window is not full yetaveraged = moving_average(bars, 3)print(averaged.filter(pl.col("symbol") == "KO").head(4).select("date", "close", "ma").rows())print("null averages:", averaged["ma"].null_count(), "= 2 for each of", bars["symbol"].n_unique(), "symbols")
[(datetime.date(2000, 1, 3), 19.4546, None), (datetime.date(2000, 1, 4), 19.4752, None), (datetime.date(2000, 1, 5), 19.6445, 19.524766666666668), (datetime.date(2000, 1, 6), 19.6689, 19.5962)]
null averages: 10 = 2 for each of 5 symbols
03

Volatility: the spread of recent returns

pct_change() turns closes into daily returns. A rolling standard deviation of those returns measures how wildly the stock has been moving lately, which is the working definition of volatility. The first return of each symbol is null, so a 20-day volatility is first available on the 21st row. Multiply by the square root of 252 to read it per year.

main.pyPython
# 60-day volatility per year for AAPL: its calmest and its wildest moment in 26 yearsv = rolling_volatility(bars, 60).filter(pl.col("symbol") == "AAPL").drop_nulls("vol")yearly = v["vol"] * 252 ** 0.5print("calmest:", round(yearly.min(), 2), "| wildest:", round(yearly.max(), 2), "| typical:", round(yearly.median(), 2))
calmest: 0.1 | wildest: 1.31 | typical: 0.3
04

Growth and drawdown: cumulative expressions

A cumulative expression looks at everything from the first row up to this one. cum_prod() of 1 + return compounds the daily returns, so it is the growth of one dollar. cum_max() is the highest close so far, and the close divided by it, minus 1, is the drawdown: how far the price sits below its own record, 0 at a new high and negative below it. The worst drawdown is the lowest value.

main.pyPython
# What one dollar grew into since 2000, and the worst fall from a peak, for each stockfinal = cumulative_return(bars).group_by("symbol").agg(pl.col("cum_ret").last()).sort("symbol")print([(s, round(g + 1, 1)) for s, g in final.rows()])worst = drawdown(bars).group_by("symbol").agg(pl.col("drawdown").min()).sort("symbol")print([(s, round(d, 2)) for s, d in worst.rows()])
[('AAPL', 369.0), ('JNJ', 8.4), ('JPM', 10.4), ('KO', 4.7), ('XOM', 7.0)]
[('AAPL', -0.82), ('JNJ', -0.36), ('JPM', -0.76), ('KO', -0.45), ('XOM', -0.62)]
Forget `over` and the windows leak

Without .over("symbol") the code still runs and the numbers look plausible, but a moving average at the top of one stock includes the end of another, and cum_max carries one stock's record into the next. The error is small and silent, which is the worst kind. When a table holds many assets, every rolling or cumulative column needs over.

05

What the tasks ask

  1. 1
    `moving_average` and `rolling_volatility`rolling_mean(window).over("symbol"); pct_change().over("symbol") as ret, then rolling_std(window).over("symbol") as vol.
  2. 2
    `cumulative_return` and `drawdown`(1 + daily).cum_prod().over("symbol") - 1 with the first return filled with 0; close / close.cum_max().over("symbol") - 1.

Key takeaways

  • Rolling is a count of rows rolling_mean, rolling_std and friends are null until the window is full.
  • `cum_*` accumulates cum_prod compounds growth and cum_max tracks the record, which gives the drawdown.
  • `over` keeps assets apart Add .over("symbol") to every such column. Next: Polars with pandas and Arrow.
Quick check
A table stacks five stocks. You add pl.col("close").cum_max() with no over. What goes wrong?
Pick an answer.

Lab · what's graded

4 tasks · 100 pts
  • A moving average: moving_average25 pts
  • Rolling volatility: rolling_volatility25 pts
  • Growth so far: cumulative_return25 pts
  • Below the peak: drawdown25 pts
Explorer · lab-6-1
▾ lab-6-1
▾ data
…
bash · in-browser
learner@quantcraft:~/lab-6-1$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

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