Market Data Collection and Parsing: Turning Flat Text Snapshots into Reliable Data Assets
This article walks through the engineering practice of collecting and parsing digital asset market data. It explains why raw text snapshots are hard to use directly, how to define a unified MarketSnapshot model with high-precision decimals and timezone-aware timestamps, how to build a fault-tolerant parsing layer with explicit validation, and how to decouple the pipeline into collection, buffering, computation, and serving layers. It also covers zero-value semantics, data quality flags, observability, and cost control. Readers will gain a practical blueprint for converting unstructured quotes into trustworthy data with units, timezones, and quality markers.
1. Background: Why Raw Market Data Is Hard to Use Directly
When building a market dashboard, a quantitative research environment, or a risk monitoring module, developers often receive not a normalized API object but a flat text snapshot with fields such as symbol, trading pair, market type, last price, change percentage, open, high, low, market cap, rank, and update time. A typical snapshot looks like this:
Symbol: GLM, Pair: GLMUSDT, Market Type: CRYPTOLast Price: 0.09359, Currency: USD24h Change: 0, Change %: 0.000%Open: 0.09359, High: 0.09539, Low: 0.09119Market Cap: 9373.31万, Market Cap Rank: 164Updated: 2026-12-01 19:55:40
This kind of data has three typical engineering problems. First, inconsistent units: “9373.31万” is a localized counting expression, and storing it directly breaks the numeric type. Second, semantic ambiguity: the change is 0 and the change percentage is 0.000%, yet the high and low clearly define a range, which indicates this is a static snapshot at a single moment rather than a statistical aggregate. Third, unclear time semantics: the update time lacks timezone information, which can easily cause an 8-hour offset in cross-timezone deployments. Collection is therefore only the starting point; the real cost lies in establishing a stable parsing and validation specification.
2. Unified Data Model: Abstracting Flat Text into a Market Snapshot
The recommended first step is to abstract data from any source into a unified entity before discussing storage and computation. The core fields can be divided into four groups: identity (symbol, pair, market type), price (last, open, high, low), statistics (change, change percentage, market cap, rank), and metadata (quote currency, snapshot time, data source marker).
from dataclasses import dataclassfrom decimal import Decimalfrom datetime import datetime, timezone@dataclassclass MarketSnapshot:symbol: str # Instrument symbolpair: str # Trading pairmarket_type: str # Market type, e.g. CRYPTOlast: Decimal # Last priceopen: Decimalhigh: Decimallow: Decimalchange: Decimal # Price changechange_pct: Decimal # Change percentage, normalized to a decimalmarket_cap: Decimal # Normalized to the primary unit (CNY/USD)rank: intquote_currency: strts: datetime # Must be timezone-aware
There are two key conventions here. First, all prices and statistics use a high-precision decimal type rather than floating point to avoid accumulation errors. Second, the change percentage is normalized to a decimal (0.1% is stored as 0.001) in the parsing layer, and repeated conversion in the presentation layer is forbidden. This is the prerequisite for the correctness of all subsequent metric calculations.
3. Parsing Layer: Fault Tolerance First, No Silent Failures
The design principle of the parser is “fail explicitly rather than silently produce dirty data.” Localized numbers, percent signs, null values, and placeholder zeros must all be handled explicitly.
import redef parse_localized_number(raw: str) -> Decimal:s = raw.strip().replace(",", "")scale = Decimal(1)if s.endswith("万"):scale, s = Decimal(10000), s[:-1]elif s.endswith("亿"):scale, s = Decimal(100000000), s[:-1]return Decimal(s) * scaledef parse_percent(raw: str) -> Decimal:return Decimal(raw.strip().rstrip("%")) / Decimal(100)def parse_snapshot(text: str) -> MarketSnapshot:kv = dict(re.findall(r"([^,:]+):\s*([^,]+)", text))return MarketSnapshot(symbol=kv["代码"].strip(),pair=kv["交易对"].strip(),market_type=kv["市场类型"].strip(),last=Decimal(kv["最新价"].strip()),open=Decimal(kv["开盘价"].strip()),high=Decimal(kv["最高价"].strip()),low=Decimal(kv["最低价"].strip()),change=Decimal(kv["过去24小时涨跌额"].strip()),change_pct=parse_percent(kv["涨跌幅"]),market_cap=parse_localized_number(kv["市值"]),rank=int(kv["市值排名"].strip()),quote_currency=kv["货币"].strip(),ts=datetime.strptime(kv["更新时间"].strip(), "%Y-%m-%d %H:%M:%S").replace(tzinfo=timezone.utc),)
After parsing, consistency checks must be performed, for example: the low is not greater than the last price and not higher than the high; the open falls between the low and the high; the deviation between the change and (last minus open) is within tolerance; and the market cap rank is a positive integer. Data that fails validation goes into a quarantine queue rather than being discarded outright, which makes retrospective investigation easier.
4. Pipeline Architecture: Decoupling Collection, Buffering, Computation, and Serving
The recommended design splits the pipeline into four layers. The collection layer pulls snapshots at fixed intervals with rate limiting and retries. The buffering layer uses a message queue to smooth peaks and guarantee no data loss under burst traffic. The computation layer handles cleaning, validation, and metric aggregation. The serving layer exposes queries through a cache. Raw snapshots and cleaned data are written to different prefixes in object storage, achieving “immutable raw data, replayable processing.”
Collector -> Message Queue (topic: market.raw) -> Clean & Validate -> Object Storage (raw/ cleaned/)-> Error Queue (market.invalid)-> Metric Aggregation -> Cache -> Query API
For time-window aggregation, a rolling window is recommended to avoid metric jumps caused by natural window boundaries:
def rolling_change_pct(prices, window=24):"""prices: (ts, Decimal) sequence sorted in ascending time order"""if len(prices) < 2:return Decimal(0)base = prices[-1][1]for ts, p in reversed(prices):if prices[-1][0] - ts >= window:return (base - p) / p if p else Decimal(0)return Decimal(0)
5. Zero-Value Semantics and Data Quality Pitfalls
When the change and change percentage in a snapshot are both 0, there are usually three possible causes: the data source has not finished initializing the statistics window, the market genuinely did not move within the window, or a missing field was filled with a placeholder zero. These three cases have completely different business meanings. Engineering practice should introduce a quality_flag field to distinguish a “true zero” from an “unknown,” and render them with different styles on the dashboard. Similarly, market cap and rank are slow-changing fields, and high-frequency refreshes only amplify noise, so a lower sampling frequency is appropriate. Price fields are the opposite: they need higher-frequency collection and retention of the raw sequence to support retrospective analysis.
6. Observability and Cost Control
When deploying on Baidu AI Cloud, you can use the log service to centrally collect parsing exceptions and validation failure details, use monitoring and alerting to set thresholds for collection latency, error queue backlog, and field missing rate, and use object storage to host tiered hot and cold historical snapshots. Cost control points include: setting lifecycle policies for high-frequency raw data to automatically move it to lower-frequency storage, caching only aggregated results, and avoiding real-time recomputation of the full window for every query.
7. Summary
The core of market data engineering is not scraping but turning unstructured text into trustworthy data assets with units, timezones, and quality markers. A unified data model, explicit parsing, strict validation, four-layer decoupling, and observability are all essential; missing any one of them will expose problems as scale grows. With the approach described above, upper-layer dashboards, backtesting, and risk control modules can iterate quickly on top of a stable data contract.
