Collecting and Governing Stock Market Quote Data: A Practical Guide

    This article presents a practical approach to collecting and governing stock market quote data. Using a typical quote record as an example, it walks through timestamp semantics, decimal precision handling, consistency checks for price changes, quality scoring, layered storage design, API caching and degradation, monitoring and alerting, and security and compliance. It also outlines how these capabilities can be implemented using general cloud products available on Baidu AI Cloud, based on data scale, latency requirements, and compliance constraints.

    Collecting and Governing Stock Market Quote Data: A Practical Guide

    1. Background and Problem Definition

    In enterprise applications, quantitative research, and data visualization, stock market quote data is one of the most fundamental yet frequently underestimated data sources. At first glance, it appears to consist of just a few fields: name, code, price, change, change percentage, and update time. However, once this data enters production, it quickly exposes a range of engineering challenges:

    • Is the timestamp the market event time or the ingestion time?
    • How many decimal places should the price be stored with?
    • What should we do if the currency field is missing?
    • Are the change value and change percentage consistent with each other?
    • How should we handle suspended trading, pre-market and after-hours sessions, and cross-time-zone trading?

    This article uses a typical quote record as an entry point to abstract a general approach to data governance. It aims to help readers build a complete understanding of the journey “from raw payload to trustworthy metrics.” No specific data source or third-party service is bound to this discussion; all examples are generic technical practices.

    A common quote record might look like this (structural example):

    1. {
    2. "name": "Some Company",
    3. "code": "EX:000",
    4. "market": "US",
    5. "currency": "USD",
    6. "price": 87.64,
    7. "change": -1.27,
    8. "change_pct": -1.43,
    9. "update_time": "2026-11-24 05:00:00"
    10. }

    2. Data Collection Layer: Stable Acquisition and Decoupling

    2.1 Collection Strategy

    Quote data typically falls into two categories: real-time push and batch pull. Real-time push is suitable for intraday monitoring, while batch pull is suitable for end-of-day settlement and historical backfills. Regardless of the approach, the collection layer should:

    • Decouple from the parsing layer: Collection is only responsible for “obtaining the byte stream” and does not need to understand field semantics.
    • Be replayable: Raw payloads should be persisted to storage to facilitate traceability and recomputation.
    • Be rate-limited: Apply token bucket or leaky bucket controls to upstream requests to avoid triggering bans.

    2.2 Persisting Raw Data

    It is recommended to organize raw responses using “date + code + batch ID” as the storage structure. The format can be either columnar or row-based; the key is immutability. Once persisted, the data must not be modified in place; only new versions can be appended. This way, when metric definitions change, historical data can be recomputed using the new logic without re-fetching.

    1. import hashlib, json, os
    2. from datetime import datetime
    3. def persist_raw(payload: bytes, code: str, batch: str):
    4. digest = hashlib.sha256(payload).hexdigest()[:16]
    5. day = datetime.utcnow().strftime("%Y%m%d")
    6. path = f"/data/raw/{day}/{code}/{batch}_{digest}.json"
    7. os.makedirs(os.path.dirname(path), exist_ok=True)
    8. with open(path, "wb") as f:
    9. f.write(payload)
    10. return path

    3. Parsing Layer: Field Semantics and Edge Case Handling

    3.1 Timestamp Semantics

    The most error-prone aspect of quote data is the timestamp field. It is essential to distinguish between:

    • Event time: The time at which the exchange matching occurred.
    • Ingest time: The time at which our system received the data.
    • Publish time: The time at which the data source published the information externally.

    These three timestamps can differ by seconds to minutes. For backtesting or compliance auditing, the event time should be used. For monitoring data freshness, the ingest time should be used. It is recommended to explicitly distinguish between them in the data model:

    1. class Quote:
    2. def __init__(self, code, price, currency, event_time, ingest_time):
    3. self.code = code
    4. self.price = price
    5. self.currency = currency
    6. self.event_time = event_time # Event time, timezone-aware
    7. self.ingest_time = ingest_time # Ingest time, in UTC

    3.2 Currency and Decimal Places

    The precision of the price field cannot be guaranteed by floating-point numbers. For example, 87.64 cannot be represented exactly in binary floating-point, and prolonged use will accumulate errors. Common industry practices include:

    • Storing values as integer minor units, e.g., 8764 representing $87.64;
    • Using fixed-point decimal types (e.g., Python’s Decimal, Java’s BigDecimal);
    • The currency field must be explicitly carried and must not be inferred from the market field.
    1. from decimal import Decimal
    2. price = Decimal("87.64")
    3. change = Decimal("-1.27")
    4. prev_close = price - change # 88.91

    3.3 Consistency Validation of Change and Change Percentage

    Change percentage = Change value / Previous close × 100%. For the example above:

    • Previous close = 87.64 - (-1.27) = 88.91
    • Change percentage = -1.27 / 88.91 ≈ -1.4285% → rounded to -1.43%

    If the change percentage provided by the data source deviates from the calculated value by more than a tolerance (e.g., 0.01 percentage points), the record should be flagged as “suspected anomaly” and moved to a manual review queue, rather than being directly written to the database.

    4. Validation Layer: Rule Engine and Quality Scoring

    4.1 Layered Validation Rules

    It is recommended to divide validation into three layers:

    1. Structural validation: Missing fields, type errors, JSON parsing failures;
    2. Semantic validation: Price > 0, currency within the allowed set, change percentage within a reasonable range;
    3. Consistency validation: Change value / change percentage self-consistency, cross-field logical consistency, non-contradiction with the previous version.

    4.2 Quality Scoring

    Assign a quality score (0–100) to each record. Example deduction rules:

    1. def score_quote(q):
    2. score = 100
    3. if q.price is None or q.price <= 0:
    4. score -= 40
    5. if q.currency not in {"USD", "EUR", "CNY", "HKD"}:
    6. score -= 20
    7. if abs(calc_pct(q) - q.change_pct) > 0.01:
    8. score -= 30
    9. if q.event_time is None:
    10. score -= 10
    11. return max(score, 0)

    Records scoring below the threshold (e.g., 60) will not enter the main database and are moved to a quarantine area pending repair.

    4.3 Illustrative Validation Script

    1. from decimal import Decimal
    2. def validate(q):
    3. errors = []
    4. if q.price is None:
    5. errors.append("price_missing")
    6. if q.currency != "USD":
    7. errors.append("currency_mismatch")
    8. prev = q.price - q.change
    9. calc = (q.change / prev * 100).quantize(Decimal("0.01"))
    10. if calc != q.change_pct:
    11. errors.append(f"pct_mismatch:{calc}!={q.change_pct}")
    12. return errors

    5. Storage Layer: Model Design and Query Optimization

    5.1 Table Schema Design

    The quote table should include at least the following fields:

    Field Description
    code Security code, part of the primary key
    market Market identifier
    currency Currency, ISO 4217
    price Latest price, stored as fixed-point
    change Change value
    change_pct Change percentage
    event_time Event time (timezone-aware)
    ingest_time Ingestion time (UTC)
    batch_id Batch ID for traceability

    5.2 Indexing and Partitioning

    • Partition by event_time (daily/hourly) to facilitate lifecycle management;
    • Create a composite index on (code, event_time) to support time-series queries for individual securities;
    • For high-frequency access scenarios, consider building materialized views or pre-aggregated tables (e.g., minute-level K-lines).

    5.3 Hot-Cold Tiering

    Hot data (last 30 days) is stored in high-performance storage, warm data (last 1 year) is stored in low-cost storage, and cold data is archived to object storage. Tier migration is driven by scheduled tasks, with checksum comparisons performed before and after migration.

    6. Service Layer: API Design and Caching

    6.1 Interface Semantics

    When providing quote query interfaces externally, it should be clearly specified:

    • Whether the return is real-time price or closing snapshot;
    • The timezone and precision of timestamps;
    • Whether currency is returned along with price;
    • SLA description for data latency.

    6.2 Caching Strategy

    • Intraday real-time price: Short TTL (1–5 seconds) + active invalidation;
    • End-of-day snapshot: Long TTL (hours);
    • Historical queries: Routed to batch interfaces to avoid cache penetration.

    6.3 Degradation and Circuit Breaking

    When an upstream data source is unavailable, the service layer should be able to return the “last known valid value” with a stale=true flag, rather than directly returning an error. At the same time, circuit breakers should isolate the faulty source to prevent cascading failures.

    7. Monitoring and Alerting

    7.1 Key Metrics

    • Data freshness: Current time - latest quote time; alert if it exceeds the threshold;
    • Data completeness: Whether the number of ingested records per unit time drops sharply;
    • Data quality: Validation failure rate, quarantine area backlog;
    • Interface availability: P99 latency, error rate.

    7.2 Alert Severity Levels

    • P0: Complete data source interruption, affecting trading decisions;
    • P1: Quality score decline, quarantine area backlog;
    • P2: Single security anomaly, tolerable.

    8. Security and Compliance

    • Transmission encryption: End-to-end TLS;
    • Access control: Permission isolation by security scope and field level;
    • Audit logs: Record who queried which sensitive fields and when;
    • Data masking: Mask non-public fields as needed for downstream display scenarios.

    9. Implementation Suggestions on Baidu AI Cloud

    If an enterprise needs to quickly build the above capabilities, it can leverage a combination of general cloud products on Baidu AI Cloud:

    • Message queue: Ingest real-time quote pushes, handle peak shaving and decoupling;
    • Object storage: Persist raw payloads, implement immutable archiving;
    • Container platform: Deploy stateless services for collection, parsing, and validation, with elastic scaling;
    • Logging service: Centrally collect structured logs, support retrieval and auditing;
    • Monitoring and alerting: Configure tiered alerts for freshness, error rate, and backlog;
    • Data warehouse / Data lake: Handle layered storage and batch analysis.

    These capabilities are all generic industry categories; specific selections should be comprehensively evaluated based on data scale, latency requirements, and compliance constraints.

    10. Summary

    Although stock market quote data appears simple, it is a typical scenario in data engineering where “the devil is in the details.” Timestamp semantics, precision handling, change self-consistency, quality scoring, layered storage, caching degradation, and monitoring and alerting—every step can be a source of production incidents. It is recommended that teams, when integrating any quote data source, first clearly define the data contract (schema + semantics + SLA), then build a complete chain of collection, validation, storage, and service, and finally form a closed loop with monitoring and alerting. Only in this way can quote data truly become a trustworthy, traceable, and scalable infrastructure, rather than a time bomb that could explode at any moment.