Interactive Brokers python API - convert ReportsFinSummary to pandas

313 views Asked by At

I'm trying to do something that I thought was simple.... clearly not. I'd like to extract some data from the ReportFinSummary using the python ib api. I'd like to be able to use the DPS figures. I'm trying to sort the xml code with beautiful soup without any joy. Any help would be greatly appreciated. Allan

from ib.opt import ibConnection, message
from ib.ext.Contract import Contract
from time import sleep
from bs4 import BeautifulSoup
import pandas as pd

def fundamentalData_handler(msg):
    print(msg)

def error_handler(msg):
    print(msg)

tws = ibConnection(port=7497, clientId=123)
tws.register(error_handler, message.Error)
tws.register(fundamentalData_handler, message.fundamentalData)
tws.connect()

c = Contract()
c.m_symbol = 'RDSA'
c.m_secType = 'STK'
c.m_exchange = "SMART"
c.m_currency = "GBP"

tws.reqFundamentalData(1,c,'ReportsFinSummary')

soup = BeautifulSoup(tws.reqFundamentalData(1,c,'ReportsFinSummary'),'xml')
DPS_Data = soup.find_all('DividendPerShares')
DPS = []
for dates in DPS_Data:
    DPS.append(DPS_Data.get_text())

print(pd.DataFrame({'DPS_Data': DPS}))

sleep(2)

tws.disconnect()
1

There are 1 answers

1
misantroop On

This is untested but should get you on the right track. You're using IbPy which is out of development for years, it's best to use the native API or IbPythonic.

from ib.opt import ibConnection, message
from ib.ext.Contract import Contract
from time import sleep
from bs4 import BeautifulSoup
import pandas as pd

class IB():
    def __init__(self):
        pass

    def fundamentalData_handler(self, msg):
        self.data = msg

    def error_handler(self, msg):
        print(msg)

    def connect(self, port=7497, clientId=123):
        self.tws = ibConnection(port, clientId)
        self.tws.register(self.error_handler, message.Error)
        self.tws.register(self.fundamentalData_handler, message.fundamentalData)
        self.tws.connect()

    def disconnect(self):
        self.tws.disconnect()

    def get(self):
        c = Contract()
        c.m_symbol = 'RDSA'
        c.m_secType = 'STK'
        c.m_exchange = "SMART"
        c.m_currency = "GBP"

        self.tws.reqFundamentalData(1, c, 'ReportsFinSummary')
        while not hasattr(self, 'data'):
            sleep(0.1)

        soup = BeautifulSoup(self.data)
        DPS_Data = soup.find_all('DividendPerShares')
        DPS = [DPS_Data.get_text() for dates in DPS_Data]

        return pd.DataFrame({'DPS_Data': DPS})

ib = IB()
ib.connect()
df = ib.get()
ib.disconnect()
print(df)