Ejemplo n.º 1
0
    def generate_naive_order(self, signal):
        """
        Simply files an Order object as a constant quantity
        sizing of the signal object, without risk management
        or position sizing considerations.
        """
        order = None

        symbol = signal.symbol
        datetime = signal.datetime
        direction = signal.signal_type
        strength = signal.strength
        price = signal.price

        lmt_quantity = 100
        cur_quantity = self.current_positions[symbol]
        order_type = 'LMT'

        if direction == 'LONG':
            order = OrderEvent(symbol, datetime, order_type, lmt_quantity,
                               price, 'BUY')
        if direction == 'EXIT':
            if cur_quantity < 100:
                print 'Current quantity: %s is smaller than 100.' \
                      % cur_quantity
                raise KeyError
            else:
                order = OrderEvent(symbol, datetime, order_type, cur_quantity,
                                   price, 'SELL')

        return order
    def generate_naive_order(self, signal):
        '''
        Generates an Order object (event?) with a constant quantity of shares to purchase

        Parameters:
        signal - A tuple containing the Signal information
        '''
        order = None

        symbol = signal.symbol
        direction = signal.signal_type
        strength = signal.strength

        mkt_quantity = 100
        cur_quantity = self.current_positions[symbol]
        order_type = 'MKT'

        # only buy if current hold 0 shares of the symbol
        if direction == 'LONG' and cur_quantity == 0:  # long stock
            order = OrderEvent(symbol, order_type, mkt_quantity, 'BUY')
        if direction == 'SHORT' and cur_quantity == 0:  # short stock
            order = OrderEvent(symbol, order_type, mkt_quantity, 'SELL')

        if direction == 'EXIT' and cur_quantity > 0:  # sell to close
            order = OrderEvent(symbol, order_type, abs(cur_quantity), 'SELL')
        if direction == 'EXIT' and cur_quantity < 0:  # buy to cover
            order = OrderEvent(symbol, order_type, abs(cur_quantity), 'BUY')

        return order
Ejemplo n.º 3
0
 def generate_naive_order(self, signal):
     """
     Simply files an Order object as a constant quantity
     sizing of the signal object, without risk management or
     position sizing considerations.
     Parameters:
     signal - The tuple containing Signal information.
     """
     order = None
     symbol = signal.symbol
     direction = signal.signal_type
     strength = signal.strength
     price = self.bars.latest_symbol_data[symbol][
         len(self.bars.latest_symbol_data[symbol]) - 1][1]['adj_close']
     mkt_quantity = (self.current_holdings['cash']) // price  # 100
     # TODO предыдущую строчку обязательно поменять, исходя из количества акций
     cur_quantity = self.current_positions[symbol]
     order_type = "MKT"
     if direction == "LONG" and cur_quantity == 0:
         order = OrderEvent(symbol, order_type, mkt_quantity, "BUY")
     if direction == "SHORT" and cur_quantity == 0:
         order = OrderEvent(symbol, order_type, mkt_quantity, "SELL")
     if direction == "EXIT" and cur_quantity > 0:
         order = OrderEvent(symbol, order_type, abs(cur_quantity), "SELL")
     if direction == "EXIT" and cur_quantity < 0:
         order = OrderEvent(symbol, order_type, abs(cur_quantity), "BUY")
     return order
    def generate_navie_order(self, signal):
        """
        Create OrderEvent using SignalEvent.

        :param signal: SignalEvent;  it's created in strategy.calculate_signals()

        :return: OrderEvent; use the attributes of SignalEvent to generate OrderEvent.
        """
        order = None

        symbol = signal.symbol
        direction = signal.signal_type
        strength = signal.strength

        mkt_quantity = 100
        cur_quantity = self.current_positions[symbol]
        order_type = 'MKT'

        if direction == 'LONG' and cur_quantity == 0:
            order = OrderEvent(symbol, order_type, mkt_quantity, 'BUY')
        if direction == 'SHORT' and cur_quantity == 0:
            order = OrderEvent(symbol, order_type, mkt_quantity, 'SELL')
        if direction == 'EXIT' and cur_quantity > 0:
            order = OrderEvent(symbol, order_type, abs(cur_quantity), 'SELL')
        if direction == 'EXIT' and cur_quantity < 0:
            order = OrderEvent(symbol, order_type, abs(cur_quantity), 'BUY')
        return order
