How to Get Historical Stock Data: An Engineering Guide
This guide breaks down the requirements for building a reproducible stock data pipeline, covering security master data, quotes, fundamentals, corporate actions, and trading behavior data. It outlines a four-layer architecture, shows Python examples for fetching and adjusting daily prices, and explains how to handle financial disclosure dates, dividends, and limit-up behavior. It also highlights data quality pitfalls such as survivorship bias and look-ahead bias, plus storage and scheduling recommendations. Readers will learn how to organize raw data, standardize adjustments, and version datasets so research results can be reproduced and audited.
1. Problem Background and Data Requirements
In quantitative research, financial engineering, and academic writing, data quality often determines how reliable the conclusions are. Beginners searching for historical market data tend to focus only on whether data can be obtained, while overlooking deeper issues such as data definitions, price adjustment methods, timestamp conventions, and survivorship bias. To build a reproducible research workflow, start by breaking the requirements into several categories of base data:
- Security master data (universe): security codes, names, listing status, market, listing and delisting dates, and industry classification. This defines the sample space for the study.
- Market data (quotes/klines): daily bars are the most common granularity, typically containing open, high, low, close, volume, turnover value, and turnover rate. Intraday strategies also require minute-level or tick data.
- Fundamentals: balance sheets, income statements, cash flow statements, reporting periods, and announcement dates. A common mistake is confusing the reporting period with the actual disclosure date, which introduces look-ahead bias.
- Corporate actions: dividends, bonus issues, rights issues, splits, and mergers, which directly affect price adjustment calculations.
- Trading behavior data: price limits, suspensions, resumptions, and block trades, used to characterize liquidity and regulatory constraints.
Organizing these data into layers is the foundation for all subsequent work.
2. Overall Architecture for Data Acquisition
A robust data acquisition design usually consists of four layers:
- Ingestion layer: issues requests through a unified data API client, abstracting away differences in underlying protocols.
- Scheduling layer: handles task orchestration, rate control, failure retries, and incremental cursor management.
- Storage layer: a raw layer stores data exactly as returned by the API, a clean layer stores standardized results, and a serving layer supports direct queries for research.
- Governance layer: includes the data dictionary, definition notes, data versions, and validation rules.
The following is illustrative code for initializing a client and retrieving the security list (the API names are generic examples and do not represent any specific product):
from datahub import DataClientclient = DataClient(token="<YOUR_TOKEN>")# Get all securities with active listing statusdf_listed = client.universes.get(list_status="L", as_df=True)# Filter by market and fieldsdf_sse = client.universes.get(market_sign=["SSE"],fields="ts_code,name,area,list_status,delist_date",as_df=True)print(df_listed.head(), df_sse.head())
The key point is not the specific function names but three general design principles: a unified return structure (a DataFrame is convenient for downstream processing), selectable fields (to reduce bandwidth and memory usage), and filterable status (to split the sample by listed, suspended, or delisted).
3. Fetching Daily Bars and Handling Price Adjustments
Daily bars are the most common research granularity. A typical request looks like this:
symbol = "600000.SH"df = client.klines.get_history_data(symbol, period="d", count=100, adjust="normal", as_df=True)print(df.head())
The returned structure generally includes fields such as ts_code, trade_time, open, high, low, close, volume, amount, turnover_rate. In real projects, pay attention to the following:
- Adjustment method: the common options are unadjusted, forward-adjusted, and backward-adjusted. Forward adjustment is convenient for visualization and indicator calculation, while backward adjustment is better for compounding returns over long periods. For factor research, apply the same convention across the full sample and avoid switching midway through a series.
- Timestamp convention: convert to timezone-aware date types and distinguish calendar days from trading days. Align data using the trading calendar to avoid misalignment when combining markets.
- Sorting and deduplication: API responses are often in reverse chronological order, so sort ascending by
ts_code, trade_timeand remove duplicates before storing. - Volume units: different sources may use lots or shares. Record this in the data dictionary to prevent magnitude errors.
Example code for batch retrieval:
import timeimport pandas as pdframes = []for code in df_listed["ts_code"]:try:d = client.klines.get_history_data(code, period="d", start="20100101", end="20251231",adjust="qfq", as_df=True)frames.append(d)except Exception as e:print("failed:", code, e)time.sleep(0.2) # Control request rateraw = pd.concat(frames, ignore_index=True)raw = raw.sort_values(["ts_code", "trade_time"]).drop_duplicates()raw.to_parquet("raw_daily.parquet")
The engineering recommendation is to append to the raw layer without modification and perform all cleaning downstream, ensuring traceability and rerun capability.
4. Handling Financial, Dividend, and Limit-Up Data
1. Financial data
The core of financial research is point-in-time correctness. Store both the reporting period (for example, 2024Q3) and the actual announcement date, and split features by the announcement date to avoid look-ahead bias. Also handle changes in consolidation scope, accounting standard adjustments, and unit differences (yuan versus ten thousand yuan).
2. Dividend and bonus issue data
Corporate action data is used to compute adjustment factors. Recommended fields include the ex-dividend date, dividend per share, bonus and conversion ratios, and rights issue price and ratio. Adjustment factors can be derived from these fields, and the raw values should be retained for auditing.
3. Trading behavior (limit-up) data
Price limits and sealing behavior reflect supply-demand imbalances under regulatory constraints. Research requires clarifying the price limit calculation rules (accounting for ST stocks, new listings, and different board limits), identifying board openings and reseals, and measuring sealed order value and seal duration. This data is sensitive to noise, so always retain the raw snapshots.
5. Data Quality Governance and Common Pitfalls
- Survivorship bias: backtesting only with currently listed securities overstates returns. Include delisted samples.
- Missing data and suspensions: prices do not update during suspensions, so align by the trading calendar when computing returns rather than simply forward filling.
- Outliers: sudden volume spikes and zero or negative prices should be flagged separately rather than deleted outright.
- Definition drift: index constituents and industry classifications change, so version them.
- Reproducibility: fix the data version, random seed, and code commit, and state the data retrieval date in the paper appendix.
6. Storage and Scheduling Recommendations
As data volume grows, use columnar storage such as Parquet with partitioning by year or market, and use a task scheduler for incremental updates: use the latest trading day as a cursor, fetch only the increment, and merge with deduplication. For team collaboration, host the clean layer data in object storage and use logging and monitoring with alerts to track task success rate and latency. General capabilities such as object storage, container platforms, and monitoring and alerting offered by platforms like Baidu AI Cloud can serve as infrastructure options for such data pipelines.
7. Conclusion
Getting historical stock data is not a one-off API call but an engineering effort that spans sample construction, price adjustment, point-in-time alignment, quality validation, and version management. Breaking down the requirements clearly, documenting the definitions, and retaining complete raw data are what make research conclusions reproducible and reviewable.
