*** NOTE: I posted this yesterday, but accidentally deleted it when editing it to provide a small revision to the algo code**
This algo attempts to implement the GLD/USO pair trading algo from Ernie Chan's book.
Additionally, I place the trades under the constraint of always opening positions whereby my resulting portfolio leverage at trade open never exceeds 1.0 (ie: I don't go on margin) and I'm fully invested whenever I open a trade based upon whatever my current portfolio value is.
In accounting terms: long_exposure + abs(short_exposure) = portfolio_value
This was accomplished using a short helper function I baked into the algo called computeHoldingsPct() which does all the normalizing and returns the long and short holdings amount as percentages based on my current portfolio value when placing the orders. I've also setup the algo to record the % exposures in both GLD and USO whenever a trade is placed for later investigation in case I want to investigate some of the drawdowns that seem to have come up once in a while. What I like about implementing a pairs strategy in this manner, by using constant leverage, is that it seems to smooth out my equity curve.
Would love to hear folks' thoughts to see if whether approaching a pairs trading strategy in this manner is interesting, or if perhaps my approach can be further improved.
UPDATE:
This updated algo (seen here. If you cloned the original, you should grab this new one instead) addresses very minor issues I discovered in the original. Additionally, I reduced the backtest dates so as to better view the daily values for performance and recorded values that display leverage and % equity invested in each stock of the pair trade. Leverage was chosen to be 1.0 upon trade entry, but since I'm not rebalancing the portfolio daily (churning the portfolio excessively and accruing excess transaction costs would be detrimental for a strategy like this), leverage oscillates a bit up or down depending on how the strategy performs after trade entry. Then at next trade entry positions are taken once again at 1.0 leverage.