Ejemplo n.º 5
0
    def generate_naive_order(self, signal):
        """
        Simply files an Order object as a constant quantity
        sizing of the signal object, without risk management or
        position sizing considerations.

        Parameters:
        signal - The tuple containing Signal information.
        """
        order = None

        symbol = signal.symbol
        direction = signal.signal_type
        strength = signal.strength

        mkt_quantity = 100
        cur_quantity = self.current_positions[symbol]
        order_type = 'MKT'

        if direction == 'LONG' and cur_quantity == 0:
            order = OrderEvent(symbol, order_type, mkt_quantity, 'BUY')
        if direction == 'SHORT' and cur_quantity == 0:
            order = OrderEvent(symbol, order_type, mkt_quantity, 'SELL')   
    
        if direction == 'EXIT' and cur_quantity > 0:
            order = OrderEvent(symbol, order_type, abs(cur_quantity), 'SELL')
        if direction == 'EXIT' and cur_quantity < 0:
            order = OrderEvent(symbol, order_type, abs(cur_quantity), 'BUY')
        return order
Ejemplo n.º 6
0
    def generate_order(self, signal: SignalEvent, order_type: str = 'market'):
        """

        :param signal:
        :param order_type:
        :return:
        """

        if order_type == 'market':

            cur_positions = self.current_positions[signal.symbol]

            if signal.signal_type == 'long' and cur_positions == 0:
                quantity = self.capital_allocation_to_position(signal)
                return OrderEvent(symbol=signal.symbol,
                                  order_type=order_type,
                                  quantity=quantity,
                                  direction='buy')
        # elif signal.signal_type == 'short' and cur_positions == 0:
        # return OrderEvent(symbol=signal.symbol, order_type=order_type, quantity=quantity, direction='sell')
            elif signal.signal_type == 'exit' and cur_positions > 0:
                return OrderEvent(symbol=signal.symbol,
                                  order_type=order_type,
                                  quantity=cur_positions,
                                  direction='sell')
        # elif signal.signal_type == 'exit' and cur_positions < 0:
        # return OrderEvent(symbol=signal.symbol, order_type=order_type, quantity=abs(cur_positions), direction='buy')
        else:
            pass
Ejemplo n.º 7
0
 def generate_naive_order(self,signal):
     """
     简单的生成一个订单对象,固定的数量,利用信号对象,没有风险管理
     或头寸调整的考虑
     """
     order=None
     
     symbol=signal.symbol
     direction=signal.signal_type
     strength=signal.strength
     
     mkt_quantity=100
     cur_quantity=self.current_positions[symbol]
     order_type='MKT'
     
     if direction=='LONG' and cur_quantity==0:
         order=OrderEvent(symbol,order_type,mkt_quantity,'BUY')
     if direction=='SHORT' and cur_quantity==0:
         order=OrderEvent(symbol,order_type,mkt_quantity,'SELL')
     if direction=='EXIT' and cur_quantity>0:
         order=OrderEvent(symbol,order_type,abs(cur_quantity),'SELL')
     if direction=='EXIT' and cur_quantity<0:
         order=OrderEvent(symbol,order_type,abs(cur_quantity),'BUY')
     
     return order
Ejemplo n.º 8
0
    def _generate_order(self, signal):
        """
        Based on the signal generated by the strategy, it creates an Order Event object with risk management and position sizing considerations.
        """
        order = None

        symbol = signal.symbol
        direction = signal.signal_type
        strength = signal.strength
        self.indicators = signal.indicators

        order_type = 'MKT'

        current_quantity = self.current_positions[symbol]
        fill_cost = self.data_handler.current_price(symbol)

        # Define the position sizing of the order.
        # TODO: kelly criterion
        position_size = self.current_holdings['cash'] * \
            self.pct_capital_risk * strength

        if direction == 'LONG' and current_quantity == 0:
            order_quantity = position_size / fill_cost
            order = OrderEvent(symbol, order_type, order_quantity, fill_cost,
                               'BUY')

        if direction == 'EXIT' and current_quantity > 0:
            order_quantity = current_quantity
            order = OrderEvent(symbol, order_type, order_quantity, fill_cost,
                               'SELL')

        return order
Ejemplo n.º 9
0
    def generate_naive_order(self, signal):
        """
        Simply transacts an OrderEvent object as a constant quantity
        sizing of the signal object, without risk mangement or
        position sizing considerations.
        :param signal: The SignalEvent signal information
        :return:
        """
        order = None

        symbol = signal.symbol
        direction = signal.signal_type
        strength = signal.strength

        mkt_quantity = floor(100 * strength)
        cur_quantity = self.current_positions[symbol]
        order_type = 'MKT'

        if direction == 'LONG' and cur_quantity == 0:
            order = OrderEvent(symbol, order_type, mkt_quantity, 'BUY')
        if direction == 'SHORT' and cur_quantity == 0:
            order = OrderEvent(symbol, order_type, mkt_quantity, 'SELL')

        if direction == 'EXIT' and cur_quantity > 0:
            order = OrderEvent(symbol, order_type, abs(cur_quantity), 'SELL')
        if direction == 'EXIT' and cur_quantity < 0:
            order = OrderEvent(symbol, order_type, abs(cur_quantity), 'BUY')
        return order
