Skip to content

Synthetic data

A seeded generator of per-order (L3) sessions, with the true maker and taker of every trade. See Generate synthetic L3 data.

generate_session

generate_session(
    config: SynthConfig | None = None, /, **overrides: Any
) -> SynthSession

Generate one synthetic L3 session.

Parameters:

Name Type Description Default
config SynthConfig

Base configuration. Defaults to :class:SynthConfig with all defaults.

None
**overrides Any

Field overrides applied on top of config (e.g. seed=7, duration=60). Convenience for generate_session(seed=7) without constructing a config explicitly.

{}

Returns:

Type Description
SynthSession

The events frame, the trades frame, and the resolved config.

Examples:

>>> from ob_analytics.synth import generate_session
>>> session = generate_session(seed=1, duration=30)
>>> sorted(session.events["type"].unique().astype(str))
['cancelled-limit', 'market', 'resting-limit']

SynthConfig dataclass

SynthConfig(
    seed: int = 0,
    duration: float = 300.0,
    start_time: Timestamp = _DEFAULT_START_TIME,
    arrival_process: Literal[
        "poisson", "hawkes"
    ] = "poisson",
    limit_rate: float = 6.0,
    cancel_rate: float = 4.0,
    market_rate: float = 1.5,
    hawkes_excitation: float = 0.5,
    hawkes_decay: float = 1.0,
    mid_price: float = 100.0,
    tick_size: float = 0.01,
    lot_size: float = 1e-08,
    half_spread_ticks: int = 2,
    depth_levels: int = 10,
    level_decay: float = 0.5,
    mean_size: float = 1.0,
    min_size: float = 0.01,
    limit_bid_prob: float = 0.5,
    market_buy_prob: float = 0.5,
    price_decimals: int = 2,
    volume_decimals: int = 8,
    iceberg_fraction: float = 0.0,
    iceberg_size_multiple: float = 5.0,
    toxic_fraction: float = 0.0,
    toxic_size_multiple: float = 3.0,
)

Typed parameters for :func:generate_session.

Every field has a default that produces a lively but bounded BTC/USD-style book around a mid of 100 over five simulated minutes. Override individual fields for other instruments, intensities, or session lengths.

Parameters:

Name Type Description Default
seed int

Seed for the single :class:numpy.random.Generator. Identical configs with the same seed produce byte-identical output.

0
duration float

Length of the simulated session in seconds.

300.0
start_time Timestamp

Wall-clock anchor for the first possible event. Emitted timestamps are tz-aware UTC nanoseconds, matching the schema's timestamp policy; a tz-naive anchor is read as UTC.

_DEFAULT_START_TIME
arrival_process ('poisson', 'hawkes')

Arrival model for all three streams. "poisson" is the constant-rate baseline; "hawkes" is self-exciting (each event briefly raises the arrival rate), generated with Ogata thinning.

"poisson"
limit_rate float

Baseline arrival intensities in events per second for new limit orders, cancellations, and market orders. For Hawkes these are the background rates mu before self-excitation.

6.0
cancel_rate float

Baseline arrival intensities in events per second for new limit orders, cancellations, and market orders. For Hawkes these are the background rates mu before self-excitation.

6.0
market_rate float

Baseline arrival intensities in events per second for new limit orders, cancellations, and market orders. For Hawkes these are the background rates mu before self-excitation.

6.0
hawkes_excitation float

Branching ratio of the Hawkes kernel (mean offspring per event). Must be below 1 for a stationary process; higher values cluster arrivals more tightly. Ignored for Poisson.

0.5
hawkes_decay float

Exponential decay rate beta of the Hawkes kernel (per second): how fast the excitation from one event fades. Ignored for Poisson.

1.0
mid_price float

Reference mid price. The book is anchored here; new limit orders are priced relative to it, so the session is roughly stationary.

100.0
tick_size float

Smallest price increment. Prices are whole multiples of this value.

0.01
half_spread_ticks int

Distance in ticks from the mid to the best price on each side, so the resting spread is 2 * half_spread_ticks ticks.

2
depth_levels int

Number of distinct price levels available on each side.

10
level_decay float

Success probability of the geometric distribution used to pick how many ticks behind the touch a new order sits. Higher values concentrate orders at the touch; must be in (0, 1].

0.5
mean_size float

Mean of the exponential order-size distribution.

1.0
min_size float

Lower bound applied to every drawn size.

0.01
limit_bid_prob float

Probability that a new limit order is a bid, and that a market order is a buy. 0.5 each gives a balanced book.

0.5
market_buy_prob float

Probability that a new limit order is a bid, and that a market order is a buy. 0.5 each gives a balanced book.

0.5
lot_size float

Minimum size increment. Sizes are emitted as a whole number of lots (int64), matching the canonical schema; the base-asset size is lots * lot_size.

1e-08
price_decimals int

Display precision, matching :class:~ob_analytics.config.PipelineConfig. Emitted prices are integer ticks, so price_decimals only describes how many places to show when a tick is rendered back to the quote currency (tick * tick_size); volume_decimals rounds sizes.

2
volume_decimals int

Display precision, matching :class:~ob_analytics.config.PipelineConfig. Emitted prices are integer ticks, so price_decimals only describes how many places to show when a tick is rendered back to the quote currency (tick * tick_size); volume_decimals rounds sizes.

2
iceberg_fraction float

Probability that a new limit order is an iceberg (off at 0.0).

0.0
iceberg_size_multiple float

An iceberg's total size is this multiple of its displayed peak; the remainder is hidden and refilled one peak at a time.

5.0
toxic_fraction float

Probability that a market order is toxic / informed (off at 0.0).

0.0
toxic_size_multiple float

Size-mean multiplier applied to a toxic market order.

3.0

SynthSession dataclass

SynthSession(
    events: DataFrame,
    trades: DataFrame,
    config: SynthConfig,
    icebergs: DataFrame = (
        lambda: pd.DataFrame(
            {
                "id": pd.Series(dtype="int64"),
                "iceberg": pd.Series(dtype="int64"),
            }
        )
    )(),
)

A generated session: the two canonical frames plus the config used.

Attributes:

Name Type Description
events DataFrame

Per-order events satisfying :func:~ob_analytics.schemas.validate_events_df, in event_id order, already classified by :func:~ob_analytics.analytics.set_order_types.

trades DataFrame

Executions satisfying :func:~ob_analytics.schemas.validate_trades_df; every row references the event_id of its maker and taker events.

config SynthConfig

The configuration that produced this session.

icebergs DataFrame

Ground truth for the iceberg injection: one row per visible slice of an iceberg order, with the slice's order id and iceberg, the order id of the iceberg's first slice. Empty unless iceberg_fraction is above zero.

SynthLoader

SynthLoader(session: SynthSession)

Serve a pre-generated session's events to :class:~ob_analytics.pipeline.Pipeline.

Satisfies the :class:~ob_analytics.protocols.EventLoader protocol, so a synthetic session runs through the real pipeline::

from ob_analytics import Pipeline
from ob_analytics.synth import (
    generate_session, SynthLoader, SynthTradeReader,
)

session = generate_session(seed=1)
result = Pipeline(
    loader=SynthLoader(session),
    trade_reader=SynthTradeReader(session),
).run(path=None)

SynthTradeReader

SynthTradeReader(session: SynthSession)

Serve a pre-generated session's trades to :class:~ob_analytics.pipeline.Pipeline.

Satisfies the :class:~ob_analytics.protocols.TradeReader protocol. See :class:SynthLoader for the paired usage.