【问题标题】:Converting TD Ameritrade's JSON API output into Pandas dataframe将 TD Ameritrade 的 JSON API 输出转换为 Pandas 数据帧
【发布时间】:2020-12-22 03:45:52
【问题描述】:

这里是 Python 初学者。最近连接到我的 TD Ameritrade 的 API 并试图提取我账户的头寸信息以进行进一步分析。但是,我在将 API 的 JSON 输出转换为 Pandas 数据帧时遇到问题,非常感谢任何指导。

代码如下:

import pprint
import pandas as pd
from config import consumer_key, redirect_uri, credentials_path
from td.client import TDClient

# Create a new instance of the client
td_client = TDClient(client_id = consumer_key, redirect_uri = redirect_uri, credentials_path = credentials_path)

# Login to a new session
td_client.login()

# Positions and Orders for an account or account(s)
positions = td_client.get_accounts(account = 'all', fields = ['positions'])
pprint.pprint(positions)

这是输出的sn-p:

{'securitiesAccount': {'accountId': 'xxxx',
                       'currentBalances': {'accruedInterest': 0.0,
                                           'bondValue': 0.0,
                                           'cashAvailableForTrading': xxx,
                                           'cashAvailableForWithdrawal': xxx,
                                           'cashBalance': 0.0,
                                           'cashCall': 0.0,
                                           'cashDebitCallValue': 0.0,
                                           'cashReceipts': 0.0,
                                           'liquidationValue': xxx,
                                           'longMarketValue': xxx,
                                           'longNonMarginableMarketValue': xxx,
                                           'longOptionMarketValue': 0.0,
                                           'moneyMarketFund': xxx,
                                           'mutualFundValue': 0.0,
                                           'pendingDeposits': 0.0,
                                           'savings': 0.0,
                                           'shortMarketValue': 0.0,
                                           'shortOptionMarketValue': 0.0,
                                           'totalCash': 0.0,
                                           'unsettledCash': 0.0},
                       'initialBalances': {'accountValue': xxx,
                                           'accruedInterest': 0.0,
                                           'bondValue': 0.0,
                                           'cashAvailableForTrading': xxx,
                                           'cashAvailableForWithdrawal': xxx,
                                           'cashBalance': 0.0,
                                           'cashDebitCallValue': 0.0,
                                           'cashReceipts': 0.0,
                                           'isInCall': False,
                                           'liquidationValue': xxx,
                                           'longOptionMarketValue': 0.0,
                                           'longStockValue': xxx,
                                           'moneyMarketFund': xxx,
                                           'mutualFundValue': 0.0,
                                           'pendingDeposits': 0.0,
                                           'shortOptionMarketValue': 0.0,
                                           'shortStockValue': 0.0,
                                           'unsettledCash': 0.0},
                       'isClosingOnlyRestricted': False,
                       'isDayTrader': False,
                       'positions': [
                                     {'averagePrice': 46.14,
                                      'currentDayProfitLoss': -8.4,
                                      'currentDayProfitLossPercentage': -1.92,
                                      'instrument': {'assetType': 'EQUITY',
                                                     'cusip': '02209S103',
                                                     'symbol': 'MO'},
                                      'longQuantity': 10.0,
                                      'maintenanceRequirement': 0.0,
                                      'marketValue': 429.4,
                                      'settledLongQuantity': 10.0,
                                      'settledShortQuantity': 0.0,
                                      'shortQuantity': 0.0},
                                     {'averagePrice': 152.14,
                                      'currentDayProfitLoss': -1.52,
                                      'currentDayProfitLossPercentage': -0.43,
                                      'instrument': {'assetType': 'EQUITY',
                                                     'cusip': '88579Y101',
                                                     'symbol': 'MMM'},
                                      'longQuantity': 2.0,
                                      'maintenanceRequirement': 0.0,
                                      'marketValue': 351.32,
                                      'settledLongQuantity': 2.0,
                                      'settledShortQuantity': 0.0,
                                      'shortQuantity': 0.0},
                                ],
                       'projectedBalances': {'cashAvailableForTrading': xxx,
                                             'cashAvailableForWithdrawal': xxx},
                       'roundTrips': 0,
                       'type': 'CASH'}}

如何将其转换为仅包含职位信息的数据框? (例如,将我拥有的每只股票作为单独一行的数据框)。

我已经尝试了以下代码,但它没有返回所需的结果:

df = pd.json_normalize(positions)
print(positions)

感谢您的宝贵时间!

【问题讨论】:

    标签: json dataframe type-conversion


    【解决方案1】:

    将您的响应称为“位置”然后查找该键可能会让人感到困惑,但您仍然需要使用位置键的完整路径。

    pd.json_normalize(positions['securitiesAccount']['positions'])
    

    输出

       averagePrice  currentDayProfitLoss  currentDayProfitLossPercentage  longQuantity  maintenanceRequirement  marketValue  settledLongQuantity  settledShortQuantity  shortQuantity instrument.assetType instrument.cusip instrument.symbol
    0        46.140                -8.400                          -1.920        10.000                   0.000      429.400               10.000                 0.000          0.000               EQUITY        02209S103                MO
    1       152.140                -1.520                          -0.430         2.000                   0.000      351.320                2.000                 0.000          0.000               EQUITY        88579Y101               MMM
    

    【讨论】:

      【解决方案2】:

      您始终可以通过创建 new_dict 来隔离您的数据。

      new_dict = (字典['securitiesAccount']['positions'])

      【讨论】:

        猜你喜欢
        • 2020-12-31
        • 2018-10-27
        • 2018-06-15
        • 1970-01-01
        • 2023-03-31
        • 2023-03-31
        • 2020-10-28
        • 2017-02-04
        • 1970-01-01
        相关资源
        最近更新 更多