def is_trade(context, data):
    i = 0
    for s in get_open_orders():
        for o in get_open_orders(s):
            if o.amount > 0:
                i += 1
    i = len(context.portfolio.positions) + i
    return False if i > 9 else True
Beispiel #2
0
def my_rebalance(context, data):
    BuyFactor = .99
    SellFactor = 1.01
    cash = context.portfolio.cash

    cancel_open_buy_orders(context, data)
    log.info("My Rebalance.")

    # Order sell at profit target in hope that somebody actually buys it
    open_orders = get_open_orders()
    for stock in context.portfolio.positions:
        print(stock.sid)
        print(get_open_orders(stock.sid))
        if stock in open_orders:
            pass
        else:
            print("no orders")
            StockShares = context.portfolio.positions[stock].amount
            CurrPrice = float(data.current([stock], 'price'))
            CostBasis = float(context.portfolio.positions[stock].cost_basis)
            SellPrice = float(make_div_by_05(CostBasis * SellFactor,
                                             buy=False))

            if np.isnan(SellPrice):
                log.info("My Rebalance: NaN")
                pass  # probably best to wait until nan goes away
            elif (stock in context.age and context.age[stock] == 0):
                log.info("My Rebalance: Age")
                pass
            elif (stock in context.age
                  and context.MyFireSaleAge <= context.age[stock]
                  and (context.MyFireSalePrice > CurrPrice
                       or CostBasis > CurrPrice)):
                log.info("My Rebalance: Losing")
                if (stock in context.age and context.age[stock] < 2):
                    pass
                elif stock not in context.age:
                    context.age[stock] = 1
                else:
                    SellPrice = float(
                        make_div_by_05(.95 * CurrPrice, buy=False))
                    order(stock, -StockShares, style=LimitOrder(SellPrice))
            else:
                if (stock in context.age and context.age[stock] < 1):
                    log.info("My Rebalance: too young")
                    pass
                elif stock not in context.age:
                    log.info("My Rebalance: no age")
                    context.age[stock] = 1
                else:
                    log.info("My Rebalance: Place order")
                    order(stock, -StockShares, style=LimitOrder(SellPrice))
Beispiel #3
0
def submit_sell(stock, context, data):
    if get_open_orders(stock):
        return

    # We bought a stock but don't know it's age yet
    if stock not in context.age:
        context.age[stock] = 0

    # Don't sell stuff that's less than 1 day old
    if stock in context.age and context.age[stock] < 1:
        return

    shares = context.portfolio.positions[stock].amount
    current_price = float(data.current([stock], 'price'))
    cost_basis = float(context.portfolio.positions[stock].cost_basis)

    if (context.age[stock] >= context.MyFireSaleAge
            and (current_price < context.MyFireSalePrice
                 or current_price < cost_basis)):
        log.info("%s is in fire sale!" % stock.symbol)
        sell_price = float(make_div_by_05(.95 * current_price, buy=False))

        order(stock, -shares, style=LimitOrder(sell_price))
    else:
        sell_price = float(
            make_div_by_05(cost_basis * context.sell_factor, buy=False))

        order(stock, -shares, style=LimitOrder(sell_price))
Beispiel #4
0
def submit_sell(stock, context, data):
    
    if get_open_orders(stock):
        return

    # We bought a stock but don't know it's age yet
    if stock not in context.age:
        context.age[stock] = 0

    # Don't sell stuff that's less than 1 day old
    if stock in context.age and context.age[stock] < 1:
        return

    shares = context.portfolio.positions[stock].amount
    current_price = float(data.current([stock], 'price'))
    two_week_price_history = data.history([stock], 'price', 10, '1d')
    average_two_week_price = float(two_week_price_history.mean())
    current_price = float(data.current([stock], 'price'))
    context.stocks = [ symbol('UGAZ'), symbol('DGAZ') ]

    if (context.age[stock] >= context.MyFireSaleAge and
            (current_price < float(0.8 * average_two_week_price))):
            log.info("First sell function is working!" % stock.symbol)
        
    if (context.age[stock] >= context.MyFireSaleAge and
            (current_price > average_two_week_price)):
            log.info("Second sell function is working!" % stock.symbol)

    order(context.stock, -shares)
def handle_data(context, data):
    if context.first_time is True:
        if len(context.portfolio.positions) > 0:
            sys.exit("Found positions not traded by the algorithm. Shutting down...")
        if len(get_open_orders()) > 0:
            sys.exit("Found open orders not traded by the algorithm. Shutting down...")
        context.first_time = False
