baostock A-share data retrieval
Task Objective
- This Skill is used to: obtain A-share market data, financial indicators, and stock information through the BaoStock interface
- Capabilities include: historical K-lines, financial data, stock information, industry classification, index constituent stocks, trading calendar
- Trigger conditions: when the user mentions baostock or needs to obtain free A-share data, historical quotes, or financial information
Prerequisites
- Dependency description: install the baostock library (already included in dependency)
- Credential configuration: BaoStock requires no registration or API Key and can be used directly
- Optional configuration: supports customizing the server address through environment variables (for proxy scenarios)
BAOSTOCK_SERVER_IP: custom server IP (for scenarios such as nginx proxy)
BAOSTOCK_SERVER_PORT: server port, default 10030
Operation Steps
- Standard process:
- Determine data requirements — the agent understands the user's intent (quotes/K-lines/financials/stock information, etc.)
- Call the corresponding script — select the script according to the data type
- Parse results — the agent analyzes the returned JSON-format data
- Script call mapping:
- K-line/quote data →
python scripts/market_data.py --type kline --code sh.600000 --start 2024-01-01 --end 2024-01-31
- Financial data →
python scripts/financial_data.py --type profit --code sh.600000 --year 2023 --quarter 4
- Stock list/information →
python scripts/stock_info.py --type all_stocks --date 2024-01-02
- Index constituent stocks →
python scripts/stock_info.py --type index_stocks --index hs300
- Industry classification →
python scripts/stock_info.py --type industry
- Trading calendar →
python scripts/stock_info.py --type trade_dates --start 2024-01-01 --end 2024-12-31
- Optional branches:
- When data for multiple stocks is needed: use commas to separate multiple codes, or use
--file to specify a code list file
- When a specific frequency is needed: use the
--frequency parameter (d/w/m/5/15/30/60)
- When the adjustment type needs to be changed: use the
--adjust parameter (1=post-adjustment, 2=pre-adjustment, 3=no adjustment)
Usage Examples
- Example 1: Obtain daily K-line data for a stock
- Scenario/Input: the user says "view the K-line data for Kweichow Moutai over the past month"
- Expected output: return OHLCV data such as date, opening price, highest price, lowest price, closing price, and trading volume
- Key point: call
python scripts/market_data.py --type kline --code sh.600519 --start 2024-03-01 --end 2024-03-31 --frequency d --adjust 2
- Example 2: Query financial indicators
- Scenario/Input: the user says "obtain ICBC's profitability indicators for 2023"
- Expected output: return financial indicators such as ROE, net profit margin, and gross profit margin
- Key point: call
python scripts/financial_data.py --type profit --code sh.601398 --year 2023 --quarter 4
- Example 3: Obtain CSI 300 constituent stocks
- Scenario/Input: the user says "query the list of constituent stocks of the CSI 300 Index"
- Expected output: return the codes and names of all constituent stocks of the CSI 300 Index
- Key point: call
python scripts/stock_info.py --type index_stocks --index hs300
- Example 4: Batch download data for multiple stocks
- Scenario/Input: the user says "download the 2024 daily K-line data for Moutai, Ping An, and China Merchants Bank"
- Expected output: return the K-line data for multiple stocks and save it as CSV
- Key points: Call
python scripts/market_data.py --type kline --code sh.600519,sz.000001,sh.600036 --start 2024-01-01 --end 2024-12-31 --output stocks.csv
Quick reference
Common code examples
import baostock as bs
import pandas as pd
# 登录系统
lg = bs.login()
# 获取日K线数据
rs = bs.query_history_k_data_plus(
"sh.600519",
"date,code,open,high,low,close,volume,amount",
start_date='2024-01-01', end_date='2024-12-31',
frequency="d", adjustflag="2"
)
# 转换为 DataFrame
data_list = []
while (rs.error_code == '0') & rs.next():
data_list.append(rs.get_row_data())
df = pd.DataFrame(data_list, columns=rs.fields)
# 登出系统
bs.logout()
Comparison with other data sources
| Feature |
baostock |
tushare |
jqdatasdk |
akshare |
| Cost |
Free |
Free/Paid |
Credits required upon registration |
Free |
| Registration requirement |
❌ Not required |
✅ Required |
✅ Required |
❌ Not required |
| Data coverage |
Mainly A-shares |
Comprehensive (including macro) |
A-shares + factors |
Comprehensive (including cryptocurrency) |
| K-line data |
✅ |
✅ |
✅ |
✅ |
| Financial data |
✅ |
✅ |
✅ |
✅ |
| Minute-level data |
✅ |
✅ |
✅ |
✅ |
| Real-time quotes |
❌ |
❌ |
❌ |
✅ |
| Specialized data |
Trading calendar |
Macro/Shibor |
Factor data |
Dragon-Tiger List/Northbound/Cryptocurrency |
Resource index
Scripts:
- scripts/market_data.pyPurpose and parameters: Retrieve K-line/quote data, supporting --type/--code/--start/--end/--frequency/--adjust/--fields/--output
- scripts/financial_data.pyPurpose and parameters: Retrieve financial data, supporting --type/--code/--year/--quarter/--output
- scripts/stock_info.pyPurpose and parameters: Retrieve stock list/information/industry/index constituents, supporting --type/--date/--code/--index/--output
- scripts/auth.pyPurpose and parameters: Authentication module, supporting custom server configuration
Reference documentation
Notes
- BaoStock requires no registration or API Key; simply call
bs.login() to use it
- BaoStock stock code format:
sh.600000(Shanghai),sz.000001(Shenzhen),bj.430047(Beijing)
- Some data (such as financial data) may be delayed; it is recommended to retrieve it outside trading hours 9:30-15:00 on trading days
- Scripts return data in JSON format; the agent is responsible for parsing and converting it into a user-friendly display
- Each session must start with
bs.login() andbs.logout() end
- K-line data is returned as strings by default; before numerical calculations, use
.astype(float) to convert
- Not thread-safe; for parallel downloads, use multiprocessing rather than multithreading
- Financial data is provided quarterly, with about a 2-month delay after the end of the reporting period