def trade(context, data, wts):
    lev = context.LEV  #Should allow for a small percentage of Cash, to enable ordering fluctuations without having order cancelled.

    ### ajjc: Find a way to return if already traded today
    print("TradingLinkData: Zipline-broker: context.portfolio : {}".format(
        context.portfolio))
    print("TradingLinkData: IB-Account    : context.account   : {}".format(
        context.account))
    acct_liq = context.portfolio.starting_cash  #Same as IB net_liquidation
    acct_invest = lev * acct_liq
    positions = context.portfolio.positions
    #Live positions      = context.broker.positions

    # Get rid of positions not in wts
    for key in positions:
        if (key not in wts and not get_open_orders(key)):
            order(key, -positions[key].amount)

    for stk, weight in wts.items():
        if data.can_trade(stk) and not get_open_orders(stk):
            if stk in positions:
                current_amt = positions[stk].amount
                rebalance_amt = int(acct_invest * (weight) /
                                    data.current(stk, 'price'))
                delta_amt = rebalance_amt - current_amt
                if delta_amt != 0:
                    order(stk, delta_amt)
                else:
                    print("No new orders for : {}".format(stk))

            if (stk not in positions and data.can_trade(stk)
                    and not get_open_orders(stk)):

                amt = int(acct_invest * (weight) / data.current(stk, 'price'))
                order(stk, amt)
Exemple #2
0
def trade(context,data):
    lev = 0.9 #Should allow for a small percentage of Cash, to enable ordering fluctuations without having order cancelled.
    stocks = context.stocks
    num_stocks = context.num_stocks
    ### ajjc: Find a way to return if already traded today
    print("TradingLinkData: Zipline-broker: context.portfolio : {}".format(context.portfolio))
    print("TradingLinkData: IB-Account    : context.account   : {}".format(context.account))
    acct_liq    = context.portfolio.starting_cash #Same as IB net_liquidation
    acct_invest = lev * acct_liq   
    positions      = context.broker.positions   
    
    for key in positions:
        if (key not in stocks and key != context.bonds and not get_open_orders(key)):
            order(key, -positions[key].amount)      
        
    for i in range(len(stocks)):
        if data.can_trade(stocks[i]) and not get_open_orders(stocks[i]) and stocks[i] != context.bonds:
            
            if stocks[i] in positions:
                
                current_amt = positions[stocks[i]].amount
                rebalance_amt = int(acct_invest*(1/num_stocks) / data.current(stocks[i],'price'))
                delta_amt = rebalance_amt - current_amt
                
                if delta_amt != 0:
                    order(stocks[i], delta_amt) 
                else:
                    print("No new orders for : {}".format(stocks[i]))
            
            if (stocks[i] not in positions and data.can_trade(stocks[i]) 
                and not get_open_orders(stocks[i]) and stocks[i] != context.bonds):
                
                amt = int(acct_invest*(1/context.num_stocks) / data.current(stocks[i],'price'))
                order(stocks[i], amt)                                                
        
        if data.can_trade(stocks[i]) and not get_open_orders(stocks[i]) and stocks[i] == context.bonds: 
            
            rebalance_amt = int(acct_invest*(1-(1/context.num_stocks)*(len(stocks)-1)) / data.current(stocks[i],'price'))
            
            if stocks[i] in positions:  
                
                current_amt = positions[stocks[i]].amount
                delta_amt = rebalance_amt - current_amt
                
                if delta_amt != 0:
                    order(stocks[i], delta_amt)
                else:
                    print("No new orders for : {}".format(stocks[i]))    
            else:
                
                if rebalance_amt > 0:
                    order(stocks[i], rebalance_amt)
Exemple #3
0
def handle_data(context, data):

    slowma = data.history(symbol("BTC"), fields='price', bar_count=50, frequency='1m').mean()
    fastma = data.history(symbol("BTC"), fields='price', bar_count=10, frequency='1m').mean()

    if fastma < slowma:
        if symbol("BTC") not in get_open_orders():
            order_target_percent(symbol("BTC"), 0.04)

    if fastma > slowma:
        if symbol("BTC") not in get_open_orders():
            order_target_percent(symbol("BTC"), 0.96)

    record(BTC=data.current(symbol('BTC'), fields='price'))
