Ejemplo n.º 1
0
 def __init__(self, ticker, env):
     self.bars_data = Bars(ticker)
     self.prices = self.bars_data.get_data()
     self.first_run = True
     self.stream = StreamBar(ticker)
     self.parser = Parser()
     self.called = 0
     self._offset = 0
     self.env = env
Ejemplo n.º 2
0
    def _fetch_next_bars(self, smallestDateTime):
        '''Find the next earliest datetime and emit all Bars that have an entry for it.'''
        if smallestDateTime == None:
            return None

        # Make a second pass to get all the bars that had the smallest datetime.
        self._current_bars = Bars()
        for symbol, feed in self._feeds.iteritems():
            if feed.get_next_bar_date() == smallestDateTime:
                self._current_bars.add_bar(symbol, feed.get_current_bar())

        return self._current_bars
Ejemplo n.º 3
0
def data_for(data_date, series, earliest, pct: bool):
    bars = Bars.get(series, earliest=earliest)
    data, data_date = bars.data_for(data_date)
    if pct:
        data = data.divide(data.sum(axis='columns'), axis='rows')
    data = data.rolling(7).mean().dropna(how='all')
    return data, data_date, bars
Ejemplo n.º 4
0
    def new_message(self, message):

        if message.upper() == self._COMMANDS[0]:
            return self._HELLO[randint(0, len(self._HELLO) - 1)]

        elif message.upper() == self._COMMANDS[1] or message.upper() == self._COMMANDS_SHORT[1]:
            return self._get_time()

        elif message.upper() == self._COMMANDS[2]:
            return self._BYE[randint(0, len(self._BYE) - 1)]

        elif message.upper().split(' ')[0] == self._COMMANDS[3] or message.upper().split(' ')[0] == self._COMMANDS_SHORT[3]:
            data = message.split(' ')
            db = Database()
            if(not db._check_if_user_exists(self._USER_ID)):
                return f"Пожалуйста сначала зарегистрируйтесь!"
            user_info = db._get_user_info(self._USER_ID)
            if len(data) == 2:
                if(data[1] not in self._GROUPS):
                    if(data[1] in self._GROUPS_ENG):
                        data[1] = self._GROUPS[self._GROUPS_ENG.index(data[1])]
                    else:
                        return "Ошибка группы!"
                sc = Schedule(data[1], user_info[1], user_info[2])
            else:
                sc = Schedule(user_info[0], user_info[1], user_info[2])
            return sc._get_schedule()

        elif message.upper() == self._COMMANDS[4] or message.upper() == self._COMMANDS_SHORT[4]:
            return "Всё что я понимаю это: \nПРИВЕТ - бесполезная опция, но если вам нечем больше заняться, можете также попробовать команду ПОКА\n\n\
            (В)РЕМЯ - скажу, который сейчас час\n\n(П)ОМОЩЬ - выведу вот это сообщение :)\n\n(Р)АСПИСАНИЕ [А-XX-18]- покажу расписание. Если группа не указана, расписание будет для вашей группы.\n\n\
            (З)АРЕГИСТРИРОВАТЬСЯ - если вы не зарегистрировались, для просмотра ваших оценок придётся это сделать, написав следующее:\n(З)АРЕГИСТРИРОВАТЬСЯ ваш_логин ваш_пароль А-XX-18 \n\n\
            (Б)АРС - просмотр оценок\n"

        elif message.split(' ')[0].upper() == self._COMMANDS[5] or message.split(' ')[0].upper() == self._COMMANDS_SHORT[5]:
            return self._register(message)

        elif message.upper() == self._COMMANDS[6] or message.upper() == self._COMMANDS_SHORT[6]:
            db = Database()
            if(not db._check_if_user_exists(self._USER_ID)):
                return f"Пожалуйста сначала зарегистрируйтесь!"
            user_info = db._get_user_info(self._USER_ID)
            bars = Bars(user_info[1], user_info[2])
            return bars._get_data()

        else:
            return self._DONT_KNOW[randint(0, len(self._DONT_KNOW) - 1)]
