Example #1
0
    def checkInformationData(self):
        """Update information symbols' data"""

        # If infobar is empty, which means it is the first time calling this method
        if self.infobar == {}:
            for info_symbol in self.InfoCursor:
                try:
                    self.infobar[info_symbol] = next(
                        self.InfoCursor[info_symbol])
                except StopIteration:
                    print "Data of information symbols is empty! Input must be a list, not str."
                    raise

        temp = {}
        for info_symbol in self.infobar:

            data = self.infobar[info_symbol]

            # Update data only when Time Stamp is matched
            if (data is not None) and (data['datetime'] <= self.dt):

                try:
                    temp[info_symbol] = VtBarData()
                    temp[info_symbol].__dict__ = data
                    self.infobar[info_symbol] = next(
                        self.InfoCursor[info_symbol])
                except StopIteration:
                    self.infobar[info_symbol] = None
                    self.output("No more data in information database.")
            else:
                temp[info_symbol] = None

        return temp
Example #2
0
    def loadBar(self, dbName, collectionName, days):
        """从数据库中读取Bar数据,startDate是datetime对象"""
        startDate = self.today - timedelta(days)

        d = {'datetime': {'$gte': startDate}}
        barData = self.mainEngine.dbQuery(
            dbName, collectionName, d, 'datetime')

        l = []
        for d in barData:
            bar = VtBarData()
            bar.__dict__ = d
            l.append(bar)
        return l
    def updateTick(self, tick):
        """TICK更新"""
        newMinute = False  # 默认不是新的一分钟

        # 尚未创建对象
        if not self.bar:
            self.bar = VtBarData()
            newMinute = True
        # 新的一分钟
        elif self.bar.datetime.minute != tick.datetime.minute:
            # 生成上一分钟K线的时间戳
            self.bar.datetime = self.bar.datetime.replace(
                second=0, microsecond=0)  # 将秒和微秒设为0
            self.bar.date = self.bar.datetime.strftime('%Y%m%d')
            self.bar.time = self.bar.datetime.strftime('%H:%M:%S.%f')

            # 推送已经结束的上一分钟K线
            self.onBar(self.bar)

            # 创建新的K线对象
            self.bar = VtBarData()
            newMinute = True

        # 初始化新一分钟的K线数据
        if newMinute:
            self.bar.vtSymbol = tick.vtSymbol
            self.bar.symbol = tick.symbol
            self.bar.exchange = tick.exchange

            self.bar.open = tick.lastPrice
            self.bar.high = tick.lastPrice
            self.bar.low = tick.lastPrice
        # 累加更新老一分钟的K线数据
        else:
            self.bar.high = max(self.bar.high, tick.lastPrice)
            self.bar.low = min(self.bar.low, tick.lastPrice)

        # 通用更新部分
        self.bar.close = tick.lastPrice
        self.bar.datetime = tick.datetime
        self.bar.openInterest = tick.openInterest

        if self.lastTick:
            self.bar.volume += (tick.volume - self.lastTick.volume
                                )  # 当前K线内的成交量

        # 缓存Tick
        self.lastTick = tick
Example #4
0
 def updateBar(self, bar):
     """1分钟K线更新"""
     # 尚未创建对象
     if not self.xminBar:
         self.xminBar = VtBarData()
         
         self.xminBar.vtSymbol = bar.vtSymbol
         self.xminBar.symbol = bar.symbol
         self.xminBar.exchange = bar.exchange
     
         self.xminBar.open = bar.open
         self.xminBar.high = bar.high
         self.xminBar.low = bar.low            
         
         self.xminBar.datetime = bar.datetime    # 以第一根分钟K线的开始时间戳作为X分钟线的时间戳
     # 累加老K线
     else:
         self.xminBar.high = max(self.xminBar.high, bar.high)
         self.xminBar.low = min(self.xminBar.low, bar.low)
 
     # 通用部分
     self.xminBar.close = bar.close        
     self.xminBar.openInterest = bar.openInterest
     self.xminBar.volume += int(bar.volume)                
         
     # X分钟已经走完
     if not (bar.datetime.minute + 1) % self.xmin:   # 可以用X整除
         # 生成上一X分钟K线的时间戳
         self.xminBar.datetime = self.xminBar.datetime.replace(second=0, microsecond=0)  # 将秒和微秒设为0
         self.xminBar.date = self.xminBar.datetime.strftime('%Y%m%d')
         self.xminBar.time = self.xminBar.datetime.strftime('%H:%M:%S.%f')
         
         # 推送
         self.onXminBar(self.xminBar)
         
         # 清空老K线缓存对象
         self.xminBar = None
