Standardizing and Validating Market Snapshot Data: Engineering Practices

    This guide explains how to standardize and validate market snapshot data before calculating indicators. It covers field definitions, change and amplitude formulas, decimal precision, UTC timestamp handling, validation rules, anomaly detection, degradation strategies, and a four-layer pipeline design.

    1. Background

    Market data is usually published as snapshots. Each snapshot records the latest price of an instrument at a specific moment, along with the open, high, and low prices within the statistics window and the update time. Display pages, analysis reports, and alerting systems all read these records. If the same data is calculated repeatedly in several places, the results can diverge. The change rate on a page may differ from the one in a report, alert thresholds may fire at different times in different time zones, and floating-point errors can produce unexpected comparison results.

    Engineers should therefore standardize snapshot data before calculating metrics and running validation. The goal of standardization is that the same record is interpreted the same way everywhere.

    2. Field Meanings and Definitions

    Common snapshot fields include:

    • Symbol: the unique identifier of a trading pair or asset. Letter case and separator rules must be standardized.
    • Last price (last): the price of the most recent trade or the most recent quote.
    • Open price (open): the price at the start of the statistics window.
    • High and low prices (high, low): the extreme prices within the statistics window.
    • Change amount and change rate: the change relative to a reference price, in absolute and percentage terms.
    • Market cap and market cap rank: derived from circulating supply and price. The definition varies by data source.
    • Update time (updated_at): the point in time when the data was generated. It must include time zone information.

    Field definitions are the easiest thing to overlook. Whether “24 hours” means a rolling window or a calendar day, and whether the reference price for the change rate is the window’s opening price or the previous period’s closing price, both directly affect the final values. When connecting a new data source, first confirm its documented definitions and record them in the internal data dictionary. This keeps different modules from interpreting the fields differently.

    3. Indicator Calculation

    Let L be the last price, R the reference price, H the window high, and Lo the window low. The common indicators are defined as follows:

    • Change amount = L - R
    • Change rate = (L - R) / R × 100%
    • Amplitude = (H - Lo) / R × 100%

    The code below implements these three indicators and guards against a zero reference price.

    1. from decimal import Decimal
    2. def change_amount(last: Decimal, ref: Decimal) -> Decimal:
    3. """Change amount: the change of the last price relative to the reference price."""
    4. return last - ref
    5. def change_rate(last: Decimal, ref: Decimal) -> Decimal:
    6. """Change rate in percent. Refuses to calculate when the reference price is zero."""
    7. if ref == 0:
    8. raise ValueError("Reference price is 0, cannot calculate change rate")
    9. return (last - ref) / ref * Decimal("100")
    10. def amplitude(high: Decimal, low: Decimal, ref: Decimal) -> Decimal:
    11. """Amplitude in percent."""
    12. if ref == 0:
    13. raise ValueError("Reference price is 0, cannot calculate amplitude")
    14. return (high - low) / ref * Decimal("100")

    The choice of reference price changes the result. Suppose an instrument has a last price of 105.20 and an open price of 102.00. The change amount is 3.20. Using the open price as the reference, the change rate is about 3.14%. If the data source uses 102.50 as the reference price, the change amount becomes 2.70 and the change rate about 2.63%. Both calculations are correct, but they follow different definitions. So when a recalculated value differs slightly from the value returned by the data source, first check the reference price definition. Do not conclude that the data is wrong.

    4. Numeric Precision and Monetary Representation

    Floating-point numbers cannot exactly represent most decimal fractions. In Python, for example, 0.1 + 0.2 evaluates to 0.30000000000000004. Such errors cause problems when comparing prices or checking boundaries. Financial and market data systems should use decimal types and parse raw data from strings.

    1. from decimal import Decimal
    2. raw_last = "105.20" # Raw data is transmitted as a string
    3. last = Decimal(raw_last) # Parse directly as decimal, without going through float
    4. print(Decimal("0.1") + Decimal("0.2") == Decimal("0.3")) # True
    5. print(float("0.1") + float("0.2") == float("0.3")) # False

    Calculation precision and display precision should be handled separately. Keep full precision internally and round only when producing output. Use one rounding rule throughout. A common choice is rounding half up to a fixed number of decimal places. Do not hardcode the number of decimal places to two. Prices vary widely in magnitude, and low-priced instruments often need more decimal places to show changes. The display layer can choose the number of decimal places based on the price magnitude.

    1. from decimal import Decimal, ROUND_HALF_UP
    2. def format_price(value: Decimal, places: int) -> str:
    3. quant = Decimal(1).scaleb(-places) # places=2 gives Decimal("0.01")
    4. return str(value.quantize(quant, rounding=ROUND_HALF_UP))
    5. print(format_price(Decimal("3.14159"), 2)) # 3.14
    6. print(format_price(Decimal("0.0091234"), 6)) # 0.009123

    5. Time and Time Zone Handling

    If a snapshot’s update time lacks time zone information, the system cannot determine whether it is earlier or later than the current time. It also cannot compare times correctly across systems in different regions. The recommended approach is to enforce time zone validation at the entry point, store times internally in UTC, and convert them to the user’s time zone only when displaying them.

    1. from datetime import datetime, timezone
    2. def normalize_time(raw: str) -> datetime:
    3. """Parse an ISO 8601 time string and convert it to UTC."""
    4. dt = datetime.fromisoformat(raw)
    5. if dt.tzinfo is None:
    6. raise ValueError("Time has no time zone information, rejected before storage")
    7. return dt.astimezone(timezone.utc)
    8. print(normalize_time("2026-11-24T14:40:39+00:00"))
    9. print(normalize_time("2026-11-24T22:40:39+08:00")) # Same instant as the line above

    Time zones also affect statistics windows. The start of a calendar day depends on which time zone is used to divide days. The same data can therefore produce different daily change rates in different time zones. Documentation should state the time zone used for each window, and the system should pass it as an explicit parameter.

    6. Data Validation Rules

    Snapshot data can contain missing values, misaligned fields, and inconsistent units. The validation layer should reject clearly invalid data before indicators are calculated. The recommended rules are:

    1. Price fields must be positive numbers.
    2. The low price must not be higher than the high price. The open price and the last price must both fall between the low and high prices.
    3. The update time must include a time zone and must not be older than the maximum allowed delay.
    4. The difference between the recalculated change rate and the value returned by the data source must fall within an agreed tolerance.
    1. from dataclasses import dataclass
    2. from datetime import datetime, timezone
    3. from decimal import Decimal
    4. @dataclass(frozen=True)
    5. class Snapshot:
    6. symbol: str
    7. last: Decimal
    8. open: Decimal
    9. high: Decimal
    10. low: Decimal
    11. updated_at: datetime # Must be a UTC time
    12. MAX_DELAY_SECONDS = 300
    13. def validate(s: Snapshot, now: datetime) -> list[str]:
    14. errors = []
    15. if min(s.last, s.open, s.high, s.low) <= 0:
    16. errors.append("Non-positive price found")
    17. if s.low > s.high:
    18. errors.append("Low price is higher than high price")
    19. if not (s.low <= s.last <= s.high):
    20. errors.append("Last price is outside the high-low range")
    21. if not (s.low <= s.open <= s.high):
    22. errors.append("Open price is outside the high-low range")
    23. delay = (now - s.updated_at).total_seconds()
    24. if delay > MAX_DELAY_SECONDS:
    25. errors.append(f"Data is delayed by {delay:.0f} seconds, exceeding the threshold")
    26. return errors
    27. snap = Snapshot(
    28. symbol="EXAMPLE-USD",
    29. last=Decimal("105.20"),
    30. open=Decimal("102.00"),
    31. high=Decimal("106.00"),
    32. low=Decimal("101.50"),
    33. updated_at=datetime(2026, 11, 24, 14, 40, 39, tzinfo=timezone.utc),
    34. )
    35. now = datetime(2026, 11, 24, 14, 42, 0, tzinfo=timezone.utc)
    36. print(validate(snap, now) or "Validation passed")

    Snapshots that fail validation should not be discarded outright. A better approach is to write them to an exception queue and keep the original payload for later investigation. Meanwhile, the display layer can keep showing the last valid snapshot and label it with its update time.

    7. Anomaly Detection and Degradation Strategies

    Beyond static rules, the system also needs to detect dynamic anomalies. The most common case is a single-point jump, where the price change between two consecutive snapshots exceeds a set threshold. The jump may reflect real, sharp volatility, or it may be an erroneous quote from the data source. The two cases call for different handling. Jumping data should be marked as “pending confirmation” rather than overwriting historical data.

    Degradation strategies matter as well. When the data source is interrupted or delays exceed the limit, the system should behave in a defined way:

    • Keep showing the last valid snapshot, along with its timestamp.
    • Stop triggering alerts that depend on real-time prices, so that no decisions are made from stale data.
    • After recovery, backfill the missing periods and recalculate the indicators that depend on them.

    8. Engineering Implementation

    Split the pipeline into four layers. Each layer has a single responsibility, which makes independent testing and replacement easier.

    1. Collection -> Cleaning -> Calculation -> Publishing
    2. | | | |
    3. Raw payloads Field mapping Indicator Caching and
    4. Type conversion calculation APIs
    5. Validation Historical
    6. rules storage
    • The collection layer only fetches raw payloads and records the time of receipt. It makes no business decisions.
    • The cleaning layer performs field mapping and type conversion.