σμ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 10 · High-performance Python engineering›Topic 10.2·~45 minAdvanced

Type hints and static checking

Skill positionModule 10 of 11 · Topic 2 of 13
10.2 Type hints and static checking
—Lab score— / 100Total XP—Streak—
Lecture0% read

3 min readCode examples: 4

  1. 01Hints are documentation a tool can check
  2. 02Containers, None and unions
  3. 03Shapes of data, and the checker at work
01

Hints are documentation a tool can check

Python is dynamically typed: a variable can hold anything, and a wrong type shows up only when the line runs, perhaps in the middle of a trading day. Type hints let you write down what a function expects and returns: def mid_price(bid: float, ask: float) -> float. Python itself ignores them when running. Their value is that an editor and a static checker such as mypy or pyright read them and warn you about a wrong call before the code ever runs, and that they document the function better than a comment that goes stale.

Python
1
2
3
4
5
6
7
8
9
10
11# Hints describe the function; Python does not enforce them when it runs
def mid_price(bid: float, ask: float) -> float:
    return (bid + ask) / 2

print(mid_price(100.0, 100.5))                      # 100.25
print(mid_price.__annotations__)                    # {'bid': <class 'float'>, 'ask': <class 'float'>, 'return': <class 'float'>}
print(mid_price(10, 12))                            # 11.0   an int is accepted where float is hinted
try:
    mid_price("a", "b")                             # a checker flags this line before the code runs
except TypeError as error:
    print("only fails when it runs:", error)       # only fails when it runs: unsupported operand type(s) for /
02

Containers, None and unions

Built-in containers take their element types in brackets: list[float], dict[str, float], tuple[str, float] (one type per position). A value that may be missing is float | None, which forces the caller to handle None; the checker complains if they use the result as a number without checking first. Inside the function, an if x is None: return narrows the type so the rest is known to be a float. For arguments you only read, prefer a general type such as Sequence[float] (lists, tuples) over list[float], so more callers fit; return a concrete type, like list[float].

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15# Containers, an optional result, and narrowing with an is None check
def best_quote(quotes: list[tuple[str, float]]) -> tuple[str, float] | None:
    if not quotes:
        return None
    return min(quotes, key=lambda quote: quote[1])

def describe(quotes: list[tuple[str, float]]) -> str:
    best = best_quote(quotes)
    if best is None:                                 # after this check the checker knows best is a tuple
        return "no quotes"
    venue, price = best
    return f"{venue} at {price:.2f}"

print(describe([("XNAS", 100.02), ("ARCX", 100.01)]))     # ARCX at 100.01
print(describe([]))                                       # no quotes
03

Shapes of data, and the checker at work

A dictionary with fixed keys, such as an order, is better described than left as dict. A TypedDict or a dataclass names every field and its type, so a typo like order["quantiy"] is an error in your editor instead of a KeyError at 15:59. You run the checker from the command line (mypy main.py); it prints each place where the code contradicts its hints and exits non-zero, so it fits in the automated checks you will meet later. Hints can be added gradually: Any turns checking off for a value, and untyped code is simply skipped. The hints are also data, so tools can read them at runtime with typing.get_type_hints, which is exactly how this lab checks them.

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14# A TypedDict names the fields of an order; the checker would flag order["quantiy"]
from typing import TypedDict

class Order(TypedDict):
    symbol: str
    quantity: int
    price: float

def notional(order: Order) -> float:
    return order["quantity"] * order["price"]

order: Order = {"symbol": "AAPL", "quantity": 100, "price": 184.5}
print(notional(order))                              # 18450.0
print(Order.__annotations__)                        # {'symbol': <class 'str'>, 'quantity': <class 'int'>, 'price': <class 'float'>}
Python
1
2
3
4
5
6
7
8
9
10# The hints can be read at run time, which is how tools (and this lab) inspect a function
import typing

def apply_fee(prices: typing.Sequence[float], fee_rate: float = 0.001) -> list[float]:
    return [price * (1 + fee_rate) for price in prices]

hints = typing.get_type_hints(apply_fee)
print(hints["fee_rate"], hints["return"])           # <class 'float'> list[float]
print(typing.get_origin(hints["prices"]).__name__)  # Sequence
print(apply_fee((100.0, 200.0)))                    # a tuple is accepted: [100.1, 200.2]
Hints are not validation

A hint does not stop a wrong value at run time: data arriving from a file, an API or a websocket is still whatever it is. Check external data explicitly (or with a library that builds objects from hints), and use hints to catch the mistakes in your own calls between functions. A green checker means the hints agree with each other, not that the numbers are right; the tests still do that job.

  • Hints (bid: float, -> float) document a function and are ignored when Python runs it; a checker like mypy reads them.
  • Containers take element types (list[tuple[str, float]]); a missing value is float | None; read-only arguments can be a general Sequence[float].
  • Use TypedDict or dataclass for records, run the checker in your automated checks, and still validate external data and test the numbers.

Next up: testing with pytest, fixtures, parametrised cases and the checks that keep a strategy honest.

Lab · what's graded

4 tasks · 100 pts
  • Annotate numbers with mid_price25 pts
  • Type a container with best_quote25 pts
  • Admit a missing value in safe_ratio25 pts
  • Accept any sequence in apply_fee25 pts
Explorer · lab-118-1
▾ lab-118-1
…
bash · in-browser
learner@quantcraft:~/lab-118-1$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

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