Markets: A Rigorous Course

Exercise · m01_execution.py

Execution cost = spread + impact + statutory charges

  1. market_impact(book, side, qty) -> (avg_fill_price, slippage_bps) Send a market order of qty into an OrderBook. Return the volume-weighted average fill price and the slippage versus the mid BEFORE the order, in basis points, signed so that a cost is positive (buying above mid or selling below mid). If nothing fills, return (nan, nan). 1 bp = 0.01%.

  2. round_trip_bps(price, qty, segment, rates, spread) -> float Cost of buying and immediately selling qty at price, in bps of the buy value: buy at price + spread/2, sell at price - spread/2, plus all charges from m01_costs_tax.trade_costs.

Check: cd exercises && .venv/bin/python -m pytest modules/M01-market-structure/tests

Tests (4)

  • test_market_impact_buy_and_sell
  • test_impact_is_increasing_and_convex_in_size
  • test_impact_empty_book
  • test_round_trip_bps

Theory: M01 notes. Run with Ctrl/⌘+Enter.

not run yet

Not saved: sign up to keep your code
"""Exercise 1.4: execution cost = spread + impact + statutory charges.

1) market_impact(book, side, qty) -> (avg_fill_price, slippage_bps)
   Send a market order of `qty` into an OrderBook. Return the volume-weighted
   average fill price and the slippage versus the mid BEFORE the order, in
   basis points, signed so that a cost is positive (buying above mid or
   selling below mid). If nothing fills, return (nan, nan). 1 bp = 0.01%.

2) round_trip_bps(price, qty, segment, rates, spread) -> float
   Cost of buying and immediately selling `qty` at `price`, in bps of the buy
   value: buy at price + spread/2, sell at price - spread/2, plus all charges
   from m01_costs_tax.trade_costs.

Check: cd exercises && .venv/bin/python -m pytest modules/M01-market-structure/tests
"""

import math

from m01_costs_tax import trade_costs  # noqa: F401
from m01_order_book import OrderBook  # noqa: F401


def market_impact(book: "OrderBook", side: str, qty: int) -> tuple[float, float]:
    raise NotImplementedError


def round_trip_bps(price: float, qty: float, segment: str, rates: dict, spread: float) -> float:
    raise NotImplementedError

No runs yet

The stub's functions raise NotImplementedError until you write them. Fill in one, press Run tests, and watch its tests turn green.

Reference solution

Available after your first run, with an account approved for code runs.

Create a free account

Reading is open to everyone. An account keeps your progress, answers, notes and code drafts, and gives you the study plan, the journals and the simulator. Running code needs an account approved for it.