Ejemplo n.º 10
0
    def handle_signal(self, event):
        """
            event is a signal event
                datetime: 
                    timestamp of when signal was generated
                signal_type:
                    "BUY", "SELL" or "EXIT"
                symbol:
                    representation of company eg
                    "APPL"
                strength:
                    adjustment factor
            return order dict of
                quantity
                signal
        """
        mkt_quantity = 100
        cur_quantity = self.current_positions[event.symbol]

        if event.signal_type == "BUY":
            order = OrderEvent(symbol=event.symbol,
                               quantity=mkt_quantity,
                               direction="BUY")
            self.events.put(order)
        elif event.signal_type == "SELL":
            order = OrderEvent(symbol=event.symbol,
                               quantity=cur_quantity,
                               direction="SELL")
            self.events.put(order)
Ejemplo n.º 11
0
    def calculate_signals(self, event):
        if event.type == "MARKET":
            for symbol in self.symbol_list:
                bars = self.bars.get_latest_bars_values(
                    symbol, "close", self.look_back)
                if bars.shape[0] < self.look_back:
                    continue

                price = self.bars.get_latest_bar_value(symbol, "close")
                sma = bars.mean()
                if price > sma and self.bought[symbol] == 'OUT':
                    order = OrderEvent(symbol, 'ALLBUY')
                    self.events.put(order)
                    self.bought[symbol] = 'LONG'
                if price < sma and self.bought[symbol] == 'LONG':
                    order = OrderEvent(symbol, 'EXIT')
                    self.events.put(order)
                    self.bought[symbol] = 'OUT'

                # allow short
                if price < sma and self.bought[symbol] == 'OUT':
                    order = OrderEvent(symbol, 'ALLSELL')
                    self.events.put(order)
                    self.bought[symbol] = 'SHORT'
                if price > sma and self.bought[symbol] == 'SHORT':
                    order = OrderEvent(symbol, 'EXIT')
                    self.events.put(order)
                    self.bought[symbol] = 'OUT'
Ejemplo n.º 12
0
    def generate_naive_order(self, signal):
        """
        一个简单的买卖策略,按照固定数量买,全部持仓卖
        """
        order = None

        symbol = signal.symbol
        direction = signal.signal_type
        strength = signal.strength

        mkt_quantity = 10000
        cur_quantity = self.current_positions[symbol]
        order_type = 'MKT'

        # 按mkt_quantity买进,按全部卖出
        if direction == 'LONG' and cur_quantity == 0:
            order = OrderEvent(symbol, order_type, mkt_quantity, 'BUY')
        if direction == 'SHORT' and cur_quantity == 0:
            order = OrderEvent(symbol, order_type, mkt_quantity, 'SELL')

        if direction == 'EXIT' and cur_quantity > 0:
            order = OrderEvent(symbol, order_type, abs(cur_quantity), 'SELL')
        if direction == 'EXIT' and cur_quantity < 0:
            order = OrderEvent(symbol, order_type, abs(cur_quantity), 'BUY')
        return order
Ejemplo n.º 13
0
    def generate_naive_order(self, signal):
        """
        Simply fills an Order object as a constant quantity sizing of the signal object, without risk management or position sizing considerations. Will send order of 100 with market order.

        Parameters:
        signal - The tuple containing Signal information.
        """
        order = []
        init_order_date = signal.datetime
        symbol = signal.symbol
        direction = signal.signal_type
        strength = signal.strength

        mkt_quantity = signal.quantity
        cur_quantity = self.current_positions[symbol]
        order_type = 'MKT'

        if direction == 'LONG': # and cur_quantity == 0:
            order.append(OrderEvent(init_order_date, symbol, order_type, mkt_quantity, 'BUY'))
        if direction == 'SHORT' and cur_quantity == 0:
            order.append(OrderEvent(init_order_date, symbol, order_type, mkt_quantity, 'SELL'))

        if direction == 'EXIT' and cur_quantity > 0:
            order.append(OrderEvent(init_order_date, symbol, order_type, abs(cur_quantity), 'SELL'))
        if direction == 'EXIT' and cur_quantity < 0:
            order.append(OrderEvent(init_order_date, symbol, order_type, abs(cur_quantity), 'BUY'))

        return order
