You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas列转字符串调用Tiingo API出现格式错误如何解决?

报错原因

你调用接口报错的核心问题是使用Series.to_string(index=False)处理DataFrame整列数据,这个方法会把整列的所有值拼接成一个带换行符的多行字符串,而不是你需要的单条记录对应的值。比如最终请求里的symbol参数会变成AABA\nAAL\nAAPL\nABGX,日期参数同理是多个日期拼接的带换行的字符串,完全不符合Tiingo接口的参数格式要求。

修复步骤
  1. 删除错误的整列转字符串代码,也就是以下几行:
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)
  1. 新增逐行遍历逻辑,你有4条股票记录,需要循环处理每行的对应字段发起请求,用iterrows遍历可以直接按列名取值,不需要额外处理特殊列名。
  2. 额外优化: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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 14:30:04