akshare-stock

akshare-stock

A-share stock analysis skill covering real-time quotes, technical analysis, fundamentals, sectors, derivatives, and cross-market data, powered by akshare and natural language routing.

15stars
0forks
Updated 7/11/2026
SKILL.md
readonlyread-only
name
akshare-stock
description

A-share stock analysis skill covering real-time quotes, technical analysis, fundamentals, sectors, derivatives, and cross-market data, powered by akshare and natural language routing.

A-share Stock Analysis Skill (AKShare)

Goal: Trigger A-share and related market analysis via natural language in OpenClaw, outputting compact text suitable for QQ/Telegram.

  • Runtime: Mac + Python 3.9
  • akshare path: /Users/molezz/Library/Python/3.9/lib/python3.9/site-packages
  • Skill entry: python3 skills/akshare-stock/main.py --query "${USER_QUERY}"

1) Overall Architecture

Four-layer structure: Router -> Service -> Analyzer -> Formatter for extensibility and maintainability.

A. Directory Layout (Suggested)

skills/akshare-stock/
  SKILL.md
  main.py                 # OpenClaw entry point
  router.py               # Intent recognition + parameter parsing
  schemas.py              # Data structure definitions (dataclass)
  formatter.py            # QQ/Telegram output templates
  services/
    market_service.py     # Index/stock quotes, K-line, intraday, limit stats, money flow
    fundamental_service.py# Financial indicators, earnings reports, margin trading, dragon & tiger list
    sector_service.py     # Industry/concept sectors, rotation, sector money flow
    cross_service.py      # Futures/options, funds, convertible bonds, HK/US stocks
  analyzers/
    kline_analyzer.py     # Moving averages, amplitude, change, volume ratio
    flow_analyzer.py      # Net inflow, continuity, strength ranking
    rotation_analyzer.py  # Sector rotation strength, persistence
  adapters/
    akshare_adapter.py    # Wraps akshare API, isolates changes
  utils/
    trading_calendar.py   # Trading day detection
    symbols.py            # Alias mapping for indices/stocks/sectors
    cache.py              # Short cache (30-120 seconds)

