σμ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
  • 日本語
  • 中文
Python skill›Module 1 · Python foundations for quants›Topic 1.28·~35 minBeginner

Dataclasses

Skill positionModule 1 of 11 · Topic 28 of 33
1.28 Dataclasses
—Lab score— / 100Total XP—Streak—
Lecture0% read

3 min readCode examples: 4

  1. 01Less boilerplate for classes that hold data
  2. 02Defaults, field() and mutable values
  3. 03Your own methods, __post_init__ and alternative constructors
  4. 04Frozen, ordered, and when plain classes win
01

Less boilerplate for classes that hold data

Many classes exist mainly to hold a few fields: a trade, a quote, a configuration. Writing __init__, __repr__ and __eq__ for each is repetitive. The @dataclass decorator from the dataclasses module writes them for you from a list of annotated fields. You declare symbol: str, price: float, quantity: int once, and you get a constructor Trade("AAPL", 184.25, 200), a readable repr like Trade(symbol='AAPL', price=184.25, quantity=200) and field-by-field equality. The annotations document intent; Python does not enforce them.

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14from dataclasses import dataclass

@dataclass
class Trade:
    symbol: str
    price: float
    quantity: int

a = Trade("AAPL", 184.25, 200)
b = Trade("AAPL", 184.25, 200)

print(a)                       # Trade(symbol='AAPL', price=184.25, quantity=200)
print(a == b)                  # True: compared field by field
print(a.price * a.quantity)    # 36850.0
02

Defaults, field() and mutable values

A field can have a default (currency: str = "USD"), and fields with defaults must come after those without. For a mutable default such as a list, a plain = [] would be shared by every object (and Python refuses it); write trades: list = field(default_factory=list) so each object gets its own new list. field(...) also lets you hide a field from the repr (repr=False) or from comparisons (compare=False).

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15from dataclasses import dataclass, field

@dataclass
class Book:
    name: str
    currency: str = "USD"                       # a default
    trades: list = field(default_factory=list)  # a fresh list per object

one = Book("desk-a")
two = Book("desk-b")
one.trades.append(("AAPL", 100))

print(one)                  # Book(name='desk-a', currency='USD', trades=[('AAPL', 100)])
print(two.trades)           # []   (not shared)
print(Book("x", "EUR"))     # Book(name='x', currency='EUR', trades=[])
03

Your own methods, __post_init__ and alternative constructors

A dataclass is still a normal class, so you can add methods. __post_init__(self) runs right after the generated __init__, which is the place to validate or clean values (self.symbol = self.symbol.upper(), raise ValueError(...) for a bad price). A @classmethod receives the class as cls and is the usual way to build an object from another form, such as text: Trade.from_line("AAPL,184.25,200") returns cls(symbol, float(price), int(quantity)), so the validation still runs and subclasses work too.

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24from dataclasses import dataclass

@dataclass
class Trade:
    symbol: str
    price: float
    quantity: int

    def __post_init__(self):
        self.symbol = self.symbol.strip().upper()
        if self.price <= 0:
            raise ValueError("price must be positive")

    def notional(self):
        return self.price * abs(self.quantity)

    @classmethod
    def from_line(cls, line):
        symbol, price, quantity = line.split(",")
        return cls(symbol, float(price), int(quantity))

t = Trade.from_line(" aapl,184.25,-200")
print(t)              # Trade(symbol='AAPL', price=184.25, quantity=-200)
print(t.notional())   # 36850.0
04

Frozen, ordered, and when plain classes win

@dataclass(frozen=True) makes instances read-only (assigning to a field raises FrozenInstanceError) and gives them a hash, so they can be dictionary keys or set members: ideal for values that must not change, like a contract specification. @dataclass(order=True) adds <, <=, >, >= comparing the fields in order. Use a dataclass for records of data; for objects with a lot of behaviour and hidden state, a hand-written class with careful methods is clearer.

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16from dataclasses import dataclass

@dataclass(frozen=True, order=True)
class Contract:
    symbol: str
    expiry: str          # ISO dates sort correctly as text

a = Contract("ESZ5", "2025-12-19")
b = Contract("ESZ5", "2026-03-20")
print(a < b)                          # True
print({a: "front", b: "next"}[a])     # front  (frozen => hashable)

try:
    a.symbol = "NQZ5"
except Exception as error:
    print(type(error).__name__)       # FrozenInstanceError
Validate where the data enters

Annotations like price: float do not stop Trade("AAPL", "abc", 1) from being created. If bad values would silently corrupt later calculations, check them in __post_init__ and raise ValueError, so a broken record cannot exist. Always create dataclass objects through the normal constructor, including from from_line, so the check cannot be skipped.

  • @dataclass turns annotated fields into __init__, __repr__ and __eq__.
  • Defaults come last; use field(default_factory=list) for lists and dicts.
  • __post_init__ validates; @classmethod builds from other forms; frozen=True makes values read-only.

Next up: derivatives in code, estimating how fast a quantity changes, the idea behind option sensitivities such as delta and gamma.

Lab · what's graded

4 tasks · 100 pts
  • Clean and validate a trade with __post_init__25 pts
  • Compute the traded value with notional25 pts
  • Build a trade from text with from_line25 pts
  • Net the trades of one symbol with net_quantity25 pts
Explorer · lab-28-1
▾ lab-28-1
…
bash · in-browser
learner@quantcraft:~/lab-28-1$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

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