使用Alpha Vantage API获取GLD与XAU数据时XAU请求失败问题
解决Alpha Vantage获取XAU数据失败的问题
核心问题分析
- 货币对参数方向错误:你当前请求的是USD兑换XAU的汇率,但Alpha Vantage的
CURRENCY_EXCHANGE_RATE接口中,XAU作为黄金标的,标准查询应为XAU/USD(1盎司黄金对应的美元价格),参数需设为from_currency=XAU&to_currency=USD,而非反向。 - 错误信息缺失:代码仅打印通用错误,无法定位具体问题(比如参数错误、API限流、密钥无效等)。
- GLD查询未做错误处理:若API返回异常(如超限),会直接抛出KeyError导致程序崩溃。
修复后的代码
import time import requests API_KEY = "你的有效API密钥" SYMBOLS = ["XAU", "GLD"] def get_price(symbol): if symbol == "XAU": # 修正货币对方向,查询XAU/USD汇率 url = f"https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_currency=XAU&to_currency=USD&apikey={API_KEY}" response = requests.get(url) data = response.json() # 打印完整返回数据,方便排查问题 print(f"XAU API返回数据: {data}") if "Realtime Currency Exchange Rate" in data: return data["Realtime Currency Exchange Rate"]["5. Exchange Rate"] else: # 提取具体错误信息 error_msg = data.get("Error Message", data.get("Note", "未知错误")) print(f"获取XAU数据失败: {error_msg}") return None elif symbol == "GLD": url = f"https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=GLD&apikey={API_KEY}" response = requests.get(url) data = response.json() print(f"GLD API返回数据: {data}") if "Global Quote" in data and data["Global Quote"]["05. price"]: return data["Global Quote"]["05. price"] else: error_msg = data.get("Error Message", data.get("Note", "未知错误")) print(f"获取GLD数据失败: {error_msg}") return None else: return None def write_to_file(filename, content): with open(filename, "a") as f: f.write(content) while True: current_time = time.strftime("%Y-%m-%d %H:%M:%S") for symbol in SYMBOLS: price = get_price(symbol) if price is not None: data = f"{current_time} - {symbol} Price: {price}\n" write_to_file("prices.txt", data) else: print(f"{current_time} - 获取{symbol}价格失败") time.sleep(600)
额外注意事项
- API调用限制:免费版Alpha Vantage限制5次/分钟、500次/天,10分钟一次调用在限额内,但测试时不要频繁触发请求。
- 数据一致性:XAU返回的是每盎司黄金的美元价格,GLD是黄金ETF的价格,计算价差时需注意单位(GLD每份约对应0.1盎司黄金)。
内容的提问来源于stack exchange,提问作者Thomas Xx
相关产品推荐
相关产品推荐

