如何用Python对接金价实时行情API?

对接实时金价 API 可以通过以下步骤完成,主要包括获取 API 地址、发送 HTTP 请求、解析返回数据等操作。以下是一个完整的实现示例。 ### 获取 API 接口地址 通常,实时金价 API 可以从提供贵金属数据的服务商获取,例如 `goldapi.io`、`alphavantage.co` 或 `metals-api.com`。这些服务通常提供 RESTful API 接口,并支持 JSON 或 XML 格式的数据返回。 以 `goldapi.io` 为例,其基础 API 地址为: ``` https://www.goldapi.io/api/XAU/USD ``` 请求时需要在 Header 中添加 `x-access-token` 字段作为身份验证。 ### 发送 HTTP 请求并处理数据 在 Python 中,可以使用 `requests` 库来发送 HTTP 请求,并解析返回的 JSON 数据。 以下是一个完整的 Python 示例代码: ```python import requests def get_gold_price(): url = "https://www.goldapi.io/api/XAU/USD" headers = { "x-access-token": "YOUR_API_KEY" } response = requests.get(url, headers=headers) if response.status_code == 200: data = response.json() price = data.get("price") unit = data.get("unit") print(f"Current gold price: {price} {unit}") else: print(f"Failed to retrieve data. Status code: {response.status_code}") # 调用函数获取金价 get_gold_price() ``` 请将 `YOUR_API_KEY` 替换为你从 API 提供商处获取的实际密钥。 ### 解析返回数据 API 返回的 JSON 数据可能包含以下字段: - `price`: 当前黄金价格(以美元/盎司为单位) - `unit`: 价格单位(如 USD/oz) - `timestamp`: 数据更新时间戳 例如: ```json { "price": 2345.67, "unit": "USD/oz", "timestamp": "2024-06-15T12:00:00Z" } ``` ### 错误处理与重试机制 为了增强程序的健壮性,可以在代码中加入异常处理和重试逻辑: ```python import time def get_gold_price_with_retry(retries=3, delay=5): url = "https://www.goldapi.io/api/XAU/USD" headers = { "x-access-token": "YOUR_API_KEY" } for i in range(retries): try: response = requests.get(url, headers=headers, timeout=10) if response.status_code == 200: data = response.json() price = data.get("price") unit = data.get("unit") print(f"Current gold price: {price} {unit}") return else: print(f"Attempt {i+1} failed with status code {response.status_code}. Retrying in {delay} seconds...") time.sleep(delay) except requests.exceptions.RequestException as e: print(f"Network error: {e}. Retrying in {delay} seconds...") time.sleep(delay) print("Failed to retrieve gold price after multiple attempts.") # 调用带重试机制的函数 get_gold_price_with_retry() ``` 以上代码通过设置 `retries` 和 `delay` 参数,实现自动重试功能,确保在网络不稳定时仍能获取数据。 ---

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考