Skip to content

Sample and toy data

Bundled sample

A Bitstamp BTC/USD capture ships with the package, for examples and tests.

sample_csv_path

sample_csv_path() -> Path

Return the path to the bundled Bitstamp sample orders.csv.gz.

The orders capture ships gzip-compressed (~23 MB -> ~2.9 MB) so it does not bloat installs; :func:pandas.read_csv decompresses it transparently. The companion trades.csv in the same directory is required for :class:Pipeline runs.

sample_data_dir

sample_data_dir() -> Path

Return the directory holding the bundled Bitstamp sample.

The directory contains orders.csv.gz (gzip-compressed; pandas reads it transparently), trades.csv, and a meta.json describing the live capture. Pass it to :class:Pipeline (or to :class:BitstampTradeReader.load) so the companion trades.csv is auto-located.

Toy book

A hand-written session small enough to check by hand: 24 events, 12 orders and 5 trades. The tutorial builds on it.

toy_events

toy_events() -> pd.DataFrame

Return the toy session's canonical events DataFrame.

24 events over one synthetic minute, in the exact column layout and dtypes of :class:~ob_analytics.bitstamp.BitstampLoader output (plus a non-canonical actor column naming each order). Rows are in chronological event_id order.

Returns:

Type Description
DataFrame

Columns original_number, id, timestamp, exchange_timestamp, price, volume, action, direction, event_id, fill, raw_event_type, actor.

Examples:

>>> from ob_analytics.datasets import toy_events, toy_trades
>>> from ob_analytics.analytics import set_order_types
>>> events = set_order_types(toy_events(), toy_trades())
>>> sorted(events["type"].unique().dropna().astype(str))
['cancelled-limit', 'market', 'market-limit', 'resting-limit']

toy_trades

toy_trades() -> pd.DataFrame

Return the toy session's canonical trades DataFrame.

Five trades consistent with :func:toy_events: each trade's maker_event_id / taker_event_id points at the event row carrying that fill, in the column layout of :class:~ob_analytics.bitstamp.BitstampTradeReader output and the dtypes of :data:~ob_analytics.schemas.TRADE_DTYPES (plus non-canonical maker_actor / taker_actor columns).

Returns:

Type Description
DataFrame

Columns timestamp, price, volume, direction (taker side, buy/sell), maker_event_id, taker_event_id, maker, taker, maker_og, taker_og, maker_actor, taker_actor.

toy_orders

toy_orders() -> dict[str, ToyOrder]

Return the toy session's twelve orders, keyed by actor, in arrival order.

Change, add or remove entries, then pass the result to :func:match_toy_orders to get the events and trades of the session you wrote. Each call returns a new dictionary, so editing it never changes the toy session itself.

Returns:

Type Description
dict of str to ToyOrder

{"Alice": ToyOrder(...), "Bob": ..., ...}.

Examples:

>>> from dataclasses import replace
>>> from ob_analytics.datasets import ToyOrder, match_toy_orders, toy_orders
>>> orders = toy_orders()
>>> orders["Jo"] = ToyOrder(at=10, direction="bid", price=99, volume=1)
>>> orders["Eve"] = replace(orders["Eve"], cancel_at=None)  # Eve stays
>>> events, trades = match_toy_orders(orders)

ToyOrder dataclass

ToyOrder(
    at: float,
    direction: Literal["bid", "ask"],
    price: int,
    volume: int,
    cancel_at: float | None = None,
)

One order in a toy session script, and when it is cancelled, if it is.

An order whose price reaches the other side of the book is matched on arrival, so a market order is written as a limit order priced through the touch (Frank's bid at 101 is the toy session's market buy).

Attributes:

Name Type Description
at float

Seconds from the start of the session when the order arrives.

direction {'bid', 'ask'}

The side of the book.

price int

