Conversation guidance specifications
Clarify intent (must ask when intent is ambiguous)
User input is often imprecise; determine the intent before calling,do not guess and run directly。
| User says | Possible intent | Must ask |
|---|---|---|
| "Help me check stock XX" | Real-time quotes? K-line trend? Large orders? | ✅ |
| "Analyze XX" | Technical aspects? Capital flow? Compare with whom? | ✅ |
| "How is sector XX doing" | Sector overall rise/fall? Constituent stocks? Leading stocks? | ✅ |
| "Pick some good stocks" | Short-term? Value? Which industry? Conditions? | ✅ |
| "XX's 5-minute K-line" | Intent is clear | ❌ Execute directly |
| "Today's limit-up stocks" | Intent is clear | ❌ Execute directly |
Examples of clarifying wording:
用户:"帮我分析一下宁德时代"
Claude:"好的,请问你主要想看哪个方向?
1. 今日实时行情 + 资金流向
2. 分钟K线(盘中走势)
3. 近期日K线趋势
4. 和比亚迪、亿纬锂能等对比
5. 用问财筛选相关概念股"
Follow-up prompts after a call (only mention when there is extended value)
Do not mechanically list "you can also do XYZ" every time. Only bring it up naturally in the following situations:
| Scenario | Appropriate follow-up prompt |
|---|---|
| Industry ranking displayed | "Do you need to check the constituent stock quotes of a certain industry?" |
| Minute K-line displayed | "Do you need to also look at large order flow or order book depth?" |
| Multi-stock comparison table displayed | "Do you need to display a normalized trend chart or correlation?" |
| Wencai selected candidate stocks | "Do you need to perform K-line technical verification on these stocks?" |
| Auction anomalies displayed | "Do you need to pull the pre-market time-sharing for a certain anomalous stock to see the details?" |
Complete call examples (directly runnable)
See details in examples/ directory, 4 end-to-end scenarios:
| File | Scenario |
|---|---|
examples/01_minute_kline.py |
Minute K-line + moving averages + volume anomaly annotation |
examples/02_sector_industry.py |
Industry ranking + concept sector constituent stocks + index quotes |
examples/03_multi_stock_compare.py |
Multi-stock batch comparison: table + normalized trend + correlation |
examples/04_bigorder_auction.py |
Large order flow + auction anomaly scan + time-sharing/order book |
examples/05_wencai_nlp.py |
Wencai NLP: stock selection/quotes/financials/technical/complex combinations + combined with klines |
Scenario quick reference
| User need | How to use |
|---|---|
| Today's limit-up/consecutive limit-up/strong auction stocks | wencai_nlp("今日涨停,非ST") |
| Financial indicator stock selection (ROE/PE/PB) | wencai_nlp("连续3年ROE大于15%,非ST") |
| Technical pattern stock selection (MACD golden cross) | wencai_nlp("均线多头排列,MACD金叉") |
| Complex combination condition stock selection | wencai_nlp("...多条件...") See case 5 |
| CATL 5-minute K-line | klines(code, interval="5m", count=78) |
| Moutai today's time-sharing chart | intraday_data(code) |
| Time-sharing on a certain historical day | min_snapshot(code, date="20250101") |
| Order book five-level bid/ask | depth(code) or tick_level1(code) |
| Large order flow | big_order_flow(code) |
| Today's auction anomalies | call_auction_anomaly(market) |
| Shenwan industry list | ths_industry() |
| Concept sector list | ths_concept() |
| Sector constituent stocks | block_constituents(link_code) |
| Index quotes | market_data_index(ths_code) |
| Multi-stock comparison | Batch market_data_cn + klines |
| Rights and dividends data/ex-rights | corporate_action(code) |
| Today's IPO | ipo_today() |
Step Zero: Installation
pip install --upgrade thsdk
Package source:PyPI
Connect
All calls uniformly use guest mode, no account configuration required:
from thsdk import THS
with THS() as ths:
...
Step One: Stock code resolution
All Chinese names/abbreviations/short codes first use search_symbols to get the complete ths_code:
with THS() as ths:
resp = ths.search_symbols("宁德时代")
# resp.data → [{'THSCODE': 'USZA300750', 'Name': '宁德时代', 'Code': '300750', 'MarketDisplay': '深A'}, ...]
Code selection rules:
| Case | Handling |
|---|---|
| 0 results | Inform the user that none was found |
| 1 result | Use directly |
| Multiple results, only 1 A-share | Automatically select the A-share |
| Multiple results, multiple A-shares | Display the list and wait for the user to choose |
Indices use dedicated market prefixes (no need for search_symbols):
| Index | THSCODE |
|---|---|
| SSE Composite Index | USHI000001 |
| SZSE Component Index | USZI399001 |
| ChiNext Index | USZI399006 |
| STAR 50 | USHI000688 |
| CSI 300 | USHI000300 |
| CSI 500 | USHI000905 |
| SSE 50 | USHI000016 |
⚠️ The index prefix is
USHI/USZI(notUSHA/USZA), you need to callmarket_data_indexinstead ofmarket_data_cn
Market code description
| Prefix | Meaning |
|---|---|
USHA |
Shanghai A-shares |
USZA |
Shenzhen A-shares |
USHI |
Shanghai index |
USZI |
Shenzhen index |
USTM |
Beijing Stock Exchange |
UHKG |
Hong Kong stocks |
K-line data
Complete interval parameters
"1m" / "5m" / "15m" / "30m" / "60m" / "120m" / "day" / "week" / "month" / "quarter" / "year"
⚠️ The correct way to write it is
"5m"instead of"5min"
Usage (choose one of count or start/end, they cannot be mixed)
from datetime import datetime
from zoneinfo import ZoneInfo
tz = ZoneInfo('Asia/Shanghai')
with THS() as ths:
# 方式1:按条数(最常用)
resp = ths.klines("USZA300750", interval="5m", count=78)
# 方式2:按时间范围
resp = ths.klines(
"USZA300750",
interval="day",
start_time=datetime(2025, 1, 1, tzinfo=tz),
end_time=datetime(2025, 3, 1, tzinfo=tz)
)
# 复权:前复权 forward / 后复权 backward / 不复权 ""(默认)
resp = ths.klines("USHA600519", interval="day", count=250, adjust="forward")
df = resp.df # 列: 时间, 开盘价, 最高价, 最低价, 收盘价, 成交量 等
# 分钟K线的"时间"已自动转为 datetime;日K的"时间"为 datetime(YYYYMMDD)
Minute K-line analysis example
with THS() as ths:
resp = ths.klines("USZA300750", interval="5m", count=78)
df = resp.df
df['ma5'] = df['收盘价'].rolling(5).mean()
df['ma20'] = df['收盘价'].rolling(20).mean()
# 成交量异动(超均量2倍)
df['vol_avg'] = df['成交量'].rolling(20).mean()
df['vol_spike'] = df['成交量'] > df['vol_avg'] * 2
# 支撑/压力位
support = df['最低价'].tail(20).min()
resistance = df['最高价'].tail(20).max()
Order book and real-time data
Intraday time series (current day)
with THS() as ths:
resp = ths.intraday_data("USZA300750")
df = resp.df # 列: 时间(datetime), 价格, 成交量, 均价 等
Historical time series (any date within the past year)
with THS() as ths:
resp = ths.min_snapshot("USZA300750", date="20250301")
df = resp.df
Five-level bid/ask order book
with THS() as ths:
resp = ths.depth("USZA300750") # 单只
resp = ths.depth(["USZA300750", "USHA600519"]) # 多只
df = resp.df # 含 买1~5价/量, 卖1~5价/量
3-second Tick data
with THS() as ths:
resp = ths.tick_level1("USZA300750")
df = resp.df
Super order book (including ten-level orders)
with THS() as ths:
resp = ths.tick_super_level1("USZA300750") # 实时
resp = ths.tick_super_level1("USZA300750", date="20250301") # 历史(近一年)
df = resp.df
Large orders and auction
Large order flow
with THS() as ths:
resp = ths.big_order_flow("USZA300750")
df = resp.df
# 含字段:主动买入特大单量/金额/笔数、主动卖出特大单量/金额/笔数、
# 主动买入大单量/金额/笔数、资金流入/流出 等
Call auction unusual activity (pre-market 9:15–9:25 monitoring)
with THS() as ths:
resp = ths.call_auction_anomaly("USHA") # 沪市
resp = ths.call_auction_anomaly("USZA") # 深市
df = resp.df
# 异动类型1 已自动映射中文:
# 涨停试盘 / 跌停试盘 / 涨停撤单 / 竞价抢筹 / 竞价砸盘
# 大幅高开 / 大幅低开 / 急速上涨 / 急速下跌
# 买一剩余大 / 卖一剩余大 / 大买单试盘 / 大卖单试盘
Morning call auction snapshot
with THS() as ths:
resp = ths.call_auction("USZA300750")
df = resp.df
Sectors and indices
Industry sector list
with THS() as ths:
resp = ths.ths_industry() # 同花顺行业(含 URFI 前缀的 link_code)
df = resp.df # 含板块名称、代码(link_code)、涨幅、成交量、上涨/下跌家数 等
Concept sector list
with THS() as ths:
resp = ths.ths_concept()
df = resp.df # 含概念名称、link_code、涨幅、领涨股 等
Sector constituent stocks
with THS() as ths:
# 先获取行业/概念列表,找到 link_code(格式 URFIXXXXXX)
industry_resp = ths.ths_industry()
target_row = [r for r in industry_resp.data if '新能源' in str(r.get('名称', ''))][0]
link_code = target_row.get('代码') or target_row.get('link_code')
resp = ths.block_constituents(link_code)
df = resp.df # 含成分股代码、名称等
Sector real-time quotes
with THS() as ths:
# query_key: "基础数据"(涨幅/成交/市值)或 "扩展"(涨速/主力净流入)
resp = ths.market_data_block("URFI881273", "基础数据")
df = resp.df
# 含: 价格, 涨幅, 成交量, 板块总市值, 板块流通市值, 上涨家数, 下跌家数, 领涨股
Index real-time quotes
with THS() as ths:
# 单只
resp = ths.market_data_index("USHI000001", "基础数据")
# 多只(必须同市场:同为 USHI 或同为 USZI)
resp = ths.market_data_index(["USHI000001", "USHI000300", "USHI000905"])
df = resp.df # 含: 价格, 涨幅, 涨跌, 成交量, 总金额, 最高价, 最低价
# 扩展(含量比、振幅等)
resp = ths.market_data_index("USHI000001", "扩展")
Available query_key for market_data_cn
| query_key | Meaning |
|---|---|
"基础数据" |
Price, change percentage, trading volume, amount, open/high/low, speed of change, current volume |
"基础数据2" |
Simplified version |
"基础数据3" |
Minimal (price, previous close, trading volume) |
"扩展1" |
Gain, change, turnover rate, volume ratio, main force net inflow, order ratio |
"扩展2" |
Gain, turnover rate, total market cap, circulating market cap, order ratio, circulating market cap |
"汇总" |
Full fields (basic + extended merged, preferred for multi-stock comparison) |
⚠️
market_data_cnrequires the same market: Shanghai A-shares (USHA) and Shenzhen A-shares (USZA) cannot be mixed in the same call
Multi-stock batch comparison
Complete workflow
import pandas as pd
from collections import defaultdict
from thsdk import THS
stock_names = ["贵州茅台", "五粮液", "泸州老窖"]
with THS() as ths:
# Step 1: 批量解析代码
stock_codes = []
for name in stock_names:
resp = ths.search_symbols(name)
a_shares = [s for s in resp.data
if any(m in s.get('MarketDisplay', '') for m in ['沪A', '深A'])]
if a_shares:
stock_codes.append({'name': name, 'code': a_shares[0]['THSCODE']})
# Step 2: 按市场分组(market_data_cn 要求同市场)
by_market = defaultdict(list)
for s in stock_codes:
by_market[s['code'][:4]].append(s)
# Step 3: 批量获取行情
rows = []
for market, stocks in by_market.items():
codes = [s['code'] for s in stocks]
resp = ths.market_data_cn(codes, "汇总")
for i, row in enumerate(resp.data):
row['股票名称'] = stocks[i]['name']
rows.append(row)
quote_df = pd.DataFrame(rows)
# Step 4: 批量K线
klines_data = {}
for s in stock_codes:
resp = ths.klines(s['code'], interval="day", count=30, adjust="forward")
klines_data[s['name']] = resp.df
# Step 5: 归一化
for name, df in klines_data.items():
df['归一化'] = df['收盘价'] / df['收盘价'].iloc[0] * 100
# Step 6: 相关性(量化场景)
returns = pd.DataFrame({
name: df['收盘价'].pct_change()
for name, df in klines_data.items()
})
corr_matrix = returns.corr()
Output specifications (two-step approach)
Step 1: Table(rendered by show_widget)
| Stock | Latest Price | Change % | Turnover | Turnover Rate | Volume Ratio | Main Net Inflow | Total Market Cap |
Step 2: Chart(rendered by show_widget)
- Normalized trend line chart (multiple lines, distinguished by color, starting point = 100)
- Additional output for quantitative scenarios: correlation heatmap
Wencai natural language query (wencai_nlp)
Wencai is an AI stock-picking platform under Hithink RoyalFlush (iwencai.com), supporting full-market scans using natural language.
wencai_nlp Directly connects to the same interface; for multiple conditions usecomma/semicolon/spaceas separators.
with THS() as ths:
resp = ths.wencai_nlp("连续3日主力净流入,换手率大于5%,非ST")
df = resp.df # 每行一只股票,列为查询涉及的字段
⚠️ buffer_size has been set to 8MB; no manual adjustment is needed when the returned data volume is large
Quick reference for six query types
① Quotes & market board
"今日涨停,非ST"
"连续2日涨停,非一字板,非ST"
"今日涨停原因类别,涨停封单额,封单量"
"竞价涨幅大于3%,竞价量大于昨日成交量5%,非ST"
"主力净流入由大到小排名前20,非ST"
"近10日区间主力资金流向大于5000万,市值大于100亿,日成交额大于30亿"
② Sectors & industries
"今日申万行业涨跌幅排名"
"今日概念板块涨幅排名前20"
"人工智能概念股,今日涨跌幅,成交额,主力净流入"
"半导体行业股票,涨幅,换手率,市值"
"今日涨幅最大的5个概念板块,涨幅,成分股数量"
③ Financial indicators
"连续3年ROE大于15%,非ST,上市大于3年"
"净利润增长率大于30%,营业收入增长率大于20%,非ST"
"市盈率小于15,股息率大于3%,市净率小于2,非ST"
"市净率小于1,非ST,流通市值大于20亿" # 破净股
"连续5年分红,股息率大于4%,资产负债率小于60%"
④ Technical patterns
"均线多头排列,MACD金叉,换手率大于3%,非ST"
"5日均线上穿20日均线,成交量放大,涨幅大于1%"
"均线粘合,平台突破,成交量大于5日均量1.5倍"
"仙人指路,非ST,非停牌"
"250日新高,非ST,沪深A,上市超过250天"
⑤ Complex combinations (short-term/quantitative)
# 短线强势选股
"均线多头排列,MACD金叉,DIFF上穿中轴,换手率大于1%且小于10%,30日内有2个交易日涨幅大于4%,非ST"
# 竞价选股(隔日打板)
"昨日非一字板涨停,今日竞价涨幅大于等于0%且小于等于9.9%,今日隔夜买单额小于10亿,非ST,非科创板"
# 连板选股
"最近5日有过涨停,最近5日没有跌停,今日成交量大于5日平均成交量,今日竞价涨幅在2%到3%之间,非北交所非科创板非ST"
⑥ Information queries (non-stock-picking)
"涨停原因归类前20" # 今日涨停题材分布
"今日龙虎榜" # 龙虎榜数据
"今日大宗交易" # 大宗交易
"今日融资融券余额最大的前20只股票"
"近一周北向资金净买入前20"
Processing wencai_nlp returned data
with THS() as ths:
resp = ths.wencai_nlp("连续3日主力净流入,换手率大于5%,非ST,市值大于30亿")
if not resp:
print(f"查询失败: {resp.error}")
else:
df = resp.df
# 字段名来自查询语句,常见列:股票代码、股票简称、涨幅、成交额、主力净流入 等
# 补全 ths_code(供后续调用 klines/market_data_cn)
def to_ths_code(code_str):
code_str = str(code_str).zfill(6)
if code_str.startswith('6'): return f"USHA{code_str}"
if code_str.startswith(('0','3')): return f"USZA{code_str}"
if code_str.startswith('8'): return f"USTM{code_str}"
return None
df['ths_code'] = df.get('股票代码', df.get('代码', pd.Series())).apply(to_ths_code)
wencai_nlp vs wencai_base
| Method | Purpose |
|---|---|
wencai_nlp(condition) |
Main usage. Complete natural language, returns stock list + field data |
wencai_base(condition) |
Simple conditional queries, such as "所属行业" to check the affiliation of a single stock |
For complete examples see examples/05_wencai_nlp.py
Other useful APIs
Rights and dividend data (ex-rights/ex-dividend history)
with THS() as ths:
resp = ths.corporate_action("USHA600519")
df = resp.df
Today's IPO / pending subscription
with THS() as ths:
resp = ths.ipo_today() # 今日上市新股
resp = ths.ipo_wait() # 待申购打新
Wencai natural language query
with THS() as ths:
resp = ths.wencai_nlp("今日申万行业涨跌幅排名")
resp = ths.wencai_nlp("今日概念板块涨跌幅排名前20")
resp = ths.wencai_nlp("换手率大于10%且涨幅大于5%的股票")
df_list = resp.data
Error handling
with THS() as ths:
resp = ths.klines("USZA300750", interval="5m", count=60)
if not resp: # resp.success == False
print(f"调用失败: {resp.error}")
elif resp.df.empty:
print("数据为空,可能是非交易时间")
else:
df = resp.df
Quick reference for common errors:
| Error message | Cause | Solution |
|---|---|---|
"未登录" |
Not connected | Ensure using with THS() as ths |
"证券代码必须为10个字符" |
Incorrect code format | First pass search_symbols |
"一次性查询多支股票必须市场代码相同" |
Shanghai-Shenzhen mixed | Query separately grouped by market |
"无效的周期类型: 5min" |
Incorrect interval syntax | Change to "5m" |
"'count' 参数不能与 'start_time' 同时使用" |
Parameter conflict | Choose one of the two |
Division of labor with ths-financial-data
| Scenario | skill |
|---|---|
| Single A-share quotes/capital flow/daily K | ths-financial-data |
| Minute K-line / intraday monitoring | This skill |
| Order book depth / large orders / auction anomalies | This skill |
| Sector/index quotes and constituent stocks | This skill |
| Multi-stock batch comparison | This skill |
| Wencai natural language query | Both are acceptable |