Example #5
0
    def __firstTick(self,tick):
        """ K线的第一个Tick数据"""
        self.bar = VtBarData()                  # 创建新的K线

        self.bar.vtSymbol = tick.vtSymbol
        self.bar.symbol = tick.symbol
        self.bar.exchange = tick.exchange

        self.bar.open = tick.lastPrice            # O L H C
        self.bar.high = tick.lastPrice
        self.bar.low = tick.lastPrice
        self.bar.close = tick.lastPrice

        # K线的日期时间
        self.bar.date = tick.date                # K线的日期时间(去除秒)设为第一个Tick的时间
        self.bar.time = tick.time              # K线的日期时间(去除秒)设为第一个Tick的时间
        self.bar.datetime = tick.datetime

        self.bar.volume = tick.volume
        self.bar.openInterest = tick.openInterest

        self.barFirstTick = True                  # 标识该Tick属于该Bar的第一个tick数据

        self.lineBar.append(self.bar)           # 推入到lineBar队列
def generateVtBar(row):
    """生成K线"""
    bar = VtBarData()

    symbol, exchange = row['symbol'].split('.')

    bar.symbol = symbol
    bar.exchange = exchangeMapReverse[exchange]
    bar.vtSymbol = '.'.join([bar.symbol, bar.exchange])
    bar.open = row['open']
    bar.high = row['high']
    bar.low = row['low']
    bar.close = row['close']
    bar.volume = row['volume']

    bar.date = str(row['date'])
    bar.time = str(row['time']).rjust(6, '0')

    # 将bar的时间改成提前一分钟
    hour = bar.time[0:2]
    minute = bar.time[2:4]
    sec = bar.time[4:6]
    if minute == "00":
        minute = "59"

        h = int(hour)
        if h == 0:
            h = 24

        hour = str(h - 1).rjust(2, '0')
    else:
        minute = str(int(minute) - 1).rjust(2, '0')
    bar.time = hour + minute + sec

    bar.datetime = dt.datetime.strptime(
        ' '.join([bar.date, bar.time]), '%Y%m%d %H%M%S')

    return bar
def loadMcCsv(fileName, dbName, symbol):
    """将Multicharts导出的csv格式的历史数据插入到Mongo数据库中"""
    start = time()
    print(u'开始读取CSV文件%s中的数据插入到%s的%s中' % (fileName, dbName, symbol))

    # 锁定集合,并创建索引
    client = pymongo.MongoClient(globalSetting['mongoHost'],
                                 globalSetting['mongoPort'])
    collection = client[dbName][symbol]
    collection.ensure_index([('datetime', pymongo.ASCENDING)], unique=True)

    # 读取数据和插入到数据库
    with open(fileName, 'r') as f:
        reader = csv.DictReader(f)
        for d in reader:
            bar = VtBarData()
            bar.vtSymbol = symbol
            bar.symbol = symbol
            bar.open = float(d['Open'])
            bar.high = float(d['High'])
            bar.low = float(d['Low'])
            bar.close = float(d['Close'])
            bar.date = datetime.strptime(d['Date'],
                                         '%Y-%m-%d').strftime('%Y%m%d')
            bar.time = d['Time']
            bar.datetime = datetime.strptime(bar.date + ' ' + bar.time,
                                             '%Y%m%d %H:%M:%S')
            bar.volume = d['TotalVolume']
            bar.lastBar = False

            flt = {'datetime': bar.datetime}
            collection.update_one(flt, {'$set': bar.__dict__}, upsert=True)
            print(bar.date, bar.time)

    print(u'插入完毕,耗时:%s' % (time() - start))
