Market Index (pm-index)¶
Objective¶
Configure and operate the pm-index calculation process, observe a
cap-weighted index updating in real time, apply corporate actions without
disrupting the index level using pm-index-admin-cli, and analyse historical
data with pm-index-cli and pm-stats-cli.
You will practice:
- generating an index config with
pm-config-gen - starting
pm-indexand verifying initialisation - querying the live index level through the
INDEXgateway command - watching the index move as trades execute
- applying a stock split and a cash dividend corporate action with
pm-index-admin-cli - adding and removing index constituents without restarting, with
pm-index-admin-cli - querying structural/audit history with
pm-index-cli - querying level and EOD time-series history with
pm-stats-cli - exporting history to CSV and JSON for offline analysis
Background reading
Prerequisites¶
- Chapters 01–25 completed. This chapter generates its own configuration; stop the processes of chapter 25 first.
- Every constituent symbol must have
outstanding_sharesset insymbols:. - For Exercise 8 (level/EOD queries via
pm-stats-cli),pm-statsmust also be running (see Chapter 15) — it needs to be up before the trades happen so it can capture theindex.updateticks live.
Recommended startup order for this chapter:
- Generate
engine_config.yaml(Exercise 1). - Start
pm-engine. - Start
pm-index. - Start
pm-stats(needed later for Exercise 8's level/EOD history). - Connect two gateway terminals (one TRADER, one ADMIN).
Background¶
pm-index is a standalone process — it never sends commands to the engine.
It subscribes to trade events published by pm-engine on port 5556 and
recomputes configured indices in real time.
Cap-weighted formula¶
Each index level is:
The divisor is chosen at first launch so the level equals base_value. It
changes only when a corporate action alters share structures. This keeps the
index level continuous across structural events.
Key processes and ports¶
pm-engine PUB :5556 ──► pm-index PUB :5558 ──► pm-md-gwy ──► CALF clients
PULL :5559 ◄── ADMIN gateways
ADMIN gateways send corporate-action and history-request commands to pm-index
on the PULL socket (port 5559).
Two different history stores
pm-index writes a JSONL file per index, but it only records
structural/audit events — INIT, CORP_ACTION, ADD_CONSTITUENT,
DELIST. It does not write intraday level ticks or end-of-day OHLC
records to that file. Those are captured instead by pm-stats, which
subscribes to the live index.update broadcast and records every tick
(plus the EOD-forced publish) into its own SQLite database. This means
pm-stats must be running while trades occur for level/EOD history to
exist later — unlike the JSONL file, which pm-index-cli can read at any
time, even offline.
Exercise 1: Configure an Index¶
Generate a complete config with one index, three constituents, and outstanding
shares. pm-index also needs a reference price for every constituent, and
pm-config-gen only writes one by seeding it from a market maker's midpoint:
hence the MM01:MARKET_MAKER participant and the --seed-mm-mid-range /
--seed-last-prices-from-mm flags. --no-mm-seed-quotes keeps the book empty
at startup. AMZN is configured but left out of the index: Exercise 7 adds
it, and pm-index only accepts a constituent the exchange is configured to
trade.
pm-config-gen \
--symbols AAPL MSFT TSLA AMZN \
--participants TRADER01 OPS01:ADMIN MM01:MARKET_MAKER \
--outstanding-shares AAPL:15000000000 \
--outstanding-shares MSFT:7400000000 \
--outstanding-shares TSLA:3200000000 \
--seed-mm-mid-range 100:400 \
--seed-last-prices-from-mm \
--no-mm-seed-quotes \
--sessions-enabled \
--seed 20260625 \
--index EDU100:"EduMatcher broad index" \
--index-constituents EDU100:AAPL,MSFT,TSLA \
--output engine_config.yaml --force
Back up, check, deploy — then restart
This chapter starts from a fresh configuration (its operator is OPS01),
and --force replaces your engine_config.yaml: save a copy first if you
want to come back to it (cp engine_config.yaml engine_config.before-ch26.yaml).
As always, nothing changes until you deploy it and restart the engine:
pm-cverifier engine_config.yaml, then pm-config-deploy engine_config.yaml. Sessions are enabled, so the restarted engine starts in CLOSED: open
the market from the operator console (pm-admin --id OPS01, then
SESSION|STATE=PRE_OPEN and SESSION|STATE=CONTINUOUS).
Open engine_config.yaml and locate the indices: block. It should look like:
indices:
- id: EDU100
description: "EduMatcher broad index"
base_value: 1000.0
publish_interval_sec: 1.0
history_file: data/indexes/EDU100_history.jsonl
state_file: data/indexes/EDU100_state.json
constituents:
- AAPL
- MSFT
- TSLA
Outstanding shares
Every constituent must have outstanding_shares set in symbols:.
The default pm-config-gen behaviour adds this from --outstanding-shares.
Without it pm-index will refuse to start.
Checkpoint: engine_config.yaml contains a valid indices: block with all three symbols.
Exercise 2: Start pm-index¶
In a dedicated terminal, start the index calculation process:
Without -v, pm-index logs at WARNING and starts silently. With it, the
startup includes:
loaded 1 index runtime config(s)
index ready index_id=EDU100 constituents=3 level=1000.0
received initial engine session status=CLOSED
(Each line is preceded by the usual timestamp, level and logger name.)
The INIT record has been written to $EDUMATCHER_DATA_DIR/indexes/EDU100_history.jsonl
(the config's relative data/indexes/... path resolves under the data directory).
Verify:
{"type":"INIT","ts_ns":...,"index_id":"EDU100","level":1000.0,"base_value":1000.0,"divisor":8187542000.0,"constituents":["AAPL","MSFT","TSLA"]}
Checkpoint: pm-index running, INIT record visible in history file.
Exercise 3: Query the Live Index Level¶
Connect your TRADER01 gateway and run the INDEX command:
pm-index publishes a level when a constituent trades (and once at the end of
the day), not on a timer. Until the first trade, INDEX answers
No index data received yet. Is pm-index running? — that does not mean
pm-index is down. Come back to this exercise's output after Exercise 4's first
trade. Expected response (close to 1000, because the market maker quotes
around the seeded reference prices the index started from):
Fields shown:
| Field | Description |
|---|---|
| Timestamp | UTC time of the reading |
| Index ID | EDU100 |
| Level | Current calculated level |
| Change / % | Change from day open (empty before first open) |
| O / H / L | Day open, high, low (empty before continuous trading begins) |
| Session state | Current engine session state |
The INDEX command works in pm-alf-console under any authenticated gateway
role (TRADER, ADMIN, or read-only). The separate pm-admin operator console
has no INDEX command (Unknown command 'INDEX'); use
pm-alf-console --id OPS01 when you want it as the operator. It prints only
the most recent index update this console has received, as a single line,
so it is a spot check, not a list of constituents or of indices.
Checkpoint: INDEX command returns a level for EDU100.
Exercise 4: Watch the Index Move¶
Move the session into CONTINUOUS (if the scheduler hasn't already done so —
from CLOSED that is PRE_OPEN first, then CONTINUOUS). The books start
empty (--no-mm-seed-quotes), so connect pm-alf-console --id MM01 and give
each symbol a market, with prices near the seeded ones (print the seeded
prices with grep -E "last_(buy|sell)_price" engine_config.yaml), for example
QUOTE|SYM=AAPL|BID=<p-1>|ASK=<p+1>|BID_QTY=1000|ASK_QTY=1000|TIF=DAY|QUOTE_ID=Q-AAPL
and the same for MSFT and TSLA. Then execute a few trades:
[OPS01|ADMIN]> SESSION|STATE=PRE_OPEN
[OPS01|ADMIN]> SESSION|STATE=CONTINUOUS
[TRADER01]> NEW|SYM=AAPL|SIDE=BUY|TYPE=MARKET|QTY=500
[TRADER01]> NEW|SYM=MSFT|SIDE=BUY|TYPE=MARKET|QTY=300
[TRADER01]> NEW|SYM=TSLA|SIDE=SELL|TYPE=MARKET|QTY=200
After each fill, query the index again:
Observe the level changing as trades update the constituent prices. The index is
recalculated on every trade but published at most once per second (the
publish_interval_sec throttle).
Tip
Run INDEX several times in quick succession to see the throttle in action —
the level updates, but the published timestamp advances at most once per second.
Checkpoint: index level changed after trades; querying INDEX shows the new value.
Exercise 5: Apply a Stock Split¶
Suppose AAPL announces a 2-for-1 stock split. Without adjustment, the index would drop by ~50% when AAPL's price halves — which is wrong because no value was destroyed.
No gateway command for corporate actions
Unlike INDEX|HISTORY (Exercise 10), corporate actions and constituent
changes have no pm-alf-console command, no pm-admin/pm-admin-cli
subcommand, and no ALF/CALF wire message — there is no CORP_ACTION|...
line you can type at a gateway prompt. Instead, use the dedicated
pm-index-admin-cli tool, which
talks directly to pm-index's PULL socket (port 5559). See
Market Index → Applying corporate actions.
Apply the split:
You'll be shown a confirmation prompt before the command is sent. Add -y to
skip it, or --dry-run to preview the payload without sending — both are
options of the tool itself, so they go before the sub-command
(pm-index-admin-cli --id OPS01 -y split …). The command
blocks for the index.corp_action_ack.OPS01 response and prints the result.
pm-index applies the action in-process, publishes an updated index value
live, and writes a CORP_ACTION record to the structural/audit history file.
Query the index immediately after, from any gateway terminal:
The level should be unchanged (or differ by only rounding). Now check that the divisor was adjusted in the history file:
You should see old_divisor and new_divisor in the record, and the two
values should be approximately equal (differing only by integer-rounding
of the new share count). This is expected: a split doubles AAPL's outstanding
shares and halves AAPL's price, so AAPL's contribution to the aggregate cap
(shares × price) is unchanged — no divisor adjustment is needed to keep the
index level continuous. Contrast this with ADD/DELIST (Exercise 7), where
the aggregate cap genuinely changes and the divisor must move to compensate.
Apply during PRE_OPEN
Applying a corporate action mid-session means one more trade at the old
price may be processed before the divisor update. Best practice is to apply
all corporate actions during PRE_OPEN.
The index has split; the market has not
pm-index now prices AAPL at half its old price, with twice the shares.
The exchange itself knows nothing of the split: MM01 still quotes the
old price, and the next AAPL trade at that price makes the index jump
by about half of AAPL's weight (+54% here). On a real exchange the
market reopens at the adjusted price. Do the same — re-quote AAPL at
half before anyone trades it (for a seeded 348.83, about 173.92 / 174.92):
A trade at the new price leaves the level where it was.
Checkpoint: compare the level field of the CORP_ACTION
record to the INDEX reading you took just before applying the split — the
absolute difference should be at most a few cents (rounding only), never a
~50% jump. CORP_ACTION record confirmed written to history, and AAPL
re-quoted at its post-split price.
Exercise 6: Apply a Cash Dividend¶
Apply a $2.50 cash dividend for MSFT — same pm-index-admin-cli mechanism
as Exercise 5, no gateway command:
A cash dividend reduces the effective price by the dividend amount. The divisor is adjusted to compensate so the index level is preserved.
Checkpoint: index level preserved across dividend adjustment.
Under the hood: ExchangeCommandClient
pm-index-admin-cli is a thin wrapper over the same
ExchangeCommandClient class pm-admin-cli uses internally. If you ever
need to script a corporate action directly (e.g. from a test harness),
the equivalent code is:
from edumatcher.commands import ExchangeCommandClient
client = ExchangeCommandClient("OPS01")
result = client.index_corp_action(
"EDU100", "CASH_DIVIDEND", "MSFT",
dividend_per_share=2.50,
)
print("CORP_ACTION result:", result)
client.close()
Note pm-index's PULL socket has no connect()/auth handshake, unlike
the engine socket pm-admin-cli talks to.
Exercise 7: Add and Remove a Constituent¶
Constituent changes also use pm-index-admin-cli
— no gateway command exists for these either.
Add AMZN to the index¶
Adding a constituent adjusts the divisor so the level does not jump at the moment of addition. You must supply the new shares and a reference price:
INDEX prints only the level, not the constituents, so check the change in
the history instead (the ADD OK reply also prints the new divisor):
Nobody trades AMZN in this chapter, so its price stays at the reference price
you gave until it trades; it contributes to the cap at 195.00. (delist
needs no price.) A symbol the exchange is not configured to trade is refused
(REJECTED AMZN is not a configured symbol), so a typo cannot become a
constituent that never moves — which is why Exercise 1 configured AMZN.
Remove TSLA from the index¶
Confirm it with pm-index-cli --config engine_config.yaml events --index EDU100 --type DELIST,
and run INDEX again: the level should be the same as before the change.
Checkpoint: AMZN added and TSLA removed without visible discontinuity in the index level.
Exercise 8: Query History with pm-index-cli and pm-stats-cli¶
Two tools cover two different slices of index history:
pm-index-clireads the JSONL structural/audit file directly from disk —pm-indexdoes not need to be running. It only knows aboutINIT,CORP_ACTION,ADD_CONSTITUENT, andDELISTrecords.pm-stats-clireads level ticks and end-of-day OHLC rollups frompm-stats' SQLite database. Those rows only exist ifpm-statswas running while the ticks happened — it captures them live from theindex.updatebroadcast, it does not replay history after the fact.
If you started pm-stats back in the Prerequisites step, it has been
recording every EDU100 tick since. If you skipped that step, go start it
now — pm-stats-cli will simply return no rows for anything that happened
before it was running.
List configured indices¶
View recent intraday level snapshots¶
Every recorded tick (throttled to publish_interval_sec, same as the live
INDEX command) is available via pm-stats-cli index-snapshots:
Sample table output:
ts | index_id | level | aggregate_cap | divisor | session_state | day_open | day_high | day_low
------------------------------+----------+------------------+---------------+------------+---------------+-----------------+------------------+----------------
2026-06-25T10:00:38.798+00:00 | EDU100 | 1001.8320516707 | 8202542000000 | 8187542000 | CONTINUOUS | 1001.8320516707 | 1001.8320516707 | 1001.8320516707
2026-06-25T10:00:40.511+00:00 | EDU100 | 1002.73586382824 | 8209942000000 | 8187542000 | CONTINUOUS | 1001.8320516707 | 1002.73586382824 | 1001.8320516707
...
You can list which index IDs pm-stats has actually recorded with:
View EOD records¶
pm-index no longer writes an end-of-day record to its own JSONL file —
that file is structural/audit only now. Instead, pm-stats treats the
EOD-forced publish like any other tick and rolls the day's ticks up into
one daily OHLC row. Query it with pm-stats-cli index-daily:
date | index_id | open_level | high_level | low_level | close_level | close_session_state | update_count
-----------+----------+-----------------+------------------+-----------------+-----------------+---------------------+-------------
2026-06-25 | EDU100 | 1001.8320516707 | 1002.73586382824 | 1001.8320516707 | 1002.3633466552 | CONTINUOUS | 7
Add --wide to also show the opening/closing aggregate market cap:
View all structural events¶
This shows INIT, CORP_ACTION, ADD_CONSTITUENT, and DELIST records.
You should see the split, dividend, add, and delist from earlier exercises.
Filter to only corporate actions:
Export for offline analysis¶
The global --format option turns any of these into CSV or JSON.
Export EOD data to CSV¶
Export intraday data to JSON¶
pm-stats-cli --format json index-snapshots --index-id EDU100 \
| python3 -c "
import json, sys
rows = json.load(sys.stdin)
print(f'{len(rows)} snapshots')
if rows:
print(f'First: {rows[0][\"ts\"]} level={rows[0][\"level\"]}')
print(f'Last: {rows[-1][\"ts\"]} level={rows[-1][\"level\"]}')
"
Date-range query¶
For a single trading day, --date is the simplest filter:
For an arbitrary time window, use --from/--to with full ISO-8601
timestamps instead:
pm-stats-cli index-snapshots --index-id EDU100 \
--from 2026-06-25T09:30:00+00:00 \
--to 2026-06-25T16:00:00+00:00 \
--limit 500
Checkpoint: pm-index-cli returns structural
events; pm-stats-cli index-snapshots and index-daily return level and EOD
rows for EDU100; the CSV and JSON exports contain the same data.
Exercise 9: Two Indices¶
Configure a second, narrower index alongside EDU100:
pm-config-gen \
--symbols AAPL MSFT TSLA AMZN \
--participants TRADER01 OPS01:ADMIN MM01:MARKET_MAKER \
--outstanding-shares AAPL:15000000000 \
--outstanding-shares MSFT:7400000000 \
--outstanding-shares TSLA:3200000000 \
--seed-mm-mid-range 100:400 \
--seed-last-prices-from-mm \
--no-mm-seed-quotes \
--sessions-enabled \
--seed 20260625 \
--index EDU100:"EduMatcher broad index" \
--index-constituents EDU100:AAPL,MSFT,TSLA \
--index TECH2:"Technology pair" \
--index-constituents TECH2:AAPL,MSFT \
--index-base-value TECH2:500.0 \
--index-interval TECH2:2.0 \
--output engine_config.yaml --force
Deploy the new configuration (pm-index reads the compiled artifact, so
without this it still loads one index), then restart pm-index with --reset
to clear state and re-initialise. Stop the running pm-index first:
--reset discards divisors
--reset removes all state files. The divisors for both indices are
recomputed from scratch using current reference prices. Use only when
you intentionally want a clean slate.
Both indices start at their base value (pm-index -v prints
index ready index_id=EDU100 … level=1000.0 and
index ready index_id=TECH2 … level=500.0), but nothing is published until a
constituent trades. Make two trades in MSFT a few seconds apart (re-quote
MM01 if its quote has gone; TECH2 publishes at most every 2 seconds, so the
first trade right after the restart may only reach EDU100), then run
INDEX in the TRADER terminal:
You see one line, for whichever index published last — TECH2 here, EDU100
just as often (both publish after an MSFT trade, TECH2 at most every 2
seconds). INDEX is not a multi-index listing; use pm-index-cli indices to list both indices
and pm-stats-cli index-daily to verify recorded daily data. On startup,
pm-index requests the engine's current session status and publishes an
initial update for each configured index, so a restart during CONTINUOUS
does not leave the index reporting the default phase until the next
transition. Before that status reply arrives, its phase is UNKNOWN, not a
misleading PRE_OPEN.
Use pm-index-cli to list both configured indices, and pm-stats-cli to
confirm pm-stats is capturing ticks for both:
pm-index-cli indices always shows every index in the config. pm-stats-cli
index-daily with no --index-id filter shows the daily rollup for every
index pm-stats has recorded — useful here to confirm both EDU100 and
TECH2 are being tracked. pm-stats-cli index-snapshots, by contrast,
requires an explicit --index-id (it returns raw ticks, not a summary, so a
single-index scope keeps the output meaningful).
Checkpoint: INDEX shows the most recently received update; pm-index-cli indices lists both EDU100 and TECH2; pm-stats-cli index-daily confirms daily rows for both.
Exercise 10: History Query via the Gateway¶
pm-index also accepts history requests directly through the ADMIN gateway.
These go over the PULL socket (port 5559) and return records inline:
Run it in a pm-alf-console session (pm-alf-console --id OPS01), not in
pm-admin, which has no INDEX command. Leave pm-admin --id OPS01 first:
both log on as OPS01, and the engine takes one connection per ID. Without a prior index update seen by
that console it answers INDEX|HISTORY requires INDEX=<id> or prior index.update.,
so a console you have just started needs the index named:
INDEX|HISTORY|INDEX=EDU100. With one, it returns the last 30 days of
structural/audit records — INIT,
CORP_ACTION, ADD_CONSTITUENT, DELIST — for whichever index you last
saw an INDEX update for (or pass INDEX=<id> explicitly, e.g.
INDEX|HISTORY|INDEX=EDU100).
Returns structural/audit records within the specified date range, newest
last. FROM is local midnight at the start of its date; date-only TO
includes the entire date, through the final nanosecond before the next local
midnight. FROM=2026-06-25|TO=2026-06-25 therefore returns records from that
day. Exact timestamp bounds on the history request are inclusive.
No level or EOD ticks here
INDEX|HISTORY never returns intraday level ticks or end-of-day OHLC
rows — only the same four structural/audit record types you saw in
Exercise 8's pm-index-cli events output. For level and EOD history,
use pm-stats-cli index-snapshots / pm-stats-cli index-daily instead;
the gateway command has no equivalent for that data.
Gateway vs pm-index-cli vs pm-stats-cli
The gateway INDEX|HISTORY command is convenient for a quick structural
lookup in the operator terminal without leaving your session. For richer
filtering, multi-index queries, CSV/JSON export, or scripting workflows,
use pm-index-cli instead — it reads the structural/audit JSONL file
directly without going through the network. For level and EOD
time-series data, neither of those tools applies — use pm-stats-cli.
Checkpoint: INDEX|HISTORY returns structural/audit records only; date-range filter works.
Summary¶
| Concept | Command / file |
|---|---|
| Start index process | pm-index |
| Re-initialise from scratch | pm-index --reset |
| Live level query | INDEX (any gateway) |
| Structural/audit history query (gateway) | INDEX\|HISTORY, INDEX\|HISTORY\|FROM=…\|TO=… — INIT/CORP_ACTION/ADD_CONSTITUENT/DELIST only |
Stock split (no gateway command — use pm-index-admin-cli) |
pm-index-admin-cli --id ID split --index IDX --sym SYM --ratio N:M |
| Cash dividend | pm-index-admin-cli --id ID dividend --index IDX --sym SYM --amount … |
| Shares issuance / buy-back | pm-index-admin-cli --id ID shares --index IDX --sym SYM --new-shares … (or --delta …) |
| Add constituent | pm-index-admin-cli --id ID add --index IDX --sym SYM --shares … --price … |
| Remove constituent | pm-index-admin-cli --id ID delist --index IDX --sym SYM |
| List configured indices | pm-index-cli --config … indices |
| Structural/audit events | pm-index-cli --config … events [--type TYPE] |
| Intraday level snapshots | pm-stats-cli index-snapshots --index-id ID |
| Daily OHLC (EOD) rollup | pm-stats-cli index-daily [--index-id ID] |
| List indices seen by pm-stats | pm-stats-cli index-ids |
| CSV export (structural events) | pm-index-cli --config … events --format csv > out.csv |
| CSV export (daily OHLC) | pm-stats-cli --format csv index-daily > out.csv |
Reflection¶
Why does a stock split leave the index divisor roughly unchanged while a cash dividend or shares issuance actually changes it? What would happen to the index's continuity (its "don't jump on non-economic events" property) if the divisor were recalculated the same way for all four corporate action types?
See Also¶
In this book:
- Chapter 15 — Statistics & Reporting — starting
pm-statsand querying its SQLite database
Operator's Guide:
- Market Index — Operator's Guide — full reference for config fields, formulas, and history record types
- Index Admin CLI — full
pm-index-admin-clisubcommand reference,--dry-run, and confirmation-prompt behaviour - pm-index-cli reference —
events/indicessubcommands, column descriptions, and output-format options - Statistics and Reporting —
pm-stats-cli index-daily/index-snapshots/index-idsreference - Engine Configuration —
indices:YAML field reference
Reference Manual:
- Process Reference — pm-index — socket layout and message types