← Back to Blog

SEC 官方 EDGAR API 工具指南

Xiao Wu
Xiao WuAuthor
June 25, 2025工具
Tags:
工具SEC

SEC 官方 EDGAR API 工具指南

这个文档介绍如何使用SEC官方EDGAR API工具来获取美国上市公司的财务数据。

概述

SEC官方EDGAR API工具使用美国证券交易委员会的官方API (data.sec.gov),具有以下优势:

免费使用 - 无需API密钥
官方数据源 - 数据权威性高
实时数据 - 直接从SEC获取最新数据
标准化格式 - 支持XBRL标准化财务数据
自动速率限制 - 符合SEC公平访问规则(每秒最多10个请求)

工具功能

1. 股票代码转CIK (ticker_to_cik)

将股票代码转换为SEC的中央索引密钥(CIK)。

输入: { ticker: "AAPL" }
输出: { success: true, ticker: "AAPL", cik: "320193" }

2. 公司提交数据 (sec_submissions)

获取公司向SEC提交的所有文件信息。

输入: { cik: "320193" }
输出: 包含公司基本信息和所有提交文件的详细数据

3. 公司财务事实 (sec_company_facts)

获取公司的所有标准化财务数据(XBRL格式)。

输入: { cik: "320193" }
输出: 包含所有财务指标的历史数据

4. 特定财务概念 (sec_company_concept)

获取公司特定财务指标的详细数据。

输入: { cik: "320193", taxonomy: "us-gaap", tag: "Assets" }
输出: 该公司资产数据的所有历史记录

5. 框架数据 (sec_frames)

获取特定时期内所有公司的某个财务指标数据。

输入: { taxonomy: "us-gaap", tag: "Assets", unit: "USD", year: "2023" }
输出: 2023年所有公司的资产数据

环境配置

1. 设置用户代理 (重要!)

SEC要求所有API请求提供标识信息,设置环境变量:

# 在 .env 文件中添加
SEC_USER_AGENT="Your Company Name admin@yourcompany.com"

格式: "公司名称 联系邮箱"
示例: "Financial Analysis Bot admin@example.com"

2. 网络配置

确保您的网络环境可以访问 data.sec.gov

  • 某些企业网络可能会阻止对SEC API的访问
  • 如果在服务器环境中运行,确保有适当的出站网络权限
  • 建议在生产环境中使用稳定的网络连接

常用财务指标标签

工具提供了预定义的常用财务指标标签:

import { COMMON_FINANCIAL_TAGS } from './lib/tools/sec-edgar-official';
 
// 资产类指标
COMMON_FINANCIAL_TAGS.assets.totalAssets        // 'Assets'
COMMON_FINANCIAL_TAGS.assets.currentAssets      // 'AssetsCurrent'
COMMON_FINANCIAL_TAGS.assets.cash               // 'CashAndCashEquivalentsAtCarryingValue'
 
// 收入类指标
COMMON_FINANCIAL_TAGS.income.revenue            // 'Revenues'
COMMON_FINANCIAL_TAGS.income.netIncome          // 'NetIncomeLoss'
COMMON_FINANCIAL_TAGS.income.grossProfit        // 'GrossProfit'
 
// 现金流指标
COMMON_FINANCIAL_TAGS.cashFlow.operatingCashFlow // 'NetCashProvidedByUsedInOperatingActivities'

使用示例

基础使用

import { getAllSECOfficialTools } from './lib/tools/sec-edgar-official';
 
async function basicUsage() {
  const tools = await getAllSECOfficialTools();
  
  // 1. 获取苹果公司的CIK
  const tickerTool = tools.find(t => t.actionName === 'ticker_to_cik');
  const cikResult = await tickerTool.callback({ ticker: 'AAPL' });
  
  if (cikResult.success) {
    console.log(`Apple CIK: ${cikResult.cik}`);
    
    // 2. 获取公司基本信息
    const submissionsTool = tools.find(t => t.actionName === 'sec_submissions');
    const companyInfo = await submissionsTool.callback({ cik: cikResult.cik });
    
    if (companyInfo.success) {
      console.log(`Company: ${companyInfo.data.name}`);
      console.log(`Industry: ${companyInfo.data.sicDescription}`);
    }
  }
}

财务数据分析

import { 
  getAllSECOfficialTools, 
  getCompanyFinancialMetrics,
  COMMON_FINANCIAL_TAGS 
} from './lib/tools/sec-edgar-official';
 