Ejemplo n.º 5
0
    def _fetch_next_bars(self, smallestDateTime):
        '''Find the next earliest datetime and emit all Bars that have an entry for it.'''
        if smallestDateTime == None:
            return None

        # Make a second pass to get all the bars that had the smallest datetime.
        self._current_bars = Bars()
        for symbol, feed in self._feeds.iteritems():
            if feed.get_next_bar_date() == smallestDateTime:
                self._current_bars.add_bar(symbol, feed.get_current_bar())

        return self._current_bars
Ejemplo n.º 6
0
def main():
    parser = ArgumentParser()
    add_date_arg(parser, help='first release to use', default=earliest_testing)
    add_parallel_args(parser,
                      default_duration=0.1,
                      default_output='gif',
                      from_date=False)
    parser.add_argument('config', choices=BARS.keys())
    add_date_arg(parser,
                 '--earliest',
                 help='min for x-axis',
                 default=second_wave)
    parser.add_argument('--diff-log-scale', action='store_true')
    parser.add_argument('--diff-no-lims', action='store_true')
    parser.add_argument('--ylim', type=float)
    parser.add_argument('--y-max-factor', type=float, default=1.02)
    args = parser.parse_args()

    config = Bars.get(args.config, earliest=args.earliest)

    from_date = max(args.from_date, args.earliest)
    dates = available_dates(config.metric,
                            config.data_file_stem,
                            earliest=from_date)
    to_date = parallel_to_date(args, dates[0])
    if to_date != dates[0]:
        dates = [d for d in dates if d <= to_date]

    latest_date = dates[0]

    max_metric = config.data_for(latest_date)[0].sum(
        axis=1).max() * args.y_max_factor

    params = {}

    if args.diff_no_lims:
        params['diff_ylims'] = None

    lines = config.lines_for(latest_date)
    if lines:
        params['line_ylim'] = max(l.data.max()
                                  for l in lines) * args.y_max_factor

    parallel_render(
        f'animated_{args.config}',
        partial(plot_bars,
                config=config,
                ylim=args.ylim or max_metric,
                diff_log_scale=args.diff_log_scale,
                show_title=True,
                to_date=date.today(),
                **params), dates,
        **parallel_params(args, item_is_timestamp=False))
Ejemplo n.º 7
0
class Observation:
    def __init__(self, ticker, env):
        self.bars_data = Bars(ticker)
        self.prices = self.bars_data.get_data()
        self.first_run = True
        self.stream = StreamBar(ticker)
        self.parser = Parser()
        self.called = 0
        self._offset = 0
        self.env = env

    def create_obs(self):
        state_obs = np.ndarray(shape=self.env._state.shape, dtype=np.float32)
        shift = 0  # counter of shift

        # Loop through bars and get price values for ohlc, position, and pnl
        for bar_idx in range(10):
            ofs = self._offset + bar_idx
            print(type(self.prices['open']))
            state_obs[shift] = self.prices['open'][ofs]
            shift += 1
            state_obs[shift] = self.prices['high'][ofs]
            shift += 1
            state_obs[shift] = self.prices['low'][ofs]
            shift += 1
            state_obs[shift] = self.prices['close'][ofs]
            shift += 1

            state_obs[shift] = float(self.env._state.have_position)
            shift += 1

            if not self.env._state.have_position:
                state_obs[shift] = 0.0
            else:
                state_obs[shift] = np.sign(self.env._state.curr_close() -
                                           self.env._state.open_price)
            shift += 1

        self.first_run = False
        return state_obs
