Tushare Skill

repository·master·Indexed 19 days ago

https://github.com/waditu-tushare/skills

An AI-ready toolkit providing access to over 220 financial data interfaces from Tushare Pro. It enables AI agents, such as Claude Code, OpenClaw, and Trae, to retrieve stocks, financial reports, indices, and macroeconomic data using natural language. The toolkit includes support for Python-based data retrieval and automated documentation generation from CSV sources, covering diverse datasets including public funds, LLM training corpora, futures, options, and Hong Kong and US stock markets.

Tokens
27.7K
Snippets
30
Records
57
Agent score
63%

What's inside waditu-tushare-skills

  1. Understand the Tushare skill capabilities and limitations

    master

    The Tushare skill converts natural language financial requests into executable data workflows (fetching, cleaning, comparing, filtering, and exporting data).

    Supported Scenarios

    • Market Trends: Stock/Index/ETF price trends, volume analysis.
    • Fundamentals: Financial reports, valuation (PE/PB/ROE), company quality.
    • Comparison: Cross-sectional analysis and ranking of stocks/companies.
    • Sectors & Themes: Sector strength, index constituents, and thematic trends.
    • Capital Flow: Northbound funds (HK-Mainland Connect), main force inflows, and Dragon-Tiger lists.
    • News & Policy: Announcements, research reports, and macro policy analysis.
    • Macro Data: CPI, PPI, PMI, GDP, interest rates, etc.
    • Data Export: Generating CSV or Parquet files for backtesting or research.

    What it is NOT for

    • Providing direct buy/sell investment advice.
    • Automated order execution or trading.
    • Millisecond-level real-time trading decisions.
    • Implementing complex backtesting engines or portfolio optimization systems.
    • Faking data when permissions or积分 (points) are insufficient.
  2. Entity resolution and time defaults

    master

    When processing natural language, the skill follows specific rules for resolving entities and timeframes:

    Entity Resolution

    • Ticker Formats: Standardizes codes to formats like 600519.SH or 000001.SZ.
    • Market Default: Defaults to A-shares unless Hong Kong, US, Funds, Bonds, or Futures are explicitly mentioned.
    • Ambiguity: If a name is ambiguous, the skill will list candidates and ask for clarification.

    Default Time Windows

    If the user does not specify a timeframe, the following defaults are applied:

    • "Recent trends": Last 20 trading days.
    • "This period / Recent period": Last 3 months.
    • "Financial reports / Performance": Last 8 quarters + most recent annual report.
    • "Capital flow": Last 5–20 trading days (adjusted by task granularity).
    • "Macro data": Last 6–12 periods.
  3. Understand when to use the Tushare skill

    master

    The Tushare skill is designed to convert natural language financial queries into executable data workflows (acquisition, cleaning, comparison, filtering, and export).

    Use Cases

    • Price/Trend: Analyzing stock/index/ETF performance, volatility, or volume.
    • Financials/Valuation: Checking company profiles, financial trends (revenue, profit), cash flow, and valuation metrics (PE, PB, ROE).
    • Comparison/Screening: Comparing multiple stocks or screening for specific criteria (e.g., high ROE, low debt).
    • Sectors/Indices: Identifying strong sectors, industry rotation, or index constituents.
    • Capital Flow/Sentiment: Tracking Northbound funds, main force inflows, or Dragon-Tiger list activity.
    • News/Announcements: Summarizing company announcements, research reports, or policy news.
    • Macro Data: Accessing CPI, PPI, PMI, GDP, interest rates, and cross-market data (US/HK stocks).
    • Data Export: Generating CSV or Parquet files for backtesting or further research.

    What it is NOT for

    • Providing direct buy/sell investment advice.
    • Automated trading or execution.
    • Millisecond-level real-time trading decisions.
    • Implementing complex backtesting engines or portfolio optimization systems.
  4. Manage Cache and Data Reuse

    master

    To ensure long-term reusability of the skill, prioritize the following patterns:

    • Base Table Caching: Cache static or slow-changing data like stock_basic, trading calendars (trade_cal), and index basic info.
    • Incremental Updates: Prefer incremental updates over full re-fetches.
    • Checkpointing: Support resuming large tasks from breakpoints.
    • Standardized Naming: Use consistent naming for result files:
      • daily_600519.SH_20230101_20231231_20260322.csv
      • fina_indicator_300750.SZ_20260322.parquet

    When a cache hit occurs, explicitly state which data came from the cache and which was newly fetched.

  5. Entity resolution and normalization rules

    master

    To ensure accurate data retrieval, the skill follows specific rules for interpreting user input:

    Entity Resolution

    • Ticker/Name: Prioritizes stock names, codes, indices, ETFs, and funds. Standardizes codes to formats like 600519.SH or 000001.SZ.
    • Market: Defaults to A-shares unless HK, US, Funds, Bonds, or Futures are explicitly mentioned.
    • Time Defaults:
      • "Recent trend" $\rightarrow$ last 20 trading days.
      • "Recent period" $\rightarrow$ last 3 months.
      • "Financials" $\rightarrow$ last 8 quarters + last annual report.
      • "Macro" $\rightarrow$ last 6–12 periods.
    • Sector/Industry: Uses Shenwan/CITIC for industries and THS/EastMoney for concept/theme classifications.

    Input Normalization

    • Dates are unified to YYYYMMDD.
    • Ensures start_date <= end_date.
    • Future dates are automatically clipped to the most recent available date.
    • Resolves conflicts between parameters (e.g., if both trade_date and start_date are provided).
  6. Data Quality and Caching Best Practices

    master

    To ensure reliable and reusable research, follow these data management rules.

    Data Quality Checks

    After fetching data, always perform:

    • Schema validation
    • Existence check for key fields
    • Primary key deduplication
    • Fixed sorting
    • Date standardization
    • Numerical field type normalization

    Caching and Reuse

    Prioritize incremental updates over full re-fetches. Use a standardized naming format for result files to facilitate reuse:

    • Format: {type}_{symbol}_{start_date}_{end_date}_{fetch_date}.{ext}
    • Examples:
      • daily_600519.SH_20230101_20231231_20260322.csv
      • fina_indicator_300750.SZ_20260322.parquet

    When a cache hit occurs, specify which data is from the cache and which is newly fetched.

  7. Use Tushare Skill with AI Agents

    master

    Once installed and configured, load the skill into your local AI agent. The skill supports natural language interaction in Chinese and is compatible with general-purpose agents such as Claude Code, OpenClaw, and Trae.

    Interaction Examples

    You can request data using natural language queries:

    • Stock Data: 获取平安银行最近 30 天的股价数据 (Get Ping An Bank's stock price data for the last 30 days)
    • Financial Analysis: 查看招商银行最近的财务报表,分析营收和净利润 (View China Merchants Bank's recent financial statements and analyze revenue and net profit)
    • Stock Screening: 帮我查找所有银行股并分析最近表现 (Help me find all banking stocks and analyze their recent performance)
    • Index Data: 获取上证指数最近的行情数据 (Get recent market data for the Shanghai Composite Index)
    • Macro Data: 查询最近一年的 GDP 和 CPI 数据 (Query GDP and CPI data for the last year)
  8. Install Tushare Skill

    master

    To use the Tushare Skill for financial data retrieval, follow these three steps:

    1. Install Dependencies

    2. Install the Skill

    You can install the skill using one of the following methods:

    • Copy the tushare directory directly into your local skills directory.
    • Use npx skills to install from GitHub:
      npx skills add https://github.com/waditu-tushare/skills.git --skill tushare-data
    • Use npx skills to install from Gitee:
      npx skills add https://gitee.com/lwdt/skills.git --skill tushare-data

    3. Configure Token

    Register an account at the Tushare official website to obtain your API token, then set it as an environment variable:

    export TUSHARE_TOKEN="your_token_here"
    npx skills add https://github.com/waditu-tushare/skills.git --skill tushare-data
  9. Install and configure the Tushare skill

    master

    To use the Tushare skill for natural language financial research, ensure your environment meets the requirements and configure your authentication token.

    Requirements

    • Python: 3.7+
    • Package: tushare must be installed.
    • Environment Variable: TUSHARE_TOKEN (required for authentication).
    • Network: Internet access is required.

    Setup Steps

    1. Install the dependency:
      pip install tushare
    2. Configure your Tushare Token. You can obtain one by registering at https://tushare.pro/register. Set it as an environment variable:
      export TUSHARE_TOKEN=your_token
    export TUSHARE_TOKEN=your_token
  10. Implement Data Quality and Error Handling Rules

    master

    When processing data via the Tushare skill, follow these standards to ensure reliability and user clarity.

    Data Quality Checks

    After fetching data, perform at least these checks:

    • Schema validation
    • Existence check for key fields
    • Primary key deduplication
    • Fixed sorting
    • Date standardization
    • Numerical field type normalization

    Handling Empty Results

    Do not treat all empty results as failures. Distinguish between:

    • Non-trading days
    • No data in the specified interval
    • Stock not yet listed
    • Parameter errors
    • Insufficient API permissions

    Error Reporting Strategy

    Use a layered approach for errors:

    1. User-Visible Layer: Provide "human-readable" explanations (e.g., "Token not configured", "Higher permissions/points required", "Time range too large, switching to segmented fetching", "Stock name not unique", "Result empty due to non-trading day/unlisted status/no permission").
    2. Debugging Layer: Provide technical details when necessary (API name, parameters, failed segment, raw exception).
    3. Partial Success Principle: If some segments fail, do not report "Success". Explicitly state which parts succeeded, which failed, and if an incomplete result was generated.
  11. Use Workflow Templates for Financial Analysis Tasks

    master

    Instead of thinking in terms of individual API calls, use the following workflow templates to accomplish common financial research tasks. These templates define the logical steps and data requirements for high-quality outputs.

    1. Single Asset Price Analysis

    Use for: "How is XX doing lately?", "Is this stock strong recently?", "How has it performed this year?" Workflow: Parse asset $\rightarrow$ Determine time range $\rightarrow$ Fetch price + basic indicators $\rightarrow$ Summarize price change, volume, highs/lows, and volatility $\rightarrow$ Output conclusion + key numbers.

    2. Multi-Asset Comparison

    Use for: "Who is stronger, XX or YY?", "Compare these few companies." Workflow: Lock targets $\rightarrow$ Unify timeframes $\rightarrow$ Select 3-5 key indicators $\rightarrow$ Output comparison table $\rightarrow$ Summarize strengths.

    3. Financial Quality Snapshot

    Use for: "Check XX's financial report", "Profit trends over recent quarters." Workflow: Fetch last 8 quarters + latest annual core data $\rightarrow$ Categorize Revenue, Profit, Gross Margin, ROE, and Cash Flow $\rightarrow$ Highlight improvements/deteriorations $\rightarrow$ Specify cumulative vs. single-quarter vs. YoY metrics.

    4. Valuation Analysis & Screening

    Use for: "Is the valuation high?", "Who is cheaper?", "Screen for low valuation and high dividend stocks." Workflow: Define target pool $\rightarrow$ Fetch daily_basic and other valuation indicators $\rightarrow$ Link with financial quality if necessary $\rightarrow$ Output rankings and extremes.

    5. Fund Flow Tracking

    Use for: "What are funds buying lately?", "Where is Northbound capital flowing?", "Who has the most main force inflow?" Workflow: Define flow type (Northbound / Main Force / Dragon-Tiger List / Sector) $\rightarrow$ Determine time window $\rightarrow$ Fetch net inflow / active volume / persistence $\rightarrow$ Correlate with price action.

    6. Sector / Theme Rotation Analysis

    Use for: "Which sector is strongest lately?", "What is driving the Robotics sector?", "Which stocks are in the [Concept] sector?" Workflow: Determine classification $\rightarrow$ Fetch sector performance $\rightarrow$ Link with constituent stocks, fund flows, and limit-up teams $\rightarrow$ Output sector rankings and representative stocks.

    7. Announcement / News / Event Review

    Use for: "What are the recent announcements?", "Any catalysts recently?" Workflow: Define target and time window $\rightarrow$ Fetch announcements / news / research reports / policies $\rightarrow$ De-noise to extract 3-5 main lines $\rightarrow$ Distinguish facts from media interpretation.

    8. Data Export & Research Preparation

    Use for: "Pull a CSV", "Create backtesting data tables", "Export historical price/financial data." Workflow: Define range, frequency, and fields $\rightarrow$ Use segmented fetching $\rightarrow$ Clean, deduplicate, and unify types $\rightarrow$ Output CSV/Parquet with file path and metadata.

    9. Comprehensive Research Briefing

    Use for: "Quickly research XX", "Provide an investor-perspective briefing." Workflow: One-sentence conclusion $\rightarrow$ Price performance $\rightarrow$ Financial trends $\rightarrow$ Valuation $\rightarrow$ Fund flow $\rightarrow$ News catalysts $\rightarrow$ Risk points $\rightarrow$ Deep-dive questions.

  12. Data retrieval and output best practices

    master

    When performing data retrieval, follow these operational guidelines to ensure stability and usability:

    Retrieval Rules

    • Verification: Always verify API names, required parameters, and permission/integral limits before execution.
    • Chunking (Segmented Pulling): For long-range data, pull in segments (e.g., by year/quarter for daily/weekly data, or by year for financials) to avoid timeouts or limit hits.
    • Merging: After segmented pulling, merge, deduplicate, and sort by primary key. If segments fail, report the specific failures to the user.
    • Error Handling: Only retry on transient errors (network jitter, timeouts, 429). Do not retry on parameter, permission, or field errors.

    Output Contract

    Unless raw tables are requested, outputs should follow this structure:

    1. One-sentence conclusion.
    2. Data scope and methodology.
    3. Key indicators / Key tables.
    4. Anomalies / Risks / Limitations.
    5. File paths (if local output was generated).

    Delivery Formats

    • Small results: Markdown summary + short tables.
    • Medium data: CSV.
    • Large scale/Analysis: Parquet.
    • Visuals: PNG charts or instructions for plotting.