Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Stop loss in gap strategy

Hi everyone,

I am trying to build a simple algo that would buy when the market make a gap up of more than 3% but I have some trouble to implement a stop loss.

Any idea ?

Thanks
Chris

import numpy as np  
import pandas as pd

def initialize(context):  
    set_universe(universe.DollarVolumeUniverse(floor_percentile=95.0, ceiling_percentile=100.0))  
    context.stop_price = 0  
    context.stop_pct = 0.99  
    schedule_function(  
        func=market_open,  
        date_rule=date_rules.every_day(),  
        time_rule=time_rules.market_open(hours=0, minutes=5),  
        half_days=True)  
    schedule_function(  
        func=close_all_positions,  
        date_rule=date_rules.every_day(),  
        time_rule=time_rules.market_close(hours=0, minutes=5),  
        half_days=True)  
    # Set execution cost assumptions. For live trading with Interactive Brokers  
    # we will assume a $1.00 minimum per trade fee, with a per share cost of $0.0075.  
    set_commission(commission.PerShare(cost=0.0075, min_trade_cost=1.00))  
    # Set market impact assumptions. We limit the simulation to  
    # trade up to 2.5% of the traded volume for any one minute,  
    # and  our price impact constant is 0.1.  
    set_slippage(slippage.VolumeShareSlippage(volume_limit=0.025, price_impact=0.10))

def market_open(context, data):  
    for stock in data:  
        price_history = history(bar_count=5, frequency='1d', field='price')  
        #close_2_day_ago = price_history[data.stock][-3] # close two days ago  
        close_yesterday = price_history[stock][-2] # close of yesterday  
        open_today = price_history[stock][-1]  
        cash = context.portfolio.cash  
        nb_of_shares = int(cash / open_today)  
        #target_shares = cash / stock.price  
        gap_percent = (open_today / close_yesterday - 1)  
        #log.info('Percent change {}'.format(gap_percent))  
### ENTRY ###  
        if gap_percent > 0.03 and len(get_open_orders()) == 0:  
            order(stock, nb_of_shares)  
            log.info('Bought {} shares of {}'.format(nb_of_shares, stock.symbol))


def handle_data(context, data):  
    set_stop_loss(context, data)  
    if data[context.stock].price < context.stop_price:  
        order_target(context.stock, 0)  


def set_stop_loss(context, data):  
    if context.portfolio.positions[context.stock].amount:  
        price = data[context.stock].price  
        context.stop_price = context.stop_pct * price  


def close_all_positions(context, data):  
    for stock in data:  
        current_positions = context.portfolio.positions  
        if current_positions != 0:  
            order_target_percent(stock, 0)  
            log.info('cover before the close of the day')

4 responses

Any idea how to add a stop loss to this simple strategy ?

One thing you could do would be to place a stop order as soon as you purchase a stock, then keep that order open.

Here's an excerpt from the API:

stop order: Call order(security, amount, style=StopOrder(price)) to place a stop order (also known as a stop-loss order). When the specified price is hit, the order converts into a market order.  
Disclaimer

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.

Simple but powerful.
I think that I was looking for something too complex.

Thank you Lotanna.

nice. make sure to cancel the order if you close your position yourselves