Пример #1
0
 def __init__(self):
     # TODO framework to test different parameter in parallel
     self.HZ = 14000.0
     self.price_sum = 0
     # perhaps make arg in Q(arg) an arg in __init__
     self.prices = AutoQueue(10)
     self.price_sum_sq = 0
     self.count = 0
     self.boundary = 0.025  # percent change from mean
Пример #2
0
    def __init__(self):
        self.HZ = 1.0 / 1.0
        self.local_strategies = [self.tsla]

        # variables needed for tsla()
        self.prices = AutoQueue(10)
        self.boundary = 0.01
        self.holding = False
        self.volume = 0
Пример #3
0
class LiveTestStrat():
    """Same as Previous strat but this should use live prices
    and trade the same stratey as Strategy()
    """
    def __init__(self):
        self.HZ = 1.0 / 1.0
        self.local_strategies = [self.tsla]

        # variables needed for tsla()
        self.prices = AutoQueue(10)
        self.boundary = 0.01
        self.holding = False
        self.volume = 0

    def execute(self, portfolio):
        while True:
            for local_strategy in self.local_strategies:
                local_strategy()
            sleep(1.0 / self.HZ)

    def tsla(self):
        tsla = Security('TSLA')
        price = tsla.get_price()
        self.prices.put(price)
        volume = tsla.security.get_volume()
        # if volume != self.volume:
        #     print(volume)
        #     self.volume = volume
        # else:
        #     return

        # do things necessary for avg and stddev calc
        # self.price_sum = self.prices.sum()
        # self.price_sum_sq = self.prices.sum_sq()
        # self.count = len(self.prices)

        avg = self.prices.average()
        var = self.prices.variance()

        if price < avg * (1 - self.boundary):
            # low price, want to buy
            while portfolio.buy(tsla, 1):
                pass
            self.holding = True
        elif price > avg * (1 + self.boundary):
            # high price, want to sell_all
            portfolio.sell_all(tsla)
            self.holding = False
        print(
            f'Price: {price:.2f}\tAvg: {avg:.2f}\tvar: {var:.2f} <{time.asctime()}',
            end='\r')
Пример #4
0
    def __init__(self, udp_ip='127.0.0.1', udp_port='8888', message_size=16):
        super(InterfaceEvents, self).__init__()

        self.udp_ip = udp_ip
        self.udp_port = udp_port
        self.message_size = message_size

        self.list_events = AutoQueue(maxsize=250)
        self.list_events_time = AutoQueue(maxsize=250)

        self.lock = Lock()

        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  # UDP
        self.sock.bind((self.udp_ip, self.udp_port))

        # first message, with the sequence
        first_message, addr = self.sock.recvfrom(
            4096)  # buffer size is 1024 bytes

        self.frq_event, self.type_event, self.sequence_usage, self.sequence_training = self.decript_first_message(
            first_message)
Пример #5
0
    def prepare_processes(self):
        list_queue = [
            AutoQueue(maxsize=1) for _ in range(self.number_of_process)
        ]
        list_queue.append(AutoQueue(maxsize=100,
                                    autodrop=True))  # last queue has no limit
        self.queue_in = list_queue[0]
        self.queue_out = list_queue[-1]

        for i, process in enumerate(self.list_process_string):
            if isinstance(process, str):
                mod = __import__('pymuse.processes', fromlist=[process])
                klass = getattr(mod, process)
                if self.list_params[i] is not None:
                    self.list_process.append(
                        klass(list_queue[i], list_queue[i + 1],
                              self.list_params[i]))
                else:
                    self.list_process.append(
                        klass(list_queue[i], list_queue[i + 1]))
            else:
                process.queue_in = list_queue[i]
                process.queue_out = list_queue[i + 1]
                self.list_process.append(process)
