解析交互式代理flex xml报告并转换为python类型
ibflex的Python项目详细描述
ibflex是一个python库,用于在 交互式代理的flex xml格式转换成标准python数据结构, 因此可以使用python脚本方便地对其进行处理和分析。
n.b.此模块与编程交易无关。 这是关于阅读经纪公司的报告。
ibflex与python 3.7+版本兼容。分析器没有 python标准库之外的依赖项(尽管可选的客户端 从交互代理的服务器获取flex语句依赖于 在requests上)。
这个模块是alpha软件!它有效而且很有用,但是 api、数据结构等可能会出现重大变化。几种xml schemata丢失了,还有一些新引入的属性 对于现有的图式。可能有虫子。
打破0.13版的变化
如果不想重写代码,请不要升级到0.13版。
版本0.13是一个几乎完全重写,具有不同的数据结构。 不返回嵌套字典,ibflex.parser.parse()现在 返回对象实例(ibflex.Types.FlexElement的子类)。 因此,值是通过属性“dot access”而不是字典来检索的 关键查找。下面是一个例子。
flex引用中更有趣/有用的枚举值 (例如商业票据、公司行为类型)现在被解析为python枚举。
所有序列都是元组而不是列表。一切都是不变的。
现在已经有了对Python3.7的严格依赖;整个库都建立在 数据类和PEP 484类型提示。
很抱歉中断,但必须将库从 快速破解一个更容易维护的坚实基础。基本的 数据结构(实例属性访问而不是dict键)不应 再换一次。
安装
pip install ibflex
flex解析器
提供的主要工具是ibflex.parser模块,它解析 flex将xml数据格式化为python对象的层次结构 对应于最初的flex语句,数据转换为 进入适当的python类型(datetime.datetime、decimal.decimal等)
用法示例:
In[1]:fromibfleximportparserIn[2]:response=parser.parse("2017-01_ibkr.xml")In[3]:responseOut[3]:FlexQueryResponse(queryName='SCP Everything',type='AF',len(FlexStatements)=1)In[4]:stmt=response.FlexStatements[0]In[5]:stmtOut[5]:FlexStatement(accountId='U770993',fromDate=datetime.date(2017,1,2),toDate=datetime.date(2017,1,31),period=None,whenGenerated=datetime.datetime(2017,5,10,11,41,38),len(CashReport)=3,len(EquitySummaryInBase)=23,len(StmtFunds)=344,len(ChangeInPositionValues)=2,len(OpenPositions)=2140,len(FxPositions)=1,len(Trades)=339,len(CorporateActions)=1,len(CashTransactions)=4,len(InterestAccruals)=1,len(ChangeInDividendAccruals)=5,len(OpenDividendAccruals)=2,len(SecuritiesInfo)=30,len(ConversionRates)=550)In[6]:trade=stmt.Trades[-1]In[7]:tradeOut[7]:Trade(transactionType=<TradeType.EXCHTRADE:'ExchTrade'>,openCloseIndicator=<OpenClose.CLOSE:'C'>,buySell=<BuySell.SELL:'SELL'>,orderType=<OrderType.LIMIT:'LMT'>,assetCategory=<AssetClass.STOCK:'STK'>,accountId='U770993',currency='USD',fxRateToBase=Decimal('1'),symbol='WMIH',description='WMIH CORP',conid='105068604',cusip=None,isin=None,listingExchange=None,multiplier=Decimal('1'),strike=None,expiry=None,putCall=None,tradeID='1742757182',reportDate=datetime.date(2017,1,30),tradeDate=datetime.date(2017,1,30),tradeTime=datetime.time(15,39,36),settleDateTarget=datetime.date(2017,2,2),exchange='BYX',quantity=Decimal('-8'),tradePrice=Decimal('1.4'),tradeMoney=Decimal('-11.2'),taxes=Decimal('0'),ibCommission=Decimal('-0.00680792'),ibCommissionCurrency='USD',netCash=Decimal('11.19319208'),netCashInBase=None,closePrice=Decimal('1.4'),notes=(<Code.PARTIAL:'P'>,),cost=Decimal('-10.853621'),mtmPnl=Decimal('0'),origTradePrice=Decimal('0'),origTradeDate=None,origTradeID=None,origOrderID='0',openDateTime=None,fifoPnlRealized=Decimal('0.339571'),capitalGainsPnl=None,levelOfDetail='EXECUTION',ibOrderID='865480117',orderTime=datetime.datetime(2017,1,30,15,39,36),changeInPrice=Decimal('0'),changeInQuantity=Decimal('0'),proceeds=Decimal('11.2'),fxPnl=Decimal('0'),clearingFirmID=None,transactionID='7248583136',holdingPeriodDateTime=None,ibExecID='0001090f.588f449a.01.01',brokerageOrderID=None,orderReference=None,volatilityOrderLink=None,exchOrderId=None,extExecID='S2367553204796',traderID=None,isAPIOrder=False,acctAlias='SCP 0-0',model=None,securityID=None,securityIDType=None,principalAdjustFactor=None,dateTime=None,underlyingConid=None,underlyingSecurityID=None,underlyingSymbol=None,underlyingListingExchange=None,issuer=None,sedol=None,whenRealized=None,whenReopened=None)In[8]:print(f"{trade.tradeDate} {trade.buySell.name} {abs(trade.quantity)} {trade.symbol} @ {trade.tradePrice} {trade.currency}")2017-01-30SELL8WMIH@1.4USDIn[9]:pos=stmt.OpenPositions[-1]In[10]:posOut[10]:OpenPosition(side=<LongShort.SHORT:'Short'>,assetCategory=<AssetClass.STOCK:'STK'>,accountId='U770993',currency='USD',fxRateToBase=Decimal('1'),reportDate=datetime.date(2017,1,31),symbol='VXX',description='IPATH S&P 500 VIX S/T FU ETN',conid='242500577',securityID=None,cusip=None,isin=None,multiplier=Decimal('1'),position=Decimal('-75'),markPrice=Decimal('19.42'),positionValue=Decimal('-1456.5'),openPrice=Decimal('109.210703693'),costBasisPrice=Decimal('109.210703693'),costBasisMoney=Decimal('-8190.802777'),fifoPnlUnrealized=Decimal('6734.302777'),levelOfDetail='LOT',openDateTime=datetime.datetime(2015,8,24,9,28,9),holdingPeriodDateTime=datetime.datetime(2015,8,24,9,28,9),securityIDType=None,issuer=None,underlyingConid=None,underlyingSymbol=None,code=(),originatingOrderID='699501861',originatingTransactionID='5634129129',accruedInt=None,acctAlias='SCP 0-0',model=None,sedol=None,percentOfNAV=None,strike=None,expiry=None,putCall=None,principalAdjustFactor=None,listingExchange=None,underlyingSecurityID=None,underlyingListingExchange=None,positionValueInBase=None,unrealizedCapitalGainsPnl=None,unrealizedlFxPnl=None)In[11]:print(f"{trade.tradeDate} {trade.buySell.name} {abs(trade.quantity)} {trade.symbol} @ {trade.tradePrice} {trade.currency}")2017-01-30SELL8WMIH@1.4USDIn[12]:[secforsecinstmt.SecuritiesInfoifsec.conid==trade.conid][0]Out[12]:SecurityInfo(assetCategory=<AssetClass.STOCK:'STK'>,symbol='WMIH',description='WMIH CORP',conid='105068604',securityID=None,cusip=None,isin=None,listingExchange=None,underlyingSecurityID=None,underlyingListingExchange=None,underlyingConid=None,underlyingCategory=None,subCategory=None,multiplier=Decimal('1'),strike=None,expiry=None,maturity=None,issueDate=None,type=None,sedol=None,securityIDType=None,underlyingSymbol=None,issuer=None,putCall=None,principalAdjustFactor=Decimal('1'),code=())
flex查询报表配置
通过Interactive Brokers account management配置flex语句。 报表>;flex查询>;自定义flex查询>;配置
您可以随意配置,ibflex应该解析它,但有以下例外:
- You can’t use European-style date formats (dd/MM/yy or dd/MM/yyyy). Just accept the default (yyyyMMdd) or get with the program and use ISO-8601 (yyyy-MM-dd).
- You should use some delimiter between dates & times. The default delimiter (semicolon) is fastest to process.
- For the Trades section of the statement, you can’t select the options at the top for “Symbol Summary”, “Asset Class”, or “Orders”. These will blow up the parser. It’s fine to check the box for “Asset Class” down below, along with the other selections for XML attributes.
flex客户端
一旦定义了各种flex查询,就可以生成一个访问令牌 这将允许您生成语句并通过web下载它们 API,而不是登录获取它们。
报告设置flexweb服务
一旦你准备好了-带着令牌和想要的身份证 flex查询-ibflex.client包含检索所需的工具 他们:
In[1]:fromibfleximportclientIn[2]:token='111111111111111111111111'In[3]:query_id='111111'In[4]:response=client.download(token,query_id)In[5]:response[:215]Out[5]:b'<FlexQueryResponse queryName="Get Everything" type="AF">\n<FlexStatements count="1">\n<FlexStatement accountId="U111111" fromDate="2018-01-01" toDate="2018-01-31" period="LastMonth" whenGenerated="2018-02-01;211353">\n'
您也可以将client.main()作为脚本执行:
$ python client.py -t 111111111111111111111111 -q 111111 > 2018-01_ibkr.xml
最后,setup.py在~/.local/bin/flexget…cron tastic安装一个脚本!
$ flexget -t 111111111111111111111111 -q 111111 > 2018-01_ibkr.xml
资源
- 交互式代理Activity Flex Query Reference
- 交互式代理FlexWeb Service Reference
- capgains-使用ibflex(特别是)计算已实现收益的包
- ib-flex-analyzer-使用pandas分析交互式代理flex xml报告