Parsing, Validation, and Change Calculation for Hong Kong Stock Market Quotes

    This article introduces methods for reliably parsing Hong Kong stock market quote snapshots, validating data integrity, and calculating derived metrics such as price change and amplitude. It covers field semantics, time zone handling, and engineering best practices to ensure consistent and verifiable financial data display.

    I. Background

    Market quote data is typically delivered in a “key: value” text format, including fields such as latest price, open price, previous close price, high price, low price, and update time. Displaying this data to users is not difficult; the challenges lie in two areas: reliably extracting fields from the text and deriving consistent, verifiable metrics based on these fields. If the parsing and calculation processes lack constraints, the same data might show different price change percentages on different pages, making troubleshooting time-consuming.

    Let’s illustrate this with an example snapshot. The snapshot content is as follows:

    • Latest price: 20.74
    • Open price: 21.12
    • Previous close price: 21.28
    • High price: 21.28
    • Low price: 20.68
    • Update time: 2026-11-24 12:30:08

    The subsequent parsing, calculation, and validation will revolve around this set of fields.

    II. Field Semantics and Usage

    Understanding field semantics is a prerequisite for correct calculations.

    The latest price is the price of the most recent transaction at the current moment. If the snapshot occurs during non-trading hours, the latest price reflects the result of the last trading session.

    The previous close price is the reference price determined at the close of the previous trading day, serving as the baseline for almost all price change metrics.

    The open price, high price, and low price describe the price boundaries during the current trading day. The high and low prices are continuously updated as trading progresses, so they only represent the interval up to the snapshot moment.

    The update time determines whether the data is usable. Snapshot text does not necessarily include a time zone, so the receiving party must explicitly agree on the time zone to avoid time discrepancies.

    III. Calculating Derived Metrics

    Common derived metrics include the following four. Let P be the previous close price, L be the latest price, O be the open price, H be the high price, and W be the low price:

    1. Change = L − P
    2. Change Percentage = (L − P) / P × 100%
    3. Amplitude = (H − W) / P × 100%
    4. Open Gap Percentage = (O − P) / P × 100%

    There are two common approaches for the denominator of amplitude: one uses the previous close price, and the other uses the low price. This article uniformly uses the previous close price and notes this in the API documentation to prevent inconsistencies across different modules.

    Substituting the example data, the results are: Change is −0.54, Change Percentage is approximately −2.54%, Amplitude is approximately 2.82%, and Open Gap Percentage is approximately −0.75%.

    The following code uses Decimal for calculations. Floating-point numbers cannot accurately represent decimals like 0.1 in binary. Using float directly for monetary or price calculations may result in cumulative errors. Using Decimal and specifying a rounding method ensures stable and reproducible results.

    1. from decimal import Decimal, ROUND_HALF_UP
    2. FIELD_MAP = {
    3. "价格": "last",
    4. "开盘价": "open",
    5. "昨收价": "prev_close",
    6. "最高价": "high",
    7. "最低价": "low",
    8. "股票更新时间": "updated_at",
    9. }
    10. def parse_quote(raw: str) -> dict:
    11. """Parse "key: value" snapshot text into a dictionary, ignoring unknown fields."""
    12. result = {}
    13. for item in raw.split(","):
    14. if ":" not in item:
    15. continue
    16. key, value = item.split(":", 1)
    17. key = key.strip()
    18. if key in FIELD_MAP:
    19. result[FIELD_MAP[key]] = value.strip()
    20. return result
    21. def _pct(numerator: Decimal, base: Decimal) -> Decimal:
    22. return (numerator / base * 100).quantize(Decimal("0.01"), ROUND_HALF_UP)
    23. def derive(q: dict) -> dict:
    24. last = Decimal(q["last"])
    25. prev = Decimal(q["prev_close"])
    26. open_ = Decimal(q["open"])
    27. high = Decimal(q["high"])
    28. low = Decimal(q["low"])
    29. return {
    30. "change": last - prev,
    31. "change_pct": _pct(last - prev, prev),
    32. "amplitude_pct": _pct(high - low, prev),
    33. "open_gap_pct": _pct(open_ - prev, prev),
    34. }

    IV. Data Validation Rules

    Parsing and calculation results are only meaningful when the input is valid. Validation should be completed before calculation, and error reasons should be returned to the caller rather than being silently handled. It is recommended to check at least the following types of issues:

    • Numeric Validity: All price fields must be convertible to positive decimal numbers. The previous close price cannot be zero, otherwise the change percentage cannot be calculated.
    • Interval Consistency: The high price must not be lower than the low price; both the latest price and the open price should fall between the low price and the high price.
    • Time Validity: The update time must be parsable and should not be too far in the future relative to the current system time, which might indicate a clock skew.
    • Timeliness: If the update time exceeds a threshold compared to the current time, it should be marked as expired data.
    1. from datetime import datetime, timezone, timedelta
    2. HKT = timezone(timedelta(hours=8))
    3. def validate(q: dict) -> list[str]:
    4. errors = []
    5. try:
    6. last = Decimal(q["last"])
    7. prev = Decimal(q["prev_close"])
    8. open_ = Decimal(q["open"])
    9. high = Decimal(q["high"])
    10. low = Decimal(q["low"])
    11. except (KeyError, ArithmeticError):
    12. return ["Missing fields or invalid numeric format"]
    13. if prev <= 0:
    14. errors.append("Previous close price must be positive")
    15. if high < low:
    16. errors.append("High price is lower than low price")
    17. if not (low <= last <= high):
    18. errors.append("Latest price is out of the low-high range")
    19. if not (low <= open_ <= high):
    20. errors.append("Open price is out of the low-high range")
    21. return errors
    22. def age_seconds(updated_at: str, now: datetime) -> float:
    23. """Calculate the time difference between the snapshot and the current time based on the exchange's time zone (assumed to be Hong Kong Time UTC+8)."""
    24. ts = datetime.strptime(updated_at, "%Y-%m-%d %H:%M:%S").replace(tzinfo=HKT)
    25. return (now - ts).total_seconds()
    26. now = datetime(2026, 11, 24, 14, 21, 29, tzinfo=timezone.utc)
    27. print(age_seconds("2026-11-24 12:30:08", now)) # 35481.0

    The snapshot in the example is about 9 hours and 51 minutes behind the reference time. If the display system treats this data as a real-time quote, users will see significantly lagged prices. Therefore, timeliness checks should be a mandatory step before display, and expired data should carry a clear indicator.

    V. Time Zones and Trading Sessions

    The time in the snapshot is not labeled with a time zone, so this needs to be confirmed with the data provider upon integration. The Hong Kong stock market uses local Hong Kong Time (UTC+8). In practice, it is recommended to uniformly convert to UTC for storage and then convert to the user’s local time zone upon display.

    The update time 12:30:08 falls within the lunch break of the regular Hong Kong stock trading session. According to the exchange’s standard schedule, the lunch break is typically from 12:00 to 13:00. Therefore, the latest price in this snapshot is likely the last transaction price from the morning trading session. The display layer should distinguish between states such as “In Trading”, “Lunch Break”, and “Closed”, preventing users from mistakenly assuming that the price is still changing in real time. Trading calendars and break schedules may be adjusted due to holidays, so the status determination should be based on the calendar published by the exchange.

    VI. Design Considerations for Display and Alerting

    The display layer typically uses colors to distinguish the direction of price changes and applies different visual weights based on the absolute value of the change percentage. Color definitions should be centralized in configurations to avoid being scattered across the code of various pages.

    Alerting features can set thresholds based on the change percentage or amplitude, such as triggering a notification when the absolute value of the change percentage exceeds a certain value. Thresholds should be configurable, and the original snapshot at the time of triggering should be recorded for later review. If alerts need to be pushed through external channels, attention must be paid to deduplication; identical events within the same time window should only trigger a single notification.

    This article discusses data processing and engineering implementation and does not involve any investment judgments.

    VII. Engineering Practice Recommendations

    1. Retain Original Text: When parsing fails, the original snapshot is the only basis for troubleshooting and should be stored alongside the parsing results.
    2. Standardize Numeric Types: Use Decimal or the smallest integer unit (e.g., cents) throughout for monetary and price calculations. Do not convert to floating-point numbers in intermediate steps.
    3. Clarify Specifications: The denominators, rounding rules, and time zone conventions for metrics like change percentage and amplitude should be documented in the API documentation and fixed through unit tests.
    4. Layered Processing: Parsing, validation, calculation, and display belong to different modules. Each layer should only handle its own responsibilities, making it easier to test independently and replace data sources.
    5. Design Fallback Strategies: When data is expired or validation fails, the interface should display the last valid data and its timestamp, rather than leaving it blank or showing incorrect values.

    By implementing the methods described above, the market quote module can provide explainable results in scenarios involving data anomalies, time zone deviations, and non-trading hours, significantly reducing maintenance costs.