Overview
This skill provides stock market data retrieval functionality based on the thsdk library, supporting data queries for multiple markets such as A-shares, Hong Kong stocks, and U.S. stocks. This skill should be used when users need to obtain financial market data, conduct stock analysis, or build financial applications.
Automatic Dependency Installation
This skill automatically handles the installation of the thsdk library, with no manual operation required from the user:
首次使用时:
│
▼
检查 thsdk 是否安装?
│
┌────┴────┐
YES NO
│ │
▼ ▼
检查版本 自动执行
>= 1.7.14? pip install --upgrade thsdk
│
┌────┴────┐
YES NO
│ │
▼ ▼
正常使用 自动升级
If it detects that thsdk is not installed or the version is lower than 1.7.14, it will automatically execute:
pip install --upgrade thsdk
Code Auto-Parsing Workflow (Core Rules)
Before any operation that requires a stock code, the following decision process must first be executed:
用户输入的 stock_code
│
▼
是否满足"直通"条件?
USHA + 6位数字 (如 USHA600519,上交所A股)
USZA + 6位数字 (如 USZA000001,深交所A股)
│
┌────┴────┐
YES NO(短代码/中文/缩写/其他前缀/其他任何格式)
│ │
▼ ▼
直接使用 调用 search_symbols(input) 查询候选列表
│
▼
获取完整的 ths_code
│
┌─────┴─────┐
0条 1条 多条
│ │ │
▼ ▼ ▼
返回错误 自动匹配 筛选A股
"未找到" ths_code │
┌────┴────┐
0只A股 1只A股 多只A股
│ │ │
▼ ▼ ▼
展示全部 自动选择 返回候选列表
让用户选择 等待用户选择
Multi-Stock Selection Interaction Flow (Important)
When search_symbols matchesmultiple A-shares, the function returns a special structure:
{
'need_selection': True,
'candidates': [
{'ths_code': 'USHA600520', 'name': '三佳科技', 'code': '600520', 'market': '沪A'},
{'ths_code': 'USZA002796', 'name': '世嘉科技', 'code': '002796', 'market': '深A'},
# ... 更多候选
],
'display': '\n**找到 5 只A股**:\n\n 1. **三佳科技** `USHA600520` (沪A)\n 2. **世嘉科技** `USZA002796` (深A)\n ...\n\n请输入序号选择(1-5),或输入 0 取消。'
}
The AI assistant should:
- Detect whether the return value is
dictand containsneed_selection: True - Display the
displaycontent to the user - Wait for the user to enter a sequence number
- Use
get_candidate_by_index(candidates, index)to get the stock selected by the user - Use the obtained
ths_codeto continue subsequent operations
Example Interaction Flow
from thsdk import THS
from stock_utils import search_stock_candidates, get_candidate_by_index, get_kline_data
with THS() as ths:
# 第一步:搜索股票
result = search_stock_candidates(ths, "sjkj")
if result['status'] == 'found':
# 唯一匹配,直接使用
ths_code = result['ths_code']
df = ths.klines(ths_code, interval="day", count=30)
elif result['status'] == 'need_selection':
# 多个候选,需要用户选择
print(result['display']) # 展示给用户
# AI 应该在这里等待用户输入序号
# 假设用户选择了 2
user_choice = 2
selected = get_candidate_by_index(result['candidates'], user_choice)
if selected:
ths_code = selected['ths_code']
df = ths.klines(ths_code, interval="day", count=30)
elif result['status'] == 'not_found':
print(result['display']) # 未找到提示
Quick Start
When the AI assistant uses this Skill
- Automatic installation check: it automatically checks and installs thsdk on the first call
- Get the THS instance: you can use
get_ths_instance()or directlyfrom thsdk import THS - Call query functions: use
search_stock_candidatesand other functions to obtain data
# 方式1:使用便捷函数(推荐)
from stock_utils import get_ths_instance, get_kline_data
ths = get_ths_instance()
if ths:
df = get_kline_data(ths, "平安银行", interval="day", count=30)
# 方式2:标准方式
from thsdk import THS
from stock_utils import search_stock_candidates, get_kline_data
with THS() as ths:
result = search_stock_candidates(ths, "平安银行")
if result['status'] == 'found':
df = ths.klines(result['ths_code'], interval="day", count=30)
Stock Code Format Description
thsdk requires the use ofthe complete ths_code, with the format being market prefix + code:
| Market | Prefix | Example |
|---|---|---|
| Shenzhen Stock Exchange A-shares | USZA |
USZA000001 |
| Shanghai Stock Exchange A-shares | USHA |
USHA600519 |
| Hong Kong stocks | HKHK |
HKHK00700 |
| U.S. stocks | USUS |
USUSAAPL |
No need to manually memorize prefixes, use
search_stock_candidates()to automatically handle all formats.
Core Functions
1. ensure_thsdk() - Automatic Installation Check
from stock_utils import ensure_thsdk, get_ths_instance
# 确保 thsdk 已安装
if ensure_thsdk():
print("thsdk 已就绪")
# 或直接获取实例(内部会自动检查安装)
ths = get_ths_instance()
2. search_stock_candidates (recommended)
Search for stocks and return structured results, supporting an elegant user selection flow:
from thsdk import THS
from stock_utils import search_stock_candidates
with THS() as ths:
result = search_stock_candidates(ths, "ndsd")
# result['status'] 可能的值:
# - 'found': 唯一匹配,result['ths_code'] 可直接使用
# - 'need_selection': 多个候选,需要用户选择
# - 'not_found': 未找到匹配
# result['ths_code']: 唯一匹配时的 ths_code
# result['candidates']: 候选列表
# result['display']: 格式化的展示文本(直接展示给用户)
3. get_candidate_by_index
Get the stock selected by the user based on the sequence number:
from stock_utils import get_candidate_by_index
# candidates 是 search_stock_candidates 返回的候选列表
# index 是用户输入的序号(1-based)
selected = get_candidate_by_index(candidates, 2)
if selected:
print(f"用户选择: {selected['name']} ({selected['ths_code']})")
4. get_kline_data
Get K-line data, supporting automatic parsing of stock codes:
from thsdk import THS
from stock_utils import get_kline_data
with THS() as ths:
result = get_kline_data(ths, "平安银行", interval="day", count=30)
# 检查是否需要用户选择
if isinstance(result, dict) and result.get('need_selection'):
print(result['display']) # 展示候选列表给用户
# 等待用户选择...
elif isinstance(result, pd.DataFrame):
print(result) # 成功获取数据
else:
print("获取失败")
5. get_realtime_data
Get real-time quotes:
from thsdk import THS
from stock_utils import get_realtime_data
with THS() as ths:
result = get_realtime_data(ths, "000001")
if isinstance(result, dict):
if result.get('need_selection'):
print(result['display']) # 需要选择
else:
print(f"股票:{result['name']}")
print(f"最新价:{result['price']}")
print(f"涨跌幅:{result['change_pct']}%")
6. get_fund_flow
Get capital flow:
from thsdk import THS
from stock_utils import get_fund_flow
with THS() as ths:
result = get_fund_flow(ths, "贵州茅台")
if isinstance(result, dict) and not result.get('need_selection'):
print(f"主力净流入:{result['main_net_inflow']}")
print(f"散户净流入:{result['retail_net_inflow']}")
7. wencai_query
Use WenCai natural language queries:
from thsdk import THS
from stock_utils import wencai_query
with THS() as ths:
df = wencai_query(ths, "最近热度前50的行业和涨停原因归类")
if df is not None:
print(df.head())
Complete Usage Example
Scenario: The user enters a fuzzy query
from thsdk import THS
from stock_utils import search_stock_candidates, get_candidate_by_index, get_kline_data
with THS() as ths:
# 用户输入:sjkj
result = search_stock_candidates(ths, "sjkj")
if result['status'] == 'need_selection':
# 展示候选给用户
print(result['display'])
# 输出示例:
# **找到 5 只A股**:
#
# 1. **三佳科技** `USHA600520` (沪A)
# 2. **盛剑科技** `USHA603324` (沪A)
# 3. **世嘉科技** `USZA002796` (深A)
# 4. **仕净科技** `USZA301030` (深A)
# 5. **熵基科技** `USZA301330` (深A)
#
# 请输入序号选择(1-5),或输入 0 取消。
# 等待用户选择序号
# user_choice = int(input("请选择: ")) # 假设用户输入 3
selected = get_candidate_by_index(result['candidates'], user_choice)
if selected:
ths_code = selected['ths_code']
df = ths.klines(ths_code, interval="day", count=30)
print(f"已获取 {selected['name']} 的日K线数据")
Scenario: Unique match (automatically handled)
from thsdk import THS
from stock_utils import search_stock_candidates, get_kline_data
with THS() as ths:
result = search_stock_candidates(ths, "ndsd")
if result['status'] == 'found':
# 自动匹配,无需用户选择
print(result['display']) # ✅ 已自动匹配:**宁德时代** `USZA300750` (深A)
df = ths.klines(result['ths_code'], interval="day", count=30)
print(df.head())
Return Value Description
search_stock_candidates return structure
| Field | Type | Description |
|---|---|---|
status |
str | found / need_selection / not_found |
ths_code |
str | The stock code when there is a unique match |
candidates |
list | Candidate stock list |
message |
str | Brief hint message |
display |
str | Formatted display text (Markdown format) |
get_candidate_by_index return structure
{
'ths_code': 'USZA002796',
'name': '世嘉科技',
'code': '002796',
'market': '深A'
}
Output format
All data is output in tabular form, using Markdown table format:
Real-time market data table example
| Code | Name | Latest price | Change percentage | Change amount | Volume | Turnover |
|---|---|---|---|---|---|---|
| USZA000001 | Ping An Bank | 15.20 | +1.23% | +0.18 | 125,000 | 189 million |
Daily K data table example
| Date | Open | Close | High | Low | Volume | Turnover | Change percentage |
|---|---|---|---|---|---|---|---|
| 2026-03-13 | 27.34 | 27.02 | 27.80 | 26.90 | 3.729 million | 102 million | -1.75% |
Notes
- Automatic installation: On first use, it will automatically check and install thsdk, no manual operation required
- Data delay: Data comes from Tonghuashun; real-time data may have a brief delay
- Request frequency: Avoid a large number of requests in a short period; the interval between each query is recommended to be > 100ms
- Stock code format: Only
USHA/USZA + 6位数字can pass through directly; all other formats will be queried first - User selection: When there are multiple A-shares, you must wait for the user to choose and cannot automatically select the first one
- Hong Kong stocks/US stocks: Hong Kong and US stock codes will be confirmed through
search_symbolsquery
Tool functions
Installation check function
from stock_utils import check_thsdk_installed, get_thsdk_version, ensure_thsdk
# 检查是否已安装
is_installed = check_thsdk_installed() # True/False
# 获取当前版本
version = get_thsdk_version() # "1.7.14" 或 "not installed"
# 确保已安装(未安装则自动安装)
ensure_thsdk() # 返回 True/False
Resource files
scripts/stock_utils.py— Core tool functions, including automatic installation, automatic parsing by search_stock_candidates, and all data retrieval wrappersreferences/api_reference.md— Complete reference documentation for the original thsdk APIassets/stock_template.py— Complete stock analysis template with visualization