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.