σμ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ᵀμ = μ*∫Σ∂∞λ
σμ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 Academy学习路线
Ctrl K
AO
+1.2k 位学习者
登录加入 ↗
学习路线
AO
+1.2k 位学习者
登录
  • English
  • Français
  • Español
  • العربية
  • Português
  • Deutsch
  • 日本語
  • 中文
Python 学习路线›模块 10 · 高性能 Python 工程›主题 10.2·~45分钟高级

类型注解与静态检查

路线进度模块 10/11 · 主题 2/13
10.2 类型注解与静态检查
—实验得分— / 100总 XP—连续天数—

类型提示是工具可以检查的文档

Python 是动态类型的:变量可以保存任何东西,错误的类型只有在那一行运行时才暴露,也许正在交易日中途。类型提示让你写下函数期望什么、返回什么:def mid_price(bid: float, ask: float) -> float。Python 运行时会忽略它们。它们的价值在于:编辑器和 mypy、pyright 这样的静态检查器会读取它们,在代码运行之前就警告错误的调用;而且它们比容易过时的注释更好地说明了函数。

# 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 /

容器、None 与联合类型

内置容器在方括号中给出元素类型:list[float]、dict[str, float]、tuple[str, float](每个位置一个类型)。可能缺失的值写成 float | None,这迫使调用者处理 None;如果不先检查就把结果当数字用,检查器会报错。在函数内部,if x is None: return 会收窄类型,后面的代码就知道它是 float。对于只读的参数,宁可用 Sequence[float](列表、元组)这样的通用类型而非 list[float],这样适配更多调用者;返回值则用具体类型,如 list[float]。

# 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

数据的形状与检查器的工作

像订单这样键固定的字典,最好把它描述清楚,而不是只写 dict。TypedDict 或 dataclass 为每个字段及其类型命名,这样像 order["quantiy"] 这样的拼写错误会在编辑器里报错,而不是在 15:59 变成 KeyError。检查器从命令行运行(mypy main.py),它会打印代码与提示相矛盾的每个位置并以非零状态退出,因此能融入你之后会遇到的自动化检查。提示可以逐步添加:Any 会关闭对某个值的检查,没有类型的代码会被直接跳过。提示本身也是数据,工具可在运行时用 typing.get_type_hints 读取,本实验正是这样检查它们的。

# 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'>}
# 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]
类型提示不是校验类型提示不会在运行时拦截错误的值:来自文件、API 或 websocket 的数据仍然是什么就是什么。要显式校验外部数据(或使用能根据提示构建对象的库),并用类型提示捕捉你自己函数之间调用的错误。检查器通过只说明提示之间互相一致,并不说明数字正确;这仍是测试的工作。
  • 提示(bid: float、-> float)为函数提供文档,运行时被忽略;mypy 这样的检查器会读取它们。
  • 容器带元素类型(list[tuple[str, float]]);缺失值是 float | None;只读参数可用通用的 Sequence[float]。
  • 记录用 TypedDict 或 dataclass,在自动化检查中运行检查器,同时仍要校验外部数据并测试数字。

下一节:用 pytest 测试,包括 fixture、参数化用例,以及让策略保持诚实的检查。

实验:评分内容

  • 在 mid_price 中为数字加类型提示25 分
  • 在 best_quote 中为容器标注类型25 分
  • 在 safe_ratio 中允许缺失值25 分
  • 让 apply_fee 接受任意序列25 分
资源管理器 · lab-118-1
▾ lab-118-1
…
bash · 浏览器内
learner@quantcraft:~/lab-118-1$
Python 尚未加载PythonLn 1, Col 1Spaces: 4UTF-8

要重置此主题吗?

lab-118-1 中的所有内容将恢复为初始文件,终端也会被清空。你当前的解答将丢失,且无法撤销。

将被重置
  • main.py → 初始代码
  • 终端历史与测试输出
  • 未提交的更改
将被保留
  • 实验最高得分
  • 你的 XP 与连续天数
  • 讲解进度与笔记

登录后即可运行你的代码。

所有讲解均可免费阅读。创建账户或登录后,即可运行代码、运行测试并提交此实验。

  • 浏览器内 IDE 与 bash 终端,无需安装
  • 即时评分、XP 以及你在学习路线中的位置
创建账户登录
或
使用 GitHub 继续