Ejemplo n.º 8
0
class MultiFeed(object):
    '''
    MultiFeed is an aggregator of multiple feeds.  This is essential for any
    portfolio-based strategy and an instance of this class serves as the core
    for Strategy execution.
    '''
    
    def __init__(self):
        '''Constructor.'''
        self._feeds = {}
        self._on_bars_event = observer.Event()
        self._current_bars = {}
        
    def register_feed(self, feed):
        '''
        Registers a new Feed in the MultiFeed.  Each symbol may only exist
        once in the MultiFeed
        
        :param Feed feed: feed to add
        
        :raises: Exception if a feed with the same symbol already exists
        '''
        if self._feeds.has_key(feed.instrument().symbol()):
            raise Exception("MultiFeed already has a Feed for symbol %s" % feed.instrument().symbol())
        self._feeds[feed.instrument().symbol()] = feed
        
    def symbols(self):
        '''Returns a list of the symbols in the MultiFeed.'''
        return self._feeds.keys()
    
    def get_feed(self, symbol):
        '''Returns the Feed instance for the symbol.'''
        return self._feeds[symbol]
    
    def subscribe(self, handler):
        '''Subscribes the handler to the on_bars_event Observer.'''
        return self._on_bars_event.subscribe(handler)

    def unsubscribe(self, handler):
        '''Unsubscribes the handler from the on_bars_event Observer.'''
        return self._on_bars_event.unsubscribe(handler)
    
    def start(self,first=None,last=None):
        '''
        Starts emitting all bars in all feeds from either the current cursor 
        position or the cursor position corresponding to <first> if specified.
        Bars are emitted up to the end of each feed or <last> if specified.
        All Bars for a given datetime are emitted at once and receivers of the 
        event are guaranteed that all bars passed to one handler callback are 
        for the same datetime.  Note that this means each callback may or may not 
        have a Bar for each Feed since it is not the case that all securities 
        trade all days.
        
        :param datetime first: if not None,earliest date emitted from the feed
        :param datetime last: if not None, last date emitted from the feed
        '''
        # first reset all feeds to the start if we need to
        if first != None:
            for f in self._feeds:
                self._feeds[f].set_cursor(first)
        # simply some checks below by setting last to an arbitrary future date
        if last == None:
            last = datetime.datetime(9999,12,31)
            
        bars = None
        smallestDateTime = self.get_next_bars_date()
        if smallestDateTime <= last:
            bars = self._fetch_next_bars(smallestDateTime)
        while bars != None:
            self._on_bars_event.emit(bars)
            smallestDateTime = self.get_next_bars_date()
            if smallestDateTime != None and smallestDateTime <= last:
                bars = self._fetch_next_bars(smallestDateTime)
            else:
                bars = None            
            
    def get_next_bars_date(self):
        '''Returns the next datetime that will be emitted from this feeds.'''
        # all feeds may or may not have the same bars - we need to return the
        # smallest datetime at the head of one of our feeds
        smallestDateTime = None

        # Make a first pass to get the smallest datetime.
        for symbol, feed in self._feeds.iteritems():
            if feed.get_next_bar_date() != None:
                if (smallestDateTime != None and feed.get_next_bar_date() < smallestDateTime) or smallestDateTime == None:
                    smallestDateTime = feed.get_next_bar_date()                    

        return smallestDateTime
        
    def set_cursor(self, datetime=None):
        '''
        Sets each feeds' cursor to the date specified by start.  The cursor 
        determines which Bar is returned on the next call to get_current_bar.
        
        :param datetime start: if present, each feed will be set to the first 
                               Bar that is >= start.  If no date is >=
                               start then the cursor will be set to the end of
                               the list.  If not present, the feed will cursor
                               will be reset to the beginning of the list
        '''
        for symbol, feed in self._feeds.iteritems():
            feed.set_cursor(datetime)
        
    def _fetch_next_bars(self, smallestDateTime):
        '''Find the next earliest datetime and emit all Bars that have an entry for it.'''
        if smallestDateTime == None:
            return None

        # Make a second pass to get all the bars that had the smallest datetime.
        self._current_bars = Bars()
        for symbol, feed in self._feeds.iteritems():
            if feed.get_next_bar_date() == smallestDateTime:
                self._current_bars.add_bar(symbol, feed.get_current_bar())

        return self._current_bars
    
    def get_current_bars(self):
        '''Returns the last set of bars that were emitted by the feed.'''
        return self._current_bars
    
    def get_last_close(self, symbol):
        '''Returns the last closing price for symbol.'''
        return self._feeds[symbol].get_last_close()