Exemple #4
0
def cancel_open_orders_and_clear_non_universe_positions(context):
    from zipline.api import get_open_orders, order

    for security in get_open_orders():
        for order in get_open_orders(security):
            cancel_order(order)
            print('Security {} had open orders: now cancelled'.format(str(security)))
            
    positions      = context.broker.positions
    
    # Get rid of positions not in current universe
    for key in positions:
        if (key not in context.universe and not get_open_orders(key)):
            print('Dump {}: Shares: {}'.format(key,-positions[key].amount))
            order(key, -positions[key].amount)      
Exemple #5
0
def cancel_orders_eod(context, data):
    """
    Cancel all open orders at the end of the day. We do it manually, to store
    the canceled orders and resubmit them a day later at market open.

    See also zipline.finance.blotter.simulation_blotter.SimulationBlotter.execute_cancel_policy

    To apply, use:
        schedule_function(cancel_orders_eod, date_rules.every_day(), time_rules.market_close())
    """
    # Delete the previous stored orders

    # Store all orders that have been canceled to resubmit them later
    if not hasattr(context, 'canceled_orders'):
        context.canceled_orders = {}
    else:
        context.canceled_orders.clear()

    for security, open_orders in list(get_open_orders().items()):
        for order in open_orders:
            if order.sid in context.canceled_orders:
                context.canceled_orders[order.sid] += order.amount - order.filled
            else:
                context.canceled_orders[order.sid] = order.amount - order.filled

            cancel_order(order)
def my_func(context, data):
    # Order 100 shares of AAPL.
    # order_target(context.asset, 1000)

    close = data.current(context.asset, "close")
    uplimit = data.current(context.asset, "up_limit") / 1000

    # print(context.asset, "价格限制", 'close', close, 'uplimit', uplimit)

    if (close >= uplimit):
        print(context.asset, "价格限制", 'close', close, 'uplimit', uplimit)
    else:
        order(context.asset, 1000)
    # Retrieve all open orders.

    open_orders = get_open_orders()

    # If there are any open orders.
    if open_orders:
        # open_orders is a dictionary keyed by sid, with values that are lists of orders. Iterate over the dictionary
        for security, orders in open_orders.items():
            # Iterate over the orders and log the total open amount
            # for each order.
            for oo in orders:
                message = 'Open order for {amount} shares in {stock}'
                message = message.format(amount=oo.amount, stock=security)
                log.info(message)

    record(AAPL=data.current(context.asset, 'price'))
Exemple #7
0
def show_positions (context, data):

    if context.order_placed == True :

        print ('\n{}'.format(get_datetime().date()))

        print ('\nPOSITIONS\n\n')
        for asset in context.stocks : 
            if context.portfolio.positions[asset].amount > 0 :
                print ( '{0} : QTY = {1}, COST BASIS {2:3.2f}, CASH = {3:7.2f}, POSITIONS VALUE = {4:7.2f}, TOTAL = {5:7.2f}'
                       .format(asset, context.portfolio.positions[asset].amount,
                               context.portfolio.positions[asset].cost_basis,
                               context.portfolio.cash, 
                               context.portfolio.positions[asset].amount * data[asset].price,
                               context.portfolio.portfolio_value))

        # retrieve all the open orders and log the total open amount  
        # for each order  
        open_orders = get_open_orders()  
        # open_orders is a dictionary keyed by sid, with values that are lists of orders.  
        if open_orders:  
            # iterate over the dictionary  
            for security, orders in open_orders.iteritems():  
                # iterate over the orders  
                for oo in orders:  
                    message = '\nOutstanding open order for {amount} shares in {stock}'  
                    message = message.format(amount=oo.amount, stock=security)  
                    print(message)
            return
        else:
            # wait until all orders filled before resetting this flag
            context.order_placed = False
    return
Exemple #8
0
    def stop_loss(context, data):

        prices = data.history(list(context.portfolio.positions), 'price',
                              context.lookback, '1d')

        for s in context.portfolio.positions:

            if s not in context.weights or context.weights[s] == 0:
                context.shares[s] = 0
                continue

            if s not in prices or s in get_open_orders():
                continue

            gain = get_gain(context, s)

            if context.portfolio.positions[s].amount > 0 and drawdown(
                    prices[s].values) > context.drawdown[s]:
                context.weights[s] = 0
                context.shares[s] = 0  # stop loss

                ws.send(msg_placeholder % (
                    'Exited from long because of stop loss with change of %+2d%% for %s,'
                    % (gain * 100, str(s))))

            elif context.portfolio.positions[s].amount < 0 and drawdown(
                    -prices[s].values) > context.drawdown[s]:
                context.weights[s] = 0
                context.shares[s] = 0

                ws.send(msg_placeholder % (
                    'Exited from short because of stop loss with change of %+2d%% for %s,'
                    % (gain * 100, str(s))))
