Quant Modelling [HFT] All modules
9 Module 09

Quant Infrastructure & KDB+/q

Modern markets emit billions of time-stamped events per day. This module follows the data from exchange to research desk, explains tick and time-series storage, and shows why columnar KDB+/q is the quant's database of choice.

Exam: Market Data Infrastructure Source: Session 9 KDB+/q

Why infrastructure matters

Every strategy you have studied โ€” alpha signals, backtesting, portfolio construction, machine learning โ€” rests on one question: where does the data come from, and how is it stored and served? Infrastructure is the bridge between raw market data and a deployable strategy.

Modern markets continuously emit many types of time-stamped data: trades, quotes, order-book updates and news events. The scale of a single trading day is enormous.

๐Ÿ“Š

Millions of trades

Every execution across every venue, timestamped to the microsecond.

๐Ÿ’ฌ

Millions of quotes

Bid/ask updates change far more often than trades print.

๐Ÿท๏ธ

Thousands of securities

Each name streams its own independent flow of events.

๐ŸŒŠ

Billions of data points

The combined daily total dwarfs anything a spreadsheet can hold.

โ–ฒ Can Excel handle this?

No. A worksheet caps out around a million rows and loads everything into memory. Billions of daily events demand purpose-built systems for four jobs: storage (keep it cheaply), processing (transform at scale), retrieval (find any slice fast) and analytics (compute on it in place).

How data flows: exchange to research

Almost every market-data architecture follows the same pipeline. Data is born at the exchange, cleaned by a feed handler, persisted in a database, then consumed by research and trading.

flowchart LR
  EX([Exchange]) --> FH([Feed Handler])
  FH --> DB[(Database)]
  DB --> RS([Research Team])
  DB --> TR([Traders])
  classDef s fill:#eef2ff,stroke:#4f46e5,stroke-width:1px,color:#3730a3;
  classDef d fill:#ecfdf5,stroke:#0d9488,color:#0d9488;
  class EX,FH,DB s
  class RS,TR d
      
The mental model for most market-data infrastructure: Exchange โ†’ Feed Handler โ†’ Database โ†’ Research / Trading.

What is an exchange?

An exchange is the venue where buyers and sellers meet โ€” NSE, BSE, NASDAQ, NYSE. Its core output for a quant is a continuous stream of two things: trades and quotes.

What is market data?

Market data splits into the two records every downstream system is built around:

โœ…

Trades

A completed execution: time, symbol, price, size.

โ†”๏ธ

Quotes

The current market: time, bid, ask, and the implied spread.

TimeSymbolPriceSize
09:30:01AAPL100.20500
09:30:02AAPL100.25300
09:30:03MSFT241.10150

A trade record โ€” exactly what was bought, at what price, in what size, and when.

TimeBidAskSpread
09:30:01100.10100.200.10
09:30:02100.15100.250.10
09:30:03100.18100.280.10

A quote record โ€” the best bid and ask, with the spread $= \text{ask} - \text{bid}$.

Feed handlers

Each exchange speaks its own wire format. A feed handler is the translator that sits between the raw exchange streams and the firm's internal systems. It performs four steps:

๐Ÿ“ก

Receive

Connect to and ingest the live exchange feed.

๐Ÿ”

Parse

Decode each exchange-specific message.

๐Ÿงน

Normalize

Map many formats into one internal schema, validating as it goes.

โžก๏ธ

Forward

Push clean data to the tick database and live apps.

โ˜… Why feed handlers matter

Different exchanges produce different formats. Feed handlers turn that chaos into one standardized stream, so every downstream consumer reads a single consistent schema rather than a dozen.

Tick data

โ–ฃ Definition โ€” Tick data

Tick data records every trade, every quote update and every market event, each stamped with an exact timestamp. It is the maximum-detail view of the market โ€” nothing is summarised or thrown away.

A short slice of a tick stream interleaves event types down to the millisecond:

TimestampEvent
09:30:00.001Trade
09:30:00.002Quote
09:30:00.004Trade
09:30:00.006Book update
09:30:00.008Quote

Tick vs OHLC

The alternative to ticks is OHLC โ€” Open, High, Low, Close โ€” a periodic summary over a fixed interval (e.g. one bar per minute). The trade-off is detail versus compactness.

DimensionTick dataOHLC data
GranularityEvery market eventPeriodic summary
StorageHigh storage needCompact
Best forMicrostructure analysisCharting
TimingExact event timeInterval-based
๐Ÿ”ฌ

