Reinforcement learning¶
MarketMakingEnv turns market making into a
Gymnasium environment. One learning agent quotes
in the closed-loop market of build_market(), with
the same noise and informed traders as every other strategy in microbook, so a
learned policy can be compared directly with the hand-written market makers.
It needs the optional dependency:
The environment¶
Every decision_interval steps (10 by default) the agent chooses where to quote,
and the market runs until the next decision.
Action: MultiDiscrete([max_offset + 1, max_offset + 1]). For the bid and
the ask, how many ticks behind the most aggressive passive price to quote; 0 is
as close to the mid as the grid allows without crossing. Quote handling is the
same as the library's market makers (TwoSidedQuoter):
quotes are post-only, an unchanged quote keeps its queue position, and the side
that would push |inventory| past inv_limit is not quoted.
Observation: six float32 values.
| Index | Feature |
|---|---|
| 0 | inventory ÷ inv_limit |
| 1 | spread, in ticks |
| 2 | depth imbalance of the top 3 levels, in [−1, 1] |
| 3 | mid change over the last interval, in ticks |
| 4 | mean absolute mid change per interval over the last 20, in ticks |
| 5 | fraction of the episode remaining |
Reward: the change in mark-to-mid PnL over the interval, minus
inventory_penalty × inventory², in ticks (a reward of 1 is one tick on one
share). An episode ends after horizon steps, following warmup steps in which
the agent does not quote.
Each reset draws a fresh market seed from the environment's random generator,
so reset(seed=s) makes a whole episode reproducible, and different seeds give
different market days.
A first episode¶
A hand-written policy: quote one tick out on both sides, and shift both quotes
two ticks against any inventory, the rule of MarketMaker:
import numpy as np
from microbook.rl import MarketMakingEnv
from microbook.sim import MarketConfig
env = MarketMakingEnv(MarketConfig.realistic(), horizon=2_000, inv_limit=40, inventory_penalty=2e-5)
obs, info = env.reset(seed=0)
print(env.action_space, env.observation_space.shape)
# MultiDiscrete([6 6]) (6,)
def skewed(obs):
shift = 2 if obs[0] > 0 else -2 if obs[0] < 0 else 0 # obs[0] is inventory / inv_limit
return np.array([np.clip(1 + shift, 0, 5), np.clip(1 - shift, 0, 5)])
total, done = 0.0, False
while not done:
obs, reward, done, truncated, info = env.step(skewed(obs))
total += reward
print(f"reward {total:.1f} ticks, PnL {info['pnl']:.2f}, inventory {info['inventory']}, volume {info['volume']}")
# reward -19.4 ticks, PnL -0.14, inventory 0, volume 274
One short episode is noisy; evaluate a policy over many seeds, and keep the seeds you train on apart from the ones you test on.
info carries the time, mid, inventory, PnL and traded volume after each step.
With render_mode="ansi", env.render() returns the same as one line of text.
Training a policy¶
The environment works with any Gymnasium-compatible library, such as
Stable-Baselines3. examples/rl_market_making.py needs nothing beyond numpy: it
trains a 7-parameter linear policy with the cross-entropy method (sample weight
vectors, score each on the same training seeds, refit to the best, repeat) in
about a minute, then evaluates it on 32 held-out seeds:
| Policy | PnL per episode ($) | Mean peak |inventory| |
|---|---|---|
| Random offsets | −5.57 ± 1.11 | 37.5 |
| Always join the touch | −11.01 ± 1.12 | 43.8 |
Hand-written MarketMaker rule (shift 2 ticks against inventory) |
1.00 ± 0.07 | 6.2 |
| Learned | 1.10 ± 0.05 | 6.7 |
Starting from "one tick out, no skew", the learner rediscovers the two-tick inventory shift and adds a strong lean toward the heavier side of the book and wider quotes when volatility is high. Paired by seed, it is ahead of the hand-written rule by 9.8 ± 7.2 ticks, which is not a significant difference. Quoting without inventory control loses money to the informed traders.
Choosing the settings¶
| Parameter | Default | Effect |
|---|---|---|
market |
MarketConfig() |
the market; MarketConfig.realistic() is harder and closer to real data |
horizon |
5,000 | steps per episode |
decision_interval |
10 | steps between decisions |
warmup |
200 | steps the market runs before the first decision |
max_offset |
5 | the largest offset, in ticks |
size |
5 | shares per quote |
inv_limit |
50 | inventory beyond which a side is not quoted |
inventory_penalty |
0 | quadratic penalty per step, in price units per share² |
latency |
0 | order-entry latency of the agent's quotes, in steps |
Latency matters a great deal: slow quotes go stale and get picked off. See Comparing strategies for how fast that happens for a hand-written market maker.