雅虎财经API封装工具

一个为Yahoo Finance API提供的TypeScript封装工具,内置MCP服务器,支持股票报价、金融数据、期权、筛选器、研究和市场数据等功能,适用于AI代理和开发者。

  • by anconina
  • TypeScript
  • 本地部署
  • 2 星标
  • 更新于
在 GitHub 查看 anconina/yfinance-mcp-ts

使用说明

A TypeScript wrapper for the Yahoo Finance API with a built-in MCP server for AI agents like Claude.

特性

  • 20个MCP工具 --股票报价、财务、期权、筛选器、研究和市场数据
  • LLM优化输出 --具有自动聚合和大小保护的紧凑文本/markdown响应
  • 浏览器模拟 --通过以下方式绕过TLS指纹识别 impit 100%成功率
  • 代理旋转 --具有自动故障跟踪和冷却功能的循环旋转
  • 使用回退重试 --速率限制和瞬态误差的抖动指数退避
  • 300+筛选器 --预定义的股票筛选器(日内上涨股、最活跃股、成长股等)
  • 高级支持 --通过Puppeteer进行可选的Yahoo Finance Premium身份验证

安装

npm install yfinance-mcp-ts

MCP服务器设置

克劳德桌面/克劳德代码

添加到您的配置(~/.config/claude/claude_desktop_config.json 在macOS/Linux上, %APPDATA%\Claude\claude_desktop_config.json 在Windows上):

{
  "mcpServers": {
    "yfinance": {
      "command": "npx",
      "args": ["yfinance-mcp-ts"]
    }
  }
}

使用代理轮换:

{
  "mcpServers": {
    "yfinance": {
      "command": "npx",
      "args": ["yfinance-mcp-ts"],
      "env": {
        "YFINANCE_PROXY_LIST": "http://user:pass@proxy1.com:8080\nhttp://user:pass@proxy2.com:8080"
      }
    }
  }
}

您还可以手动运行服务器:

npm run mcp          # production
npm run mcp:dev      # development (ts-node)
npx yfinance-mcp-ts  # from npm

可用工具

工具 说明
股票数据
get_stock_price 当前价格、市值、交易量
get_stock_summary 市盈率,52周区间,股息收益率
get_stock_profile 公司信息、行业、员工
get_stock_history 历史OHLCV数据
get_financials 损益表、资产负债表、现金流量表
get_options 希腊期权链
get_key_stats 远期市盈率、PEG、贝塔系数、每股收益
get_recommendations 分析师建议
get_earnings EPS估计值和实际值
筛选器
list_screeners 列出所有300+筛选器
get_screener 运行筛选器
get_screener_info 获取筛选器详细信息
研究
get_earnings_calendar 即将发布的收益公告
get_ipos 即将到来和最近的首次公开募股
get_splits 即将和最近的股票分割
市场数据
search_stocks 按名称或符号搜索
get_market_summary 主要指数(标准普尔500指数、道琼斯指数、纳斯达克指数)
get_trending 趋势股
get_currencies 货币对和汇率
get_supported_countries 支持的国家列表

默认情况下,所有工具都返回压缩文本。添加 format: "json" 任何对原始JSON输出的调用。

环境变量

变量 描述 默认值
YFINANCE_HTTP_CLIENT impit 或 axios impit
YFINANCE_HTTP3 启用HTTP/3(仅限impit) false
YFINANCE_IGNORE_TLS_ERRORS 忽略TLS证书错误 false
YFINANCE_TIMEOUT 请求超时(ms) 30000
YFINANCE_PROXY_LIST 换行分隔的代理URL --
YFINANCE_PROXY_MAX_FAILURES 在将代理标记为不健康之前失败 3
YFINANCE_PROXY_COOLDOWN_MS 重试不健康代理之前的冷却时间(毫秒) 300000
YFINANCE_RETRY_ENABLED 启用自动重试 true
YFINANCE_RETRY_MAX_RETRIES 最大重试次数 5
YFINANCE_RETRY_INITIAL_DELAY 初始重试延迟(ms) 2000
YFINANCE_RETRY_MAX_DELAY 最大重试延迟(ms) 60000

图书馆使用情况

股票行情自动收录器

import { Ticker } from 'yfinance-mcp-ts';

const ticker = new Ticker('AAPL');
// or multiple: new Ticker('AAPL MSFT GOOG') / new Ticker(['AAPL', 'MSFT'])

await ticker.getPrice();
await ticker.getSummaryDetail();
await ticker.getSummaryProfile();
await ticker.getKeyStats();
await ticker.getEarnings();
await ticker.getRecommendationTrend();