Ejemplo n.º 9
0
class MultiFeed(object):
    '''
    MultiFeed is an aggregator of multiple feeds.  This is essential for any
    portfolio-based strategy and an instance of this class serves as the core
    for Strategy execution.
    '''
    def __init__(self):
        '''Constructor.'''
        self._feeds = {}
        self._on_bars_event = observer.Event()
        self._current_bars = {}

    def register_feed(self, feed):
        '''
        Registers a new Feed in the MultiFeed.  Each symbol may only exist
        once in the MultiFeed
        
        :param Feed feed: feed to add
        
        :raises: Exception if a feed with the same symbol already exists
        '''
        if self._feeds.has_key(feed.instrument().symbol()):
            raise Exception("MultiFeed already has a Feed for symbol %s" %
                            feed.instrument().symbol())
        self._feeds[feed.instrument().symbol()] = feed

    def symbols(self):
        '''Returns a list of the symbols in the MultiFeed.'''
        return self._feeds.keys()

    def get_feed(self, symbol):
        '''Returns the Feed instance for the symbol.'''
        return self._feeds[symbol]

    def subscribe(self, handler):
        '''Subscribes the handler to the on_bars_event Observer.'''
        return self._on_bars_event.subscribe(handler)

    def unsubscribe(self, handler):
        '''Unsubscribes the handler from the on_bars_event Observer.'''
        return self._on_bars_event.unsubscribe(handler)

    def start(self, first=None, last=None):
        '''
        Starts emitting all bars in all feeds from either the current cursor 
        position or the cursor position corresponding to <first> if specified.
        Bars are emitted up to the end of each feed or <last> if specified.
        All Bars for a given datetime are emitted at once and receivers of the 
        event are guaranteed that all bars passed to one handler callback are 
        for the same datetime.  Note that this means each callback may or may not 
        have a Bar for each Feed since it is not the case that all securities 
        trade all days.
        
        :param datetime first: if not None,earliest date emitted from the feed
        :param datetime last: if not None, last date emitted from the feed
        '''
        # first reset all feeds to the start if we need to
        if first != None:
            for f in self._feeds:
                self._feeds[f].set_cursor(first)
        # simply some checks below by setting last to an arbitrary future date
        if last == None:
            last = datetime.datetime(9999, 12, 31)

        bars = None
        smallestDateTime = self.get_next_bars_date()
        if smallestDateTime <= last:
            bars = self._fetch_next_bars(smallestDateTime)
        while bars != None:
            self._on_bars_event.emit(bars)
            smallestDateTime = self.get_next_bars_date()
            if smallestDateTime != None and smallestDateTime <= last:
                bars = self._fetch_next_bars(smallestDateTime)
            else:
                bars = None

    def get_next_bars_date(self):
        '''Returns the next datetime that will be emitted from this feeds.'''
        # all feeds may or may not have the same bars - we need to return the
        # smallest datetime at the head of one of our feeds
        smallestDateTime = None

        # Make a first pass to get the smallest datetime.
        for symbol, feed in self._feeds.iteritems():
            if feed.get_next_bar_date() != None:
                if (smallestDateTime != None and feed.get_next_bar_date() <
                        smallestDateTime) or smallestDateTime == None:
                    smallestDateTime = feed.get_next_bar_date()

        return smallestDateTime

    def set_cursor(self, datetime=None):
        '''
        Sets each feeds' cursor to the date specified by start.  The cursor 
        determines which Bar is returned on the next call to get_current_bar.
        
        :param datetime start: if present, each feed will be set to the first 
                               Bar that is >= start.  If no date is >=
                               start then the cursor will be set to the end of
                               the list.  If not present, the feed will cursor
                               will be reset to the beginning of the list
        '''
        for symbol, feed in self._feeds.iteritems():
            feed.set_cursor(datetime)

    def _fetch_next_bars(self, smallestDateTime):
        '''Find the next earliest datetime and emit all Bars that have an entry for it.'''
        if smallestDateTime == None:
            return None

        # Make a second pass to get all the bars that had the smallest datetime.
        self._current_bars = Bars()
        for symbol, feed in self._feeds.iteritems():
            if feed.get_next_bar_date() == smallestDateTime:
                self._current_bars.add_bar(symbol, feed.get_current_bar())

        return self._current_bars

    def get_current_bars(self):
        '''Returns the last set of bars that were emitted by the feed.'''
        return self._current_bars

    def get_last_close(self, symbol):
        '''Returns the last closing price for symbol.'''
        return self._feeds[symbol].get_last_close()