Beispiel #6
0
def initialize (context): # runs once when script starts
    #context is a python dictionary that contains information on portfolio/performance.
    context.idr_losers = pd.Series(([]))
    context.day_count = 0
    context.daily_message = "Day {}."
    context.open_orders = get_open_orders()
    context.backup_stocks = symbols('VTI')

    #Factor criteria
    #dolvol = AverageDollarVolume(window_length = 1)
    close_price = USEquityPricing.close.latest
    vol = USEquityPricing.volume.latest
    ann_var = AnnualizedVolatility()
    #daily_return = DailyReturns([USEquityPricing.close], window_length = 2) #-- going to use history instead of pipeline
    
    #screening
    mask_custom = (IsPrimaryShare() & (vol < 200000) & (close_price > 1) & (close_price < 3) & (ann_var > 0.815)) # Q3000US(8000000) &
    stockBasket = USEquityPricing.close.latest.top(3000,  mask = mask_custom)
    
    #Column construction
    pipe_columns = {'close_price': close_price, "volume": vol, 'ann_var': ann_var}
    
    #Ceation of actual pipeline
    pipe = Pipeline(columns = pipe_columns, screen = stockBasket)
    attach_pipeline(pipe, "Stocks")

    #Schedule functions
    schedule_function(late_day_trade, date_rules.every_day(), time_rules.market_open(hours = 5, minutes = 56)) #offset open tells when to run a user defined function
    schedule_function(check_portfolio, date_rules.every_day(), time_rules.market_open(hours = 0, minutes = 1))
    schedule_function(morning_day_trade1, date_rules.every_day(), time_rules.market_open(hours = 0, minutes = 15))
    #schedule_function(check_portfolio, date_rules.every_day(), time_rules.market_open(hours = 0, minutes = 16))
    schedule_function(morning_day_trade2, date_rules.every_day(), time_rules.market_open(hours = 0, minutes = 45))
Beispiel #7
0
def check_order_status(context, data):

    """Logs any open orders every 10 minutes."""

    open_orders = get_open_orders()
    if open_orders:
        LOG.info('Open Orders: {}'.format(open_orders))
Beispiel #8
0
def closeAnyOpenOrders(stock):
    orders = get_open_orders(stock)
    if orders:
        for order in orders:
            message = 'Canceling order for {amount} shares in {stock}'
            message = message.format(amount=order.amount, stock=stock)
            #log.debug(message)
            cancel_order(order)
def log_open_orders():
    oo = get_open_orders()
    if len(oo) == 0:
        return
    for stock, orders in oo.items():
        for o in orders:
            message = 'Found open order for {amount} shares in {stock}'
            log.info(message.format(amount=o.amount, stock=stock))
def cancel_open_orders(context, data):
    oo = get_open_orders()
    if len(oo) == 0:
        return
    for stock, orders in oo.items():
        for o in orders:
            log.info("Canceling order of {} shares in {}", o.amount, stock)
            cancel_order(o)
Beispiel #11
0
def my_rebalance(context, data):
    log.info("my_rebalance")
    BuyFactor = .99
    SellFactor = 1.01
    cash = context.portfolio.cash
    log.info(cash)
    cancel_open_buy_orders(context, data)

    # Order sell at profit target in hope that somebody actually buys it
    for stock in context.portfolio.positions:
        if not get_open_orders(stock):
            StockShares = context.portfolio.positions[stock].amount
            CurrPrice = float(data.current([stock], 'price'))
            CostBasis = float(context.portfolio.positions[stock].cost_basis)
            SellPrice = float(make_div_by_05(CostBasis * SellFactor,
                                             buy=False))

            if np.isnan(SellPrice):
                pass  # probably best to wait until nan goes away
            elif (stock in context.age and context.age[stock] == 1):
                pass
            elif (stock in context.age
                  and context.MyFireSaleAge <= context.age[stock]
                  and (context.MyFireSalePrice > CurrPrice
                       or CostBasis > CurrPrice)):
                if (stock in context.age and context.age[stock] < 2):
                    pass
                elif stock not in context.age:
                    context.age[stock] = 1
                else:
                    SellPrice = float(
                        make_div_by_05(.95 * CurrPrice, buy=False))
                    order(stock, -StockShares, style=LimitOrder(SellPrice))
            else:
                if (stock in context.age and context.age[stock] < 2):
                    pass
                elif stock not in context.age:
                    context.age[stock] = 1
                else:

                    order(stock, -StockShares, style=LimitOrder(SellPrice))

    WeightThisBuyOrder = float(1.00 / context.MaxBuyOrdersAtOnce)
    for ThisBuyOrder in range(context.MaxBuyOrdersAtOnce):
        stock = next(context.MyCandidate)
        PH = data.history([stock], 'price', 20, '1d')
        PH_Avg = float(PH.mean())
        CurrPrice = float(data.current([stock], 'price'))
        if np.isnan(CurrPrice):
            pass  # probably best to wait until nan goes away
        else:
            if CurrPrice > float(1.25 * PH_Avg):
                BuyPrice = float(CurrPrice)
            else:
                BuyPrice = float(CurrPrice * BuyFactor)
            BuyPrice = float(make_div_by_05(BuyPrice, buy=True))
            StockShares = int(WeightThisBuyOrder * cash / BuyPrice)
            order(stock, StockShares, style=LimitOrder(BuyPrice))
