Pandas列转字符串调用Tiingo API出现格式错误如何解决?
报错原因
你调用接口报错的核心问题是使用Series.to_string(index=False)处理DataFrame整列数据,这个方法会把整列的所有值拼接成一个带换行符的多行字符串,而不是你需要的单条记录对应的值。比如最终请求里的symbol参数会变成AABA\nAAL\nAAPL\nABGX,日期参数同理是多个日期拼接的带换行的字符串,完全不符合Tiingo接口的参数格式要求。
修复步骤
- 删除错误的整列转字符串代码,也就是以下几行:
symbol=df["Ticker No -"].to_string(index=False) symbolfile=df["Nome File"].to_string(index=False) start_date=df["Data Inizio"].to_string(index=False) end_date=df["Data Fine"].to_string(index=False)
- 新增逐行遍历逻辑,你有4条股票记录,需要循环处理每行的对应字段发起请求,用
iterrows遍历可以直接按列名取值,不需要额外处理特殊列名。 - 额外优化:Tiingo接口返回的是JSON格式数据,不需要用BeautifulSoup解析,直接调用
response.json()即可拿到结构化数据;请求拼接用f-string可读性更强,也不容易出现拼接错误。
修复后完整代码
import requests import time import json import os import pandas as pd from win32com.client import Dispatch df = pd.read_csv('NQ TICKER BIAS 1.csv', delimiter=";") # 提前转换日期格式 df["Data Inizio"] = pd.to_datetime(df["Data Inizio"]).dt.strftime('%Y-%m-%d') df["Data Fine"] = pd.to_datetime(df["Data Fine"]).dt.strftime('%Y-%m-%d') # 替换为你自己的Tiingo密钥 headers = { 'Content-Type': 'application/json', 'Authorization': 'Token 你的Tiingo API密钥' } # 逐行遍历处理每条股票记录 for idx, row in df.iterrows(): symbol = row["Ticker No -"] symbolfile = row["Nome File"] start_date = row["Data Inizio"] end_date = row["Data Fine"] try: # 用f-string拼接请求链接 url = f"https://api.tiingo.com/tiingo/daily/{symbol}/prices?startDate={start_date}&endDate={end_date}" response = requests.get(url, headers=headers) # 接口返回4xx/5xx错误时主动抛出异常方便捕获 response.raise_for_status() # 直接解析JSON数据 data = response.json() # 这里可以加保存数据到文件的逻辑,示例如下: # with open(f"{symbolfile}.json", "w", encoding="utf-8") as f: # json.dump(data, f, indent=2) print(f"finished writing {symbol} txt file.") # 避免请求频率过高被接口限制 time.sleep(1) except Exception as e: print(f"error downloading {symbol}: {str(e)}")
内容的提问来源于stack exchange,提问作者Davide Serafini
相关产品推荐
相关产品推荐