async function financialAnalysis() {
  // 获取苹果公司的关键财务指标
  const metrics = await getCompanyFinancialMetrics('320193', [
    COMMON_FINANCIAL_TAGS.assets.totalAssets,
    COMMON_FINANCIAL_TAGS.income.revenue,
    COMMON_FINANCIAL_TAGS.income.netIncome
  ]);
  
  if (metrics.success) {
    console.log('Apple Financial Metrics:');
    Object.entries(metrics.metrics).forEach(([metric, data]) => {
      console.log(`${metric}:`, data);
    });
  }
}

获取10-K报告列表

import { getCompany10KFilings } from './lib/tools/sec-edgar-official';
 
async function get10KReports() {
  const filings = await getCompany10KFilings('320193'); // Apple
  
  if (filings.success) {
    console.log(`Found ${filings.count} 10-K filings`);
    
    filings.tenKFilings.forEach(filing => {
      console.log(`${filing.filingDate}: ${filing.primaryDocDescription}`);
    });
  }
}

行业对比分析

async function industryComparison() {
  const tools = await getAllSECOfficialTools();
  const framesTool = tools.find(t => t.actionName === 'sec_frames');
  
  // 获取2023年所有公司的收入数据
  const revenueData = await framesTool.callback({
    taxonomy: 'us-gaap',
    tag: 'Revenues',
    unit: 'USD',
    year: '2023'
  });
  
  if (revenueData.success) {
    // 按收入排序,显示前10名
    const topCompanies = revenueData.data.data
      .sort((a, b) => b.val - a.val)
      .slice(0, 10);
    
    console.log('2023年收入前10名公司:');
    topCompanies.forEach((company, index) => {
      const revenue = (company.val / 1000000000).toFixed(1);
      console.log(`${index + 1}. ${company.entityName}: $${revenue}B`);
    });
  }
}

工具集成

与现有工具系统集成

// 更新 composio-config.ts
export const SUPPORTED_APPS = [
  // ... 其他工具
  'sec_edgar_official', // 添加SEC官方API工具
] as const;
 
export const INTERNAL_APPS = [
  'tavily',
  'sec_edgar_official', // 添加到内部工具列表
  'user_query',
  // ...
] as const;
// 更新 tool-manager.ts
import { registerSECOfficialTools } from './sec-edgar-official';
 
// 在工具管理器中注册
private async initializeSECOfficialTools() {
  if (this.config.enabled && this.config.apps.includes('sec_edgar_official')) {
    try {
      await registerSECOfficialTools(this.toolset);
      console.log('✅ SEC official tools registered successfully');
    } catch (error) {
      console.error('❌ Failed to register SEC official tools:', error);
    }
  }
}

LangGraph工作流集成

import { StateGraph } from "@langchain/langgraph";
import { getAllSECOfficialTools } from './lib/tools/sec-edgar-official';
 
const workflow = new StateGraph(YourAnnotation)
  .addNode("sec_data", async (state) => {
    const tools = await getAllSECOfficialTools();
    const tickerTool = tools.find(t => t.actionName === 'ticker_to_cik');
    const submissionsTool = tools.find(t => t.actionName === 'sec_submissions');
    
    // 获取CIK
    const cikResult = await tickerTool.callback({ ticker: state.ticker });
    
    if (cikResult.success) {
      // 获取公司数据
      const companyData = await submissionsTool.callback({ cik: cikResult.cik });
      
      return {
        ...state,
        cik: cikResult.cik,
        companyData: companyData.success ? companyData.data : null
      };
    }
    
    return { ...state, error: 'Failed to get CIK' };
  })
  .addNode("analysis", analysisNode)
  .addEdge("sec_data", "analysis");

支持的公司

工具包含40+主要美国上市公司的ticker到CIK映射:

科技公司: AAPL, MSFT, GOOGL, AMZN, META, TSLA, NVDA, NFLX, INTC, ORCL, IBM
金融公司: JPM, BAC, WFC, GS, MS, V, MA
医疗保健: UNH, JNJ, PFE
消费品: KO, PG, WMT, HD
能源: XOM, CVX
通信: VZ, T
娱乐: DIS

对于未包含的公司,可以通过SEC官网查找CIK,或提交PR添加到映射表。

数据格式说明

财务数据结构

SEC API返回的财务数据采用XBRL标准格式:

{
  "cik": 320193,
  "taxonomy": "us-gaap",
  "tag": "Assets",
  "label": "Assets",
  "description": "Sum of the carrying amounts as of the balance sheet date...",
  "units": {
    "USD": [
      {
        "end": "2023-09-30",
        "val": 352755000000,
        "accn": "0000320193-23-000106",
        "fy": 2023,
        "fp": "FY",
        "form": "10-K",
        "filed": "2023-11-03"
      },
      // ... 更多历史数据
    ]
  }
}

