我正在运行一个Python脚本,以从InteractiveBrokersAPI收集金融市场数据。连接到API后,终端打印出请求的历史数据。如何将数据保存到数据帧中,而不是流式传输到终端中
from ibapi.wrapper import EWrapper
from ibapi.client import EClient
from ibapi.contract import Contract
from ibapi.ticktype import TickTypeEnum
class TestApp(EWrapper, EClient):
def __init__(self):
EClient.__init__(self,self)
def error(self, reqId, errorCode, errorString):
print("Error: ", reqId, " ", errorCode, " ", errorString)
def historicalData(self, reqId, bar):
print("historicalData. ", reqId, "Data:", bar.date, "Open:", bar.open, "High:", bar.high, "low:", bar.low, "close:", bar.close, "Volume:", bar.volume, "WAP:", bar.average)
def main():
app = TestApp()
app.connect("127.0.0.1", 7497, 0)
contract = Contract()
contract.symbol = "EUR"
contract.secType = "CASH"
contract.exchange = "IDEALPRO"
contract.currency = "USD"
app.reqHistoricalData(1, contract, "", "1 D", "1 min", "MIDPOINT", 0, 1, False, [])
app.run()
if __name__ == "__main__":
main()
代码的输出打印历史数据的提要,例如:
historicalData. 1 Data: 20200616 11:53:00 Open: 1.125985 High: 1.12601 low: 1.12592 close: 1.12592 Volume: -1 WAP: -1.0
historicalData. 1 Data: 20200616 11:54:00 Open: 1.12592 High: 1.125925 low: 1.12583 close: 1.125885 Volume: -1 WAP: -1.0
historicalData. 1 Data: 20200616 11:55:00 Open: 1.125885 High: 1.126045 low: 1.125865 close: 1.126045 Volume: -1 WAP: -1.0
如何将这些信息存储到数据框中,而不是仅打印在终端中
您可以在TestApp对象中创建一个dataframe,然后在每次调用historicalData()时向其添加一行
您也可以使用DataFrame.append()函数
返回所有历史数据后,将整个数据帧写入数据库,然后清除原始数据帧以供下一个周期重用
相关问题 更多 >
编程相关推荐