Exemple #9
0
def end_of_day(context, data):
    # cancle any order at the end of day. Do it ourselves so we can see slow moving stocks.
    open_orders = get_open_orders()
    
    if open_orders or context.portfolio.positions_value > 0.:
        #log.info("")
        print("*** EOD: Stoping Orders & Printing Held ***")

    # Print what positions we are holding overnight
    for stock in data:
        if context.portfolio.positions[stock].amount != 0:
            print("{0:s} has remaining {1:,d} Positions worth ${2:,.2f}"\
                     .format(stock,
                             context.portfolio.positions[stock].amount,
                             context.portfolio.positions[stock].cost_basis\
                             *context.portfolio.positions[stock].amount))
    # Cancle any open orders ourselves(In live trading this would be done for us, soon in backtest too)
    if open_orders:  
        # Cancle any open orders ourselves(In live trading this would be done for us, soon in backtest too)
        for security, orders in open_orders.iteritems():
            for oo in orders:
                print("X CANCLED {0:s} with {1:,d} / {2:,d} filled"\
                                     .format(stock,
                                             oo.filled,
                                             oo.amount))
                cancel_order(oo)
Exemple #10
0
def handle_data(context, data):
    # Skip first 200 days to get full windows
    context.i += 1
    if context.i < 200:
        return
    # Compute averages
    short_mavg = data.history(context.asset, 'price',
                              bar_count=50, frequency="1d").mean()
    long_mavg = data.history(context.asset, 'price',
                             bar_count=200, frequency="1d").mean()

    # Trading logic
    open_orders = get_open_orders()

    if context.asset not in open_orders:
        if short_mavg > long_mavg:
            # order_target orders as many shares as needed to
                        # achieve the desired number of shares.
            order_target_percent(context.asset, 1.0)
        elif short_mavg < long_mavg:
            order_target_percent(context.asset, 0.0)

    # Save values for later inspection
    record(AAPL=data.current(context.asset, 'price'),
           short_mavg=short_mavg, long_mavg=long_mavg)
def handle_data(context, data):
    context.i += 1
    avg_days = 20
    if context.i < avg_days:
        record(data=data, context=context)
        return
    short_mavg = data.history(context.asset,
                              'price',
                              bar_count=avg_days,
                              frequency="1d")
    Mean = short_mavg.mean()
    Std = short_mavg.std()
    bollinger_high = Mean + Std * 2
    bollinger_low = Mean - Std * 2

    curr_price = data.history(context.asset,
                              'price',
                              bar_count=1,
                              frequency="1d").mean()
    open_orders = get_open_orders()

    if context.asset not in open_orders:
        if curr_price > bollinger_high:
            order(context.asset, -1)  #-1 indicates selling 1 stock
        elif curr_price < bollinger_low:
            order(context.asset, 1)
    record(price=data.current(symbol(stock), 'price'),
           short_mavg=short_mavg,
           data=data,
           context=context)
Exemple #12
0
def has_orders(context, data):
    # Return true if there are pending orders.
    has_orders = False
    for stock in data:
        orders = get_open_orders(stock)
        if orders:
            return True
Exemple #13
0
def has_orders(context, data):
	# Return true if there are pending orders.
	has_orders = False
	for stock in data:
		orders = get_open_orders(stock)
		if orders:
			return True
Exemple #14
0
def end_of_day(context, data):
    # cancle any order at the end of day. Do it ourselves so we can see slow moving stocks.
    open_orders = get_open_orders()

    if open_orders or context.portfolio.positions_value > 0.:
        #log.info("")
        print("*** EOD: Stoping Orders & Printing Held ***")

    # Print what positions we are holding overnight
    for stock in data:
        if context.portfolio.positions[stock].amount != 0:
            print("{0:s} has remaining {1:,d} Positions worth ${2:,.2f}"\
                     .format(stock,
                             context.portfolio.positions[stock].amount,
                             context.portfolio.positions[stock].cost_basis\
                             *context.portfolio.positions[stock].amount))
    # Cancle any open orders ourselves(In live trading this would be done for us, soon in backtest too)
    if open_orders:
        # Cancle any open orders ourselves(In live trading this would be done for us, soon in backtest too)
        for security, orders in open_orders.iteritems():
            for oo in orders:
                print("X CANCLED {0:s} with {1:,d} / {2:,d} filled"\
                                     .format(stock,
                                             oo.filled,
                                             oo.amount))
                cancel_order(oo)
