如何用SQL Server将TD Ameritrade期权链JSON转为扁平表格式
处理TD Ameritrade期权链动态键提取与格式转换
针对TD Ameritrade期权链JSON中到期日、行权价为动态键的问题,直接通过遍历动态键的方式提取所需字段,再格式化输出目标表格。以下是具体实现(以Python为例):
核心思路
TD期权链JSON的结构逻辑固定:
- 标的基础信息在
underlying字段下,直接提取symbol和lastPrice - 看涨/看跌期权分别存于
callExpDateMap和putExpDateMap,这两个对象的键是到期日字符串,每个到期日下的键是行权价字符串,对应的值包含bid、ask等期权数据
代码实现
import json # 假设已获取TD期权链的JSON数据,这里用示例数据模拟 option_chain_json = """ { "underlying": { "symbol": "AMZN", "lastPrice": 90.965 }, "callExpDateMap": { "2023-03-17:6": { "90.0": [{"bid": 1.25, "ask": 1.30}] } }, "putExpDateMap": { "2023-03-17:6": { "90.0": [{"bid": 1.83, "ask": 1.88}], "91.0": [{"bid": 2.27, "ask": 2.36}] } } } """ # 解析JSON data = json.loads(option_chain_json) # 提取标的基础信息 symbol = data["underlying"]["symbol"] underlying_price = data["underlying"]["lastPrice"] # 定义表头和分隔线 header = f"{'symbol':<8} {'underlyingprice':<16} {'putCall':<8} {'expdate':<16} {'strike':<8} {'bid':<6} {'ask':<6}" separator = "-" * len(header) # 输出表头和分隔线 print(header) print(separator) # 处理看涨期权 for exp_date, strikes in data["callExpDateMap"].items(): for strike_str, options in strikes.items(): strike = float(strike_str) for opt in options: print(f"{symbol:<8} {underlying_price:<16.3f} {'CALL':<8} {exp_date:<16} {strike:<8.1f} {opt['bid']:<6.2f} {opt['ask']:<6.2f}") # 处理看跌期权 for exp_date, strikes in data["putExpDateMap"].items(): for strike_str, options in strikes.items(): strike = float(strike_str) for opt in options: print(f"{symbol:<8} {underlying_price:<16.3f} {'PUT':<8} {exp_date:<16} {strike:<8.1f} {opt['bid']:<6.2f} {opt['ask']:<6.2f}")
输出效果
执行后会直接输出符合要求的格式化表格:
symbol underlyingprice putCall expdate strike bid ask ----------------------------------------------------------------------------- AMZN 90.965 CALL 2023-03-17:6 90.0 1.25 1.30 AMZN 90.965 PUT 2023-03-17:6 90.0 1.83 1.88 AMZN 90.965 PUT 2023-03-17:6 91.0 2.27 2.36
注意事项
- 如果是从TD API获取数据,只需将
option_chain_json替换为API返回的响应内容即可 - 部分期权可能包含多个合约(比如不同到期周期),代码中通过遍历
options列表处理所有合约 - 可根据需求调整字符串格式化的宽度,保证表格对齐美观
内容的提问来源于stack exchange,提问作者Calvin
相关产品推荐
相关产品推荐