Advantages of tick data

Enables intraday analysis, market microstructure, liquidity research and execution analysis โ€” questions OHLC simply cannot answer.

โš ๏ธ

Challenges of tick data

Massive storage, heavy memory usage, demanding query performance and serious infrastructure requirements.

โ—† Case study โ€” large-trade investigation

A large block trade prints. What happened in the 30 seconds before it? Answering needs historical ticks, accurate timestamps and fast queries: at T-30s normal activity, at T-10s quotes shift, the large trade prints, then T+10s impact and T+30s recovery. Only tick data preserves the timeline finely enough to reconstruct this.

Time-series data

โ–ฃ Definition โ€” Time-series data

Time-series data is indexed by time: events occur sequentially and time is the primary key. Prices, trades and quotes are all time-series โ€” each row's identity is fundamentally when it happened.

Time matters because trading is about sequence and causality. Around any event โ€” a trade, a news headline โ€” we constantly ask three time-ordered questions:

โฎ๏ธ

Before

What was the context leading into the event?

โบ๏ธ

During

What exactly happened at the moment it occurred?

โญ๏ธ

After

How did the market react in the aftermath?

Why KDB+ exists

KDB+ (queried with the language q) is a database built specifically for this problem. It was created because three pressures collided.

flowchart LR
  A([Massive market data]) --> P{{Problem}}
  B([Slow traditional queries]) --> P
  C([Real-time requirements]) --> P
  P --> K([KDB+ solution])
  classDef s fill:#eef2ff,stroke:#4f46e5,stroke-width:1px,color:#3730a3;
  classDef d fill:#ecfdf5,stroke:#0d9488,color:#0d9488;
  class A,B,C,P s
  class K d
      
KDB+ exists because market data is both very large and very time-sensitive โ€” general-purpose databases struggle on both at once.

The core idea is simple: store data efficiently, query it quickly, analyse it rapidly. The power comes from raw speed and a design that fits time-series naturally.

โšก

Why quants use it

Speed, scale, real-time analytics and historical research in one engine.

๐Ÿฆ

Where it is used

Hedge funds, investment banks, market makers and HFT firms.

Columnar vs row storage

The single biggest reason KDB+ is fast on market data is that it is columnar. Traditional databases are row-based โ€” a record's fields are stored together โ€” while KDB+ stores each column contiguously.

flowchart TB
  subgraph ROW [Row storage - reads entire rows]
    direction LR
    R1[time, sym, price, size]
    R2[time, sym, price, size]
    R3[time, sym, price, size]
  end
  subgraph COL [Columnar storage - reads only needed columns]
    direction LR
    C1[time time time]
    C2[sym sym sym]
    C3[price price price]
    C4[size size size]
  end
  ROW --> COL
  classDef s fill:#eef2ff,stroke:#4f46e5,stroke-width:1px,color:#3730a3;
  classDef d fill:#ecfdf5,stroke:#0d9488,color:#0d9488;
  class R1,R2,R3 s
  class C1,C2,C3,C4 d
      
Row storage keeps complete records together; columnar storage groups each field so analytics scan only the columns they need.
โ—† Case study โ€” average spread over 10 billion rows

You have 10 billion rows and 20 columns, but computing average spread needs only the bid and ask columns. A row store must read all 20 columns of every row; a columnar store scans just 2 of 20 โ€” an order-of-magnitude less I/O for the same answer. This "read only what you need" property is why columnar wins on analytics.

SQL โ†” q: the same logic, two syntaxes

If you know SQL, you already know most of q. KDB+ tables look like SQL tables โ€” the difference is they are column-oriented and tuned for symbols and time. Symbols in q are written with a leading backtick, e.g. `AAPL; that backtick is normal q syntax for a symbol literal.

Filtering โ€” WHERE โ†’ where

-- SQL
SELECT * FROM trades WHERE symbol='AAPL';

/ q
select from trades where sym=`AAPL

Grouping & averaging โ€” GROUP BY โ†’ by, AVG(price) โ†’ avg price

-- SQL
SELECT symbol, AVG(price) FROM trades GROUP BY symbol;

/ q
select avg price by sym from trades

Aggregating โ€” SUM(size) โ†’ sum size

-- SQL
SELECT symbol, SUM(size) FROM trades GROUP BY symbol;