def cancel_open_orders(context, data):
    oo = get_open_orders()
    if len(oo) == 0:
        return
    for stock, orders in oo.items():
        for o in orders:
            # message = 'Canceling order of {amount} shares in {stock}'
            # log.info(message.format(amount=o.amount, stock=stock))
            cancel_order(o)
Beispiel #13
0
def hasOrders(stock):
    hasOrders = False
    orders = get_open_orders(stock)
    if orders:
        for order in orders:
            message = 'Open order for {amount} shares in {stock}'
            message = message.format(amount=order.amount, stock=stock)
            log.info(message)
            hasOrders = True
    return hasOrders
Beispiel #14
0
def handle_data(context, data):
    today = get_datetime().floor('1D')
    last_date = getattr(context, 'last_ran_buy', None)
    if today != last_date:
        my_rebalance(context, data)
        context.last_ran_buy = today
    else:
        for stock, position in context.portfolio.positions.items():
            if get_open_orders(stock):
                continue

            current_price = data.current(stock, 'price')
            cost_basis = position.cost_basis
            stop_loss = -0.05
            current_loss = (current_price - cost_basis) / cost_basis

            if current_loss < stop_loss:
                log.info('selling early %s (%.2f)' % (stock.symbol, current_loss))
                order_target_percent(stock, 0)
def initialize (context): # runs once when script starts
    log.info("Welcome Vincent Perkins")
    #context is a python dictionary that contains information on portfolio/performance.
    context.idr_losers = pd.Series(([])) #intraday losing stocks
    context.day_count = 0
    context.daily_message = "Day {}."
    context.open_orders = get_open_orders()
    context.backup_stocks = symbols('BAM')
    context.age = {} #empty dictionary maps one value to another
    #context.usep = USEquityPricing() #USEquityPricing object

    #Factor criteria
    close_price = USEquityPricing.close.latest
    vol = USEquityPricing.volume.latest
    ann_var = AnnualizedVolatility()
    rsi = RSI()

    #screening
    mask_custom = (IsPrimaryShare() & (vol < 150000) & (close_price > 1) & (close_price < 3) & (ann_var > 0.815) & (rsi < 50))
    stockBasket = USEquityPricing.close.latest.top(3000,  mask = mask_custom)
    
    #Column construction
    pipe_columns = {'close_price': close_price, 'volume': vol, 'ann_var': ann_var}
    
    #Creation of actual pipeline
    pipe = Pipeline(columns = pipe_columns, screen = stockBasket)
    attach_pipeline(pipe, 'Stocks')
    #Testing
    log.info(USEquityPricing.get_loader())
    eng = LivePipelineEngine(list_symbols)
    df = eng.run_pipeline(pipe)
    log.info(df)

    #Schedule functions
    schedule_function(day_start, date_rules.every_day(), time_rules.market_open(hours = 0, minutes = 1))
    schedule_function(late_day_trade, date_rules.every_day(), time_rules.market_open(hours = 5, minutes = 56)) #offset open tells when to run a user defined function
    schedule_function(check_portfolio, date_rules.every_day(), time_rules.market_open(hours = 0, minutes = 1))
    schedule_function(morning_day_trade1, date_rules.every_day(), time_rules.market_open(hours = 0, minutes = 15))
    schedule_function(morning_day_trade2, date_rules.every_day(), time_rules.market_open(hours = 0, minutes = 45))
    schedule_function(check_portfolio, date_rules.every_day(), time_rules.market_open(hours = 0, minutes = 48))
    schedule_function(cancel_open_orders, date_rules.every_day(),time_rules.market_close(hours=0, minutes=1))