def downloadEquityDailyBarts(self, symbol):
    """
    下载股票的日行情,symbol是股票代码
    """
    print(u'开始下载%s日行情' % symbol)

    # 查询数据库中已有数据的最后日期
    cl = self.dbClient[DAILY_DB_NAME][symbol]
    cx = cl.find(sort=[('datetime', pymongo.DESCENDING)])
    if cx.count():
        last = cx[0]
    else:
        last = ''
    # 开始下载数据
    import tushare as ts

    if last:
        start = last['date'][:4] + '-' + last['date'][4:6] + '-' + last[
            'date'][6:]

    data = ts.get_k_data(symbol, start)

    if not data.empty:
        # 创建datetime索引
        self.dbClient[DAILY_DB_NAME][symbol].ensure_index(
            [('datetime', pymongo.ASCENDING)], unique=True)

        for index, d in data.iterrows():
            bar = VtBarData()
            bar.vtSymbol = symbol
            bar.symbol = symbol
            try:
                bar.open = d.get('open')
                bar.high = d.get('high')
                bar.low = d.get('low')
                bar.close = d.get('close')
                bar.date = d.get('date').replace('-', '')
                bar.time = ''
                bar.datetime = datetime.strptime(bar.date, '%Y%m%d')
                bar.volume = d.get('volume')
            except KeyError:
                print(d)

            flt = {'datetime': bar.datetime}
            self.dbClient[DAILY_DB_NAME][symbol].update_one(
                flt, {'$set': bar.__dict__}, upsert=True)

        print(u'%s下载完成' % symbol)
    else:
        print(u'找不到合约%s' % symbol)
def loadDeribitCsv(fileName, symbol, dbName=None):
    barlist = []
    start = time()

    reader = csv.reader(open(fileName, "r"))
    for d in reader:
        if 'open' not in d[1]:
            bar = VtBarData()
            bar.symbol = symbol
            bar.interval = '1m'  # K线周期.
            bar.exchange = EXCHANGE_DERIBIT
            bar.vtSymbol = '.'.join([bar.symbol, bar.exchange])
            bar.datetime = datetime.strptime(d[0], '%Y-%m-%d %H:%M:%S')
            bar.date = bar.datetime.date().strftime('%Y-%m-%d')
            bar.time = bar.datetime.time().strftime('%H:%M:%S')
            bar.open = float(d[1])
            bar.high = float(d[2])
            bar.low = float(d[3])
            bar.close = float(d[4])
            bar.volume = float(d[5])
            barlist.append(bar)

    return barlist
def loadOKEXCsv(fileName, dbName, symbol):
    """将OKEX导出的csv格式的历史分钟数据插入到Mongo数据库中"""
    start = time()
    print(u'开始读取CSV文件%s中的数据插入到%s的%s中' % (fileName, dbName, symbol))

    # 锁定集合,并创建索引
    client = pymongo.MongoClient(globalSetting['mongoHost'],
                                 globalSetting['mongoPort'])
    collection = client[dbName][symbol]
    collection.ensure_index([('datetime', pymongo.ASCENDING)], unique=True)

    # 读取数据和插入到数据库
    reader = csv.reader(open(fileName, "r"))
    for d in reader:
        if len(d[1]) > 10:
            bar = VtBarData()
            bar.vtSymbol = symbol
            bar.symbol = symbol

            bar.datetime = datetime.strptime(d[1], '%Y-%m-%d %H:%M:%S')
            bar.date = bar.datetime.date().strftime('%Y%m%d')
            bar.time = bar.datetime.time().strftime('%H:%M:%S')

            bar.open = float(d[2])
            bar.high = float(d[3])
            bar.low = float(d[4])
            bar.close = float(d[5])

            bar.volume = float(d[6])
            bar.tobtcvolume = float(d[7])

            flt = {'datetime': bar.datetime}
            collection.update_one(flt, {'$set': bar.__dict__}, upsert=True)
            print('%s \t %s' % (bar.date, bar.time))

    print(u'插入完毕,耗时:%s' % (time() - start))
Example #11
0
def generateVtBar(d):
    """生成K线"""
    bar = VtBarData()

    bar.symbol = d['symbol']
    bar.vtSymbol = d['symbol']
    bar.date = d['date']
    bar.time = ':'.join([d['time'][:2], d['time'][2:]])
    bar.open = d['open']
    bar.high = d['high']
    bar.low = d['low']
    bar.close = d['close']
    bar.volume = d['volume']
    bar.openInterest = d['openInterest']
    bar.datetime = datetime.datetime.strptime(' '.join([bar.date, bar.time]),
                                              '%Y%m%d %H:%M')

    return bar