Ejemplo n.º 14
0
    def generate_naive_order(self, signal):
        """
            Parametri:
            signal - La tupla che contiene le informazioni del Sygnal
            """

        order = None

        symbol = signal.symbol
        direction = signal.signal_type
        strength = signal.strength

        mkt_quantity = 100
        cur_quantity = self.current_positions[symbol]
        order_type = 'MKT'
        spread = self.bars.get_latest_bar_value(
            symbol, "close") - self.bars.get_latest_bar_value(symbol, "bid")

        if direction == 'LONG' and cur_quantity == 0:
            order = OrderEvent(symbol, order_type, mkt_quantity, 'BUY', None)
        if direction == 'SHORT' and cur_quantity == 0:
            order = OrderEvent(symbol, order_type, mkt_quantity, 'SELL', None)

        if direction == 'EXIT' and cur_quantity > 0:
            order = OrderEvent(symbol, order_type, abs(cur_quantity), 'SELL',
                               spread)
        if direction == 'EXIT' and cur_quantity < 0:
            order = OrderEvent(symbol, order_type, abs(cur_quantity), 'BUY',
                               spread)

        return order
Ejemplo n.º 15
0
    def generate_naive_order(self, signal):
        """
        Simply transacts an OrderEvent object as a constant quantity
        sizing of the signal object, without risk management or
        position sizing considerations.

        Parameters:
        signal - The SignalEvent signal information.
        """
        order = None

        symbol = signal.symbol
        direction = signal.signal_type
        strength = signal.strength

        mkt_quantity = (0.5*self.current_holdings['cash']) / self.bars.get_latest_bars(symbol, N=1)[0][3]
        cur_quantity = self.current_positions[symbol]
        order_type = 'MKT'

        #if direction == 'LONG' and cur_quantity == 0:
        if direction == 'LONG':
            order = OrderEvent(symbol, order_type, mkt_quantity, 'BUY')
        #if direction == 'SHORT' and cur_quantity == 0:
        #    order = OrderEvent(symbol, order_type, mkt_quantity, 'SELL')   
        if direction == 'SHORT':
            order = OrderEvent(symbol, order_type, cur_quantity, 'SELL')
    
        if direction == 'EXIT' and cur_quantity > 0:
            order = OrderEvent(symbol, order_type, abs(cur_quantity), 'SELL')
        if direction == 'EXIT' and cur_quantity < 0:
            order = OrderEvent(symbol, order_type, abs(cur_quantity), 'BUY')
        return order
Ejemplo n.º 16
0
    def generate_equal_weighted_order(self, signal):
        """
        Simply files an Order object as a constant quantity
        sizing of the signal object, without risk management or
        position sizing considerations.

        Parameters:
        signal - The tuple containing Signal information.
        """
        order = None

        symbol = signal.symbol
        direction = signal.signal_type
        strength = signal.strength

        cash = self.current_holdings['cash']
        mkt_price = self.bars.get_latest_bar_value(symbol, "close")
        allocation = 100

        mkt_quantity = floor(allocation * strength)
        cur_quantity = self.current_positions[symbol]
        order_type = 'MKT'

        if direction == 'LONG' and cur_quantity == 0:
            order = OrderEvent(symbol, order_type, mkt_quantity, 'BUY')
        if direction == 'SHORT' and cur_quantity == 0:
            order = OrderEvent(symbol, order_type, mkt_quantity, 'SELL')

        if direction == 'EXIT' and cur_quantity > 0:
            order = OrderEvent(symbol, order_type, abs(cur_quantity), 'SELL')
        if direction == 'EXIT' and cur_quantity < 0:
            order = OrderEvent(symbol, order_type, abs(cur_quantity), 'BUY')
        return order
Ejemplo n.º 17
0
    def generate_down_order(self, signal):
        """
        According DownAndBuyStrategy to make order to generate the OrderEvent
        """
        order = None

        symbol = signal.symbol
        direction = signal.signal_type
        strength = signal.strength

        mkt_quantity = floor(100 * strength)
        cur_quantity = self.current_positions[symbol]
        order_type = 'MKT'
        price = signal.price
        datetime = signal.datetime
        if direction == 'LONG':

            order = OrderEvent(symbol, order_type, mkt_quantity, 'BUY', price,
                               datetime)
        if direction == 'SHORT':

            order = OrderEvent(symbol, order_type, mkt_quantity, 'SELL', price,
                               datetime)
        if direction == 'EXIT':

            order = OrderEvent(symbol, order_type, abs(cur_quantity), 'SELL',
                               price, datetime)
        if direction == 'EXIT':

            order = OrderEvent(symbol, order_type, abs(cur_quantity), 'BUY',
                               price, datetime)

        return order
