在 Python 中从交易平台 API 将合约详情导出到 df 或 csv?

Export contractDetails to df or csv from TWS API in Python?

这个问题实际上已经在另一个论坛上提出并回答了,但是,答案是通过网络给出的 link 并且看起来 link 确实已经过期了。因此,我不得不再次向你们这些可爱的聪明人提出这个问题。

有谁知道如何将数据从“contractDetails”导出到 df 或 CSV 文件?这是到目前为止的代码:

class TestApp(EWrapper, EClient):
    def __init__(self):
        EWrapper.__init__(self)
        EClient.__init__(self, self)​

    def contractDetails(self, reqId, contractDetails):
        self.data = [contractDetails]
        df = pd.DataFrame(self.data)
        df.to_csv('options_test.csv')
        print(df)​

    def contractDetailsEnd(self, reqId):
        print("\ncontractDetails End\n")​

    def start(self):
        contract = Contract()
        contract.symbol = 'AAPL'
        contract.secType = 'OPT'
        contract.exchange = 'SMART'
        contract.currency = 'USD'
        #contract.primaryExchange = 'NASDAQ'
        contract.lastTradeDateOrContractMonth = '202301'
        #contract.strike = 175
        #contract.right = "C"
        #contract.multiplier = "100"
        global underlying
        underlying = contract.symbol​

        self.reqMktData(1, contract, '106', False, False, [])​

        self.reqContractDetails(1, contract)​

    def stop(self):
        self.done = True
        self.disconnect()​

    def main():
        app = TestApp()
        app.nextOrderId = 0
        app.connect('127.0.0.1', 7497, 123)
        app.data = []​

        Timer(4, app.stop).start()
        app.run()​

if __name__ == "__main__":
    main()​

这是原问题的link:https://www.elitetrader.com/et/thre...details-to-csv-from-tws-api-in-python.344314/

这是原始答案的 link:https://repl.it/repls/DamagedStandardDeprecatedsoftware

谁能想出来,放心,晚饭我请客(Y)

这是我的问题的答案...

from ib_insync import *
util.startLoop()

import logging
# util.logToConsole(logging.DEBUG)

ib = IB()
ib.connect('127.0.0.1', 7497, clientId=1)


spy = Option('SPY', '202301', '', 'C', 'SMART')

cds = ib.reqContractDetails(spy)

len(cds)

contracts = [cd.contract for cd in cds]

contracts[0]

util.df(contracts)

print(util.df(contracts))

https://nbviewer.org/github/erdewit/ib_insync/blob/master/notebooks/contract_details.ipynb

放轻松(Y)