经过认真研究,IBWrapper 不支持通用tick 数据,只能导入ibpy。
from ib.ext.Contract import Contract
from ib.opt import ibConnection
from time import sleep
import csv
class Downloader(object):
tickType47value = ''
#field4price = ''
def __init__(self):
self.tws = ibConnection('localhost', 7496, 20)
self.tws.register(self.tickPriceHandler, 'TickString')
self.tws.connect()
self._reqId = 1003 # current request id
def tickPriceHandler(self,msg):
if msg.tickType == 47: # tickType=47
self.tickType47value = msg.value
#print('[debug]', msg)
def requestData(self,contract):
self.tws.reqMktData(self._reqId, contract, "233, 236, 258", False) #"233, 236, 258",
self._reqId+=1
def cancelData(self):
#self.tws.cancelMktData(1003)
self.tws.disconnect()
以下链接是所有可用的基本比率 - “标题”中存在的标签值:
https ://interactivebrokers.github.io/tws-api/fundamental_ratios_tags.html
if __name__=='__main__':
headers = ['TickNo',
'TTMNPMGN',
'NLOW',
'TTMPRCFPS',
'TTMGROSMGN',
'TTMCFSHR',
'QCURRATIO',
'TTMREV',
'TTMINVTURN',
'TTMOPMGN',
'TTMPR2REV',
'AEPSNORM',
'TTMNIPEREM',
'EPSCHNGYR',
'TTMPRFCFPS',
'TTMRECTURN',
'TTMPTMGN',
'QCSHPS',
'TTMFCF',
'LATESTADATE',
'APTMGNPCT',
'AEBTNORM',
'TTMNIAC',
'NetDebt_I',
'PRYTDPCTR',
'TTMEBITD',
'AFEEPSNTM',
'PR2TANBK',
'EPSTRENDGR',
'QTOTD2EQ',
'TTMFCFSHR',
'QBVPS',
'NPRICE',
'YLD5YAVG',
'REVTRENDGR',
'TTMEPSXCLX',
'QTANBVPS',
'PRICE2BK',
'MKTCAP',
'TTMPAYRAT',
'TTMINTCOV',
'TTMREVCHG',
'TTMROAPCT',
'TTMROEPCT',
'TTMREVPERE',
'APENORM',
'TTMROIPCT',
'REVCHNGYR',
'CURRENCY',
'DIVGRPCT',
'TTMEPSCHG',
'PEEXCLXOR',
'QQUICKRATI',
'TTMREVPS',
'BETA',
'TTMEBT',
'ADIV5YAVG',
'ANIACNORM',
'QLTD2EQ',
'NHIG']
stocks=['700']
with open('Your path', 'w', newline='') as csvfile:
csvwriter = csv.writer(csvfile, delimiter=',', quotechar='"')
csvwriter.writerow(headers)
sleep(0.5)
for x in stocks:
for _ in range(5): #10 #If markets are open, there can be no more than 5 requests pending for the same contract.
dl = Downloader()
c = Contract()
c.m_symbol = x
c.m_secType = 'STK'
c.m_exchange = 'SEHK'
c.m_currency = 'HKD'
sleep(1)
dl.requestData(c)
sleep(1)
m0 = str(x)
m = dl.tickType47value
#data = m.split(';')
#pairs = { tuple(datum.split('=')) for datum in data}
#print(m)
sleep(1)
if dl.tickType47value:
with open(r'c:\\Users\\Owner\\Desktop\\extracedCSV\\ALLHKSTOCK@Finratio_2.csv', 'a', newline='') as csvfile:
csvwriter = csv.writer(csvfile, delimiter=',', quotechar='"')
row = []
row.append(m0)
row.append(m)
csvwriter.writerow(row)
dl.cancelData()
sleep(0.5)
break
print("Data is empty")
dl.cancelData()
sleep(0.5)