/ q
select sum size by sym from trades

Time filtering โ€” BETWEEN โ†’ within

-- SQL
SELECT * FROM trades WHERE time BETWEEN '09:30' AND '10:00';

/ q
select from trades where time within 09:30 10:00
ConceptSQLKDB / q
FilterWHEREwhere
GroupGROUP BYby
AverageAVG(price)avg price
Time filterBETWEENwithin
โ— SQL vs KDB in a sentence

SQL is general-purpose, row-based, built for business analytics measured in seconds and used broadly. KDB is time-series, column-based, built for market analytics measured in milliseconds and used mostly in finance.

VWAP and the research workflow

A canonical analytic both SQL and q solve identically is VWAP โ€” the Volume-Weighted Average Price. It weights every trade price by the size traded, so big prints count more than small ones.

Volume-weighted average price $$ \text{VWAP}=\dfrac{\sum_i (P_i \times V_i)}{\sum_i V_i} $$
Worked example VWAP from three trades
  1. The trades are price ร— size pairs: $100.20 \times 500$, $100.25 \times 300$, $100.30 \times 200$.
  2. Numerator $\sum_i (P_i \times V_i)$: $100.20\times500 = 50100$; $100.25\times300 = 30075$; $100.30\times200 = 20060$.
  3. Sum the numerator: $50100 + 30075 + 20060 = 100235$.
  4. Denominator $\sum_i V_i = 500 + 300 + 200 = 1000$.
  5. Divide: $\text{VWAP} = \dfrac{100235}{1000} = 100.235$.
VWAP = \$100.235. It sits just below the simple average price of \$100.25 because the largest trade (500 shares) executed at the lowest price (\$100.20), pulling the volume-weighted average down toward it.

In practice VWAP is computed inside a Python + q loop. KDB stores and serves the data; Python explores, builds features and evaluates.

flowchart LR
  MD([Market Data]) --> KDB[(KDB+)]
  KDB --> PY([Python])
  PY --> FE([Features])
  FE --> SG([Signals])
  SG --> BT([Backtest])
  classDef s fill:#eef2ff,stroke:#4f46e5,stroke-width:1px,color:#3730a3;
  classDef d fill:#ecfdf5,stroke:#0d9488,color:#0d9488;
  class MD,KDB,PY s
  class FE,SG,BT d
      
The Python + KDB workflow: query historical data, build features, generate signals, evaluate performance.

That four-step loop โ€” query historical data โ†’ build features โ†’ generate signals โ†’ evaluate performance โ€” is the typical quant research day.

Research vs production

DimensionResearchProduction
ToolingFlexible notebooksReliable services
MindsetExplorationMonitoring
MistakesSmall mistakes acceptableControls required
Optimised forAnalyst speedSystem stability
โœฆ A day in the life of a quant

08:30 query historical data โ†’ 10:00 build features โ†’ 14:00 research signals โ†’ 16:00 backtest strategies โ†’ 18:00 review results. The same infrastructure (KDB for data, Python for analysis) powers every stage.

Self-check: Why is a columnar store faster than a row store for "average spread across all symbols"?
Average spread needs only the bid and ask columns. A columnar store reads just those two columns; a row store must read every field of every row (all 20 columns over 10 billion rows). Less data read means less I/O and a far faster query.
Self-check: Translate SELECT symbol, AVG(price) FROM trades GROUP BY symbol into q.
select avg price by sym from trades. GROUP BY becomes by, AVG(price) becomes avg price, and the grouping column sym appears after by.
Self-check: Three trades โ€” 100.20ร—500, 100.25ร—300, 100.30ร—200. What is the VWAP?
Numerator $= 50100 + 30075 + 20060 = 100235$; denominator $= 1000$; VWAP $= 100235 / 1000 = \mathbf{100.235}$.

Key takeaways

โ˜… Remember
  • Markets generate massive data โ€” billions of time-stamped events daily, far beyond Excel.
  • Data flows Exchange โ†’ Feed Handler โ†’ Database โ†’ Research / Trading.
  • Tick data preserves detail; OHLC summarises. Tick is essential for microstructure.
  • KDB+ is built for time-series and is columnar, so it scans only the columns a query needs.
  • SQL concepts transfer to q: WHEREโ†’where, GROUP BYโ†’by, AVGโ†’avg, BETWEENโ†’within.
  • Infrastructure enables research โ€” it turns raw data into testable trading ideas.