Example #12
0
    def downloadEquityDailyBar(self, symbol):
        """
        下载股票的日行情,symbol是股票代码
        """
        print u'开始下载%s日行情' % symbol

        # 查询数据库中已有数据的最后日期
        cl = self.dbClient[DAILY_DB_NAME][symbol]
        cx = cl.find(sort=[('datetime', pymongo.DESCENDING)])
        if cx.count():
            last = cx[0]
        else:
            last = ''

        # 开始下载数据
        path = 'api/market/getMktEqud.json'

        params = {}
        params['ticker'] = symbol
        if last:
            params['beginDate'] = last['date']

        data = self.datayesClient.downloadData(path, params)

        if data:
            # 创建datetime索引
            self.dbClient[DAILY_DB_NAME][symbol].ensure_index(
                [('datetime', pymongo.ASCENDING)], unique=True)

            for d in data:
                bar = VtBarData()
                bar.vtSymbol = symbol
                bar.symbol = symbol
                try:
                    bar.exchange = DATAYES_TO_VT_EXCHANGE.get(
                        d.get('exchangeCD', ''), '')
                    bar.open = d.get('openPrice', 0)
                    bar.high = d.get('highestPrice', 0)
                    bar.low = d.get('lowestPrice', 0)
                    bar.close = d.get('closePrice', 0)
                    bar.date = d.get('tradeDate', '').replace('-', '')
                    bar.time = ''
                    bar.datetime = datetime.strptime(bar.date, '%Y%m%d')
                    bar.volume = d.get('turnoverVol', 0)
                except KeyError:
                    print d

                flt = {'datetime': bar.datetime}
                self.dbClient[DAILY_DB_NAME][symbol].update_one(
                    flt, {'$set': bar.__dict__}, upsert=True)

            print u'%s下载完成' % symbol
        else:
            print u'找不到合约%s' % symbol
 def onQueryBar(self, data, request):
     """"""
     e = request.extra.split('_')
     l = len(data)
     index = 0
     for d in reversed(data):
         bar = VtBarData()
         
         bar.symbol = d['symbol']        # 代码
         bar.interval = e[1]       # K线周期.
         bar.exchange = EXCHANGE_BITMEX
         bar.vtSymbol = '.'.join([bar.symbol, bar.exchange])
     
         bar.open = float(d['open'])             # OHLCV
         bar.high = float(d['high'])
         bar.low = float(d['low'])
         bar.close = float(d['close'])
         bar.volume = float(d['volume']) 
         
         dt = datetime.strptime(d['timestamp'][:-1]+'000Z', '%Y-%m-%dT%H:%M:%S.%fZ')
         if 'm' in bar.interval:
             bar.datetime = dt - timedelta(minutes=int(bar.interval[:-1]))
         elif 'd' in bar.interval:
             bar.datetime = dt - timedelta(days=int(bar.interval[:-1]))
         elif 'h' in bar.interval:
             bar.datetime = dt - timedelta(hours=int(bar.interval[:-1]))
             
         bar.date = bar.datetime.strftime('%Y-%m-%d')
         bar.time = bar.datetime.strftime('%H:%M:%S.%f')[:-3]                
         
         index += 1
         if index == l:
             bar.lastBar = True
             
         self.gateway.onBar(bar)
Example #14
0
    def downloadFuturesDailyBar(self, symbol):
        """
        下载期货合约的日行情,symbol是合约代码,
        若最后四位为0000(如IF0000),代表下载连续合约。
        """
        print u'开始下载%s日行情' % symbol

        # 查询数据库中已有数据的最后日期
        cl = self.dbClient[DAILY_DB_NAME][symbol]
        cx = cl.find(sort=[('datetime', pymongo.DESCENDING)])
        if cx.count():
            last = cx[0]
        else:
            last = ''

        # 主力合约
        if '0000' in symbol:
            path = 'api/market/getMktMFutd.json'

            params = {}
            params['contractObject'] = symbol.replace('0000', '')
            params['mainCon'] = 1
            if last:
                params['startDate'] = last['date']
        # 交易合约
        else:
            path = 'api/market/getMktFutd.json'

            params = {}
            params['ticker'] = symbol
            if last:
                params['startDate'] = last['date']

        # 开始下载数据
        data = self.datayesClient.downloadData(path, params)

        if data:
            # 创建datetime索引
            self.dbClient[DAILY_DB_NAME][symbol].ensure_index(
                [('datetime', pymongo.ASCENDING)], unique=True)

            for d in data:
                bar = VtBarData()
                bar.vtSymbol = symbol
                bar.symbol = symbol
                try:
                    bar.exchange = DATAYES_TO_VT_EXCHANGE.get(
                        d.get('exchangeCD', ''), '')
                    bar.open = d.get('openPrice', 0)
                    bar.high = d.get('highestPrice', 0)
                    bar.low = d.get('lowestPrice', 0)
                    bar.close = d.get('closePrice', 0)
                    bar.date = d.get('tradeDate', '').replace('-', '')
                    bar.time = ''
                    bar.datetime = datetime.strptime(bar.date, '%Y%m%d')
                    bar.volume = d.get('turnoverVol', 0)
                    bar.openInterest = d.get('openInt', 0)
                except KeyError:
                    print d

                flt = {'datetime': bar.datetime}
                self.dbClient[DAILY_DB_NAME][symbol].update_one(
                    flt, {'$set': bar.__dict__}, upsert=True)

                print u'%s下载完成' % symbol
        else:
            print u'找不到合约%s' % symbol
