I very new to this, and I've written this (my first) mean reversion algo which calculates a hedge ratio using linear regression between USO and GLD and then buys/sells depending on the deviation of the portfolio price from the mean. It hasn't turned out very well, unsurprisingly, and the results vary wildly depending on what I set as the lookback period. I was wondering if anyone could point out if I have fundamentally misunderstood how this strategy works. Pointers on my terrible, terrible code would also be appreciated.