Real-Time Market Data Ingestion and Processing: From Cleaning to Visualization
This article explores a practical approach to ingesting and processing real-time market data for quantitative research, trading terminals, and data visualization. Using a U.S. stock quote snapshot as an example, it covers field modeling, ingestion method selection, deduplication, out-of-order handling, caching architecture, and monitoring strategies to ensure data accuracy and system reliability.
In quantitative research, market data terminals, and data visualization projects, the ingestion and processing of real-time market data determine the reliability of upper-layer applications. This article uses a U.S. stock quote snapshot as an example to illustrate a deployable processing solution. A snapshot typically includes the security name, ticker symbol, trading market, base currency, latest price, price change, percentage change, and update time. Although these fields seem simple, every design decision affects data accuracy and system stability.
1. Market Data Field Modeling
Identifier fields include the security name, ticker symbol, and market. The same ticker symbol may correspond to different securities in different markets, so the market field is part of the unique identifier. It is recommended to use “market + ticker” as the primary key for the security, and a data source field for tracing the origin.
Price fields include the latest price, open price, high price, low price, and previous close price. Prices and price changes should be saved using fixed-point numbers (Decimal) with a clearly defined scale (e.g., retaining 4 decimal places for stock prices). Floating-point numbers can introduce errors during accumulation and comparison, making them unsuitable for monetary data.
It is not recommended to directly persist the percentage change. It should be calculated dynamically during queries using “(latest price - previous close price) / previous close price”. A null value should be returned if the previous close price is empty or zero. The calculation basis for the previous close price on suspension days, IPO days, and ex-dividend days needs to be verified separately; otherwise, the percentage change will be distorted.
The currency field must be stored independently. In cross-market scenarios, a single aggregated metric might mix USD, HKD, and CNY. Only by retaining the original currency can accurate conversion be achieved.
Time fields need to distinguish three types of time: exchange matching time, data source push time, and system receiving time. These should be uniformly stored as UTC timestamps, with precision recommended down to the millisecond. The presentation layer can then convert them based on the user’s or exchange’s time zone. A trading calendar should also be maintained separately to determine market closures, half-day markets, and holidays.
2. Choosing Data Ingestion Methods
Market data ingestion typically involves two methods: push and polling. Push uses long connections for subscriptions, offering low latency but requiring handling for reconnection and message duplication. Polling uses scheduled requests to fetch snapshots, which is simple to implement, but latency and request costs are affected by the polling interval. The table below lists the dimensions to compare during selection.
| Dimension | Push (Long Connection) | Polling (Scheduled Fetch) |
|---|---|---|
| Latency | Low, depends on push frequency | Limited by polling interval |
| Idempotency | Requires handling duplicate pushes | Same snapshot may be returned repeatedly |
| Out-of-order | Common, needs timestamp validation | Relatively rare, but still requires validation |
| Rate Limiting | Limited by connections and subscriptions | Limited by request frequency |
| Implementation Complexity | High, requires heartbeat and reconnection | Low |
High-frequency scenarios usually opt for push, while low-frequency dashboards or data backfill tasks can use polling. Both can coexist: push handles real-time updates, and polling periodically checks for and fills gaps.
3. Deduplication, Out-of-Order, and Exception Handling
Deduplication uses an idempotency key. The idempotency key cannot just be “ticker + timestamp”; otherwise, securities with the same ticker in different markets might be misjudged as duplicates under the same timestamp. It is recommended to use a combination of “market + ticker + source + timestamp + sequence number”. If the data source does not provide a sequence number, use “market + ticker + source + exchange timestamp”, and agree that within the same timestamp, the receiving order prevails.
Out-of-order processing is based on the timestamp carried by the data, not the arrival order. If the timestamp of a new snapshot is earlier than the stored version, discard it and log the event. If timestamps are identical but content differs, handle it according to the priority agreed upon with the data source and log the conflict.
Anomalous values must be directed to a quarantine area rather than being written directly to the primary database. The following rules can serve as a starting point, though specific thresholds should be adjusted based on security type and historical volatility:
- A single price change exceeding a certain ratio of the previous close price (e.g., 20%) triggers entry into the quarantine area and an alert;
- If the snapshot time is later than the receiving time (clock超前/skew) by more than 1 second, or earlier than the receiving time by more than a set value (e.g., 5 minutes), it enters the quarantine area;
- Prices that are negative or zero, or currencies that do not match the market, are directly rejected.
During trading suspensions or prolonged periods without transactions, the latest snapshot should be retained and marked with a status such as “Suspended”, “No Trade”, or “Delayed”. Do not overwrite old values with null values, or the frontend will experience price flashing or dropping to zero.
4. Caching and Storage Architecture
Market data involves heavy read and write operations, with a clear distinction between hot and cold data. A tiered storage approach is recommended:
- Hot data: The latest snapshots are placed in an in-memory cache, keyed by “market + ticker”, for millisecond-level reads;
- Warm data: Minute-level K-lines are written to a time-series database to support aggregated queries by time range;
- Cold data: Historical details are archived to object storage, partitioned by market and date, for retrospective analysis.
The cache write order is critical. The recommended flow is: complete validation first, then write to the persistence layer, and update the cache only after the persistence layer succeeds. This prevents the cache from containing values that do not exist in the database. If the persistence layer write fails, record the failure event and push it to a compensation queue; do not update the cache directly.
Stale value backfill is a common issue. When a cache query misses, it falls back to the database and then backfills the cache. If a new snapshot is being written at this time, the stale value might overwrite the new value. The solution is to save a version number or timestamp for each snapshot and use conditional updates when writing to the cache: only allow overwriting if the new version timestamp is greater than the timestamp in the cache.
Below is a minimal example demonstrating the processing flow and the responsibilities of key functions.
from dataclasses import dataclassfrom decimal import Decimal@dataclass(frozen=True)class Quote:market: strcode: strsource: strts_ms: int # Exchange timestamp, UTC millisecondslast: Decimalprev_close: Decimal | Nonedef key(q: Quote) -> str:return f"{q.market}:{q.code}"def is_valid(q: Quote) -> bool:if q.last <= 0:return Falseif q.prev_close is not None and q.prev_close <= 0:return Falsereturn Truedef is_stale(q: Quote, cache, now_ms: int, max_skew_ms: int = 300_000) -> bool:current = cache.get_ts(key(q)) # Returns the timestamp of the security in cache, or Noneif current is not None and q.ts_ms <= current:return True # Stale or duplicate, discardreturn now_ms - q.ts_ms > max_skew_msdef on_quote(q: Quote, cache, store, quarantine, alert, now_ms: int) -> None:if not is_valid(q):quarantine(q, reason="invalid")returnif is_stale(q, cache, now_ms):returntry:store.upsert(q) # Persist firstexcept Exception as exc:alert.notify(f"Persistence failed {key(q)}: {exc}")quarantine(q, reason="store_failed")returncache.set_if_newer(key(q), q, q.ts_ms) # Update cache after persistence succeeds, and compare versionsalert.check(q) # Abnormal movement alert
This code omits actual connection management and concurrency control. In a production environment, set_if_newer must be executed atomically by the cache service; otherwise, two concurrent requests could still overwrite each other.
5. Monitoring, Alerting, and High Availability
Monitoring for a market data system must cover both data quality and service availability.
Data quality metrics include:
- Data latency: The difference between the current time and the snapshot time. It is recommended to monitor P99. For example, alert if P99 exceeds 3 seconds during market open, and escalate to a critical alert if it exceeds 10 seconds;
- Update frequency: If a security has no updates beyond a set interval (e.g., 30 seconds) during trading hours, trigger a reminder;
- Missing rate: The ratio of expected to actual arrivals per unit of time by market. For example, alert if the missing rate exceeds 1%;
- Quarantine count: A sudden spike in isolated records usually indicates an upstream format change or data source anomaly.
These thresholds are only examples and should be set based on historical data and business tolerance. Alerts need to be tiered with clear owners and handling manuals.
High availability design should be decomposed by layers:
- Ingestion layer: Multi-instance deployment, with each instance subscribing to different shards. Automatically reconnect after disconnection and resume from the last sequence number;
- Cleaning layer: Stateless processing.
