Data API¶
Retrieve historical quotes, real-time data, financial information, A-share specific data, etc.
get_price¶
Retrieve historical price data.
| Parameter | Type | Required | Description |
|---|---|---|---|
security |
str or list |
Yes | Stock code |
start_date |
str/date |
No | Start date |
end_date |
str/date |
No | End date |
frequency |
str |
No | 'daily' / '1d'; use get_price_minute for minutes |
fields |
list |
No | Specify returned fields |
count |
int |
No | Return the most recent N bars |
Returns a DataFrame (single stock) or dict[str, DataFrame] (multiple stocks).
history¶
Retrieve count bars of data looking back from the current backtest time. Only available inside strategy callbacks.
attribute_history¶
Retrieve historical attribute data for a single stock.
attribute_history(security, count, unit='1d', fields=('close',), df=True, skip_paused=True, fq='pre')
Returns a DataFrame with columns: open, high, low, close, volume, money, pct_change, turnover.
get_current_data¶
Retrieve real-time snapshots for all A-shares. Returns dict[str, dict] containing fields such as code, name, price, pct_change, volume, pe, pb, total_value, etc.
Not point-in-time safe
Returns the latest snapshot (current price/PE/PB etc.) — there is no point-in-time history. Calling it inside a backtest session emits a FutureWarning (raises with avoid_future_data=True).
get_security_info¶
Retrieve basic information for a single stock. Returns a SecurityInfo object (code, name, industry, total_shares, float_shares, total_value, list_date).
get_valuation¶
Retrieve valuation data. Returns dict or None.
scan_market¶
Scan A-shares with filters.
get_financial_screen¶
Screen by financial metrics.
get_financial_screen(min_pe=None, max_pe=None, min_pb=None, max_pb=None,
min_roe=None, min_revenue=None, min_profit=None)
min_pe / max_pe / min_pb / max_pb filter on the real-time spot snapshot; min_roe (percent — 10 means ROE ≥ 10%), min_revenue (yuan) and min_profit (yuan) filter on the most recent essentially-complete quarterly report, and passing any of them adds roe / revenue / profit columns to the result. When the quarterly report is unavailable the function fails closed: it returns an empty DataFrame with a warning rather than pretending the filters were applied. Both data sources are latest snapshots; calling inside a backtest raises a FutureWarning (see the function docstring).
get_all_securities¶
Retrieve a list of all A-shares. Returns a DataFrame (code, name).
get_trade_days¶
Retrieve the trading calendar. Returns list[date].
Indices & Industry¶
| API | Description | Returns |
|---|---|---|
get_index_stocks(index_code) |
Index constituent stocks | DataFrame |
get_industry_list() |
All industry sectors | list[str] |
get_industry_stocks(industry_name) |
Stocks in a given industry | DataFrame |
get_industry(code) |
Industry classification for a single stock | dict or None |
get_index_weights(index_code, date=None) |
Index constituent weights | DataFrame |
Survivorship bias
get_index_stocks returns the current constituent list — there is no point-in-time historical version. Building a historical backtest universe from it introduces survivorship bias (delisted/removed stocks are silently excluded). Calling it inside a backtest session emits a warning; prefer explicit stock lists for historical universes and handle delistings yourself.
Concept Sectors¶
| API | Description | Returns |
|---|---|---|
get_concept_list() |
All concept sectors | list[str] |
get_concept_stocks(concept_name) |
Constituent stocks of a concept | DataFrame |
Minute-Level Data¶
fetch_minute_data(code, period='5m', start_date=None, end_date=None, adjust='qfq')
get_price_minute(security, count=None, period='5m', fields=None, adjust='qfq')
Supported periods: 1m, 5m, 15m, 30m, 60m.
Tick Data¶
Money Flow & Billboard¶
get_money_flow(code, start_date=None, end_date=None, count=None)
get_billboard_list(stock_list=None, date=None, start_date=None, end_date=None)
A-Share Specific Data¶
get_north_money_flow¶
Northbound money flow (Shanghai-Hong Kong Stock Connect + Shenzhen-Hong Kong Stock Connect aggregate).
| Parameter | Type | Description |
|---|---|---|
start_date |
str/date |
Start date; defaults to 30 days ago |
end_date |
str/date |
End date; defaults to today (China timezone) |
Returns a DataFrame with the following columns:
| Column | Description |
|---|---|
date |
Trading date |
net_buy |
Net buy amount (100 million yuan) |
total_buy |
Total buy amount (100 million yuan) |
total_sell |
Total sell amount (100 million yuan) |
from eqlib import get_north_money_flow
# Get northbound flow for the last 3 months
north = get_north_money_flow(start_date="2024-01-01", end_date="2024-03-31")
# Calculate net buy over the last 5 days
recent_5d = north["net_buy"].tail(5).sum()
if recent_5d > 50:
print("Strong northbound capital inflow")
Note: Uses China timezone (UTC+8) to determine "today"; cached for 1 hour.
get_margin_data¶
Margin trading data (market-wide aggregate).
Returns a DataFrame with the following columns:
| Column | Description |
|---|---|
date |
Trading date |
margin_balance |
Margin balance (100 million yuan) |
margin_buy |
Margin buy amount (100 million yuan) |
margin_repay |
Margin repayment amount (100 million yuan) — NaN for the first row |
short_balance |
Short selling balance (100 million yuan) |
from eqlib import get_margin_data
margin = get_margin_data(start_date="2024-01-01", end_date="2024-03-31")
# Margin balance rate of change
margin["change_pct"] = margin["margin_balance"].diff(5) / margin["margin_balance"].shift(5) * 100
Note: margin_repay is NaN for the first row (no prior balance to compute from). Users can handle this with dropna() or fillna().
get_limit_up_down_stats¶
Limit up/down statistics (daily count of stocks hitting price limit up / limit down).
Returns a DataFrame with the following columns:
| Column | Description |
|---|---|
date |
Trading date |
limit_up_count |
Number of stocks hitting the upper price limit |
limit_down_count |
Number of stocks hitting the lower price limit |
api_error_count |
Number of failed API calls (for data quality monitoring) |
from eqlib import get_limit_up_down_stats
stats = get_limit_up_down_stats()
# Systemic risk alert
latest_down = stats["limit_down_count"].iloc[-1]
if latest_down > 100:
print("⚠️ Systemic risk alert")
Note: The API only supports the most recent 30 trading days; a warning is issued if the requested range exceeds this limit.
get_restriction_release¶
Restricted share unlock schedule (list of upcoming unlocks within the next N days).
| Parameter | Type | Description |
|---|---|---|
days |
int |
Number of days to look ahead; defaults to 30 |
Returns a DataFrame with the following columns:
| Column | Description |
|---|---|
code |
Stock code |
name |
Stock name |
release_date |
Unlock date |
release_amount |
Unlock quantity (10,000 shares) |
release_value |
Unlock market value (100 million yuan) |
release_pct |
Percentage of pre-unlock float market cap |
from eqlib import get_restriction_release
# Get unlocks for the next 30 days
releases = get_restriction_release(days=30)
# Alert on large unlocks
large = releases[releases["release_value"] > 50]
print(f"Large unlocks: {len(large)} stocks")
Financial Data¶
Chained Stock Selection API¶
Available fields are accessed via the valuation namespace: code, market_cap, total_value, float_value, pe, pb, turnover, price, pct_change.
Chained methods: .filter(), .order_by(), .limit().
q = query(valuation.code, valuation.market_cap, valuation.pe) \
.filter(valuation.market_cap.between(20, 30), valuation.pe > 0) \
.order_by(valuation.market_cap.asc()) \
.limit(5)
df = get_fundamentals(q)
Not point-in-time safe
get_fundamentals returns the provider's latest snapshot; the date parameter is ignored in V1 (the underlying sources carry no disclosure-date history). Calling it inside a backtest leaks future information: the framework emits a FutureWarning, and set_option('avoid_future_data', True) escalates it to a ValueError. Use your own historical fundamentals for in-backtest factors; research mode and live trading are unaffected.
get_current_data_object¶
Retrieve real-time market snapshots with attribute access. Returns dict[str, _StockDataObj].
Not point-in-time safe
Same source as get_current_data — the latest snapshot (including ST status derived from the current name). Calling it inside a backtest session emits a FutureWarning (raises with avoid_future_data=True).
get_extras¶
Retrieve additional data fields ('is_st' or 'net_value').
Not point-in-time safe
Returns the latest snapshot (e.g. the current ST status) — there is no point-in-time history. Calling it inside a backtest session emits a FutureWarning (raises with avoid_future_data=True). For PIT-safe ST status inside backtests use set_option('st_status_map', ...).
Universe Management¶
Local Files¶
| API | Description |
|---|---|
download_stock_data(code, start_date, end_date, adjust='qfq', output_dir=None) |
Download daily data as CSV |
load_csv(path, index_col='date', parse_dates=True) |
Load data from a local CSV |
clear_cache() |
Clear in-memory cache |
save_stock_local(security, start_date, end_date) |
Download and save locally |
load_stock_local(security, start_date, end_date) |
Load from local storage |
has_local_data(security) |
Check if local data exists |
list_local_stocks() |
List all local files |
remove_local_data(security) |
Delete a single local file |
clear_all_local_data() |
Delete all local files |
Historical price and adjustment contracts¶
count must be a positive integer (not a boolean). Results contain the last N rows in the window, or fewer when data is unavailable. String, date and datetime inputs are supported. With an active backtest context, get_price follows attribute_history: only daily bars before the current date are visible, and explicit future end dates are clamped. Research queries without a backtest context use the requested range. frequency="1m" raises NotImplementedError rather than silently returning daily bars.
Preloaded prices must match fq: default qfq preload supports fq="pre"; requesting fq=None (raw prices) raises ValueError unless the preload explicitly contains unadjusted data. Use genuine raw prices rather than treating adjusted prices as raw. Mutating returned data does not mutate the shared cache.
get_price_minute also enforces simulation visibility: only bar timestamps strictly before current_dt are returned, conservatively excluding the current bar. Supported periods are 1m, 5m, 15m, 30m and 60m; rows are sorted before taking the last count bars.
Point-in-time truncation inside backtests¶
While a backtest is running, the following data APIs are uniformly truncated by the simulated clock, matching get_price semantics:
| API | In-session behavior |
|---|---|
fetch_stock_data |
Truncated to T-1 during decision-time callbacks (before_trading_start, scheduled functions, handle_data); the current day is included in post-close callbacks and after the loop; pure-future requests return empty without touching the network |
fetch_minute_data |
Truncated at the exact simulated clock (same as get_price_minute) |
get_money_flow |
Filtered by the cutoff date before applying count |
get_billboard_list / get_north_money_flow / get_margin_data / get_limit_up_down_stats |
Query range clamped to the cutoff date |
load_stock_local |
Local CSV rows truncated at the simulated clock (same as fetch_stock_data); engine-internal preload and post-loop benchmark reads are explicitly exempt |
fetch_cached (eqlib.data_cache) |
Disk-hit branch truncated at the same cutoff; the network-miss branch is already truncated inside fetch_stock_data |
check_golden_cross |
History truncated at the same cutoff before the moving averages are computed |
get_fundamentals / get_financial_abstract |
Snapshot APIs, cannot be truncated — emit FutureWarning (raise with avoid_future_data=True) |
get_valuation / get_extras / scan_market / get_financial_screen |
Same: latest spot snapshot (current PE/PB/ST status etc.), no point-in-time history |
get_current_data / get_current_data_object |
Same: latest full-market spot snapshot (current price/PE/PB/turnover etc.), no point-in-time history |
get_restriction_release |
Same: the unlock schedule announced as of the real today (window computed from the real clock), no announcement-date history |
get_index_stocks / get_index_weights / get_concept_stocks / get_industry_stocks |
Same: current constituents snapshot only — historical universes built from them suffer survivorship bias |
get_tick_data |
Same: current-day tick snapshot only; trade_date is ignored |
get_industry / get_concept_list / get_industry_list / get_all_securities / get_security_info |
Name/classification/master-data lookups — intentionally not guarded (caveat: get_security_info's name is the current name and may carry an ST tag, and total_value is a current snapshot — for time-sensitive uses switch to PIT channels such as st_status_map) |
Research mode (no active backtest context) and paper trading are not truncated and honor the requested range. The engine's internal full-range preload fetches are explicitly exempt.