You need to enable JavaScript to run this app. 如何将BarChart API返回的suds对象1分钟历史数据转为带时间戳索引的Pandas DataFrame
优惠活动
大模型
产品
解决方案
定价
更多

如何将BarChart API返回的suds对象1分钟历史数据转为带时间戳索引的Pandas DataFrame

suds历史响应对象转Pandas DataFrame实现方案

全程无需手动逐字段拼接,借助suds自带工具和Pandas原生能力即可快速完成转换,时间索引可自动适配返回的带时区时间格式。

依赖导入

import pandas as pd
from suds.sudsobject import asdict

核心转换代码

假设你调用BarChart API拿到的返回对象为history_resp(即示例中的getHistoryArray实例),直接执行:

# 将所有K线条目从suds对象转为普通字典列表
bar_data = [asdict(bar) for bar in history_resp.getHistoryItem]
# 生成DataFrame,将timestamp提取为时间类型索引
df = pd.DataFrame(bar_data)
df.index = pd.to_datetime(df.pop("timestamp"))

转换结果说明

  • 自动保留返回结构内的所有字段:symbol、tradingDay、open、high、low、close、volume,无需手动指定列名
  • 索引会自动识别返回的带时区时间戳(比如示例里的2020-12-03 23:57:00-06:00),无需额外处理时区转换
  • 不需要的字段可直接通过df.drop(columns=["列名"])删除,比如不需要symbol列时执行df.drop(columns=["symbol"])即可

无额外导入的兼容写法

如果不想导入suds的工具函数,也可以直接遍历属性构造数据列表,效果完全一致:

bar_data = []
for bar in history_resp.getHistoryItem:
    bar_data.append({
        "symbol": bar.symbol,
        "timestamp": bar.timestamp,
        "tradingDay": bar.tradingDay,
        "open": bar.open,
        "high": bar.high,
        "low": bar.low,
        "close": bar.close,
        "volume": bar.volume
    })
df = pd.DataFrame(bar_data)
df.index = pd.to_datetime(df.pop("timestamp"))

内容的提问来源于stack exchange,提问作者sslack88

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.14 10:54:03