常用字段说明

  • end: 报告期结束日期
  • val: 数值(单位为美元)
  • fy: 财政年度
  • fp: 财政期间("FY"=年度, "Q1/Q2/Q3/Q4"=季度)
  • form: 报告类型("10-K"=年报, "10-Q"=季报)
  • filed: 提交日期

错误处理

常见错误及解决方案

  1. "fetch failed"

    原因: 网络连接问题或SEC API不可访问
    解决: 检查网络连接,确认可以访问data.sec.gov
    
  2. "CIK not found for ticker"

    原因: 股票代码不在预定义映射表中
    解决: 手动查找CIK或添加到映射表
    
  3. "SEC API request failed: 403"

    原因: 用户代理字符串不符合要求
    解决: 设置正确的SEC_USER_AGENT环境变量
    
  4. "SEC API request failed: 429"

    原因: 超过速率限制(每秒10次请求)
    解决: 工具已内置速率限制,如仍出现请检查并发请求
    

调试模式

启用详细日志:

// 在工具调用前设置
process.env.SEC_DEBUG = 'true';

性能优化

缓存策略

虽然工具本身不包含缓存,但建议在应用层实现:

const cache = new Map();
 
async function getCachedCompanyData(cik: string) {
  const cacheKey = `company_${cik}`;
  
  if (cache.has(cacheKey)) {
    return cache.get(cacheKey);
  }
  
  const tools = await getAllSECOfficialTools();
  const submissionsTool = tools.find(t => t.actionName === 'sec_submissions');
  const result = await submissionsTool.callback({ cik });
  
  if (result.success) {
    cache.set(cacheKey, result.data);
    // 设置1小时过期
    setTimeout(() => cache.delete(cacheKey), 3600000);
  }
  
  return result;
}

批量处理

处理多个公司时,添加延迟避免速率限制:

async function batchProcessCompanies(tickers: string[]) {
  const results = [];
  
  for (const ticker of tickers) {
    const result = await processCompany(ticker);
    results.push(result);
    
    // 等待100ms,确保不超过每秒10次限制
    await new Promise(resolve => setTimeout(resolve, 100));
  }
  
  return results;
}

测试

运行测试验证工具功能:

# 基础功能测试
npx tsx -e "
import { getAllSECOfficialTools } from './lib/tools/sec-edgar-official';
 
async function test() {
  const tools = await getAllSECOfficialTools();
  console.log(\`✅ Created \${tools.length} tools\`);
  
  const tickerTool = tools.find(t => t.actionName === 'ticker_to_cik');
  const result = await tickerTool.callback({ ticker: 'AAPL' });
  console.log('AAPL CIK:', result.success ? result.cik : 'Failed');
}
 
test();
"

最佳实践

1. 财务分析工作流

// 推荐的财务分析步骤
async function comprehensiveAnalysis(ticker: string) {
  // 1. 获取CIK
  const cik = await getCIKFromTicker(ticker);
  
  // 2. 获取公司基本信息
  const companyInfo = await getCompanySubmissions(cik);
  
  // 3. 获取关键财务指标
  const metrics = await getCompanyFinancialMetrics(cik, [
    'Assets', 'Revenues', 'NetIncomeLoss'
  ]);
  
  // 4. 获取最新10-K报告
  const tenKFilings = await getCompany10KFilings(cik);
  
  return {
    company: companyInfo,
    metrics,
    latestFiling: tenKFilings.tenKFilings[0]
  };
}

2. 数据验证

function validateFinancialData(data: any) {
  if (!data.units || !data.units.USD) {
    throw new Error('No USD data available');
  }
  
  const recentData = data.units.USD
    .filter(item => item.form === '10-K')
    .sort((a, b) => new Date(b.end).getTime() - new Date(a.end).getTime());
    
  if (recentData.length === 0) {
    throw new Error('No annual data available');
  }
  
  return recentData;
}

3. 错误恢复

async function robustAPICall(apiCall: () => Promise<any>, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await apiCall();
    } catch (error) {
      if (i === maxRetries - 1) throw error;
      
      // 指数退避
      const delay = Math.pow(2, i) * 1000;
      await new Promise(resolve => setTimeout(resolve, delay));
    }
  }
}

更新日志

  • v1.0.0 - 初始版本,支持5个核心SEC API端点
  • 计划功能:更多公司映射、增强的数据解析、自动缓存

相关资源

Comments