Python API代码报错:AttributeError: 'str'对象无read属性
代码问题分析与修正
核心错误梳理
- 语法与API密钥逻辑错误:给
key赋值时,错误使用类型注解符号:而非赋值符号=,还对字符串直接调用.read()方法——字符串本身没有read()属性,这是触发报错的直接原因。另外你混淆了两个不同的API服务:导入的是Alpha Vantage的TimeSeries模块,但却传入了Polygon的API请求URL,Alpha Vantage只需要它自身的API密钥,不需要完整请求地址。 - API调用参数缺失:
ts.get_intraday()的第一个参数是必填的股票代码,你传入空字符串,会导致无法正常获取数据。 - 索引访问风险:
data.loc['2020-12-31']如果获取的日内数据不包含该日期,会触发索引不存在的错误。
修正后的代码示例
import pandas as pd import matplotlib.pyplot as plt from alpha_vantage.timeseries import TimeSeries # 替换为你的Alpha Vantage API密钥 key = "你的AlphaVantage_API密钥" # 初始化TimeSeries客户端 ts = TimeSeries(key, output_format='pandas') # 指定股票代码(如AAPL),调用日内数据接口 data, meta = ts.get_intraday('AAPL', interval='1min', outputsize='full') print(meta) data.info() print(data.head()) plt.plot(data['4. close']) plt.show() # 添加show()才能显示图表 # 重命名数据列 columns = ['open', 'high', 'low', 'close', 'volume'] data.columns = columns data['TradeDate'] = data.index.date data['time'] = data.index.time # 先检查目标日期是否存在,再进行索引访问 target_date = '2020-12-31' if target_date in data.index.strftime('%Y-%m-%d'): print(data.loc[target_date]) else: print(f"数据中不存在日期:{target_date}") # 筛选交易时段内的数据 market = data.between_time('09:30:00', '16:00:00').copy() market.sort_index(inplace=True) market.info() # 按交易日聚合计算每日高低点 daily_stats = market.groupby('TradeDate').agg({'low': min, 'high': max}) print(daily_stats)
补充:若使用Polygon API的实现方式
如果原本想调用Polygon的API,需改用requests库直接请求并解析数据,示例如下:
import pandas as pd import requests # 替换为你的Polygon API密钥 url = "https://api.polygon.io/v2/aggs/ticker/AAPL/range/1/day/2023-01-09/2023-01-09?adjusted=true&sort=asc&limit=120&apiKey=你的Polygon_API密钥" response = requests.get(url) data = pd.DataFrame(response.json()['results']) print(data)
内容的提问来源于stack exchange,提问作者Mustafa Yaray
相关产品推荐
相关产品推荐

