Book: Website: This is my attempt at a faithful recreation of his system.
Sometimes it dips into margin a little, I haven't isolated why. Also, due credit to Ted, who shared another implementation here: https:// (and James Christopher who says he's done one too).
def can_buy(context, data): latest = data[context.spy].close_price h = history(200,'1d','close_price') avg = h[context.spy].mean() return latest avg # This function is for adding new positions, by iterating through the # eligible stocks in order of momentum, and buying them if we have (anticipate # having) enough cash to do so.
def add_positions(context, data, cash_available): s = "" for i in range(0,len(context.pool)): sid = index[i] if ((sid not in context.portfolio.positions) & (sid in data)): desired_shares = desired_position_size_in_shares(context, data, sid) cash_req = desired_shares * data[sid].close_price if ((cash_req Top 10 long positions of all time (and max%) [u' BTU' u' BBD' u' AGN' u' OIBR' u' TII' u' GENZ' u' AGNC' u' DELL' u' KMP' u' CAG'] [ 0.525 0.159 0.149 0.147 0.141 0.14 0.129 0.124 0.124 0.123] This means BTU gets up to 52.5% of the portfolio.
The ATR of is calculated using closing prices, which were around -60 in the 20 days leading up to the calculation date of 2007-12-05.
This means the algorithm correctly calculates it must purchase 50 shares, worth around 00.
As an example: A stock is trading at 0, and has a 2:1 split.Position sizing is critical to the success of this (and most algorithms), and ATR position sizing is pretty common. Since ATR isn't used in te actual pre-universe screening, only for actual position sizing, it would be simplest to just calculate ATR on data from 'history()' and use that to determine position sizes.I'll do that when I have time, or of course anyone else is welcome to.I'm having trouble debugging the ATR Custom Factor, as I'm not sure how to slice into the arrays using the index columns to get the window of prices for BTU.class ATR(Custom Factor): [...] btu_sid = symbol(' BTU')def compute(self, today, assets, out, close, high, low): btu_idx = assets.get_loc(btu_sid) close[btu_idx] # use me like this to get BTU prices [...] Our [quantopian's] data uses adjusted close prices.