Пример #6
0
class Strategy():
    def __init__(self):
        # TODO framework to test different parameter in parallel
        self.HZ = 14000.0
        self.price_sum = 0
        # perhaps make arg in Q(arg) an arg in __init__
        self.prices = AutoQueue(10)
        self.price_sum_sq = 0
        self.count = 0
        self.boundary = 0.025  # percent change from mean

    # calculate average using a queue, be able to set size using some parameter
    def execute(self, portfolio):
        goog = TestSecurity("GOOG")
        counter = 0
        while counter < 949:
            price = goog.get_price()
            self.prices.put(price)

            # do things necessary for avg and stddev calc
            self.price_sum = self.prices.sum()
            self.price_sum_sq = self.prices.sum_sq()
            self.count = len(self.prices)

            avg = self.prices.average()
            var = self.prices.variance()

            if price < avg * (1 - self.boundary):
                # low price, want to buy
                while portfolio.buy(goog, 1):
                    pass
                self.holding = True
            elif price > avg * (1 + self.boundary):
                # high price, want to sell_all
                portfolio.sell_all(goog)
                self.holding = False
            # print(f'Price: {price:.2f}\tAvg: {avg:.2f}\tvar: {var:.2f}')
            counter += 1
            sleep(1.0 / self.HZ)
        print(portfolio)
Пример #7
0
class InterfaceEvents(Thread):
    def __init__(self, udp_ip='127.0.0.1', udp_port='8888', message_size=16):
        super(InterfaceEvents, self).__init__()

        self.udp_ip = udp_ip
        self.udp_port = udp_port
        self.message_size = message_size

        self.list_events = AutoQueue(maxsize=250)
        self.list_events_time = AutoQueue(maxsize=250)

        self.lock = Lock()

        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  # UDP
        self.sock.bind((self.udp_ip, self.udp_port))

        # first message, with the sequence
        first_message, addr = self.sock.recvfrom(
            4096)  # buffer size is 1024 bytes

        self.frq_event, self.type_event, self.sequence_usage, self.sequence_training = self.decript_first_message(
            first_message)

    def get_nearest_message(self):
        pass

    def start(self):
        super(InterfaceEvents, self).start()

    def decript_first_message(self, m):
        message_split_by_type = m.split(' DONE')

        split_message = message_split_by_type[0].split(' ')
        frq_event = split_message[0]
        type_event = split_message[1]
        sequence_usage = split_message[2:]

        sequence_training = None
        if type_event == 'T':
            sequence_training_list = message_split_by_type[1].split(' ')[1:]
            sequence_training = [[
                sequence_training_list[2 * i],
                sequence_training_list[2 * i + 1].split(',')
            ] for i in range(len(sequence_training_list) / 2)]

        return frq_event, type_event, sequence_usage, sequence_training

    def add_event_synchronicity(self, time_event, event):
        self.lock.acquire()
        self.list_events.put(event)
        self.list_events_time.put(time_event)
        self.lock.release()

    def find_closest_event(self, datetime_window):
        event_usage, event_training = '', ''

        self.lock.acquire()
        list_events_time = list(self.list_events_time)
        list_events = list(self.list_events)
        self.lock.release()

        # search into the list of event and return the closest match
        index_closest_after = bisect_left(list_events_time, datetime_window)
        index_closest_before = index_closest_after - 1  # datetime are sorted in self.list_events_time

        datetime_before = list_events_time[index_closest_before]
        datetime_after = list_events_time[index_closest_before]
        index_event_before = list_events[index_closest_before]
        index_event_after = list_events[index_closest_before]

        # linear interpolation to find closest match
        percentage_closest = (datetime_window - datetime_before) / (
            datetime_after - datetime_before)
        index_event_closest = index_event_before + percentage_closest * (
            index_event_after - index_event_before)
        event_usage = self.sequence_usage[index_event_closest]

        # TODO: add extraction of usage for training

        return event_usage, event_training

    def refresh(self):
        while True:
            data, addr = self.sock.recvfrom(
                self.message_size)  # buffer size is 1024 bytes
            # data is a message with the structure:
            # message: TEMPS_CLOCK,INDEX
            # exemple: 2017-03-20 19:05:45.191179,42

            split_message = data.split(',')
            time_event = datetime.strptime(split_message[0],
                                           '%Y-%m-%d %H:%M:%S.%f')
            index_event = int(split_message[1])
            event = self.sequence_usage[index_event]

            # add event to a list
            self.add_event_synchronicity(time_event, event)