04db423416
- 70 skills with code and documentation - Add .gitignore (ignore __pycache__, output/, temp/, venv/) - Clean up test intermediates and caches
79 lines
2.2 KiB
Python
79 lines
2.2 KiB
Python
#!/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()
|