Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Basic Trailing Stop Implementation

Description

Here's a pretty simple trailing stop implementation with for a basic trend following style system. The system definitely works better on daily bars, but I don't think we have the options to do a full backtest on daily data yet (hint hint).

Implementation

The implementation is pretty simplistic and is modification of the previous MA cross algorithm. This version does some risk management in the form of position sizing, and scales the width of the trailing stop based on the standard deviation of the last 30 minutes.

Bugs

I love how simple and intuitive the API is, but I found some pretty big bugs with the API in creating this algorithm:

  • You can't use variables as parameters to the mavg() or stdev() functions. You will end up with errors like these if you try it:
KeyError: __mavg_30  
File wrapper.py:68, in stream_results  
for event in self.zipline:  
File /zipline/lines.py:116, in next  
return self.gen.next()  
File /zipline/gens/tradesimulation.py:105, in simulate  
for message in performance_messages:  
File /zipline/gens/tradesimulation.py:275, in transform  
self.simulate_snapshot(date)  
File /zipline/gens/tradesimulation.py:299, in simulate_snapshot  
self.algo.handle_data(self.universe)  
File algoproxy.py:396, in handle_data  
self.ns['handle_data'](data, self.algo_context)  
File test_algorithm_sycheck.py:82, in handle_data  
File algoproxy.py:366, in _transform  
return self.transform(sid, tnfm, event, *args, **kwargs)  
File algoproxy.py:427, in transform  
t_hash = self.transform_visitor.get_hash(t_name)  
File transformvisitor.py:202, in get_hash  
return self.transforms[name].get_hash()  
  • Sometimes positions.amount() will return zero, even if you are in a position. I've added error logging for this case in the algorithm.

  • Not really a bug, but it would be nice to be able to close an entire open position with a single function.

1 response

Hello Kyle! Thanks for the post! You've got some great stuff here.

The fact that you can't put a variable into the window of mavg() and stdev() is more by design than a bug, but that error message is ugly. We need to respond more gracefully than that; I'll get that fixed.

The reason we don't have a variable window yet is related to our architecture. We create all the moving averages (and other transforms) in a dataframe at the start of the backtest, and then move those frames going forward. We don't permit the frame to be modified with new transforms. That said, I'm hoping we can get what you want anyway:

  • You can create up to 10 transforms at the start of your algorithm. So, for instance, if you want a 1, 2, 5, 10, and 25 day moving average and standard dev, you can just create them all at the beginning.
  • In the next few weeks we're going to permit you to create and access dataframes yourself, and you'll be able to do whatever you want to them!
  • Our roadmap also includes parameter optimization. When we push that out, you'll be able to optimize your algorithm's moving average window.

The positions.amount being zero is a bug that we're actively working on. I hope/expect it to be fixed later this week.

Noted on the "close position" feature request. That's a good one, and I put it on the list to get built.

I'll leave the implementation for someone else to comment on your actual code.

Thanks,

Dan

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.