Ejemplo n.º 18
0
    def generate_naive_order(self, signal):
        """

        :param signal: The tuple containing Signal information.
        :return:
        """

        order = None

        symbol = signal.symbol
        direction = signal.signal_type
        strength = signal.strength

        mkt_quantity = 100
        cur_quantity = self.current_positions[symbol]
        order_type = 'MKT'

        if direction == 'LONG' and cur_quantity == 0:
            order = OrderEvent(symbol, order_type, mkt_quantity, 'BUY')
        if direction == 'SHORT' and cur_quantity == 0:
            order = OrderEvent

        if direction == 'EXIT' and cur_quantity > 0:
            order = OrderEvent(symbol, order_type, abs(cur_quantity), 'SELL')
        if direction == 'EXIT' and cur_quantity < 0:
            order = OrderEvent(symbol, order_type, abs(cur_quantity), 'BUY')

        return order
Ejemplo n.º 19
0
    def generate_naive_order(self, signal):
        """
        Simply files an Order object as a constant quantity
        sizing of the signal object, without risk management or
        position sizing considerations.

        Parameters:
        signal - The tuple containing Signal information.
        """
        order = None

        symbol = signal.symbol
        direction = signal.signal_type
        strength = signal.strength

        mkt_quantity = floor(self.current_holdings['cash'] * 0.99 * (1 / len(self.symbol_list))
                             / (self.bars.get_latest_bar_value(symbol, "adj_close")))

        cur_quantity = self.current_positions[symbol]
        order_type = 'MKT'

        if direction == 'LONG' and cur_quantity == 0:
            order = OrderEvent(symbol, order_type, mkt_quantity, 'BUY')
        if direction == 'SHORT' and cur_quantity == 0:  # 卖空
            order = OrderEvent(symbol, order_type, mkt_quantity, 'SELL')

        if direction == 'EXIT' and cur_quantity > 0:
            order = OrderEvent(symbol, order_type, abs(cur_quantity), 'SELL')
        if direction == 'EXIT' and cur_quantity < 0:  # 平仓
            order = OrderEvent(symbol, order_type, abs(cur_quantity), 'BUY')
        return order
Ejemplo n.º 20
0
    def generate_naive_order(self, signal):
        order = None
        date_time = signal.date_time
        symbol = signal.symbol
        direction = signal.signal_type
        strength = signal.strength
        order_price = signal.order_price
        all_in_cash = self.current_holdings['cash']
        mkt_quantity = math.floor(all_in_cash / order_price)
        cur_quantity = self.current_positions[symbol]
        order_type = 'MKT'

        if direction == 'LONG' and cur_quantity == 0:
            order = OrderEvent(date_time, symbol, order_type, mkt_quantity,
                               'BUY', order_price, direction)
        if direction == 'SHORT' and cur_quantity == 0:
            order = OrderEvent(date_time, symbol, order_type, mkt_quantity,
                               'SELL', order_price, direction)
        if direction == 'EXIT' and cur_quantity > 0:
            order = OrderEvent(date_time, symbol, order_type,
                               abs(cur_quantity), 'SELL', order_price,
                               direction)
        if direction == 'EXIT' and cur_quantity < 0:
            order = OrderEvent(date_time, symbol, order_type,
                               abs(cur_quantity), 'BUY', order_price,
                               direction)

        return order
Ejemplo n.º 21
0
    def generate_naive_order(self, signal):
        """
        Simply files an Order object as a constant quantity sizing of the signal object,
        without risk management or position sizing considerations.
        :param signal: The tuple containing Signal information
        """
        order = None

        symbol = signal.symbol
        direction = signal.signal_type
        strength = signal.strength
        cur_price = signal.cur_price

        mkt_quantity = 1
        est_fill_cost = cur_price * mkt_quantity  #for Backtest & Slippage calc / slippage cost = fill_cost(HTS) - est_fill_cost
        cur_quantity = self.current_positions[symbol]
        order_type = 'MKT'  #추후 지정가 주문도 고려필요

        if direction == 'LONG' and cur_quantity == 0:
            order = OrderEvent(symbol, order_type, mkt_quantity, 'BUY',
                               est_fill_cost)
        if direction == 'SHORT' and cur_quantity == 0:
            order = OrderEvent(symbol, order_type, mkt_quantity, 'SELL',
                               est_fill_cost)

        if direction == 'EXIT' and cur_quantity > 0:
            order = OrderEvent(symbol, order_type, abs(cur_quantity), 'SELL',
                               est_fill_cost)
        if direction == 'EXIT' and cur_quantity < 0:
            order = OrderEvent(symbol, order_type, abs(cur_quantity), 'BUY',
                               est_fill_cost)
        return order