The limit price, in ticks (the toy book's tick size is 1.0).

volume int

The size, in lots, at least 1.

cancel_at (float, optional)

Seconds from the start when the owner cancels whatever is still resting. Nothing happens at that time if the order has already filled. None (the default) leaves the order in the book.

match_toy_orders

match_toy_orders(
    orders: Mapping[str, ToyOrder],
) -> tuple[pd.DataFrame, pd.DataFrame]

Match a toy session script and return its events and trades.

The orders arrive in time order and are matched by price–time priority: an arriving order trades with the best-priced resting order on the other side, the earliest one first, for as long as the prices cross; whatever is left rests at its limit price. Each trade is at the resting order's price. A cancellation removes what is still resting. At any one time, every arrival comes before every cancellation, and arrivals (or cancellations) at the same time are taken in the order of orders.

Each maker fill writes two events, the maker's and then the taker's, as the toy session does. match_toy_orders(toy_orders()) returns :func:toy_events and :func:toy_trades exactly, with one difference: here Sam's sell fills Alice and Ivy at the same instant (t=56), as a matching engine would. The hand-written session puts Ivy's fill one second later, so the tutorial's pictures can show the book between the two fills.

Parameters:

Name Type Description Default
orders mapping of str to ToyOrder

The script, keyed by actor. Start from :func:toy_orders to edit the toy session, or write a new one. The twelve toy actors keep their order ids (Alice is 1, Sam is 12); any other actor gets the next free id, in the order of orders.

required

Returns:

Name Type Description
events DataFrame

In the layout of :func:toy_events, including the actor column.

trades DataFrame

In the layout of :func:toy_trades, including maker_actor and taker_actor.

Raises:

Type Description
ConfigError

If an order's direction is not "bid" or "ask", its price or volume is not a whole number, its volume is less than 1, a time is not finite, it arrives before the start, or it is cancelled before it arrives.

TICK_SIZE module-attribute

TICK_SIZE = 1.0

Tick size of the toy book.

1.0, so the integer-tick prices equal the whole-number prices in the script. The display price is ticks * TICK_SIZE.

LOT_SIZE module-attribute

LOT_SIZE = 1.0

Lot size of the toy book.

1.0, so the integer-lot sizes equal the whole-number sizes in the script. The base-asset size is lots * LOT_SIZE.

Toy L2 feed

toy_l2_depth

toy_l2_depth() -> pd.DataFrame

Return the toy session's canonical L2 depth DataFrame.

Ten price-level updates over 30 synthetic seconds (a four-level opening snapshot at t=0 followed by six deltas), in the exact column layout :class:~ob_analytics.depth.DepthSummaryEngine / :func:~ob_analytics.depth.summarize_depth consume — the L2 counterpart to :func:toy_events. volume is each level's new absolute resting size (0 removes it), not a signed delta.

Returns:

Type Description
DataFrame

Columns timestamp, price, volume, direction (categorical bid/ask), in timestamp order — a :func:~ob_analytics.schemas.validate_depth_df frame.

Examples:

>>> from ob_analytics.datasets import toy_l2_depth
>>> from ob_analytics.depth import summarize_depth, get_spread
>>> summary = summarize_depth(toy_l2_depth())
>>> summary[["best_bid_price", "best_ask_price"]].iloc[-1].tolist()
[99, 100]

toy_l2_trades

toy_l2_trades() -> pd.DataFrame

Return the toy L2 session's canonical trades DataFrame.

Four prints consistent with :func:toy_l2_depth, in the canonical trades layout. A price-level feed carries no order identity, so maker_event_id / taker_event_id / maker / taker (and the *_og columns) are <NA>. direction is the true taker side, equal to what Lee–Ready recovers from :func:toy_l2_depth's prevailing mid — null it to exercise :func:~ob_analytics.trade_sign.classify_trade_sign.

Returns:

Type Description
DataFrame

Columns timestamp, price, volume, direction (categorical buy/sell), and the <NA> maker/taker attribution columns — a :func:~ob_analytics.schemas.validate_trades_df frame.