Beispiel #16
0
def submit_buy(stock, context, data, weight):
    
    cash = min(investment_limits(context)['remaining_to_invest'], context.portfolio.cash)

    two_week_price_history = data.history([stock], 'price', 10, '1d')
    one_week_price_history = data.history([stock], 'price', 5, '1d')
    average_two_week_price = float(two_week_price_history.mean())
    average_one_week_price = float(one_week_price_history.mean())
    current_price = float(data.current([stock], 'price'))
    
    context.stock = [ symbol('UGAZ'), symbol('DGAZ') ]
    

    if np.isnan(current_price):
            pass  # probably best to wait until nan goes away
            
    if current_price >= float(1.1 * average_two_week_price): # if the price is 10% greater than or equal to the 10d avg
            buy_price = float(current_price)
            
    if current_price >= float(1.15 * average_two_week_price): # if the price is 15% above the 10d avg
            buy_price = float(current_price)
            
    if current_price < float(0.95 * average_one_week_price): # if the price is 5% below the 5d avg
            buy_price = float(current_price)
            

            
    else:
            buy_price = float(current_price * context.buy_factor)
            shares_to_buy = int(weight * cash / buy_price)


            # This cancels open sales that would prevent these buys from being submitted if running
            # up against the PDT rule
            open_orders = get_open_orders()
            if stock in open_orders:
                for open_order in open_orders[stock]:
                    cancel_order(open_order)

    order(context.stock, shares_to_buy)
Beispiel #17
0
def submit_buy(stock, context, data, weight):
    cash = min(
        investment_limits(context)['remaining_to_invest'],
        context.portfolio.cash)

    price_history = data.history([stock], 'price', 20, '1d')
    average_price = float(price_history.mean())
    current_price = float(data.current([stock], 'price'))

    if np.isnan(current_price):
        pass  # probably best to wait until nan goes away
    else:
        if current_price > float(
                1.25 * average_price):  # if the price is 25% above the 20d avg
            buy_price = float(current_price)
        else:  # Otherwise buy at a discount
            buy_price = float(current_price * context.buy_factor)
        buy_price = float(make_div_by_05(buy_price, buy=True))
        shares_to_buy = int(weight * cash / buy_price)
        max_exposure = int(weight * context.portfolio.portfolio_value /
                           buy_price)

        # Prevent over exposing to a particular stock, never own more than 1/max_buy_orders
        # of our account value
        positions = context.portfolio.positions
        if stock in positions and positions[stock].amount >= max_exposure:
            return

        # This cancels open sales that would prevent these buys from being submitted if running
        # up against the PDT rule
        open_orders = get_open_orders()
        if stock in open_orders:
            for open_order in open_orders[stock]:
                cancel_order(open_order)

        order(stock, shares_to_buy, style=LimitOrder(buy_price))
def cancel_open_orders(context, data):
    for s in get_open_orders():
        for o in get_open_orders(s):
            cancel_order(o)
Beispiel #19
0
def check_order_status(context, data):
    open_orders = get_open_orders()
    if open_orders:
        log.info('Open Orders: {}'.format(open_orders))
def cancel_all_orders(context, data):
    for _stock, orders in get_open_orders().items():
        for pending_order in orders:
            cancel_order(pending_order)
Beispiel #21
0
def place_sells(context, data):
    SellFactor = 1.1
    cash = context.portfolio.cash
    open_orders = get_open_orders()    
    place_sell_orders = 1
    
    # exit if we have open sell orders
    if len(open_orders) != 0:
        for stock, orders in open_orders.items():
            for o in orders:
                if 0 > o.amount:  # it is a sell order
                    place_sell_orders = 0

    if place_sell_orders == 1:
        log.info("Place sells") 
        # Order sell at profit target in hope that somebody actually buys it
        for stock in context.portfolio.positions:                  
            if stock in open_orders:
                pass
            else:
                StockShares = context.portfolio.positions[stock].amount
                CurrPrice = float(data.current([stock], 'price'))
                CostBasis = float(context.portfolio.positions[stock].cost_basis)
                SellPrice = float(
                    make_div_by_05(
                        CostBasis *
                        SellFactor,
                        buy=False))            
                print(stock)      
                print(StockShares)  


                if np.isnan(SellPrice):
                    pass  # probably best to wait until nan goes away
                elif (stock in context.age and context.age[stock] < 1):
                    print("age < 1.0")
                    pass
                elif (
                    stock in context.age
                    and context.MyFireSaleAge <= context.age[stock]
                    and (
                        context.MyFireSalePrice > CurrPrice
                        or CostBasis > CurrPrice
                    )
                ):
                    if (stock in context.age and context.age[stock] < 1):
                        print("age < 1.1")
                        pass
                    elif stock not in context.age:
                        print("age = 1")                                        
                        context.age[stock] = 1
                    else:
                        print("sell loss")
                        SellPrice = float(
                            make_div_by_05(.95 * CurrPrice, buy=False))
                        order(stock, -StockShares,
                              style=LimitOrder(SellPrice)
                              )
                else:
                    if (stock in context.age and context.age[stock] < 1):
                        print("age < 1")
                        pass
                    elif stock not in context.age:
                        print("age = 0")
                        context.age[stock] = 1
                    else:
                        print("sell win")
                        order(stock, -StockShares,
                              style=LimitOrder(SellPrice)
                              )