Ejemplo n.º 22
0
    def generate_naive_order(self, signal):
        """
        Simply files an Order object as a constant quantity
        sizing of the signal object, without risk management or
        position sizing considerations.

        Parameters:
        signal - The tuple containing Signal information.
        """
        order = None
        strength = signal.strength
        direction = signal.signal_type
        target = 0
        if direction == 'LONG':
            target = strength
        elif direction == 'SHORT':
            target = -strength
        symbol = signal.symbol
        
        mkt_quantity = target*self.all_holdings[-1]['total']/self.bars.get_latest_bar_value(symbol, "adj_close")
        cur_quantity = self.current_positions[symbol]
        order_type = 'MKT'
        # print(direction)
        if direction!= 'EXIT' and mkt_quantity>cur_quantity:
            order = OrderEvent(symbol, order_type, math.trunc(mkt_quantity-cur_quantity), 'BUY')
            
            # print(order)
        if direction!= 'EXIT' and mkt_quantity<=cur_quantity:
            order = OrderEvent(symbol, order_type, math.trunc(cur_quantity-mkt_quantity), 'SELL')   
        if direction == 'EXIT' and cur_quantity > 0:
            order = OrderEvent(symbol, order_type, abs(cur_quantity), 'SELL')
        if direction == 'EXIT' and cur_quantity < 0:
            order = OrderEvent(symbol, order_type, abs(cur_quantity), 'BUY')
        return order
Ejemplo n.º 23
0
    def generate_naive_order(self, signal):
        """
        生成订单,暂未考虑资金管理与头寸管理
        Parameters:
        signal - SignalEvent
        """

        order = None

        symbol = signal.symbol
        direction = signal.signal_type
        strength = signal.strength

        mkt_quantity = 10
        cur_quantity = self.current_positions[symbol]
        order_type = 'MKT'

        if direction == 'LONG' and cur_quantity == 0:
            order = OrderEvent(symbol, order_type, mkt_quantity, 'BUY')
        if direction == 'SHORT' and cur_quantity == 0:
            order = OrderEvent(symbol, order_type, mkt_quantity, 'SELL')

        if direction == 'EXIT' and cur_quantity > 0:
            order = OrderEvent(symbol, order_type, abs(cur_quantity), 'SELL')
        if direction == 'EXIT' and cur_quantity < 0:
            order = OrderEvent(symbol, order_type, abs(cur_quantity), 'BUY')

        return order
Ejemplo n.º 24
0
    def generate_naive_order(self, signal):
        order = None

        symbol = signal.symbol
        direction = signal.signal_type
        # strength = signal.strength

        # mkt_quantity = floor(100 * strength)
        mkt_quantity = 100
        cur_quantity = self.current_positions[symbol]
        order_type = 'MKT'

        if direction == 'LONG':
            order = OrderEvent(symbol, order_type, mkt_quantity, 'BUY')
        if direction == 'SHORT':
            order = OrderEvent(symbol, order_type, mkt_quantity, 'SELL')

        # if direction == 'LONG' and cur_quantity == 0:
        #     order = OrderEvent(symbol, order_type, mkt_quantity, 'BUY')
        # if direction == 'SHORT' and cur_quantity == 0:
        #    order = OrderEvent(symbol, order_type, mkt_quantity, 'SELL')

        if direction == 'EXIT' and cur_quantity > 0:
            order = OrderEvent(symbol, order_type, abs(cur_quantity), 'SELL')
        if direction == 'EXIT' and cur_quantity < 0:
            order = OrderEvent(symbol, order_type, abs(cur_quantity), 'BUY')

        return order
