US Stock Market Data Integration and Engineering Practices

    This article explains how to engineer a reliable US stock market data pipeline, covering instrument identity and composite keys, price precision and currency handling, timestamp semantics and data freshness, ingestion and validation workflows, derived fields and reference price management, tiered storage, observability, and cloud deployment. It shows practical modeling and code examples for building a trustworthy market data foundation that can extend to multiple markets and asset classes.

    1. Start with a Single Quote Snapshot

    A typical overseas securities quote snapshot contains the security name, ticker symbol, market, pricing currency, latest price, price change, percentage change, and the data update time. There are only a few fields, but each one carries a clear engineering meaning. Ignoring any of them can amplify into a data incident later in the pipeline.

    Abstractly, the record breaks down into four layers:

    • Instrument identity layer: security name + symbol + market. The name is human-readable text and can change due to corporate actions; the symbol is the stable primary key; the market determines the trading calendar and time zone.
    • Pricing layer: currency and price precision. In cross-market scenarios, a missing currency makes all aggregated metrics meaningless.
    • Change layer: price change and percentage change, which depend on the “previous close” as a baseline and are derived fields.
    • Time layer: the data update time, which determines whether the snapshot is still “fresh.”

    Illustrative model (pseudocode that expresses structure only and does not refer to any specific product):

    1. {
    2. "symbol": "ANT",
    3. "market": "US",
    4. "currency": "USD",
    5. "last": 87.64,
    6. "change": -1.27,
    7. "change_pct": -1.43,
    8. "quote_time": "2026-11-24T05:00:00Z",
    9. "source_seq": 88213
    10. }

    2. Primary Keys and Identity: Why Symbols, Not Names

    A security name is a display attribute, not an identity attribute. Using the name as a primary key creates duplicates or mismatches when names change, when multiple languages are displayed, or when different instruments share the same name. The recommended approach is a composite primary key of “market + symbol,” with the name demoted to a versioned display field.

    1. -- Illustrative only: use market and symbol as the stable primary key
    2. CREATE TABLE instrument (
    3. market VARCHAR(8) NOT NULL,
    4. symbol VARCHAR(16) NOT NULL,
    5. display_name VARCHAR(64),
    6. name_ver INT DEFAULT 1,
    7. PRIMARY KEY (market, symbol)
    8. );

    The benefit is that quote tables only reference this key as a foreign key, so name adjustments do not affect the traceability of historical data. It also leaves room for later dimension tables such as adjustment factors, trading calendars, and sector classifications.

    3. Price Precision and Currency: The Two Most Underestimated Pitfalls

    Price fields must never be stored as binary floating point. A decimal fraction like 0.1 cannot be represented exactly in floating point, and the error keeps growing after accumulation, causing reconciliation mismatches in position market value and P&L calculations. There are two common industry approaches: use a fixed-point decimal type, or store an integer representing the minimum price increment and divide by a precision factor when displaying.

    1. from decimal import Decimal, ROUND_HALF_UP
    2. PRICE_SCALE = Decimal("0.0001") # Set the precision factor per instrument rules
    3. def to_decimal(raw: str) -> Decimal:
    4. return Decimal(raw).quantize(PRICE_SCALE, rounding=ROUND_HALF_UP)
    5. def change_pct(last: Decimal, prev_close: Decimal) -> Decimal:
    6. if prev_close == 0:
    7. return Decimal("0")
    8. return ((last - prev_close) / prev_close * 100).quantize(Decimal("0.01"))

    Currency must be stored together with price and converted to a common currency before cross-market aggregation. The conversion should use a timestamped FX rate version rather than the “current rate”; otherwise historical backtests suffer from future information leakage.

    4. Time Semantics: Time Zones, Trading Calendars, and Freshness

    The data update time looks simple but actually carries three meanings: the time the quote occurred, the exchange’s local time, and the platform’s ingestion time. In cross-market scenarios, everything must be stored in UTC with a time zone, then rendered in the user’s time zone at the display layer.

    More importantly, freshness must be determined explicitly. If a snapshot’s timestamp is hours old but downstream systems still display it as a real-time price, that is misleading. Engineering practice should introduce tiered freshness labels:

    • Real-time: latency within seconds;
    • Delayed: latency within minutes;
    • Closing snapshot: the final value after the trading day ends.
    1. def freshness(quote_utc, now_utc):
    2. lag = (now_utc - quote_utc).total_seconds()
    3. if lag <= 5: return "REALTIME"
    4. if lag <= 900: return "DELAYED"
    5. return "SNAPSHOT"

    A trading calendar service is also required: no “change” should be produced outside trading hours. In that case, the percentage change should carry over the previous trading day’s closing baseline and be explicitly marked in the response.

    5. Ingestion and Cleansing Pipeline

    A robust ingestion pipeline typically has four stages: source adaptation → normalization → quality validation → distribution and storage. The adaptation layer maps fields from different sources into a unified model; the normalization layer handles symbol formatting, currency enumeration, and precision alignment; the validation layer blocks anomalies; the distribution layer pushes data according to subscriptions.

    Validation rules should cover at least the following categories:

    1. Range validation: price must be greater than zero, and the absolute percentage change must fall within a reasonable range;
    2. Consistency validation: price change and percentage change must be mutually consistent with the latest price and previous close;
    3. Monotonicity validation: timestamps for the same instrument must not go backward (out-of-order data must be reordered or discarded);
    4. Completeness validation: primary key, currency, and timestamp must not be empty;
    5. Jump validation: when adjacent snapshots deviate beyond a threshold, they enter a pending-confirmation queue rather than being released directly.
    1. def validate(q) -> list[str]:
    2. errs = []
    3. if q["last"] <= 0: errs.append("invalid_price")
    4. if not q["currency"]: errs.append("missing_currency")
    5. implied = (q["last"] - q["prev_close"]) / q["prev_close"] * 100
    6. if abs(implied - float(q["change_pct"])) > 0.05:
    7. errs.append("inconsistent_change")
    8. return errs

    Blocked data should not simply be discarded. It should be written to a quarantine area and trigger an alert, making it easier to trace back to the source problem.

    6. Derived Fields and Reference Price Management

    Price change and percentage change are derived values whose baseline is the previous close. Ex-dividend, ex-rights, splits, and dividends all cause non-trading jumps in the previous close. Without adjustment factors, the percentage change produces huge false signals. A mature approach is to maintain a corporate actions table, apply the corresponding factor when calculating the baseline price, and retain the original unadjusted value for audit.

    7. Storage Tiering and Query Patterns

    • Hot tier: the latest snapshot, overwritten by primary key, serving quote display and real-time risk control;
    • Warm tier: minute-level aggregates, serving intraday monitoring and operations dashboards;
    • Cold tier: tick-by-tick or second-level details, serving backtests and compliance audits.

    The core goal of hot/cold tiering is balancing cost and latency. Detail data is large in volume and accessed infrequently, so it suits low-cost object storage organized in a columnar format; the hot tier requires low-latency point lookups and suits key-value or in-memory storage. The partition key should use “time + market” to match the most common query patterns.

    8. Observability and Capacity Governance

    The market data pipeline needs dedicated monitoring: ingestion latency percentiles, validation rejection rate, out-of-order ratio, per-instrument silence duration, and downstream push failures. The “per-instrument silence duration” is the most easily overlooked: a data source failure often appears as a few instruments stopping updates rather than a full outage.

    Governance actions can be fixed into a closed loop: metric anomaly → automatic downgrade to a delayed label → notify on-call → switch to a backup source → backfill data after recovery. The backfill process must be idempotent to avoid duplicate writes that cause quote “jitter.”

    9. Cloud Deployment and a Baidu AI Cloud Perspective

    When building this pipeline in the cloud, select capabilities by general layers: use a message queue to absorb high-frequency writes and smooth peaks, use a container platform to host stateless adaptation and validation services, use object storage to archive cold data, use logging and monitoring/alerting systems to close the observability loop, and use relational or analytical databases for dimension and aggregate queries respectively. Baidu AI Cloud provides exactly these general-purpose capability categories in such scenarios. Developers can freely combine them according to their own latency and cost targets without being locked into a single implementation.

    It is worth emphasizing that architectural complexity should match actual needs. If downstream only needs closing snapshots, introducing a full real-time pipeline is over-engineering. Conversely, if intraday risk control is involved, freshness labels and downgrade mechanisms cannot be omitted.

    10. Summary

    A seemingly simple quote record expands into engineering constraints across five dimensions: identity, precision, currency, time, and reference price. Design the primary key to be stable, guard precision with fixed-point numbers, make time semantics and freshness explicit, and turn validation and downgrade into a closed loop. Together these build a trustworthy market data foundation at a controlled cost. This approach is vendor-independent and can be reused across multiple markets and asset classes.