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

Python提取JSON中加密货币收盘价遇TypeError问题求助

问题排查:提取加密货币收盘价触发TypeError错误

问题背景

开发Python加密货币交易机器人时,从API获取JSON格式的价格数据,需要提取各币种的close价格用于协整分析,但调用extract_close_prices函数时触发TypeError: string indices must be integers, not 'str'错误。

JSON数据示例

{
 "10000NFTUSDT": {
 "ret_code": 0,
 "ret_msg": "OK",
 "ext_code": "",
 "ext_info": "",
 "result": [
 {
 "symbol": "10000NFTUSDT",
 "period": "60",
 "start_at": 1671559200,
 "open": 0.004533,
 "high": 0.004538,
 "low": 0.004523,
 "close": 0.004535
 },
 ...
 ]
}

代码片段

主程序代码

import json
from func_cointegration import get_cointegrated_pairs

#STEP 3 Find Cointegrated pairs
print("Calculating co-integration...")
with open("1_price_list.json") as json_file:
    price_data = json.load(json_file)
if len(price_data) > 0:
    coint_pairs = get_cointegrated_pairs(price_data)

extract_close_prices函数

import math
#Put close prices into a list
def extract_close_prices(prices):
    close_prices = []
    for price_values in prices:
        print(type(price_values))
        if math.isnan(price_values["close"]):
            return []
        close_prices.append(price_values["close"])
    print(close_prices)
    return close_prices

get_cointegrated_pairs函数片段

#Calculate cointegrated pairs
def get_cointegrated_pairs(prices):
    coint_pair_list = []
    included_list = []
    for sym_1 in prices.keys():
        for sym_2 in prices.keys():
            if sym_2 != sym_1:
                sorted_characters = sorted(sym_1 + sym_2)
                unique = "".join(sorted_characters)
                if unique in included_list:
                    break
                series_1 = extract_close_prices(prices[sym_1])
                series_2 = extract_close_prices(prices[sym_2])

报错栈

Traceback (most recent call last):
  File "/Users/xxxxxxxx/PycharmProjects/StatArbBot/Strategy/main.py", line 27, in <module>
    coint_pairs = get_cointegrated_pairs(price_data)
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/xxxxx/PycharmProjects/StatArbBot/Strategy/func_cointegration.py", line 35, in get_cointegrated_pairs
    series_1 = extract_close_prices(prices[sym_1])
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/xxxxx/PycharmProjects/StatArbBot/Strategy/func_cointegration.py", line 12, in extract_close_prices
    if math.isnan(price_values["close"]):
                  ~~~~~~~~~~~~^^^^^^^^^
TypeError: string indices must be integers, not 'str'

问题原因分析

  • 从JSON结构可知,prices[sym_1]是一个字典(包含ret_code、ret_msg、result等键),而非直接的K线数据列表。
  • extract_close_prices函数中直接遍历传入的prices参数,遍历字典默认是遍历其键名(字符串类型,比如"ret_code"、"result")。
  • 尝试对字符串类型的price_values使用price_values["close"]索引,自然触发TypeError,因为字符串只能用整数索引。

解决方法

有两种可行的修改方式:

方式一:修改函数调用传入正确的列表

在get_cointegrated_pairs函数中,传入各币种下的result列表(即实际的K线数据数组):

# 修改get_cointegrated_pairs中的调用代码
series_1 = extract_close_prices(prices[sym_1]["result"])
series_2 = extract_close_prices(prices[sym_2]["result"])

方式二:修改extract_close_prices函数适配输入

调整函数逻辑,先从传入的币种字典中提取result列表再处理:

import math

def extract_close_prices(price_dict):
    close_prices = []
    # 从字典中获取K线数据列表,默认空列表避免KeyError
    price_list = price_dict.get("result", [])
    for price_values in price_list:
        # 先检查是否存在close字段,避免KeyError
        if "close" not in price_values:
            continue
        close_price = price_values["close"]
        if math.isnan(close_price):
            return []
        close_prices.append(close_price)
    return close_prices

两种方式都能解决问题,可根据代码架构选择更合适的方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 22:25:20