Fetching A-Share Historical Data in Python: A Practical Guide to Open-Source APIs
This guide shows how to download daily A-share price data in Python with three open-source libraries: Tushare, AKShare, and BaoStock. It covers choosing a data source, handling adjustment methods and units, batch downloads with retries and resumable runs, incremental updates and data validation, storage options, and checks to run before backtesting.
Reliable historical data is the first step in any quantitative strategy. A wrong data source, mixed adjustment methods, or unverified units can all distort backtest results. This guide uses three common open-source data interfaces to show the download process, then covers batch downloads and data validation.
1. Choosing a Data Source and Installing Dependencies
Each of the three libraries has different strengths, so choose based on your needs:
| Library | Token Required | Notes |
|---|---|---|
| Tushare | Yes. Register and get the token from your personal page. | Broad coverage, including financials, dividends, and adjustment factors. Some interfaces require points. |
| AKShare | No | Free and open source. Most field names are in Chinese. Interfaces are updated frequently. |
| BaoStock | No. Call login first. |
Free and suited to historical market data for backtesting. All returned values are strings. |
Install the packages with the following command. pyarrow is needed to write Parquet files.
pip install tushare akshare baostock pandas pyarrow
Do not hard-code your token. Store it in an environment variable and read it with os.environ:
import osimport tushare as tspro = ts.pro_api(os.environ["TUSHARE_TOKEN"])
2. Retrieving the Stock List
The stock list determines which data you download later. With Tushare, the stock_basic interface filters by listing status. L means listed, D means delisted, and P means suspended from listing.
df_basic = pro.stock_basic(exchange="",list_status="L",fields="ts_code,symbol,name,area,industry,list_date,is_hs",)print(df_basic.head())
stock_basic has no status for trading suspensions. To find suspension records for individual stocks, query interfaces such as suspend_d by date.
The stock_info_a_code_name interface in AKShare returns only two columns, code and name. It is fast, but it does not include listing status, so confirm that status separately. The query_stock_basic interface in BaoStock returns the listing date, delisting date, and security type, which makes it useful for cross-checking against other sources.
3. Downloading Daily K-Line Data
Tushare’s daily interface returns unadjusted prices. Volume is in lots, and turnover is in thousands of yuan. Results are sorted by date in descending order, so sort them in ascending order before use:
df_raw = pro.daily(ts_code="600000.SH", start_date="20240101", end_date="20241231")df_raw = df_raw.sort_values("trade_date").reset_index(drop=True)
The pro_bar interface returns adjusted prices directly. Set adj to qfq for forward adjustment or hfq for backward adjustment:
df_qfq = ts.pro_bar(ts_code="600000.SH", api=pro, adj="qfq",start_date="20240101", end_date="20241231",)
AKShare’s stock_zh_a_hist interface uses stock codes without exchange suffixes. Leave adjust empty for unadjusted prices, or set it to qfq or hfq:
import akshare as akdf_ak = ak.stock_zh_a_hist(symbol="600000", period="daily",start_date="20240101", end_date="20241231", adjust="qfq",)
BaoStock codes include an exchange prefix, such as sh.600000. In the adjustflag parameter, 1 means backward adjustment, 2 means forward adjustment, and 3 means unadjusted. All returned values are strings, so convert them to numbers:
import baostock as bsimport pandas as pdbs.login()rs = bs.query_history_k_data_plus("sh.600000","date,code,open,high,low,close,volume,amount,turn",start_date="2024-01-01", end_date="2024-12-31",frequency="d", adjustflag="2",)rows = []while rs.error_code == "0" and rs.next():rows.append(rs.get_row_data())bs.logout()df_bs = pd.DataFrame(rows, columns=rs.fields)num_cols = ["open", "high", "low", "close", "volume", "amount", "turn"]df_bs[num_cols] = df_bs[num_cols].apply(pd.to_numeric)
Inconsistent units are a common cause of backtest errors. The table below summarizes the main units and adjustment parameters for each source. Check AKShare’s units against the actual returned data. The first time you use it, compare one stock against a market data terminal.
| Source | Volume | Turnover | Adjustment Parameter |
|---|---|---|---|
Tushare daily |
Lots | Thousand yuan | pro_bar supports qfq and hfq |
| AKShare | Lots | Yuan | Leave adjust empty for unadjusted. Options are qfq and hfq. |
| BaoStock | Shares | Yuan | adjustflag: 1 backward, 2 forward, 3 unadjusted |
Forward-adjusted prices are not fixed values. Each new dividend or share distribution changes all historical forward-adjusted prices. For this reason, it is better to store unadjusted prices and adjustment factors locally, then calculate adjusted prices when you need them. Tushare’s adj_factor interface provides adjustment factors. Calculate the forward-adjusted price by multiplying the unadjusted price by the factor for that day, then dividing by the factor for the latest trading day.
4. Batch Downloads: Rate Limits, Retries, and Resumable Runs
All data interfaces enforce rate limits. For Tushare, the limit depends on your account points. Check the official documentation for the exact numbers. The function below retries failed requests with exponential backoff:
import timedef fetch_daily(ts_code, start, end, max_retry=3):for attempt in range(1, max_retry + 1):try:return pro.daily(ts_code=ts_code, start_date=start, end_date=end)except Exception as exc:wait = 2 ** attemptprint(f"{ts_code} request failed on attempt {attempt}: {exc}. Retrying in {wait} seconds.")time.sleep(wait)return None
In the main loop, skip stocks whose local files already exist. If the network drops or the script exits with an error, run it again to resume from where it stopped. You do not need to start over:
import osos.makedirs("data/daily", exist_ok=True)failed = []for ts_code in df_basic["ts_code"]:path = f"data/daily/{ts_code}.parquet"if os.path.exists(path):continuedf = fetch_daily(ts_code, "20240101", "20241231")if df is None or df.empty:failed.append(ts_code)continuedf.to_parquet(path, index=False)time.sleep(0.3)print(f"Failed list: {failed}")
Save the failed list separately. In later runs, fetch only the stocks on that list. This avoids using up your call quota on repeated requests.
5. Incremental Updates, Deduplication, and Data Validation
For daily updates, fetch only the data for the latest trading day, then merge it with the historical data. Use (ts_code, trade_date) as the primary key for deduplication. This prevents duplicate records for the same day when data is fetched more than once:
import pandas as pddef merge_incremental(old, new):merged = pd.concat([old, new])merged = merged.drop_duplicates(subset=["ts_code", "trade_date"], keep="last")return merged.sort_values("trade_date").reset_index(drop=True)
Validate the data before writing it. The high price must not be lower than the open or close price. The low price must not be higher than the open or close price. Volume must not be negative. The function below returns the records that break these rules:
def check_ohlc(df):upper = df[["open", "close"]].max(axis=1)lower = df[["open", "close"]].min(axis=1)return df[(df["high"] < upper) | (df["low"] > lower)]
Check two more issues. First, compare the trading dates in your data against the trading calendar to find missing dates. Second, check whether any daily price change exceeds the exchange’s daily price limits. The limits differ for the main board, STAR Market, ChiNext, and the Beijing Stock Exchange. Special rules also apply to ST stocks. Refer to the current exchange rules for the exact figures. Move data that fails validation to a quarantine directory, and load it into your database only after someone has reviewed it.
6. Storage and Scheduled Jobs
Local Parquet files work well for single-machine backtesting. As the number of files grows, partition them by year or by stock. Partitioning by year makes cross-sectional analysis across the whole market easier. Partitioning by stock makes it easier to read the full history of a single stock.
To sync data to the cloud, you can use any object storage service that supports the S3 protocol, and upload files with boto3. Store the access keys in environment variables as well:
import boto3s3 = boto3.client("s3",endpoint_url=os.environ["OBJ_STORE_ENDPOINT"],aws_access_key_id=os.environ["OBJ_ACCESS_KEY"],aws_secret_access_key=os.environ["OBJ_SECRET_KEY"],)s3.upload_file(path, "quant-data", f"daily/{ts_code}.parquet")
You can schedule the job with cron or another scheduling tool. Data sources often need several hours after the market closes before the full day’s data is available, so schedule the job to run in the evening. When the job finishes, send a notification with the results, including the number of successful downloads, the failed list, and the number of validation errors.
7. Checks Before Backtesting
Before you run a backtest, check the following points.
First, keep historical data for delisted stocks. If you backtest using only currently listed stocks, you introduce survivorship bias, and the results will look better than they should.
Second, suspended stocks do not trade on suspension days, so do not assume you can fill orders at the closing price. Stocks at the limit-up price cannot be bought, and stocks at the limit-down price cannot be sold. Your matching logic should handle these cases.
Third, use one adjustment method consistently. Use adjusted prices for technical indicators and long-term returns. Use unadjusted prices to simulate the prices of actual orders. Do not mix the two.
Fourth, use the data only for research and backtesting. Live trading requires a trading interface from a licensed broker and must comply with applicable regulations. Also follow each data provider’s terms of service and keep your request rate within their limits.
8. Summary
Getting historical data may look simple, but it involves choosing a data source, aligning adjustment methods, converting units, managing rate limits, and validating data. Choose one data source, standardize fields and units, and add resumable downloads and validation checks. This keeps daily updates stable. With sufficient API access, controlled request rates, and proper validation, this workflow reduces duplicate collection and rework and provides a reliable base for factor calculation and strategy backtesting.
