How to Efficiently Retrieve Historical Stock Market Data

    This article explains how to build a reliable pipeline for retrieving historical stock market data, the foundation of quantitative research, backtesting, and risk monitoring. It covers defining the research universe to avoid survivorship bias, pulling historical daily K-line data, choosing the correct price adjustment method, running a data quality checklist, and engineering storage with incremental updates. The goal is reproducible, trustworthy data before any strategy code is written.

    1. Why Data Retrieval Is the Starting Point of Quant Development

    In the full pipeline of quantitative research, strategy backtesting, and risk monitoring, market data sits at the very bottom. No matter how sophisticated the upper-layer models are, if the underlying security list is incomplete, price adjustment is inconsistent, or timestamps are ambiguous, the backtest conclusions cannot be trusted. Three common problems in engineering practice all originate at the data layer: look-ahead bias (using information that was not knowable at the time), survivorship bias (backtesting only on stocks that are still listed today), and mixed adjustment conventions (returns contaminated by corporate actions). So before writing any strategy code, standardizing the data retrieval and validation process is the highest-return investment you can make.

    2. Step One: Define the Research Universe

    Downloading historical data must start from a clearly defined security scope, otherwise you easily end up covering only a handful of instruments. The common approach is to provide a security master data query capability that filters across multiple dimensions:

    1. # Illustrative code: retrieve security master data
    2. # 1) Filter by sector / Stock Connect scope
    3. df_h = client.universes.get(is_hs="H", as_df=True)
    4. # 2) Keep only listed securities to avoid survivorship bias
    5. df_l = client.universes.get(list_status="L", as_df=True)
    6. # 3) Suspended-trading list, used to exclude non-tradable samples in backtests
    7. df_t = client.universes.get(list_status="T", as_df=True)
    8. # 4) Specify exchange + specific fields to reduce transfer and memory overhead
    9. df_sse = client.universes.get(
    10. market_sign=["SSE"],
    11. fields="ts_code,name,area,list_status,delist_date",
    12. as_df=True,
    13. )

    A few easily overlooked details matter here. First, security codes usually carry an exchange suffix (such as .SH, .SZ), and the suffix must be preserved when mixing markets, otherwise code collisions occur. Second, list_status should be a dynamic condition in the backtest rather than a one-time filter: if a stock is suspended or delisted during part of the backtest window, no trade should be assumed for that period. Third, delist_date is the key field for eliminating survivorship bias; delisted samples must remain in the universe and simply stop being fetched after their delisting date. Fourth, explicitly specifying fields significantly reduces network and memory overhead, which is especially noticeable when pulling full metadata for tens of thousands of securities.

    3. Step Two: Pull Historical Daily K-Line Data

    Once the scope is defined, request the time series instrument by instrument. A typical call looks like this:

    1. symbol = "600000.SH"
    2. r = sp.klines.get_history_data(
    3. symbol, period="d", count=100,
    4. adjust="normal", as_df=True
    5. )

    The result is a tabular structure. Common fields include ts_code, trade_time, open, high, low, close, volume, amount, and turnover_rate. The number of rows is the sample size (100 rows and 9 columns in the example), and rows are sorted in reverse chronological order by default (the newest row on top). Be sure to re-sort ascending by trade_time before backtesting, otherwise indicator calculations and signal triggers will be misaligned throughout.

    The engineering meaning of the fields must be clearly distinguished: volume is generally trading volume (lots or shares, depending on the data source definition), and amount is turnover value (in currency units); dividing one by the other yields an average price, useful for a rough read on the trade distribution. turnover_rate is the turnover rate (a percentage value) and is a common threshold field for liquidity filtering and abnormal-move detection. Different data sources may define the unit of volume differently, so when integrating you should fix the convention in the documentation and record it in the data dictionary to avoid inconsistent understanding within the team.

    4. Price Adjustment: The Step Most Likely to Distort Backtests

    The adjust parameter determines how the price series is processed. There are typically three conventions in the industry:

    • No adjustment: keeps the original traded prices, suitable for analyzing real trades and price boundaries (such as limit up/down and historical prices on a chart);
    • Post-adjustment: adjusts backward from the current price, scaling historical prices up, suitable for computing long-term returns and factor values;
    • Pre-adjustment: uses the early listing period as the baseline, compressing the latest price, suitable for visualization and moving-average style indicators.

    The key principle is that only one convention may be used within a single backtest, and the convention must be written into the data version number. Ex-dividend and ex-rights events create breaks in the price series; if conventions are mixed, the model will mistake a dividend for a crash. If precise absolute returns are needed, it is recommended to store both the unadjusted series and the adjustment factors, and synthesize them on demand rather than repeatedly re-downloading.

    5. Data Quality Validation Checklist

    Finishing the download does not mean the data is usable. It is recommended to solidify the following checks into automated tasks:

    1. Completeness: count trading days per instrument and compare against the trading calendar; clustered missing days usually indicate suspension or a data source gap;
    2. Monotonicity: timestamps strictly increasing with no duplicates; duplicate rows need an explicit deduplication strategy (keep the latest or flag the conflict);
    3. Out-of-range checks: the high must not be below the open or close, the low must not be above the open or close, and price moves outside a reasonable range should trigger an alert;
    4. Null and zero values: zero volume with a price change is a non-trading situation and should be flagged separately rather than interpolated directly;
    5. Time zone and time semantics: unify daily timestamps to natural-day midnight or market close to avoid a one-day misalignment when stitching across markets;
    6. Align to the trading calendar: all instruments share the same trading calendar, and missing days are represented with an explicit mask rather than forward-filled and treated as real samples.

    6. Engineering Storage and Incremental Updates

    Downloading ten years of daily data for the whole market in one shot is not a scary amount of data; the real trouble is daily incremental updates and version management. A recommended layered scheme is: a raw layer that stores immutable sharded files (partitioned by year and exchange), an intermediate layer that stores cleaned and adjusted wide tables, and an application layer that generates factor matrices on demand. Only when the raw layer is immutable can any backtest be reproduced.

    Incremental updates use an idempotent design “driven by the trading calendar”: first determine the latest trading day, then request only data after that day, and enforce a uniqueness constraint on (code, date) before writing so that repeated runs produce no side effects. For batch pulling, control concurrency and retries, use exponential backoff to handle rate limiting, and record each task’s request volume, failure list, and elapsed time to form an observable collection log. If the data volume keeps growing, you can place raw files in object storage, trigger cleaning tasks with a message queue, run parallel pulling on a container platform, and track failure rates and latency with logging and monitoring/alerting services; Baidu AI Cloud offers corresponding product categories for these general capabilities, and you can select based on your team’s existing tech stack.

    7. Summary

    The core of retrieving historical stock data is not a single call but four conventions: how the universe is defined, the price adjustment convention, time semantics, and a reproducible storage version. Write these four points into the data dictionary with automated validation, and subsequent factor computation and backtesting can stand on a trustworthy foundation. It is recommended to first get the pipeline working end to end on a single instrument’s daily data, then gradually expand to the whole market and higher frequencies, with each step delivered only once validation passes.