Exemple #15
0
def cte_mix_handle(context, data):
    weights = {'a1': 0.33, 'a2': 0.33, 'a3': 0.33}

    for key, sym in context.assets.items():
        open_orders = get_open_orders()
        if sym not in open_orders:
            order_target_percent(sym, weights[key])

    record(leverage=context.account.leverage)
    def trading_logic(self, context, data):
        try:
            if self.kf is None:
                self.initialize_filters(context, data)
                return
            self.update(context, data)
            if get_open_orders(self._x) or get_open_orders(self._y):
                return
            spreads = self.mean_spread()

            zscore = (spreads[-1] - spreads.mean()) / spreads.std()

            reference_pos = context.portfolio.positions[self._y].amount

            now = get_datetime()
            if reference_pos:
                if (now - self.entry_dt).days > 20:
                    order_target(self._y, 0.0)
                    order_target(self._x, 0.0)
                    return
                # Do a PNL check to make sure a reversion at least covered trading costs
                # I do this because parameter drift often causes trades to be exited
                # before the original spread has become profitable.
                pnl = self.get_pnl(context, data)
                if zscore > -0.0 and reference_pos > 0 and pnl > 0:
                    order_target(self._y, 0.0)
                    order_target(self._x, 0.0)

                elif zscore < 0.0 and reference_pos < 0 and pnl > 0:
                    order_target(self._y, 0.0)
                    order_target(self._x, 0.0)

            else:
                if zscore > 1.5:
                    order_target_percent(self._y, -self.leverage / 2.)
                    order_target_percent(self._x, self.leverage / 2.)
                    self.entry_dt = now
                if zscore < -1.5:
                    order_target_percent(self._y, self.leverage / 2.)
                    order_target_percent(self._x, -self.leverage / 2.)
                    self.entry_dt = now
        except Exception as e:
            # log.debug("[{}] {}".format(self.name, str(e)))
            print(e)
Exemple #17
0
    def execute_transactions(context, data):
        open_orders = get_open_orders()

        for s in context.shares:
            if not data.can_trade(s) or s in open_orders:
                continue

            pct_shares = context.shares[s]

            order_target_percent(s, pct_shares)
def handle_data(context, data):
    c = context
    for position in c.portfolio.positions.itervalues():
        if position.amount == 0:
            if position.asset.symbol in c.stops:
                del c.stops[position.asset.symbol]
            continue
        elif position.asset.symbol not in c.stops:
            stoploss = c.stoploss if position.amount > 0 else -c.stoploss
            c.stops[position.asset.symbol] = position.last_sale_price * (
                1 - stoploss)
            # log.info(' ! I have added '+str(position.asset.symbol)+' to Stops @ '+str((position.last_sale_price)*(1-stoploss)))
        elif c.stops[
                position.asset.
                symbol] > position.last_sale_price and position.amount > 0:
            # sell
            log.info(' ! ' + str(position.asset.symbol) +
                     '- (Long) has hit stoploss @ ' +
                     str(position.last_sale_price))
            if not get_open_orders(position.sid):
                order_target_value(position.sid, 0.0)
                c.stoppedout.append(position.asset.symbol)
                del c.stops[position.asset.symbol]
        elif c.stops[
                position.asset.
                symbol] < position.last_sale_price and position.amount < 0:
            # sell
            log.info(' ! ' + str(position.asset.symbol) +
                     '- (Short) has hit stoploss @ ' +
                     str(position.last_sale_price))
            if not get_open_orders(position.sid):
                order_target_value(position.sid, 0.0)
                c.stoppedout.append(position.asset.symbol)
                del c.stops[position.asset.symbol]
        elif c.stops[position.asset.symbol] < position.last_sale_price * (
                1 - c.stoploss) and position.amount > 0:
            c.stops[position.asset.symbol] = position.last_sale_price * (
                1 - c.stoploss)
            # log.info(' ! I have updated '+str(position.asset.symbol)+'- (Long) to stop @ '+str((position.last_sale_price)*(1- c.stoploss)))
        elif c.stops[position.asset.symbol] > position.last_sale_price * (
                1 + c.stoploss) and position.amount < 0:
            c.stops[position.asset.symbol] = position.last_sale_price * (
                1 + c.stoploss)
