64 lines
1.8 KiB
Python
64 lines
1.8 KiB
Python
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
"""
|
|
测试Yahoo Finance API
|
|
"""
|
|
|
|
import requests
|
|
import json
|
|
|
|
def test_yahoo_api():
|
|
"""测试Yahoo Finance API"""
|
|
|
|
print("=" * 60)
|
|
print("测试Yahoo Finance API")
|
|
print("=" * 60)
|
|
|
|
# 测试MSFT
|
|
symbol = "MSFT"
|
|
url = f"https://query1.finance.yahoo.com/v8/finance/chart/{symbol}"
|
|
|
|
params = {
|
|
"interval": "1d",
|
|
"range": "1d"
|
|
}
|
|
|
|
headers = {
|
|
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
|
|
}
|
|
|
|
print(f"\n请求URL: {url}")
|
|
print(f"参数: {params}")
|
|
print()
|
|
|
|
try:
|
|
response = requests.get(url, params=params, headers=headers, timeout=10)
|
|
|
|
print(f"状态码: {response.status_code}")
|
|
print(f"响应头: {dict(response.headers)}")
|
|
print()
|
|
|
|
if response.status_code == 200:
|
|
data = response.json()
|
|
print("响应数据:")
|
|
print(json.dumps(data, indent=2, ensure_ascii=False))
|
|
|
|
# 解析数据
|
|
if "chart" in data and "result" in data["chart"]:
|
|
result = data["chart"]["result"]
|
|
if result and len(result) > 0:
|
|
meta = result[0].get("meta", {})
|
|
print("\n解析结果:")
|
|
print(f"股票代码: {meta.get('symbol')}")
|
|
print(f"当前价格: {meta.get('regularMarketPrice')}")
|
|
print(f"前收盘价: {meta.get('previousClose')}")
|
|
print(f"货币: {meta.get('currency')}")
|
|
else:
|
|
print(f"响应内容: {response.text}")
|
|
|
|
except Exception as e:
|
|
print(f"错误: {e}")
|
|
|
|
if __name__ == "__main__":
|
|
test_yahoo_api()
|