Example #15
0
def loadTdxCsv(fileName, dbName, symbol):
    """将通达信导出的csv格式的历史分钟数据插入到Mongo数据库中"""
    import csv

    start = time()
    print u'开始读取CSV文件%s中的数据插入到%s的%s中' % (fileName, dbName, symbol)

    # 锁定集合,并创建索引
    client = pymongo.MongoClient(globalSetting['mongoHost'],
                                 globalSetting['mongoPort'])
    collection = client[dbName][symbol]
    collection.ensure_index([('datetime', pymongo.ASCENDING)], unique=True)

    # 读取数据和插入到数据库
    reader = csv.reader(file(fileName, 'r'))
    for d in reader:
        bar = VtBarData()
        bar.vtSymbol = symbol
        bar.symbol = symbol
        bar.open = float(d[2])
        bar.high = float(d[3])
        bar.low = float(d[4])
        bar.close = float(d[5])
        bar.date = datetime.strptime(d[0], '%Y/%m/%d').strftime('%Y%m%d')
        bar.time = d[1][:2] + ':' + d[1][2:4] + ':00'
        bar.datetime = datetime.strptime(bar.date + ' ' + bar.time,
                                         '%Y%m%d %H:%M:%S')
        bar.volume = d[6]
        bar.openInterest = d[7]

        flt = {'datetime': bar.datetime}
        collection.update_one(flt, {'$set': bar.__dict__}, upsert=True)
        print bar.date, bar.time

    print u'插入完毕,耗时:%s' % (time() - start)
def generateVtBar(row):
    """生成K线"""
    bar = VtBarData()

    bar.symbol = row['code']
    bar.exchange = ''
    bar.vtSymbol = bar.symbol
    bar.open = row['open']
    bar.high = row['high']
    bar.low = row['low']
    bar.close = row['close']
    bar.volume = row['volume']
    bar.datetime = datetime.strptime(row['time_key'], '%Y-%m-%d %H:%M:%S')
    bar.date = bar.datetime.strftime("%Y%m%d")
    bar.time = bar.datetime.strftime("%H:%M:%S")

    return bar
Example #17
0
    def downloadFuturesIntradayBar(self, symbol):
        """下载期货的日内分钟行情"""
        print u'开始下载%s日内分钟行情' % symbol

        # 日内分钟行情只有具体合约
        path = 'api/market/getFutureBarRTIntraDay.json'

        params = {}
        params['instrumentID'] = symbol
        params['unit'] = 1

        data = self.datayesClient.downloadData(path, params)

        if data:
            today = datetime.now().strftime('%Y%m%d')

            # 创建datetime索引
            self.dbClient[MINUTE_DB_NAME][symbol].ensure_index(
                [('datetime', pymongo.ASCENDING)], unique=True)

            for d in data:
                bar = VtBarData()
                bar.vtSymbol = symbol
                bar.symbol = symbol
                try:
                    bar.exchange = DATAYES_TO_VT_EXCHANGE.get(
                        d.get('exchangeCD', ''), '')
                    bar.open = d.get('openPrice', 0)
                    bar.high = d.get('highestPrice', 0)
                    bar.low = d.get('lowestPrice', 0)
                    bar.close = d.get('closePrice', 0)
                    bar.date = today
                    bar.time = d.get('barTime', '')
                    bar.datetime = datetime.strptime(bar.date + ' ' + bar.time,
                                                     '%Y%m%d %H:%M')
                    bar.volume = d.get('totalVolume', 0)
                    bar.openInterest = 0
                except KeyError:
                    print d

                flt = {'datetime': bar.datetime}
                self.dbClient[MINUTE_DB_NAME][symbol].update_one(
                    flt, {'$set': bar.__dict__}, upsert=True)

            print u'%s下载完成' % symbol
        else:
            print u'找不到合约%s' % symbol