def cancel_all_open_orders(context, data, asset=None):
    '''
        Cancel all open orders on a particular assets, or all if asset is None.
    '''
    if asset:
        open_orders = get_open_orders(asset)
    else:
        open_orders = get_open_orders()

    try:
        iter(open_orders)
    except:
        open_orders = [open_orders]

    if open_orders:
        for asset in open_orders:
            if context.params['verbose']:
                print('cancelling order on {}'.format(asset.symbol))
            cancel_order(asset)
Exemple #20
0
def rebalance(context, data):

    pipeline_data = context.pipeline_data

    # Sort by P/B ratio
    assets_by_pb_ratio = pipeline_data.sort_values('pb_ratio', ascending=True)

    # Remove nulls
    assets_by_pb_ratio = assets_by_pb_ratio.loc[
        assets_by_pb_ratio.pb_ratio.notnull()]

    # If we don't have enough data for a complete portfolio, do nothing
    if len(assets_by_pb_ratio) < 6:
        return

    longs = assets_by_pb_ratio.index[:3]
    shorts = assets_by_pb_ratio.index[-3:]

    # Build a 1x-leveraged, equal-weight, long-short portfolio.
    allocation_per_asset = 1.0 / 6.0
    for asset in longs:
        for order in get_open_orders(asset):
            cancel_order(order)
        order_target_percent(asset, allocation_per_asset)

    for asset in shorts:
        for order in get_open_orders(asset):
            cancel_order(order)
        order_target_percent(asset, -allocation_per_asset)

    # Remove any assets that should no longer be in our portfolio.
    portfolio_assets = longs | shorts
    positions = context.portfolio.positions
    exit_positions = set(positions) - set(portfolio_assets)

    record(num_positions=len(positions))

    for asset in exit_positions:
        for order in get_open_orders(asset):
            cancel_order(order)

        order_target_percent(asset, 0)
Exemple #21
0
def check_if_no_conflicting_orders(stock):
    # Check that we are not already trying to move this stock
    open_orders = get_open_orders()
    safeToMove  = True
    if open_orders:
        for security, orders in open_orders.iteritems():
            for oo in orders:
                if oo.sid == stock:
                    if oo.amount != 0:
                        safeToMove = False
    return safeToMove
def buy_and_hold(context, data):
    weights = {'a1': 0.33, 'a2': 0.33, 'a3': 0.33}

    if not context.has_ordered:
        for key, sym in context.assets.items():
            open_orders = get_open_orders()
            if sym not in open_orders:
                order_target_percent(sym, weights[key])
        context.has_ordered = True

    record(leverage=context.account.leverage)
Exemple #23
0
def check_if_no_conflicting_orders(stock):
    # Check that we are not already trying to move this stock
    open_orders = get_open_orders()
    safeToMove = True
    if open_orders:
        for security, orders in open_orders.iteritems():
            for oo in orders:
                if oo.sid == stock:
                    if oo.amount != 0:
                        safeToMove = False
    return safeToMove
def trade(context, data):
    stocks = [symbol('QQQ'), symbol('XLP'), symbol('IEF'), symbol('TLT')]
    proportion = [0.25, 0.25, 0.25, 0.25]
    lev = 0.9  #Should allow for a small percentage of Cash, to enable ordering fluctuations without having order cancelled.

    ### ajjc: Find a way to return if already traded today
    print("TradingLinkData: Zipline-broker: context.portfolio : {}".format(
        context.portfolio))
    print("TradingLinkData: IB-Account    : context.account   : {}".format(
        context.account))

    acct_liq = context.portfolio.starting_cash  #Same as IB net_liquidation
    acct_invest = lev * acct_liq
    positions = context.broker.positions

    # Sell any existing positions which are not in stocks
    for key in positions:
        if (key not in stocks and not get_open_orders(key)):
            order(key, -positions[key].amount)

    # Loop through stocks and deal with the list according to whether there are existing positions or not
    for i in range(len(stocks)):
        if data.can_trade(stocks[i]) and not get_open_orders(stocks[i]):
            # If there is a position already in this stock, then rebalance it if necessary in accordance with proportion
            if stocks[i] in positions:
                current_amt = positions[stocks[i]].amount
                rebalance_amt = int(acct_invest * proportion[i] /
                                    data.current(stocks[i], 'price'))
                delta_amt = rebalance_amt - current_amt
                if delta_amt != 0:
                    order(stocks[i], delta_amt)
                else:
                    print("No new orders for : {}".format(stocks[i]))
            # If there is no existing position in the stock, take one
            if (stocks[i] not in positions and data.can_trade(stocks[i])
                    and not get_open_orders(stocks[i])):
                amt = int(acct_invest * proportion[i] /
                          data.current(stocks[i], 'price'))
                if amt != 0:
                    order(stocks[i], amt)
