Qingwei,
I don't typically post, but seems like you're fairly interested in learning so I took a look at your code really quick..
A few notes:
(1)
"When trading, the the number of units (shares) of the unit portfolio i should own is set to be the negative Z-Score."
Your code:
num_units = -(price - ref[0]) / ref[1]
gld_positions = - num_units * ref[2]
uso_positions = num_units
order(context.gld, gld_positions * 100)
order(context.uso, uso_positions * 100)
Suppose you see the following z-scores: (Day1 : 0, Day2 : 2.0, Day3 : 2.0) and to make things simple let's just say your regression coefficient remains 1.0 for all days and you will get fully filled on your orders. In your current code, your order sizes are (0,0), (-200,200), (-200,200) which means by day 3 your position sizes will be (-400, 400). If I understand what you said correctly you want your position size to be (-200, 200) on Day3.
(2) You neither have slippage or broker commission defined. Now since this is a long/short strategy, you also need to know what your borrow costs on the short position. Transaction costs will often kill the majority of strategies, beware.
(3) I haven't investigated quantopian's system enough to actually figure out how they're handling this for backtests using daily data. However, as a word of caution, your calculations are all done on closing prices then you send an order out - see the problem there? Let's suppose two scenarios of possible ways this issue has been addressed: (a) the price you're doing your calculations are are for the open of 15:59-16:00 eastern and the fill that's being reported is the close (i.e. final print) - is the liquidity there to even execute on at that price? (b) your calculation is on the last print but your fill price is the closing auction price, well the only way you can actually get the closing auction price is via MOC which needs to be sent out at by 15:45. It's entirely possible that what you're catching is excess volatility in the close that's untradable.
Some possible fixes: (a) calculate on 15:00, then execute on VWAP of last hour and (b) calculate on 15:45, send MOC but you need to assume a higher market impact. there are a few other things you could look at but I'll let you figure those out.
Good luck,
-A