Initial commit: skills library
- 70 skills with code and documentation - Add .gitignore (ignore __pycache__, output/, temp/, venv/) - Clean up test intermediates and caches
This commit is contained in:
@@ -0,0 +1,192 @@
|
||||
# 股票实时价格查询技能
|
||||
|
||||
## 技能概述
|
||||
|
||||
这是一个专门用于查询股票实时价格的专业技能,确保所有股票分析都基于准确的市场价格数据。
|
||||
|
||||
## 核心功能
|
||||
|
||||
1. **多市场支持**:A股、港股、美股等主要市场的股票价格查询
|
||||
2. **实时数据源**:使用多个可靠的数据源确保准确性
|
||||
3. **自动验证**:交叉验证多个数据源,确保价格准确性
|
||||
4. **错误处理**:当无法获取准确价格时,明确告知而非猜测
|
||||
|
||||
## 使用方法
|
||||
|
||||
### 查询单个股票
|
||||
```python
|
||||
get_stock_price("00700.HK") # 腾讯控股港股
|
||||
get_stock_price("600519.SH") # 贵州茅台A股
|
||||
get_stock_price("AAPL.US") # 苹果美股
|
||||
```
|
||||
|
||||
### 批量查询
|
||||
```python
|
||||
stock_codes = ["00700.HK", "09868.HK", "001309.SZ", "01088.HK"]
|
||||
prices = get_stock_prices(stock_codes)
|
||||
```
|
||||
|
||||
## 数据源优先级
|
||||
|
||||
1. **官方交易所数据**(最高优先级)
|
||||
- 港交所 (HKEX) - 港股
|
||||
- 上交所/深交所 - A股
|
||||
- 纳斯达克/纽交所 - 美股
|
||||
|
||||
2. **权威金融数据提供商**
|
||||
- Yahoo Finance
|
||||
- Google Finance
|
||||
- Bloomberg
|
||||
- Reuters
|
||||
|
||||
3. **国内金融数据平台**
|
||||
- 东方财富
|
||||
- 同花顺
|
||||
- 雪球
|
||||
|
||||
## 错误处理机制
|
||||
|
||||
### 当无法获取准确价格时:
|
||||
- **绝不猜测或估算**
|
||||
- **明确告知数据不可用**
|
||||
- **建议替代查询方式**
|
||||
- **记录错误以便改进**
|
||||
|
||||
### 数据验证规则:
|
||||
- **价格合理性检查**:排除明显异常的价格(如小数点错误)
|
||||
- **时间戳验证**:确保是最新交易日的数据
|
||||
- **多源一致性**:至少两个数据源价格差异不超过5%
|
||||
|
||||
## 实现细节
|
||||
|
||||
### 股票代码标准化
|
||||
```python
|
||||
def standardize_stock_code(code):
|
||||
"""
|
||||
标准化股票代码格式
|
||||
00700 -> 00700.HK (港股)
|
||||
600519 -> 600519.SH (A股)
|
||||
001309 -> 001309.SZ (A股创业板)
|
||||
AAPL -> AAPL.US (美股)
|
||||
"""
|
||||
# 实现代码标准化逻辑
|
||||
pass
|
||||
```
|
||||
|
||||
### 多源数据查询
|
||||
```python
|
||||
def query_multiple_sources(code):
|
||||
"""同时查询多个数据源"""
|
||||
sources = [
|
||||
query_yahoo_finance,
|
||||
query_google_finance,
|
||||
query_eastmoney,
|
||||
query_xueqiu
|
||||
]
|
||||
|
||||
results = []
|
||||
for source in sources:
|
||||
try:
|
||||
price = source(code)
|
||||
if price and is_reasonable_price(price):
|
||||
results.append(price)
|
||||
except Exception as e:
|
||||
log_error(f"Source {source.__name__} failed: {e}")
|
||||
|
||||
return validate_and_return_price(results)
|
||||
```
|
||||
|
||||
## 质量保证
|
||||
|
||||
### 必须遵守的原则:
|
||||
1. **准确性第一**:宁可不返回结果,也不返回错误结果
|
||||
2. **透明度**:明确说明数据来源和时间戳
|
||||
3. **一致性**:同一只股票在不同查询中返回相同结果
|
||||
4. **实时性**:确保数据是最新的交易日价格
|
||||
|
||||
### 验证清单:
|
||||
- [ ] 股票代码格式正确
|
||||
- [ ] 数据源可靠且最新
|
||||
- [ ] 价格在合理范围内
|
||||
- [ ] 多源数据一致性验证
|
||||
- [ ] 错误处理机制完善
|
||||
|
||||
## 触发条件
|
||||
|
||||
当用户需要进行任何股票相关的分析、建议或操作时,必须首先使用此技能查询准确的实时价格,然后再进行后续分析。
|
||||
|
||||
**禁止行为:**
|
||||
- ❌ 凭记忆或印象给出股票价格
|
||||
- ❌ 使用过时的价格数据
|
||||
- ❌ 在没有验证的情况下进行价格推测
|
||||
- ❌ 混淆不同市场的价格(如美股ADR vs 港股)
|
||||
|
||||
## 示例使用场景
|
||||
|
||||
**场景1:自选股分析**
|
||||
```
|
||||
用户:分析我的自选股
|
||||
步骤:1. 识别自选股代码 → 2. 查询每个股票的实时价格 → 3. 基于准确价格进行分析
|
||||
```
|
||||
|
||||
**场景2:持仓优化建议**
|
||||
```
|
||||
用户:给我持仓操作建议
|
||||
步骤:1. 读取持仓文件 → 2. 查询每个持仓股票的当前价格 → 3. 计算准确盈亏 → 4. 给出操作建议
|
||||
```
|
||||
|
||||
**场景3:新股票评估**
|
||||
```
|
||||
用户:评估德明利是否值得买入
|
||||
步骤:1. 查询德明利(001309.SZ)实时价格 → 2. 获取历史价格区间 → 3. 基于准确数据给出建议
|
||||
```
|
||||
|
||||
## 技术实现要求
|
||||
|
||||
### 依赖库
|
||||
```bash
|
||||
pip install yfinance requests beautifulsoup4 pandas
|
||||
```
|
||||
|
||||
### 主要函数
|
||||
```python
|
||||
def get_realtime_stock_price(stock_code: str) -> dict:
|
||||
"""
|
||||
获取股票实时价格
|
||||
|
||||
Args:
|
||||
stock_code: 标准化股票代码 (e.g., "00700.HK", "600519.SH")
|
||||
|
||||
Returns:
|
||||
{
|
||||
"code": "00700.HK",
|
||||
"price": 552.00,
|
||||
"currency": "HKD",
|
||||
"timestamp": "2026-03-11 16:00:00",
|
||||
"source": "Yahoo Finance",
|
||||
"previous_close": 553.50,
|
||||
"change_percent": -0.27
|
||||
}
|
||||
"""
|
||||
pass
|
||||
```
|
||||
|
||||
## 维护和更新
|
||||
|
||||
- **定期验证数据源**:每月检查各数据源的可用性
|
||||
- **错误日志记录**:记录所有查询失败的情况,持续改进
|
||||
- **用户反馈集成**:根据用户指出的错误快速修正
|
||||
- **新市场支持**:根据需求扩展支持更多交易市场
|
||||
|
||||
## 与其他技能的集成
|
||||
|
||||
此技能应作为以下技能的前置条件:
|
||||
- `stock-analysis`:股票分析技能
|
||||
- `portfolio-management`:投资组合管理技能
|
||||
- `trading-strategy`:交易策略技能
|
||||
|
||||
**执行流程:**
|
||||
1. 用户请求股票相关信息
|
||||
2. 自动调用 `stock-price-query` 技能获取准确价格
|
||||
3. 基于准确价格执行后续分析
|
||||
4. 如果价格查询失败,暂停后续分析并告知用户
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"skill_name": "stock-price-query",
|
||||
"description": "股票实时价格查询技能,确保所有股票分析都基于准确的市场价格数据",
|
||||
"version": "1.0.0",
|
||||
"status": "active",
|
||||
"data_sources": [
|
||||
"yahoo_finance",
|
||||
"eastmoney",
|
||||
"xueqiu",
|
||||
"google_finance"
|
||||
],
|
||||
"error_handling": "strict",
|
||||
"validation_required": true,
|
||||
"created_at": "2026-03-12T00:40:00Z",
|
||||
"last_updated": "2026-03-12T00:40:00Z"
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
# stock-price-query - dependencies
|
||||
requests>=0.0.1
|
||||
yfinance>=0.0.1
|
||||
@@ -0,0 +1,78 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
简化版股票价格查询工具
|
||||
使用Yahoo Finance API直接查询
|
||||
"""
|
||||
|
||||
import sys
|
||||
import json
|
||||
import requests
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
def get_stock_price_yahoo(stock_code):
|
||||
"""从Yahoo Finance获取股票价格"""
|
||||
# 标准化代码
|
||||
if not "." in stock_code:
|
||||
if len(stock_code) == 5:
|
||||
stock_code = f"{stock_code}.HK"
|
||||
elif len(stock_code) == 6:
|
||||
if stock_code.startswith(("00", "30")):
|
||||
stock_code = f"{stock_code}.SZ"
|
||||
else:
|
||||
stock_code = f"{stock_code}.SS"
|
||||
|
||||
url = f"https://query1.finance.yahoo.com/v8/finance/chart/{stock_code}"
|
||||
|
||||
try:
|
||||
response = requests.get(url, timeout=10)
|
||||
if response.status_code == 200:
|
||||
data = response.json()
|
||||
if "chart" in data and "result" in data["chart"]:
|
||||
result = data["chart"]["result"][0]
|
||||
meta = result["meta"]
|
||||
price = meta["regularMarketPrice"]
|
||||
previous_close = meta["previousClose"]
|
||||
currency = meta["currency"]
|
||||
|
||||
return {
|
||||
"code": stock_code,
|
||||
"price": price,
|
||||
"previous_close": previous_close,
|
||||
"currency": currency,
|
||||
"timestamp": datetime.now().isoformat(),
|
||||
"source": "Yahoo Finance",
|
||||
}
|
||||
except Exception as e:
|
||||
print(f"Error querying {stock_code}: {e}", file=sys.stderr)
|
||||
return None
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 2:
|
||||
print("用法: python simple_stock_query.py <stock_code>")
|
||||
sys.exit(1)
|
||||
|
||||
stock_code = sys.argv[1]
|
||||
result = get_stock_price_yahoo(stock_code)
|
||||
|
||||
if result:
|
||||
print(json.dumps(result, indent=2, ensure_ascii=False))
|
||||
else:
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"code": stock_code,
|
||||
"error": "无法获取准确价格数据",
|
||||
"timestamp": datetime.now().isoformat(),
|
||||
},
|
||||
indent=2,
|
||||
ensure_ascii=False,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,160 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
股票实时价格查询工具
|
||||
支持A股、港股、美股等多个市场的股票价格查询
|
||||
"""
|
||||
|
||||
import sys
|
||||
import json
|
||||
import time
|
||||
from typing import List, Dict, Optional
|
||||
import yfinance as yf
|
||||
import requests
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
class StockPriceQuery:
|
||||
"""股票价格查询类"""
|
||||
|
||||
def __init__(self):
|
||||
self.data_sources = {
|
||||
"yahoo_finance": self._query_yahoo_finance,
|
||||
"eastmoney": self._query_eastmoney,
|
||||
"xueqiu": self._query_xueqiu,
|
||||
}
|
||||
self.exchange_mapping = {"HK": "HK", "SH": "SS", "SZ": "SZ", "US": ""}
|
||||
|
||||
def standardize_code(self, stock_code: str) -> str:
|
||||
"""标准化股票代码"""
|
||||
stock_code = stock_code.strip()
|
||||
|
||||
# 处理已有后缀的情况
|
||||
if "." in stock_code:
|
||||
return stock_code
|
||||
|
||||
# 根据代码长度和前缀判断市场
|
||||
if len(stock_code) == 5 and stock_code.isdigit():
|
||||
# 港股5位数字
|
||||
return f"{stock_code}.HK"
|
||||
elif len(stock_code) == 6 and stock_code.isdigit():
|
||||
# A股6位数字
|
||||
if stock_code.startswith(("00", "30")):
|
||||
return f"{stock_code}.SZ" # 深圳
|
||||
else:
|
||||
return f"{stock_code}.SS" # 上海
|
||||
elif stock_code.isalpha():
|
||||
# 美股代码
|
||||
return f"{stock_code}"
|
||||
else:
|
||||
# 默认按港股处理
|
||||
return f"{stock_code}.HK"
|
||||
|
||||
def _query_yahoo_finance(self, standardized_code: str) -> Optional[Dict]:
|
||||
"""查询Yahoo Finance数据"""
|
||||
try:
|
||||
ticker = yf.Ticker(standardized_code)
|
||||
info = ticker.info
|
||||
|
||||
if "currentPrice" not in info:
|
||||
return None
|
||||
|
||||
price = info["currentPrice"]
|
||||
previous_close = info.get("previousClose", price)
|
||||
currency = info.get("currency", "USD")
|
||||
|
||||
return {
|
||||
"price": float(price),
|
||||
"previous_close": float(previous_close),
|
||||
"currency": currency,
|
||||
"timestamp": datetime.now().isoformat(),
|
||||
"source": "Yahoo Finance",
|
||||
}
|
||||
except Exception as e:
|
||||
print(
|
||||
f"Yahoo Finance query failed for {standardized_code}: {e}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return None
|
||||
|
||||
def _query_eastmoney(self, standardized_code: str) -> Optional[Dict]:
|
||||
"""查询东方财富数据(简化版)"""
|
||||
# 这里可以实现东方财富的API调用
|
||||
# 暂时返回None,主要依赖Yahoo Finance
|
||||
return None
|
||||
|
||||
def _query_xueqiu(self, standardized_code: str) -> Optional[Dict]:
|
||||
"""查询雪球数据(简化版)"""
|
||||
# 这里可以实现雪球的API调用
|
||||
# 暂时返回None,主要依赖Yahoo Finance
|
||||
return None
|
||||
|
||||
def get_price(self, stock_code: str) -> Dict:
|
||||
"""获取股票价格"""
|
||||
standardized_code = self.standardize_code(stock_code)
|
||||
results = []
|
||||
|
||||
# 尝试多个数据源
|
||||
for source_name, query_func in self.data_sources.items():
|
||||
try:
|
||||
result = query_func(standardized_code)
|
||||
if result:
|
||||
result["code"] = stock_code
|
||||
result["standardized_code"] = standardized_code
|
||||
results.append(result)
|
||||
|
||||
# 如果Yahoo Finance成功,通常就足够了
|
||||
if source_name == "yahoo_finance":
|
||||
break
|
||||
|
||||
except Exception as e:
|
||||
print(f"Query {source_name} failed: {e}", file=sys.stderr)
|
||||
continue
|
||||
|
||||
if not results:
|
||||
return {
|
||||
"code": stock_code,
|
||||
"standardized_code": standardized_code,
|
||||
"error": "无法获取准确价格数据",
|
||||
"timestamp": datetime.now().isoformat(),
|
||||
}
|
||||
|
||||
# 返回第一个成功的结果
|
||||
return results[0]
|
||||
|
||||
def get_prices(self, stock_codes: List[str]) -> List[Dict]:
|
||||
"""批量获取股票价格"""
|
||||
results = []
|
||||
for code in stock_codes:
|
||||
result = self.get_price(code)
|
||||
results.append(result)
|
||||
# 避免请求过于频繁
|
||||
time.sleep(0.1)
|
||||
return results
|
||||
|
||||
|
||||
def main():
|
||||
"""主函数"""
|
||||
if len(sys.argv) < 2:
|
||||
print("用法:")
|
||||
print(" python stock_price_query.py <stock_code>")
|
||||
print(" python stock_price_query.py <stock_code1> <stock_code2> ...")
|
||||
print("")
|
||||
print("示例:")
|
||||
print(" python stock_price_query.py 00700.HK")
|
||||
print(" python stock_price_query.py 00700.HK 09868.HK 001309.SZ")
|
||||
sys.exit(1)
|
||||
|
||||
stock_codes = sys.argv[1:]
|
||||
|
||||
if len(stock_codes) == 1:
|
||||
query = StockPriceQuery()
|
||||
result = query.get_price(stock_codes[0])
|
||||
print(json.dumps(result, indent=2, ensure_ascii=False))
|
||||
else:
|
||||
query = StockPriceQuery()
|
||||
results = query.get_prices(stock_codes)
|
||||
print(json.dumps(results, indent=2, ensure_ascii=False))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user