def handle_data(context, data):

    # Skip first 200 periods to get full windows
    context.i += 1
    if context.i < 200:
        return

    # Calculate moving averages
    short_mavg = data.history(context.fut, 'price', 50, '1m').mean()
    long_mavg = data.history(context.fut, 'price', 200, '1m').mean()

    # Enter the long position
    if short_mavg > long_mavg and not context.invested:

        fut_contract = data.current(context.fut, 'contract')

        # cancel open orders for contract, if any
        for order in get_open_orders(fut_contract):
            cancel_order(order)

        order_target_percent(fut_contract, 1)
        context.invested = True

    # Exit the long position
    elif short_mavg < long_mavg and context.invested:

        # cancel any open orders
        for order in get_open_orders():
            cancel_order(order)

        positions = context.portfolio.positions
        for asset in positions:
            order_target_percent(asset, 0)

        context.invested = False

    # Save values for later inspection
    record(current_price=data.current(context.fut, "price"),
           short_mavg=short_mavg,
           long_mavg=long_mavg)
def rebalance(context, data):

    # Pipeline data will be a dataframe with integer columns named 'deciles'
    pipeline_data = context.pipeline_data
    all_assets = pipeline_data.index

    longs = all_assets[pipeline_data.deciles >= 10 - TOP_N_DECILES]
    shorts = all_assets[pipeline_data.deciles < TOP_N_DECILES]

    universe_size = len(all_assets)
    positions_per_side = universe_size * TOP_N_DECILES / 10
    position_size = 0.5 / positions_per_side

    record(universe_size=universe_size,
           positions_per_side=positions_per_side,
           position_size=position_size)

    # Build a 1x-leveraged, equal-weight, long-short portfolio.
    for asset in longs:
        for order in get_open_orders(asset):
            cancel_order(order)
        order_target_percent(asset, position_size)

    for asset in shorts:
        for order in get_open_orders(asset):
            cancel_order(order)
        order_target_percent(asset, -position_size)

    # Remove any assets that should no longer be in our portfolio.
    portfolio_assets = longs | shorts
    positions = context.portfolio.positions
    for asset in set(positions) - set(portfolio_assets):

        for order in get_open_orders(asset):
            cancel_order(order)

        if data.can_trade(asset):
            order_target_percent(asset, 0)
Exemple #27
0
def value_of_open_orders(context, data):
    # Current cash commited to open orders, bit of an estimation for logging only
    context.currentCash = context.portfolio.cash
    open_orders = get_open_orders()
    context.cashCommitedToBuy  = 0.0
    context.cashCommitedToSell = 0.0
    if open_orders:
        for security, orders in open_orders.iteritems():
            for oo in orders:
                # Estimate value of existing order with current price, best to use order conditons?
                if(oo.amount>0):
                    context.cashCommitedToBuy  += oo.amount * data[oo.sid]['price']
                elif(oo.amount<0):
                    context.cashCommitedToSell += oo.amount * data[oo.sid]['price']
Exemple #28
0
def ma_crossover(context, data):
    weight = 1.0 / len(context.assets)
    for sym in context.assets.values():
        hist = data.history(sym, 'price', context.long_period, '1d')
        sma_long = hist.mean()
        sma_short = hist[(-1) * context.short_period:].mean()
        open_orders = get_open_orders()
        if sma_long < sma_short:
            if sym not in open_orders:
                order_target_percent(sym, weight)
        elif sma_long > sma_short:
            if sym not in open_orders:
                order_target_percent(sym, -weight)

    record(leverage=context.account.leverage)