Ejemplo n.º 25
0
    def calc(self, instrument, X, spread):
        #        X=pd.read_hdf('EUR_USD__17-07-2019.h5')

        #        self.events = events
        #model = tf.keras.Sequential()
        #        model = tf.keras.models.load_model(self.modelName)

        X = X.df
        starter = self.model.get_input_shape_at(0)[1]
        print(len(X.index), starter)
        if len(X) >= starter:

            bid = X['Bid'][-starter:]
            ask = X['Ask'][-starter:]
            time = X.index[-starter:]
            #            spreadrec=ask-bid

            X = X.drop('Instrument', axis=1)
            '''data has to be preprocessed to get the time in the right format - could also calculate some addition
            financial parameters here, could package it another class'''

            X['Time_cos'] = np.cos(
                (X.index.hour * 60 * 60 * 1e06 + X.index.minute * 60 * 1e06 +
                 X.index.second * 1e-6 + X.index.microsecond) * 2 * np.pi /
                8.64e+10)
            X['Time_sin'] = np.sin(
                (X.index.hour * 60 * 60 * 1e06 + X.index.minute * 60 * 1e06 +
                 X.index.second * 1e-6 + X.index.microsecond) * 2 * np.pi /
                8.64e+10)
            X = np.asarray(X)
            X = X[-starter:]

            h5f = h5py.File(self.normName, 'r')
            datasets = list(h5f.keys())
            h5f = np.array(h5f.get(datasets[0]))
            X = X / h5f
            X = X.reshape(-1, 256, 5)
            result = self.model.predict(X)
            units = 1
            spreadmultiplierWin = 3
            spreadmultiplierStop = 2
            #            spread=spreadrec[-1

            print(result.argmax())
            if result.argmax() == 0:
                profitValueBuy = spreadmultiplierWin * spread + ask[-1]
                stopValueBuy = ask[-1] - spreadmultiplierStop * spread
                order = OrderEvent(instrument, units, "market", 'buy', bid[-1],
                                   ask[-1], time[-1], stopValueBuy,
                                   profitValueBuy)
                self.events.put((1, time[-1], order))

            if result.argmax() == 1:
                profitValueSell = bid[-1] - spreadmultiplierWin * spread
                stopValueSell = spreadmultiplierStop * spread + bid[-1]
                order = OrderEvent(instrument, units, "market", 'sell',
                                   bid[-1], ask[-1], time[-1], stopValueSell,
                                   profitValueSell)
                self.events.put((1, time[-1], order))
Ejemplo n.º 26
0
    def generate_trend_order(self, signal):
        """
        Simply transacts an OrderEvent object as a trading quantity
        sizing of the signal object, with risk management or
        position sizing considerations.

        Parameters:
        signal - The SignalEvent signal information.
        """
        order = None

        symbol = signal.symbol
        direction = signal.signal_type
        strength = signal.strength
        price = signal.price
        datetime = signal.datetime
        # TODO : above try to set datetime in signal or event

        # mkt_quantity = floor(strength)*100
        trade_quantity = floor(strength) * 100
        # cur_quantity = self.current_positions[symbol]
        cur_quantity = self.available_positions[symbol]
        order_type = 'MKT'
        # order_type = 'LMT'

        if direction == 'LONG':
            cash_paid = trade_quantity * price * 1.0003  # add fee
            if self.current_holdings["cash"] - cash_paid >= 0.0:
                order = OrderEvent(symbol, price, order_type, trade_quantity,
                                   'BUY', datetime)
            else:
                print "!!No Cash!! ==> current cash:", self.current_holdings[
                    "cash"]

        if direction == 'SHORT':
            if self.available_positions[symbol] - trade_quantity >= 0:
                order = OrderEvent(symbol, price, order_type, trade_quantity,
                                   'SELL', datetime)
            else:
                print "!!No Available !! ==> current pos:", self.available_positions[
                    symbol]
        # TODO: EXIT to sell out all of the holdings of symbol stock
        if direction == 'EXIT' and cur_quantity > 0:
            order = OrderEvent(symbol, price, order_type, abs(cur_quantity),
                               'SELL', datetime)
        #
        # if direction == 'LONG' and cur_quantity == 0:
        #     order = OrderEvent(symbol, order_type, mkt_quantity, 'BUY')
        # if direction == 'SHORT' and cur_quantity == 0:
        #     order = OrderEvent(symbol, order_type, mkt_quantity, 'SELL')
        #
        # if direction == 'EXIT' and cur_quantity > 0:
        #     order = OrderEvent(symbol, order_type, abs(cur_quantity), 'SELL')
        # if direction == 'EXIT' and cur_quantity < 0:
        #     order = OrderEvent(symbol, order_type, abs(cur_quantity), 'BUY')
        return order
