Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
trailing stop loss runtime error

can anyone help figure out this run-time error i get in line 62? its under Def_Handle. The line with the code toward the bottom.

set_trailing_stop(context, data):

I think its close to working right but I cant figure out this last bit of my trailing stop loss function, thanks!
here is the code:

def initialize(context):
log.info(str(get_datetime("US/Eastern")) + ": initializing algorithm")
context.stock = sid(8554) # SPY
context.ETF = sid(42477), sid(42470) # ugaz and dgaz
set_benchmark(context.stock) # comparing against SPY
context.stop_price = 0
context.stop_pct = 0.99

schedule_function(check_condition,  
                  date_rules.every_day(),  
                  time_rules.market_open(minutes=15),  
                  half_days=True)  

schedule_function(sell,  
                  date_rules.every_day(),  
                  time_rules.market_open(minutes=345),  
                  half_days=True)

def check_condition(context, data):
global ugaz_OP
global ugaz_CP
price = history(bar_count=1, frequency='1m',
field='open_price').loc[14]

for UGAZ in context.ETF:  
    ugaz_OP = price[UGAZ][-14] #[-14] pulls price 14min ago  
    ugaz_CP = price[UGAZ][-1]  #[-1] pulls the price 1min ago  

if ugaz_CP - ugaz_OP > 0:  
    log.info(str(get_datetime("US/Eastern")) + " bought UGAZ 15min")  
    order_value(sid(42477), 5000,  
                style=MarketOrder(exchange=IBExchange.IEX))  
elif ugaz_CP - ugaz_OP < 0:  
    log.info(str(get_datetime("US/Eastern")) + " bought DGAZ 15min")  
    order_value(sid(42470), 5000,  
                style=MarketOrder(exchange=IBExchange.IEX))  

def sell(context, data):
if context.portfolio.positions[sid(42477)].amount:
log.info(str(get_datetime("US/Eastern")) + ": selling UGAZ 45min")
order_target(sid(42477), 0,
style=MarketOrder(exchange=IBExchange.IEX))
if context.portfolio.positions[sid(42470)].amount:
log.info(str(get_datetime("US/Eastern")) + ": selling DGAZ 45min")
order_target(sid(42470), 0,
style=MarketOrder(exchange=IBExchange.IEX))

def handle_data(context, data):
for ETF in context.ETF:
set_trailing_stop(context, data):
if data[context].price < context.stop_price:
order_target(context.ETF, 0)
context.stop_price = 0

def set_trailing_stop(context, data):
for ETF in context.ETF:
if context.portfolio.positions[context.ETF].amount > 0:
price = data[context.ETF].price
context.stop_price = max(context.stop_price, context.stop_pct * price)

        record(price=data[context.ETF].price,stop=context.stop_price)  
4 responses

That error is getting thrown because set_trailing_stop(context, data) is a method. It can't be evaluated as a condition, such as ' set_trailing_stop(context, data):'

Could you explain what you're trying to do? Perhaps we can help get you on the right track.

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.

ok, I think I understand that as an error.

I have been trying to get a trailing stop loss to work for a few weeks now and I just cant seem to iron out the errors in it.

All I am trying to do is select which ETF is up in price at 9:45am, buy that ETF and implement a trailing stop loss of 1%.

Am I making some kind of more global error here?

  1. Remove the colon at the end of set_trailing_stop(context, data):. This is not a conditional statement with a missing if, just a simple function call.
  2. If you want to trade two (or more) assets, why are you using one stop price for both? What if you were trading SPY (yesterday's close price $208.53) and VXX ($18.68) - would $206.44 be OK? You should have an array (or dictionary) of stop prices, one element per asset.
  3. You say you want to "select which ETF is up in price at 9:45am" - are you assuming they can't all be up?
  4. With no whitespace at the beginning of each line, it's hard to see the indentation structure you intended. Figure out how to use the "attach backtest" feature in following posts.

Trailing stops are actually quite difficult to do robustly, I haven't found a method that I like. In particular, you want a trailing stop to be based on dividend-adjusted prices, which we do not have access to except in pipeline, and split-adjusted, which means you can't just store yesterday's stop price in the context.

I have in the past asked for new data in the position object, two dates for the positions first entry and most recent modification, but they say it's tough to add. Those would help immensely with writing robust trailing stops that do not require fragile state in context.