Exemple #29
0
def handle_data(context, data):

    bar_days = 500  # number of previous prices

    # create list of each ticker for last 300 days price
    history = [
        data.history(ticker, 'price', bar_days, '1d')
        for ticker in context.tickers
    ]

    ma_crossovers = [
        indicators.ma_crossover(history[i])
        for i in range(len(context.tickers))
    ]
    # macds = [indicators.ma_convergence_divergence(history[i]) for i in range(len(context.tickers))]
    # rsis = [indicators.relative_strength_index(history[i]) for i in range(len(context.tickers))]
    '''longs = [1 if ma_crossovers[i] > 0 and macds[i] > 0 else 0 for i in range(len(context.tickers))]
    shorts = [1 if ma_crossovers[i] < 0 and macds[i] < 0 else 0 for i in range(len(context.tickers))]

    buys = [1 if longs[i] > 0 and rsis[i] < 30 and ticker not in context.portfolio.positions.keys() else 0 for i, ticker in enumerate(context.tickers)]
    sells = [1 if shorts[i] > 0 and rsis[i] > 70 and ticker not in context.portfolio.positions.keys() else 0 for i, ticker in enumerate(context.tickers)]'''

    # TESTING INDIVIDUAL INDICATORS
    longs = [
        1 if ma_crossovers[i] > 0 else 0 for i in range(len(context.tickers))
    ]
    shorts = [
        1 if ma_crossovers[i] < 0 else 0 for i in range(len(context.tickers))
    ]
    buys = longs
    sells = shorts

    neutral_tickers = [
        ticker for i, ticker in enumerate(context.tickers) if not longs[i]
        and not shorts[i] and ticker in context.portfolio.positions.keys()
    ]

    num_buys = sum(buys)
    num_sells = sum(sells)
    num_neu = len(neutral_tickers)
    num_pos = len(context.portfolio.positions.keys())

    if len(neutral_tickers) > 0:
        neutralize(neutral_tickers)

    elif sum(buys) > 0 or sum(sells) > 0 and len(get_open_orders()) == 0:
        order_optimal_portfolio(history, buys, sells, context.portfolio.cash,
                                context)
Exemple #30
0
def value_of_open_orders(context, data):
    # Current cash commited to open orders, bit of an estimation for logging only
    context.currentCash = context.portfolio.cash
    open_orders = get_open_orders()
    context.cashCommitedToBuy = 0.0
    context.cashCommitedToSell = 0.0
    if open_orders:
        for security, orders in open_orders.iteritems():
            for oo in orders:
                # Estimate value of existing order with current price, best to use order conditons?
                if (oo.amount > 0):
                    context.cashCommitedToBuy += oo.amount * data[
                        oo.sid]['price']
                elif (oo.amount < 0):
                    context.cashCommitedToSell += oo.amount * data[
                        oo.sid]['price']
Exemple #31
0
def ma_crossover_handling(context, data):
    hist = data.history(context.aapl, 'price', 50, '1d')
    print(hist.head())
    sma_50 = hist.mean()
    sma_20 = hist[-20:].mean

    open_orders = get_open_orders(
    )  # patikrina ar nera jau esanciu rinkoje pavedimu

    if sma_20 > sma_50:
        if context.aapl not in open_orders:
            order_target_percent(context.aapl, 1.0)
    elif sma_50 > sma_20:
        if context.aapl not in open_orders:
            order_target_percent(context.aapl, -1.0)

    record(leverage=context.account.leverage)
def rebalance(context,data):
    # Get the last N days of prices for every stock in our universe.
    prices = history(context.returns_lookback, '1d', 'price')

    # Calculate the past 5 days' returns for each security.
    returns = (prices.iloc[-1] - prices.iloc[0]) / prices.iloc[0]

    # Remove stocks with missing prices.
    # Remove any stocks we ordered last time that still have open orders.
    # Get the cutoff return percentiles for the long and short portfolios.
    returns = returns.dropna()
    open_orders = get_open_orders()
    if open_orders:
        eligible_secs = [sec for sec in data if sec not in open_orders]
        returns = returns[eligible_secs]

    # Lower percentile is the threshhold for the bottom 20%, upper percentile is for the top 20%.
    lower, upper = np.percentile(returns, [context.lower_percentile,
                                           context.upper_percentile])

    # Select the X% worst performing securities to go long.
    long_secs = returns[returns <= lower]

    # Select the Y% best performing securities to short.
    short_secs = returns[returns >= upper]

    # Set the allocations to even weights in each portfolio.
    long_weight = context.long_leverage / len(long_secs)
    short_weight = context.short_leverage / len(short_secs)

    for security in data:

        # Buy/rebalance securities in the long leg of our portfolio.
        if security in long_secs:
            order_target_percent(security, long_weight)

        # Sell/rebalance securities in the short leg of our portfolio.
        elif security in short_secs:
            order_target_percent(security, short_weight)

        # Close any positions that fell out of the list of securities to long or short.
        else:
            order_target(security, 0)

    log.info("This week's longs: "+", ".join([long_.symbol for long_ in long_secs.index]))
    log.info("This week's shorts: "  +", ".join([short_.symbol for short_ in short_secs.index]))
