Pair Trading using Mathematica
Pair Trading is one of the ideas that I have been very interested in, but could not find right tool for analysis. Sure, most traders use Excel, but that’s simply too many copying and pasting cells. Patrick showed me the cool things he could do with Mathematica, and I thought that might be the perfect tool for stock analysis.
So what is Pair Trading? In short, it is a market-neutral strategy used by hedge funds and investment bank. Trader first identifies two stocks which prices have moved together in past. When the spread between the stocks widen for any reasons, buy the underperforming stock and short the outperforming one. When the spread eventually converge and the trader will close the positions and profit.
Mathematica has lots of impressive features for stock analysis. For example, 
One line of code will grab GOOG prices since 2006 and plot on a chart. Note that I don’t have to write parsers for stock data, because financial data is part of larger set of curated data that comes with Mathematica.
Now let’s use Mathematica on Coca-Cola(KO) and Pepsi(PEP), a classic example of a correlated pair.

As expected, the pair has similar movements in prices over lasts year. Now we plot the price of KO divided by PEP and get the following chart. (Note: Blue Curve is the KO / PEP pair ratio, Red Line in middle is mean, Blue and Yellow Lines are 1 standard deviation, and Red and Green Lines are 2 standard deviation).

The price ratio seems to oscillate around a mean. But we do see when the ratio appears to go below and above 2 standard deviation from the mean. The strategy is to execute a paired trade when the pair ratio is over +/- 2 standard deviation from mean. When the ratio reverts to mean, we will close the positions.
As shown on the chart, the price ratio is currently around +2 standard deviation, now might be a good time to SHORT KO / LONG PEP. For options trading, you would buy a KO put and buy a PEP call that expire on same time.
Trader should be aware of risk of drifting. This happens when the two correlated stock prices start to drift apart. The risk can be controlled if trader closes the pair (and take loss) if their prices do not converge within a time interval (eg. 6 months) or when pair ratio is above certain tolerable line (say +/- 3 standard deviations).
Mathematica has simplified the analysis with stats and charting library and curated finance data. Only 5 lines of code are needed to produce this analysis. It is also worth mentioning Mathematica also has awesome documentation to help you get started. If you have Mathematica, you can download the notebook.