B. Core Flow

  1. main.py receives natural language query.
  2. router.py outputs structured intent: intent + symbols + timeframe + metric + top_n.
  3. services/* fetch raw data (fetch and light cleaning only).
  4. analyzers/* compute indicators and generate conclusions.
  5. formatter.py compresses output for chat platforms (short lines, sections, emoji, key numbers).

C. Key Design Points

  • Intent priority: Recognize "task type" first, then parse targets and parameters to avoid misclassification.
  • Adapter isolation: If akshare API changes, only modify adapters/akshare_adapter.py.
  • Graceful fallback: On real-time API failure, fall back to most recent trading day data with "non-real-time" label.
  • Cache strategy:
    • Index/money flow: 30-60 seconds
    • Sector rankings: 60-120 seconds
    • Earnings/financials: cache for the day
  • Message length control: Single message <= 1000 characters; auto-split into 2-3 messages if too long.

2) Trigger Design (Natural Language Routing)

Hybrid approach: keywords + regex + alias dictionary.

A. Intent Classification

  • INDEX_REALTIME: Real-time index
  • KLINE_ANALYSIS: Historical K-line
  • INTRADAY_ANALYSIS: Intraday analysis
  • LIMIT_STATS: Limit up/down statistics
  • MONEY_FLOW: Money flow
  • FUNDAMENTAL: Financial indicators / earnings
  • MARGIN_LHB: Margin trading / dragon & tiger list
  • SECTOR_ANALYSIS: Industry/concept/rotation/sector money flow
  • DERIVATIVES: Futures/options
  • FUND_BOND: Fund NAV / convertible bonds
  • HK_US_MARKET: HK / US stocks

B. Trigger Examples

  • Real-time index: A股大盘 上证现在多少 沪深300实时
  • K-line: 贵州茅台近60日K线 宁德时代周线 比亚迪月线复权
  • Intraday: 看下000001分时 平安银行今天分时走势
  • Limit stats: 今日涨停统计 跌停家数 连板梯队
  • Money flow: 主力资金流入前十 北向资金 行业资金净流入
  • Fundamentals: 茅台财务指标 宁德时代最新季报 ROE和毛利率
  • Margin/dragon: 中兴通讯融资融券 今日龙虎榜
  • Sectors: 行业板块涨幅榜 概念轮动 AI板块资金流
  • Other markets: IF主力合约 300ETF期权 基金净值 可转债行情 腾讯港股 英伟达美股

C. Parameter Extraction Rules

  • Stock code: \b\d{6}\b (e.g., 600519)
  • Date: YYYYMMDD / YYYY-MM-DD / 今天/昨日/近N日
  • Period: 1m/5m/15m/30m/60m/day/week/month
  • Ranking: 前N (default 10)
  • Adjustment: 前复权/后复权/不复权

3) Implementation Ideas per Feature

Framework: "Feature -> Recommended Data -> Analysis Output" (API based on current akshare version, unified via adapter layer).

3.1 Real-time Index (Basic version exists, enhancements)

  • Data: Shanghai, Shenzhen, ChiNext, CSI 300, SSE 50, STAR 50.
  • Enhancements: Add turnover, amplitude, leading sectors, northbound net inflow.
  • Output: 指数点位 + 涨跌幅 + 市场情绪一句话.

3.2 Market Analysis

  • Historical K-line:
    • Data: Daily/weekly/monthly K-line (adjustable).
    • Indicators: N-day change, 5/10/20 MA, volume change, volatility.
    • Output: Trend (bullish/consolidation/weak) + key levels (support/resistance).
  • Intraday:
    • Data: Minute-level quotes.
    • Indicators: VWAP deviation, intraday highs/lows, afternoon capital return.
  • Limit up/down stats:
    • Data: Limit up pool, limit down pool, consecutive board tiers.
    • Indicators: Number of limit ups, break rate, highest consecutive board, sentiment score.
  • Money flow:
    • Data: Stock/sector/market money flow.
    • Indicators: Top N net inflow, consecutive net inflow days, concentration.

3.3 Fundamental Analysis

  • Stock financials: ROE, gross margin, net margin, debt ratio, operating cash flow.
  • Earnings data: Revenue YoY, net profit YoY, recurring net profit YoY, EPS.
  • Margin trading: Margin balance, short balance, daily change, leverage preference.
  • Dragon & tiger list: Reason for listing, top 5 buy/sell net amounts, hot money activity.
  • Output style: 核心指标摘要 + 同比/环比 + 风险提示.

3.4 Sector Analysis

  • Industry sector performance: Sector change ranking, turnover, number of rising stocks.
  • Concept sector rotation: 5-day strength, persistence, intraday switching speed.
  • Sector money flow: Industry/concept net inflow ranking + leading stocks.
  • Output: 强势板块Top3 + 轮动结论 + 次日观察点.

3.5 Others (Cross-market)

  • Futures/options: Main contract price, change, open interest; option PCR (if available).
  • Fund NAV: Open-end fund NAV, valuation deviation, weekly return.
  • Convertible bonds: Price, premium, underlying stock correlation, turnover.
  • HK/US stocks: Real-time quotes, 5-day performance, A-share correlation hints.

4) Code Skeleton

Minimal framework for direct implementation, without full business details.

main.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import argparse
from router import parse_query
from services.market_service import MarketService
from services.fundamental_service import FundamentalService
from services.sector_service import SectorService
from services.cross_service import CrossService
from formatter import render_output


def dispatch(intent_obj):
    intent = intent_obj.intent

    if intent in {"INDEX_REALTIME", "KLINE_ANALYSIS", "INTRADAY_ANALYSIS", "LIMIT_STATS", "MONEY_FLOW"}:
        data = MarketService().handle(intent_obj)
    elif intent in {"FUNDAMENTAL", "MARGIN_LHB"}:
        data = FundamentalService().handle(intent_obj)
    elif intent == "SECTOR_ANALYSIS":
        data = SectorService().handle(intent_obj)
    elif intent in {"DERIVATIVES", "FUND_BOND", "HK_US_MARKET"}:
        data = CrossService().handle(intent_obj)
    else:
        data = {"ok": False, "error": "未识别请求,请补充标的或时间范围"}

    return data


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--query", required=True, help="自然语言请求")
    parser.add_argument("--platform", default="qq", choices=["qq", "telegram"])
    args = parser.parse_args()

    intent_obj = parse_query(args.query)
    result = dispatch(intent_obj)
    text = render_output(intent_obj, result, platform=args.platform)
    print(text)


if __name__ == "__main__":
    main()

router.py

from dataclasses import dataclass, field
import re


@dataclass
class IntentObj:
    intent: str
    symbols: list = field(default_factory=list)
    timeframe: str = "day"
    days: int = 60
    top_n: int = 10
    date: str = ""
    raw_query: str = ""


def parse_query(query: str) -> IntentObj:
    q = query.strip()
    obj = IntentObj(intent="INDEX_REALTIME", raw_query=q)

    # 1) intent
    if any(k in q for k in ["K线", "日线", "周线", "月线"]):
        obj.intent = "KLINE_ANALYSIS"
    elif "分时" in q:
        obj.intent = "INTRADAY_ANALYSIS"
    elif any(k in q for k in ["涨停", "跌停", "连板"]):
        obj.intent = "LIMIT_STATS"
    elif "资金" in q:
        obj.intent = "MONEY_FLOW"
    elif any(k in q for k in ["财务", "财报", "ROE", "毛利率"]):
        obj.intent = "FUNDAMENTAL"
    elif any(k in q for k in ["融资融券", "龙虎榜"]):
        obj.intent = "MARGIN_LHB"
    elif any(k in q for k in ["板块", "行业", "概念", "轮动"]):
        obj.intent = "SECTOR_ANALYSIS"
    elif any(k in q for k in ["期货", "期权"]):
        obj.intent = "DERIVATIVES"
    elif any(k in q for k in ["基金", "净值", "可转债"]):
        obj.intent = "FUND_BOND"
    elif any(k in q for k in ["港股", "美股", "纳斯达克", "道琼斯"]):
        obj.intent = "HK_US_MARKET"

    # 2) symbol
    code_hits = re.findall(r"\b\d{6}\b", q)
    if code_hits:
        obj.symbols = code_hits

    # 3) topN
    m = re.search(r"前\s*(\d+)", q)
    if m:
        obj.top_n = int(m.group(1))

    return obj

adapters/akshare_adapter.py

import akshare as ak


class AkAdapter:
    def index_spot(self):
        return ak.stock_zh_index_spot_sina()

    def stock_kline(self, symbol: str, period: str = "daily", start_date: str = "", end_date: str = "", adjust: str = "qfq"):
        # Actual parameters and function name adapt to local akshare version
        return ak.stock_zh_a_hist(symbol=symbol, period=period, start_date=start_date, end_date=end_date, adjust=adjust)

    def stock_intraday(self, symbol: str, period: str = "1"):
        return ak.stock_zh_a_minute(symbol=symbol, period=period)

    def limit_up_pool(self, date: str):
        return ak.stock_zt_pool_em(date=date)

    def limit_down_pool(self, date: str):
        return ak.stock_dt_pool_em(date=date)

formatter.py

from datetime import datetime


def render_output(intent_obj, result: dict, platform: str = "qq") -> str:
    ts = datetime.now().strftime("%Y-%m-%d %H:%M")

    if not result.get("ok", False):
        return f"⚠️ 请求失败\n原因: {result.get('error', '未知错误')}\n时间: {ts}"

    title = result.get("title", "A股分析")
    lines = result.get("lines", [])
    tips = result.get("tips", "")

    # QQ/Telegram friendly: short lines, sections, key numbers first
    text = [f"📊 {title}", f"🕒 {ts}", ""]
    text.extend(lines[:15])
    if tips:
        text.extend(["", f"💡 {tips}"])
    text.append("\n数据源: akshare")

    # Length protection
    merged = "\n".join(text)
    return merged[:1000]

Output Template Suggestions (QQ/Telegram)

Recommended three-part format: 结论 -> 关键数据 -> 风险提示.

Example:

📊 A股午盘情绪
🕒 2026-02-18 11:31

- 上证指数 3210.35(+0.62%)
- 两市成交额 6821 亿,较昨日同期 +8.4%
- 涨停 52 / 跌停 7,连板高度 4
- 主力净流入前三:证券、AI算力、汽车零部件

💡 结论:指数偏强,情绪修复中;但午后关注高位分歧。
数据源: akshare

Implementation Order (Suggested)

  1. Keep existing real-time index, abstract into MarketService.index_realtime().
  2. First complete the four market analysis modules: K-line/intraday/limit stats/money flow.
  3. Then add fundamentals and sector analysis (medium-frequency requests, high cache benefit).
  4. Finally integrate futures/options/funds/convertible bonds/HK-US stocks.
  5. Each module should first produce readable text output, then gradually add indicator depth.

This design ensures quick usability first, then gradual enhancement without overwhelming maintenance from too many interfaces at once.