jp-stock-trends-mcp
README.md
# jp-stock-trends-mcp
**Single-Tool MCP Server Unifying Japanese & US Stock Market Valuation (`yfinance`) and Rate-Limit-Free Search / News Trends with Public Data Gap Analysis**
**企業データ(官公庁落札・特許・補助金・財務)や地域トレンドを、株式市場の評価(株価・時価総額・PER・PBR・配当利回り・騰落率)および世間の検索・報道トレンドと1つのチャット内で照合できる 1ツール特化型 MCP サーバー**
[](LICENSE)
[](https://modelcontextprotocol.io)
[](https://www.python.org/)
[](#security-architecture)
[English](#english-documentation) | [日本語ドキュメント](#japanese-documentation)
---
<a name="english-documentation"></a>
## 🌍 English Documentation
### Why `jp-stock-trends-mcp`?
When analyzing corporate fundamentals using official public datasets—such as government procurement awards (`procurement`), corporate profiles (`corporate_profile`), national subsidies (`subsidies`), patent filings (`patents`), or EDINET financial statements (`edinet_financials`) via [`japan-data-mcp`](https://github.com/japan-opendata-lab/japan-data-mcp)—investors, analysts, and researchers need to immediately answer two critical questions in the same chat session:
1. **How is the stock market currently pricing this company?** (Current stock price, Market Cap, PER, PBR, Dividend Yield, 52-Week High/Low, and 1M / 3M / 1Y price momentum)
2. **Has public search and media attention already caught on, or is it still under the radar?** (Search interest score, rising autocomplete suggestions, and 7-day / 30-day news velocity)
**`jp-stock-trends-mcp`** provides a single, unified MCP tool (`get_market_and_search_trends`) designed for local LLMs (**LM Studio**, **Ollama**) and cloud AI agents (**Claude Desktop**, **Cursor**, **Cline**):
- **Automatic Ticker, Securities Code & 13-Digit Corporate Number Normalization**:
- Accepts 4-digit Japanese securities codes (`"7203"` $\rightarrow$ auto-normalized to `"7203.T"`), alphanumeric TSE codes (`"130A"` $\rightarrow$ `"130A.T"`), US tickers (`"AAPL"`, `"NVDA"`, `"MSFT"`), 13-digit Japanese corporate numbers (`"1180301018771"`), or company names (`"トヨタ自動車"`, `"日立製作所"`, `"NEC"`, `"富士通"`, `"三菱重工業"`).
- Automatically attaches `corporate_number` and `securities_code` so output records join directly with [`japan-data-mcp`](https://github.com/japan-opendata-lab/japan-data-mcp) with zero manual mapping.
- **Rate-Limit-Free Search & News Trend Aggregation (Zero HTTP 429 Errors)**:
- Combines **Google Autocomplete Suggest API**, **Google News RSS Time-Series Aggregation**, and **Google Trends Official Daily RSS** to compute a 0–100 `search_interest_score`, rising related keywords, 7d/30d/weekly news counts, and momentum ratios without scraping blockages.
- **Public Data vs. Market Attention Gap Analysis (`gap_analysis`)**:
- Automatically classifies the stock into a 4-quadrant valuation $\times$ attention matrix (e.g., *"Surging Government Procurement / Patents $\times$ Low PER & Quiet Search Attention = Hidden Gem Opportunity"*).
- **Enterprise-Grade Security & Sandboxing**:
- **SSRF Whitelist**: Outbound requests are strictly limited to HTTPS endpoints on `query1.finance.yahoo.com`, `query2.finance.yahoo.com`, `suggestqueries.google.com`, `news.google.com`, and `trends.google.co.jp` / `trends.google.com`.
- **Prompt Injection Defense**: All external text strings (news headlines, sources, autocomplete suggestions, trending keywords) are stripped of control tokens and wrapped in `<untrusted_data>...</untrusted_data>` boundary tags.
- **Path Traversal Guard**: File outputs (`.cache` and optional `.parquet` exports) are confined via `Path.resolve()` and `relative_to()` (`../` rejected) with zero file-deletion capabilities.
---
### 📊 Output Schema (`get_market_and_search_trends`)
| Section | Field | Type | Description |
| :--- | :--- | :--- | :--- |
| `join_keys` | `ticker` / `securities_code` | `string` | Normalized ticker (`"7203.T"`, `"AAPL"`) & 4-digit JP code (`"7203"`) |
| `join_keys` | `corporate_number` | `string` | 13-digit Japanese Corporate Number (`"1180301018771"`) for joining with `japan-data-mcp` |
| `market_valuation` | `current_price` / `market_cap` | `float` | Latest stock price, market cap, and `market_cap_oku_jpy` (100M JPY) |
| `market_valuation` | `trailing_pe` / `forward_pe` | `float` | Trailing & Forward Price-to-Earnings Ratio (PER) |
| `market_valuation` | `price_to_book` / `dividend_yield_pct` | `float` | Price-to-Book Ratio (PBR) & Dividend Yield (%) |
| `market_valuation` | `fifty_two_week_high` / `low` | `float` | 52-week high/low and `pct_from_52w_high` / `pct_from_52w_low` (%) |
| `market_valuation` | `return_1m_pct` / `3m` / `1y` | `float` | 1-month, 3-month, and 1-year stock price return percentages (%) |
| `search_and_news_trends` | `search_interest_score` | `int` | Composite search & media attention score (`0` to `100`) |
| `search_and_news_trends` | `rising_suggest_keywords` | `list[str]` | Rising Google Autocomplete suggestions wrapped in `<untrusted_data>` tags |
| `search_and_news_trends` | `news_volume_timeline` | `object` | 7d / 30d / 90d news counts, 4-week breakdown, and `news_momentum_ratio` |
| `search_and_news_trends` | `recent_news_headlines` | `list[obj]` | Latest news headlines & sources wrapped in `<untrusted_data>` tags |
| `gap_analysis` | `gap_quadrant` / `analytical_perspectives` | `object` | Valuation $\times$ Search Attention quadrant & cross-check steps for `japan-data-mcp` |
---
### 🚀 Quick Start
#### 1. Installation
```bash
git clone https://github.com/japan-opendata-lab/jp-stock-trends-mcp.git
cd jp-stock-trends-mcp
pip install -e ".[dev]"
pytest -v
```
#### 2. Configure in LM Studio (`~/.lmstudio/mcp.json`) or Claude Desktop / Cursor
```json
{
"mcpServers": {
"jp-stock-trends-mcp": {
"command": "python",
"args": [
"-X",
"utf8",
"./oss_mcp/jp-stock-trends-mcp/server.py"
],
"env": {
"PYTHONIOENCODING": "utf-8",
"STOCK_TRENDS_CACHE_DIR": "./oss_mcp/jp-stock-trends-mcp/.cache",
"STOCK_TRENDS_EXPORT_DIR": "./oss_mcp/jp-stock-trends-mcp/.cache"
}
}
}
}
```
---
### 🔗 Equity Research Examples with `japan-data-mcp` (Government Procurement & Corporate Profile)
By running [`japan-data-mcp`](https://github.com/japan-opendata-lab/japan-data-mcp) and **`jp-stock-trends-mcp`** side-by-side in LM Studio or Claude Desktop, you can execute institutional-grade **Public Data $\times$ Stock Valuation $\times$ Search Trend** cross-analysis in a single prompt:
1. **Case Study 1: Surging Government Procurement Awards vs. Stock Valuation (NEC `6701` / Mitsubishi Heavy Industries `7011` / Obayashi `1802`)**
- **Step 1 (`japan-data-mcp`)**: Query `search_japan_official_data(dataset="procurement", corporate_number="7010401022916")` (NEC) or `"4010001034978"` (Obayashi Corp.) to quantify recent Ministry of Defense, Digital Agency, and MLIT contract award growth.
- **Step 2 (`jp-stock-trends-mcp`)**: Call `get_market_and_search_trends(ticker_or_company="1802", keyword="大林組 国土強靭化 防衛", public_data_context="官公庁インフラ落札額が前年比増加")` to check if the stock still trades at a low PER (`~11.8x`) and low search heat (`search_interest_score < 50`) before retail investors notice.
2. **Case Study 2: National Cloud & Semiconductor Subsidies vs. High-Momentum Tech Valuation (SAKURA internet `3778` / Toyota `7203`)**
- **Step 1 (`japan-data-mcp`)**: Inspect `corporate_profile`, `subsidies`, and `patents` for `corporate_number="5120001092649"` (SAKURA internet) or `"1180301018771"` (Toyota Motor).
- **Step 2 (`jp-stock-trends-mcp`)**: Call `get_market_and_search_trends(ticker_or_company="7203", keyword="トヨタ 全固体電池 補助金")` to compare fundamental R&D/subsidy scale against current PBR (`~0.98x`), dividend yield (`~3.32%`), and 7-day news velocity.
---
<a name="japanese-documentation"></a>
## 🇯🇵 日本語ドキュメント
### なぜ `jp-stock-trends-mcp` が必要なのか?
[`japan-data-mcp`](https://github.com/japan-opendata-lab/japan-data-mcp) を用いて「官公庁の落札実績(`procurement`)」「国策補助金の採択(`subsidies`)」「特許出願(`patents`)」「EDINET有価証券報告書・財務(`edinet_financials`)」「企業プロファイル(`corporate_profile`)」を分析する際、投資家・アナリスト・事業開発担当者が同じチャット内で即座に照合したいのが**「株式市場での現在のバリュエーション評価」**と**「世間の検索・ニュース報道の盛り上がり度合い」**です。
**`jp-stock-trends-mcp`** は、単一の統合ツール `get_market_and_search_trends` で以下の3機能をワンストップ提供する汎用オープンソース MCP サーバーです。
### 3大コア機能
1. **機能1:株価・市場バリュエーション取得(`ticker_or_company`)**
- **日本の4桁証券コード自動正規化**: `"7203"` や `"6701"` のように4桁コードを入力するだけで自動的に東証ティッカー `"7203.T"`, `"6701.T"` に正規化します(新証券コード `"130A"` $\rightarrow$ `"130A.T"` や米国ティッカー `"AAPL"`, `"NVDA"`, `"MSFT"`、日本語企業名 `"トヨタ自動車"`, `"日立製作所"`, `"NEC"`, `"三菱重工業"`、および13桁法人番号 `"1180301018771"` の直接指定にも対応)。
- **取得指標**: Yahoo Finance API / `yfinance` 経由で、**現在株価・時価総額(億円 / 現地通貨)・実績PER・予想PER・PBR・配当利回り(%)・ROE・52週高値/安値・直近1ヶ月/3ヶ月/1年の株価騰落率(%)**を一括取得します。
- **13桁法人番号(`corporate_number`)自動付与**: 主要日本企業について国税庁13桁法人番号を自動付与するため、`japan-data-mcp` の官公庁落札・補助金・財務データと変換なしで即座に結合できます。
2. **機能2:レート制限(HTTP 429)が起きない検索トレンド・急上昇関連ワード取得(`keyword`)**
- 非公式スクレイピングで頻発する HTTP 429 エラーを回避するため、**Google Autocomplete サジェスト API**・**Google News RSS 時系列件数集計**・**Google Trends 公式 Daily RSS** の3系統を組み合わせ、以下を安定取得します:
- **現在の関心度スコア(`search_interest_score`: 0〜100)**
- **急上昇サジェスト関連語(`rising_suggest_keywords`)**
- **最新ニュース見出し・時系列件数推移(直近7日・30日・週次推移・モメンタム倍率 `news_momentum_ratio`)**
3. **機能3:公的データ × 市場評価 × 検索関心のギャップ分析メタデータ(`gap_analysis`)**
- 「官公庁落札や特許出願が急増しているのに、PERが10倍前後で検索トレンドもまだ静穏=**市場コンセンサス未織り込みの隠れた注目銘柄/テーマ**」なのか、「すでに高PERかつニュース・検索が過熱している**期待先行局面**」なのかを4象限で自動判定し、次に `japan-data-mcp` で確認すべき具体的なクエリ手順を提案します。
---
### 📈 `japan-data-mcp`(官公庁調達・企業プロファイル)と組み合わせた銘柄分析事例
LM Studio(`Qwen3-8B` 等)や Claude Desktop に [`japan-data-mcp`](https://github.com/japan-opendata-lab/japan-data-mcp) と **`jp-stock-trends-mcp`** を両方登録すると、1つのチャット内で以下のような**「公的ファクト × 株価バリュエーション × 検索トレンド」**の横断分析が完結します。
#### 事例1:官公庁落札(Procurement)急増企業の割安放置・出遅れ発掘
- **分析フロー**:
1. `japan-data-mcp` の `search_japan_official_data` で、防衛省・デジタル庁・国土交通省からの落札金額が増加している企業を検索(例:**日本電気(NEC)** `corporate_number="7010401022916"` / 証券コード `6701`、**大林組** `corporate_number="4010001034978"` / 証券コード `1802`、**三菱重工業** `corporate_number="2010401052465"` / 証券コード `7011`)。
2. 続けて `jp-stock-trends-mcp` の `get_market_and_search_trends` を呼び出し:
```json
{
"ticker_or_company": "1802",
"keyword": "大林組 官公庁 インフラ",
"public_data_context": "国土交通省・防衛施設関連の官公庁落札金額が堅調に推移"
}
```
3. **インサイト抽出**: 大林組(`1802.T`)が PER 約11.8倍・PBR 約1.16倍・配当利回り約3.85%と割安水準にあり、世間の検索関心度スコアも過熱前であることを確認。「公的調達の積み上がりに対し、バリュエーションと検索トレンドに出遅れギャップがある」と定量的に評価できます。
#### 事例2:企業プロファイル・国策補助金・特許データと市場期待(高PER / PBR)の妥当性照合
- **分析フロー**:
1. `japan-data-mcp` で **トヨタ自動車**(`corporate_number="1180301018771"`, 証券コード `7203`)や **さくらインターネット**(`corporate_number="5120001092649"`, 証券コード `3778`)の企業プロファイル・補助金採択・特許・EDINET財務データを取得。
2. `get_market_and_search_trends(ticker_or_company="7203", keyword="トヨタ自動車 全固体電池")` を実行。
3. **インサイト抽出**: トヨタ自動車の現在株価・時価総額・PER(約8.7倍)・PBR(約0.98倍)・直近1ヶ月/3ヶ月/1年騰落率と、Googleサジェスト急上昇ワード・直近7日間のニュースモメンタムを突き合わせ、設備投資・R&D実績に対する市場評価の割安度を検証します。
---
<a name="security-architecture"></a>
### 🔒 セキュリティ設計(SSRF防止・外部テキスト無害化・サンドボックス)
1. **SSRF(Server-Side Request Forgery)防止ホワイトリスト**:
- 外部通信先は `validate_outbound_url()` により、許可された HTTPS 金融・トレンドエンドポイント(`query1.finance.yahoo.com`, `query2.finance.yahoo.com`, `suggestqueries.google.com`, `news.google.com`, `trends.google.co.jp`, `trends.google.com`)のみに厳格制限されています。`http://` や内部IP(`localhost`, `127.0.0.1`, `169.254.169.254`)、未許可ドメインへの通信はすべて拒否されます。
2. **プロンプトインジェクション対策(`<untrusted_data>` タグ無害化)**:
- 外部から取得したニュース見出し(`title`, `source`)、Googleサジェスト語(`rising_suggest_keywords`)、トレンドワードは、制御文字および命令偽装トークン(`<system>`, `<|im_start|>`, `Ignore previous instructions` 等)を除去した上で、すべて `<untrusted_data>...</untrusted_data>` 境界タグで囲んで返却します。
3. **ファイル出力のサンドボックス化と削除機能なし**:
- キャッシュおよび `export_parquet=True` 時のファイル出力は `Path.resolve()` と `relative_to()` により指定ディレクトリ内のみに制限され、パストラバーサル(`../`)や絶対パス指定を完全拒否します。また、ファイル削除機能は一切持ちません。
---
### 🛠 セットアップと LM Studio 登録方法
#### 1. インストールとテスト実行
```bash
git clone https://github.com/japan-opendata-lab/jp-stock-trends-mcp.git
cd jp-stock-trends-mcp
pip install -e ".[dev]"
pytest -v
```
#### 2. LM Studio (`~/.lmstudio/mcp.json`) への登録例
```json
{
"mcpServers": {
"jp-stock-trends-mcp": {
"command": "python",
"args": [
"-X",
"utf8",
"./oss_mcp/jp-stock-trends-mcp/server.py"
],
"env": {
"PYTHONIOENCODING": "utf-8",
"STOCK_TRENDS_CACHE_DIR": "./oss_mcp/jp-stock-trends-mcp/.cache",
"STOCK_TRENDS_EXPORT_DIR": "./oss_mcp/jp-stock-trends-mcp/.cache"
}
}
}
}
```
---
### 🌐 関連エコシステム(Japan Open Data Lab)
- **[`japan-data-mcp`](https://github.com/japan-opendata-lab/japan-data-mcp)**: 日本の公的オープンデータ(官公庁落札・企業プロファイル・補助金・特許・EDINET財務・地域統計など全162データセット)を検索できる公式 MCP サーバー
- **[`correlation-discovery-mcp`](https://github.com/japan-opendata-lab/correlation-discovery-mcp)**: あらゆる DuckDB / Parquet / CSV データから相関係数 ($r$値)・要因ランキング・回帰外れ値を一括算出する統計探索 MCP サーバー
- **[`japan-climate-stats-mcp`](https://github.com/japan-opendata-lab/japan-climate-stats-mcp)**: 全47都道府県・市区町村の気象・自然環境統計(日照時間・寒暖差・猛暑日・降水量)を0.1秒未満で算出する MCP サーバー
- **[`japan-official-data-megabank`](https://github.com/japan-opendata-lab/japan-official-data-megabank)**: 公式 Python SDK & スターターキット
---
## License
MIT License — Copyright (c) 2026 Japan Open Data Lab (`japan.opendata.lab@gmail.com`)
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo issues