// Historical data
await ticker.getHistory({ period: '1mo', interval: '1d' });
await ticker.getHistory({ start: '2024-01-01', end: '2024-12-31', interval: '1wk' });

// Financial statements ('a' = annual, 'q' = quarterly)
await ticker.getIncomeStatement('a');
await ticker.getBalanceSheet('q');
await ticker.getCashFlow('a');
await ticker.getFinancials('income', 'a'); // type: 'income' | 'balance' | 'cash' | 'cashflow'

// Options
await ticker.getOptionChain();

// All available modules at once
await ticker.getAllModules();
All Ticker methods
方法 说明
getPrice() 当前价格和市场数据
getSummaryDetail() 汇总统计
getSummaryProfile() 公司简介
getAssetProfile() 公司详细信息
getKeyStats() 关键统计数据
getFinancialDataSummary() 财务关键绩效指标
getEarnings() 收益数据
getEarningsTrend() 收益趋势
getCalendarEvents() 即将举行的活动
getRecommendationTrend() 分析师建议
getEsgScores() ESG指标
getMajorHolders() 主要股东
getInsiderHolders() 内幕持股
getInsiderTransactions() 内幕交易
getInstitutionOwnership() 机构所有权
getFundOwnership() 基金所有权
getSecFilings() 美国证券交易委员会文件
getQuoteType() 报价类型信息
getGradingHistory() 升级/降级历史记录
getHistory() 历史OHLCV数据
getDividendHistory() 股息历史
getIncomeStatement() 损益表
getBalanceSheet() 资产负债表
getCashFlow() 现金流量表
getValuationMeasures() 估价方法
getAllFinancialData() 所有财务数据
getOptionChain() 完整选项链
getQuotes() 快速报价
getRecommendations() 类似股票
getTechnicalInsights() 技术分析
getNews() 近期新闻
getCompanyOfficers() 公司高管

特定基金: getFundHoldingInfo(), getFundTopHoldings(), getFundSectorWeightings(), getFundBondHoldings(), getFundEquityHoldings(), getFundBondRatings(), getFundPerformance(), getFundProfile()

筛选器

import { Screener } from 'yfinance-mcp-ts';

const screener = new Screener();
screener.availableScreeners;                    // list all 300+ screener IDs
screener.getScreenerInfo('day_gainers');         // screener metadata
await screener.getScreeners('day_gainers', 25); // run with result count
await screener.getScreeners('day_gainers most_actives', 10); // multiple

研究

import { Research } from 'yfinance-mcp-ts';

const research = new Research();
await research.getEarnings('2024-01-01', '2024-01-31');
await research.getSplits('2024-01-01', '2024-12-31');
await research.getIPOs('2024-01-01', '2024-12-31');

// Premium only
await research.getReports(100, { sector: 'Technology', investment_rating: 'Bullish' });
await research.getTrades(100, { trend: 'Bullish', term: 'Short term' });

独立功能

import { search, getMarketSummary, getTrending, getCurrencies, getValidCountries } from 'yfinance-mcp-ts';

await search('Apple', { quotesCount: 10, newsCount: 5 });
await search('AAPL', { firstQuote: true });
await getMarketSummary('united states');
await getTrending('united states');
await getCurrencies();
getValidCountries(); // ['united states', 'france', 'germany', ...]

配置

const ticker = new Ticker('AAPL', {
  country: 'united states',   // 14 supported countries
  timeout: 30000,
  httpClient: 'impit',        // 'impit' (default) or 'axios'
  retry: {
    enabled: true,
    maxRetries: 3,
    initialDelay: 1000,
    maxDelay: 30000,
  },
  proxyRotation: {
    proxyList: 'http://proxy1:8080\nhttp://proxy2:8080',
    maxFailures: 3,
    cooldownMs: 300000,
  },
  // Premium auth (requires puppeteer)
  username: 'your@email.com',
  password: 'password',
});

支持的国家: united states, australia, canada, france, germany, hong kong, india, italy, spain, united kingdom, brazil, new zealand, singapore, taiwan

需求

  • Node.js>=20.0.0
  • TypeScript>=5.0(用于开发)
  • puppeteer >=21.0.0(可选,用于高级功能)
  • https-proxy-agent / socks-proxy-agent (可选,用于代理支持)

许可证

麻省理工学院

学分

TypeScript端口 yahooquery 道格·格思里著。

免责声明

不隶属于雅虎股份有限公司数据仅供个人使用。在投入生产之前,请先查看雅虎的服务条款。