股票

👤 bensema 📦 v1.0.0 ⭐ 4.4 ⬇️ 16.8K 下載
📊 資料分析 免費

📖 技能介紹


name: ths-financial-data description: 該skill用於獲取股票市場資料,包括即時行情、中文名稱查詢、鍵盤縮寫轉換、資金流向和日K線資料。使用thsdk庫提供同花順資料介面支援。支援自動將中文、縮寫、短程式碼轉換為thsdk所需的完整ths_code格式。當匹配到多隻股票時,會返回候選列表供使用者選擇。如未安裝thsdk,會自動安裝。


Stock Data Skill

概述

此skill提供基於thsdk庫的股票市場資料獲取功能,支援A股、港股、美股等多市場資料查詢。該skill應於使用者需要獲取金融市場資料、進行股票分析或構建金融應用時使用。

自動安裝依賴

此skill會自動處理 thsdk 庫的安裝,無需使用者手動操作:

首次使用時:
        │
        ▼
檢查 thsdk 是否安裝?
        │
   ┌────┴────┐
  YES        NO
   │          │
   ▼          ▼
檢查版本    自動執行
>= 1.7.14?   pip install --upgrade thsdk
   │
   ┌────┴────┐
  YES        NO
   │          │
   ▼          ▼
正常使用    自動升級

如果檢測到 thsdk 未安裝或版本低於 1.7.14,會自動執行:

pip install --upgrade thsdk

程式碼自動解析工作流(核心規則)

在任何需要股票程式碼的操作之前,必須先執行以下判斷流程:

使用者輸入的 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股
                               │           │           │
                               ▼           ▼           ▼
                           展示全部    自動選擇    返回候選列表
                           讓使用者選擇             等待使用者選擇

多股票選擇互動流程(重要)

search_symbols 匹配到多隻A股時,函式會返回一個特殊結構:

{
    '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 取消。'
}

AI 助手應該: 1. 檢測返回值是否為 dict 且包含 need_selection: True 2. 將 display 內容展示給使用者 3. 等待使用者輸入序號 4. 使用 get_candidate_by_index(candidates, index) 獲取使用者選擇的股票 5. 使用獲取到的 ths_code 繼續後續操作

示例互動流程

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'])  # 未找到提示

快速開始

AI 助手使用此 Skill 時

  1. 自動安裝檢查:首次呼叫時會自動檢查並安裝 thsdk
  2. 獲取 THS 例項:可使用 get_ths_instance() 或直接 from thsdk import THS
  3. 呼叫查詢函式:使用 search_stock_candidates 等函式獲取資料
# 方式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)

股票程式碼格式說明

thsdk 要求使用完整 ths_code,格式為市場字首 + 程式碼:

市場 字首 示例
深交所A股 USZA USZA000001
上交所A股 USHA USHA600519
港股 HKHK HKHK00700
美股 USUS USUSAAPL

不需要手動記憶字首,使用 search_stock_candidates() 自動處理一切格式。

核心函式

1. ensure_thsdk() - 自動安裝檢查

from stock_utils import ensure_thsdk, get_ths_instance

# 確保 thsdk 已安裝
if ensure_thsdk():
    print("thsdk 已就緒")

# 或直接獲取例項(內部會自動檢查安裝)
ths = get_ths_instance()

2. search_stock_candidates(推薦)

搜尋股票並返回結構化結果,支援優雅的使用者選擇流程:

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

根據序號獲取使用者選擇的股票:

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

獲取K線資料,支援自動解析股票程式碼:

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

獲取即時行情:

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

獲取資金流向:

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

使用問財自然語言查詢:

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())

完整使用示例

場景:使用者輸入模糊查詢

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線資料")

場景:唯一匹配(自動處理)

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())

本技能來自小蔥技能站7w4.net。

返回值說明

search_stock_candidates 返回結構

欄位 型別 說明
status str found / need_selection / not_found
ths_code str 唯一匹配時的股票程式碼
candidates list 候選股票列表
message str 簡短提示資訊
display str 格式化的展示文本(Markdown格式)

get_candidate_by_index 返回結構

{
    'ths_code': 'USZA002796',
    'name': '世嘉科技',
    'code': '002796',
    'market': '深A'
}

輸出格式

所有資料以表格形式輸出,使用 Markdown 表格格式:

即時行情表格示例

程式碼 名稱 最新價 漲跌幅 漲跌額 成交量 成交額
USZA000001 平安銀行 15.20 +1.23% +0.18 12.5萬 1.89億

日K資料表格示例

日期 開盤 收盤 最高 最低 成交量 成交額 漲跌幅
2026-03-13 27.34 27.02 27.80 26.90 372.9萬 1.02億 -1.75%

注意事項

  1. 自動安裝:首次使用時會自動檢查並安裝 thsdk,無需手動操作
  2. 資料延遲:資料來源於同花順,即時資料可能存在短暫延遲
  3. 請求頻率:避免短時間內大量請求,每次查詢間隔建議 > 100ms
  4. 股票程式碼格式:只有 USHA/USZA + 6位數字 可以直通,其他格式都會先查詢
  5. 使用者選擇:多隻A股時必須等待使用者選擇,不能自動選擇第一隻
  6. 港股/美股:港股和美股程式碼會通過 search_symbols 查詢確認

工具函式

安裝檢查函式

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

資原始檔

  • scripts/stock_utils.py — 核心工具函式,包含自動安裝、search_stock_candidates 自動解析及所有資料獲取封裝
  • references/api_reference.md — thsdk 原始 API 完整參考文件
  • assets/stock_template.py — 含視覺化的股票分析完整模板

🤖 AI 評測

這個 Skill 整體質量不錯,文件詳細、程式碼功能完善,能自動處理各種股票程式碼格式並智慧選擇。不過實際使用時發現示例指令碼幾乎是空的,沒有真正可用的參考案例,想快速上手會有些困難。

📊 多維度評分

適應性4.2
規範性4.1
有效性4.4
可靠性4.4
可信度5

📁 包含檔案 (8 個)

📄 SKILL.md 12.7 KB
📄 _meta.json 137 B
📄 assets/example_asset.txt 865 B
📄 assets/stock_template.py 9 KB
📄 references/api_reference.md 4.5 KB
📄 scripts/example.py 595 B
📄 scripts/stock_utils.py 21.6 KB
📄 skill-card.md 2.4 KB