Ejemplo n.º 27
0
 def calculate_signals(self, event):
     if event.type == "TICK":
         self.ticks += 1
         if self.ticks % 5 == 0:
             side = random.choice(["buy", "sell"])
             if side == "buy":
                 order = OrderEvent(self.instrument, self.units, "market",
                                    side)
             elif side == "sell":
                 order = OrderEvent(self.instrument, -self.units, "market",
                                    side)
             self.events.put(order)
    def generate_percentage_order(self, signal):
        '''
        Generates an OrderEvent with a constant percentage of shares to purchase

        Parameters:
        signal - A tuple containing the Signal information
        '''
        order = None

        symbol = signal.symbol
        direction = signal.signal_type
        strength = signal.strength

        current_price = self.bars.get_latest_bar_value(signal.symbol,
                                                       'Adj_Close')
        current_date = self.bars.get_latest_bar_datetime(signal.symbol).date()
        mkt_quantity = floor(
            (self.initial_capital * 0.05) / current_price)  #100
        cur_quantity = self.current_positions[symbol]
        order_type = 'MKT'

        # only buy if current hold 0 shares of the symbol
        if direction == 'LONG' and cur_quantity == 0:  # long stock
            order = OrderEvent(symbol, order_type, mkt_quantity, 'BUY')
            print(
                str(current_date) + ': Buying ' + str(mkt_quantity) + ' of ' +
                symbol + ' at ' + str(current_price))
            print('\n')
        if direction == 'SHORT' and cur_quantity == 0:  # short stock
            order = OrderEvent(symbol, order_type, mkt_quantity, 'SELL')
            print(
                str(current_date) + ': Shorting ' + str(mkt_quantity) +
                ' of ' + symbol + ' at ' + str(current_price))
            print('\n')

        if direction == 'EXIT' and cur_quantity > 0:  # sell to close
            order = OrderEvent(symbol, order_type, abs(cur_quantity), 'SELL')
            print(
                str(current_date) + ': Selling to close ' +
                str(abs(cur_quantity)) + ' of ' + symbol + ' at ' +
                str(current_price))
            print('\n')
        if direction == 'EXIT' and cur_quantity < 0:  # buy to cover
            order = OrderEvent(symbol, order_type, abs(cur_quantity), 'BUY')
            print(
                str(current_date) + ': Buying to cover ' +
                str(abs(cur_quantity)) + ' of ' + symbol + ' at ' +
                str(current_price))
            print('\n')

        return order
Ejemplo n.º 29
0
    def generate_naive_order(self, signal):
        """
        Simply files an Order object as a constant quantity sizing
        of the signal object, without risk management or position 
        sizing considerations. 
        
        This method takes a signal to go long or short an asset, 
        sending an order to do so for 100 shares of such an asset. 
        
        In realistic implementation, this value (100) will be determined
        by a risk management of position sizing overlay. 
        
        This method handles longing, shorting, and exiting of a position, 
        based on the current quantity and particular symbol. Corresponding
        OrderEvent objects are then generated.


        Parameters
        ----------
        signal : 'tuple'
            The tuple containing Signal information.

        Returns
        -------
        'Event'
            Returns an OrderEvent to be filled

        """

        order = None

        symbol = signal.symbol
        direction = signal.signal_type
        strength = signal.strength

        mkt_quantity = 100
        cur_quantity = self.current_positions[symbol]
        order_type = 'MKT'

        if direction == 'LONG' and cur_quantity == 0:
            order = OrderEvent(symbol, order_type, mkt_quantity, 'BUY')
        if direction == 'SHORT' and cur_quantity == 0:
            order = OrderEvent(symbol, order_type, mkt_quantity, 'SELL')

        if direction == 'EXIT' and cur_quantity > 0:
            order = OrderEvent(symbol, order_type, abs(cur_quantity), 'SELL')
        if direction == 'EXIT' and cur_quantity < 0:
            order = OrderEvent(symbol, order_type, abs(cur_quantity), 'BUY')

        return order
Ejemplo n.º 30
0
 def calculate_signals(self, event):
     if event.type == "MARKET":
         for symbol in self.symbol_list:
             dt = self.bars.get_latest_bar_datetime(symbol)
             if dt in self.gold_df.index:
                 gold_return = self.gold_df.ix[dt]['return']
                 if gold_return > 0 and self.bought[symbol] == 'OUT':
                     order = OrderEvent(symbol, "ALLBUY")
                     self.events.put(order)
                     self.bought[symbol] = "LONG"
                 if gold_return < 0 and self.bought[symbol] == 'LONG':
                     order = OrderEvent(symbol, "EXIT")
                     self.events.put(order)
                     self.bought[symbol] = "OUT"