Skip to main content
Glama
Xxx00xxX33

FinanceMCP

by Xxx00xxX33

index_data

Retrieve historical data for stock market indices like SSE Composite or SZSE Component Index by specifying index code and date range to analyze market trends.

Instructions

获取指定股票指数的数据,例如上证指数、深证成指等

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
codeYes指数代码,如'000001.SH'表示上证指数,'399001.SZ'表示深证成指
start_dateYes起始日期,格式为YYYYMMDD,如'20230101'
end_dateYes结束日期,格式为YYYYMMDD,如'20230131'

Implementation Reference

  • The main handler function `indexData.run()` that executes the tool: fetches stock index daily data from Tushare API using POST request, parses response, computes overall trend (up/down/flat), formats daily OHLCV data with changes into markdown sections.
    async run(args: { code: string; start_date?: string; end_date?: string }) {
      try {
        console.log(`使用Tushare API获取指数${args.code}的数据`);
        
        // 使用全局配置中的Tushare API设置
        const TUSHARE_API_KEY = TUSHARE_CONFIG.API_TOKEN;
        const TUSHARE_API_URL = TUSHARE_CONFIG.API_URL;
        
        // 默认参数设置
        const today = new Date();
        const defaultEndDate = today.toISOString().slice(0, 10).replace(/-/g, '');
        
        const oneMonthAgo = new Date();
        oneMonthAgo.setMonth(oneMonthAgo.getMonth() - 1);
        const defaultStartDate = oneMonthAgo.toISOString().slice(0, 10).replace(/-/g, '');
        
        // 构建请求参数
        const params = {
          api_name: "index_daily",
          token: TUSHARE_API_KEY,
          params: {
            ts_code: args.code,
            start_date: args.start_date || defaultStartDate,
            end_date: args.end_date || defaultEndDate
          },
          fields: "ts_code,trade_date,open,high,low,close,pre_close,change,pct_chg,vol,amount"
        };
        
        // 设置请求超时
        const controller = new AbortController();
        const timeoutId = setTimeout(() => controller.abort(), TUSHARE_CONFIG.TIMEOUT);
        
        try {
          console.log(`请求Tushare API: ${params.api_name},参数:`, params.params);
          
          // 发送请求
          const response = await fetch(TUSHARE_API_URL, {
            method: "POST",
            headers: {
              "Content-Type": "application/json"
            },
            body: JSON.stringify(params),
            signal: controller.signal
          });
          
          if (!response.ok) {
            throw new Error(`Tushare API请求失败: ${response.status}`);
          }
          
          const data = await response.json();
          
          // 处理响应数据
          if (data.code !== 0) {
            throw new Error(`Tushare API错误: ${data.msg}`);
          }
          
          // 确保data.data和data.data.items存在
          if (!data.data || !data.data.items || data.data.items.length === 0) {
            throw new Error(`未找到指数${args.code}的数据`);
          }
          
          // 获取字段名
          const fields = data.data.fields;
          
          // 将数据转换为对象数组
          const indexData = data.data.items.map((item: any) => {
            const result: Record<string, any> = {};
            fields.forEach((field: string, index: number) => {
              result[field] = item[index];
            });
            return result;
          });
          
          // 收集涨跌数据用于生成趋势分析
          const closePrices = indexData.map((item: Record<string, any>) => parseFloat(item.close));
          let trend = "持平";
          let trendAnalysis = "";
          
          if (closePrices.length > 1) {
            const firstPrice = closePrices[closePrices.length - 1]; // 最早的收盘价
            const lastPrice = closePrices[0]; // 最近的收盘价
            const change = ((lastPrice - firstPrice) / firstPrice * 100).toFixed(2);
            
            if (lastPrice > firstPrice) {
              trend = `上涨 ${change}%`;
              trendAnalysis = `在此期间,${args.code}整体呈上涨趋势,累计涨幅达${change}%。`;
            } else if (lastPrice < firstPrice) {
              trend = `下跌 ${Math.abs(parseFloat(change))}%`;
              trendAnalysis = `在此期间,${args.code}整体呈下跌趋势,累计跌幅达${Math.abs(parseFloat(change))}%。`;
            }
          }
          
          // 格式化输出日期范围
          const startDate = indexData[indexData.length - 1]?.trade_date || args.start_date || defaultStartDate;
          const endDate = indexData[0]?.trade_date || args.end_date || defaultEndDate;
          
          // 格式化输出
          const formattedData = indexData.map((data: Record<string, any>) => {
            return `## ${data.trade_date}\n开盘: ${data.open}  最高: ${data.high}  最低: ${data.low}  收盘: ${data.close}\n涨跌: ${data.change}  涨跌幅: ${data.pct_chg}%  成交量: ${data.vol}  成交额: ${data.amount}\n`;
          }).join('\n---\n\n');
          
          return {
            content: [
              {
                type: "text",
                text: `# ${args.code}指数数据 (${startDate} 至 ${endDate})\n\n` +
                     `## 期间走势: ${trend}\n${trendAnalysis}\n\n---\n\n${formattedData}`
              }
            ]
          };
        } finally {
          clearTimeout(timeoutId);
        }
      } catch (error) {
        console.error("获取指数数据失败:", error);
        
        return {
          content: [
            {
              type: "text",
              text: `# 获取指数${args.code}数据失败\n\n无法从Tushare API获取数据:${error instanceof Error ? error.message : String(error)}\n\n请检查指数代码是否正确,常用指数代码:\n- 上证指数: 000001.SH\n- 深证成指: 399001.SZ\n- 创业板指: 399006.SZ\n- 沪深300: 000300.SH\n- 中证500: 000905.SH`
            }
          ]
        };
      }
    }
  • Input schema definition for the index_data tool, specifying parameters code (required), start_date (optional with defaults), end_date.
    parameters: {
      type: "object",
      properties: {
        code: {
          type: "string",
          description: "指数代码,如'000001.SH'表示上证指数,'399001.SZ'表示深证成指"
        },
        start_date: {
          type: "string",
          description: "起始日期,格式为YYYYMMDD,如'20230101'"
        },
        end_date: {
          type: "string",
          description: "结束日期,格式为YYYYMMDD,如'20230131'"
        }
      },
      required: ["code", "start_date", "end_date"]
    },
  • src/index.ts:190-192 (registration)
    Registration of index_data tool in the MCP server's tools list response (ListToolsRequestHandler).
    name: indexData.name,
    description: indexData.description,
    inputSchema: indexData.parameters
  • src/index.ts:297-302 (registration)
    Handler dispatch for index_data in the MCP server's CallToolRequestHandler switch statement.
    case "index_data": {
      const code = String(request.params.arguments?.code);
      const start_date = request.params.arguments?.start_date ? String(request.params.arguments.start_date) : undefined;
      const end_date = request.params.arguments?.end_date ? String(request.params.arguments.end_date) : undefined;
      return normalizeResult(await indexData.run({ code, start_date, end_date }));
    }
  • Tool dispatch for index_data in the HTTP server's /mcp POST handler for tools/call method.
    case 'index_data':
      return await indexData.run({
        code: String(args?.code),
        start_date: args?.start_date ? String(args.start_date) : undefined,
        end_date: args?.end_date ? String(args.end_date) : undefined,
      });
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden of behavioral disclosure. It states the tool retrieves data but doesn't describe what type of data (e.g., historical prices, volumes, returns), how it's returned (e.g., format, structure), any rate limits, authentication needs, or error handling. For a data retrieval tool with zero annotation coverage, this is a significant gap in transparency.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that directly states the purpose with examples. It's appropriately sized and front-loaded, with no wasted words. However, it could be slightly more structured by explicitly mentioning the data type or use case.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the complexity of a data retrieval tool with 3 required parameters, no annotations, and no output schema, the description is incomplete. It lacks details on what data is returned, behavioral traits, and differentiation from siblings. While the schema covers parameters well, the overall context for effective tool use is insufficient.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The schema description coverage is 100%, with each parameter ('code', 'start_date', 'end_date') well-documented in the schema. The description adds no additional parameter semantics beyond implying the tool handles stock indices. Since the schema does the heavy lifting, the baseline score of 3 is appropriate, as the description doesn't compensate but also doesn't detract.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: '获取指定股票指数的数据' (get data for specified stock indices) with examples like '上证指数、深证成指等' (Shanghai Composite Index, Shenzhen Component Index, etc.). It specifies the verb '获取' (get) and resource '股票指数的数据' (stock index data), making the purpose unambiguous. However, it doesn't explicitly differentiate from sibling tools like 'stock_data' or 'csi_index_constituents', which might also involve stock-related data retrieval.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. It mentions examples of indices but doesn't specify use cases, prerequisites, or exclusions. Given sibling tools like 'stock_data' (likely for individual stocks) and 'csi_index_constituents' (likely for index components), the lack of differentiation leaves the agent without clear usage context.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/Xxx00xxX33/FinanceMCP'

If you have feedback or need assistance with the MCP directory API, please join our Discord server