Exemple #33
0
def rebalance(context, data):
    # Pipeline data will be a dataframe with boolean columns named 'longs' and
    # 'shorts'.
    pipeline_data = context.pipeline_data
    all_assets = pipeline_data.index

    record(universe_size=len(all_assets))

    # Build a 2x-leveraged, equal-weight, long-short portfolio.

    cash = context.portfolio.cash / len(all_assets)

    if cash < 0:
        return

    for asset in all_assets:
        close = data.current(asset, "close")
        uplimit = data.current(asset, "up_limit") / 1000

        if (close >= uplimit):
            print(asset, "价格限制", 'close', close, 'uplimit', uplimit)
        else:
            order_value(asset, cash)

    open_orders = get_open_orders()

    # If there are any open orders.
    if open_orders:
        # open_orders is a dictionary keyed by sid, with values that are lists of orders. Iterate over the dictionary
        for security, orders in open_orders.items():
            # Iterate over the orders and log the total open amount
            # for each order.
            for oo in orders:
                message = 'Open order for {amount} shares in {stock}'
                message = message.format(amount=oo.amount, stock=security)
                log.info(message)

    # Remove any assets that should no longer be in our portfolio.
    positions = context.portfolio.positions
    for asset in viewkeys(positions) - set(all_assets):
        # This will fail if the asset was removed from our portfolio because it
        # was delisted.
        if data.can_trade(asset):
            order(asset, -positions[asset].amount)
Exemple #34
0
def bonds(context, data):
    logger.debug('buying bonds on: %s', algo.get_datetime())
    logger.debug('num open orders: %s', len(algo.get_open_orders()))
    logger.debug('len existing portfolio (afer ejection): %s',
                 len(context.portfolio.positions))
    logger.debug('cash: %s', context.portfolio.cash)
    logger.debug('portfolio_value: %s', context.portfolio.portfolio_value)
    logger.debug('num_positions: %s', len(context.portfolio.positions))
    logger.debug('positions: %s', context.portfolio.positions)

    if logger.level is logging.DEBUG:
        for equity, values in context.portfolio.positions.items():
            logger.debug(
                'context.portfolio.positions - equity: %s, amount: %s, cost_basis: %s, sold_on: %s, sold_at_price: %s',
                equity, values.amount, values.cost_basis,
                values.last_sale_date, values.last_sale_price)

    if context.portfolio.cash > 0 and context.trend_filter is False:
        logger.debug('converting all cash to bonds')
        order_target_value(algo.sid('FIBBG000NTFYM5'), context.portfolio.cash)
Exemple #35
0
def before_trading_start(context, data):
    """
    Runs once a day, before trading start
    :param context: The common namespace
    :param data:
    :return:
    """
    context.output = pipeline_output('data_pipe')

    context.cap_plays = context.output.sort_values([
        'marketcap'
    ])[-4000:]  # take top 4000 stocks by market cap for liquidity

    context.longs = rays_long_short_strategy_helpers.get_longs(
        context.cap_plays)

    context.shorts = rays_long_short_strategy_helpers.get_shorts(
        context.cap_plays)

    record(open_orders=str(get_open_orders()))
Exemple #36
0
def trade(context, positions, stops):
    """
    Execute trades.
    """
    existing_positions = list(context.portfolio.positions.keys())
    if not context.rebalance:
        trades = context.target_portfolio
    trades = positions.append(stops)
    orders = get_open_orders()
    for asset, target in trades.items():

        if not context.rebalance:
            if asset in existing_positions:
                # don't trade in existing positions unless it's stop loss
                # i.e. don't adjust position size for changes in volatility
                if target != 0:
                    continue

        if asset not in orders:
            # don't issue new orders if existing orders haven't been filled
            order_target_percent(asset, target)