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.
from decimal import Decimaldef change_amount(last: Decimal, ref: Decimal) -> Decimal:"""Change amount: the change of the last price relative to the reference price."""return last - refdef change_rate(last: Decimal, ref: Decimal) -> Decimal:"""Change rate in percent. Refuses to calculate when the reference price is zero."""if ref == 0:raise ValueError("Reference price is 0, cannot calculate change rate")return (last - ref) / ref * Decimal("100")def amplitude(high: Decimal, low: Decimal, ref: Decimal) -> Decimal:"""Amplitude in percent."""if ref == 0:raise ValueError("Reference price is 0, cannot calculate amplitude")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.
from decimal import Decimalraw_last = "105.20" # Raw data is transmitted as a stringlast = Decimal(raw_last) # Parse directly as decimal, without going through floatprint(Decimal("0.1") + Decimal("0.2") == Decimal("0.3")) # Trueprint(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.
from decimal import Decimal, ROUND_HALF_UPdef format_price(value: Decimal, places: int) -> str:quant = Decimal(1).scaleb(-places) # places=2 gives Decimal("0.01")return str(value.quantize(quant, rounding=ROUND_HALF_UP))print(format_price(Decimal("3.14159"), 2)) # 3.14print(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.
from datetime import datetime, timezonedef normalize_time(raw: str) -> datetime:"""Parse an ISO 8601 time string and convert it to UTC."""dt = datetime.fromisoformat(raw)if dt.tzinfo is None:raise ValueError("Time has no time zone information, rejected before storage")return dt.astimezone(timezone.utc)print(normalize_time("2026-11-24T14:40:39+00:00"))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:
- Price fields must be positive numbers.
- 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.
- The update time must include a time zone and must not be older than the maximum allowed delay.
- The difference between the recalculated change rate and the value returned by the data source must fall within an agreed tolerance.
from dataclasses import dataclassfrom datetime import datetime, timezonefrom decimal import Decimal@dataclass(frozen=True)class Snapshot:symbol: strlast: Decimalopen: Decimalhigh: Decimallow: Decimalupdated_at: datetime # Must be a UTC timeMAX_DELAY_SECONDS = 300def validate(s: Snapshot, now: datetime) -> list[str]:errors = []if min(s.last, s.open, s.high, s.low) <= 0:errors.append("Non-positive price found")if s.low > s.high:errors.append("Low price is higher than high price")if not (s.low <= s.last <= s.high):errors.append("Last price is outside the high-low range")if not (s.low <= s.open <= s.high):errors.append("Open price is outside the high-low range")delay = (now - s.updated_at).total_seconds()if delay > MAX_DELAY_SECONDS:errors.append(f"Data is delayed by {delay:.0f} seconds, exceeding the threshold")return errorssnap = Snapshot(symbol="EXAMPLE-USD",last=Decimal("105.20"),open=Decimal("102.00"),high=Decimal("106.00"),low=Decimal("101.50"),updated_at=datetime(2026, 11, 24, 14, 40, 39, tzinfo=timezone.utc),)now = datetime(2026, 11, 24, 14, 42, 0, tzinfo=timezone.utc)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.
Collection -> Cleaning -> Calculation -> Publishing| | | |Raw payloads Field mapping Indicator Caching andType conversion calculation APIsValidation Historicalrules 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.
