Pairs Trading

After auditing a course on Time Series stats and reading a few books, I put together some R code to do pairs trading. It's a fairly old strategy that some people claim doesn't work particularly well at the moment. Regardless, I wanted to try it out and indeed it is possible to generate profits. The hardest part is discovering pairs.

Pairs trading involves picking two stocks whoes price spread over time is cointegrated, thus forming a stationary spread. The spread must be stationary and according to the mean reversion principle any deviation from the mean of the spread will be corrected over time. It is these deviations from the mean that can be exploited for profit. A spread can be formed using StockX and StockY in the following way StockX - r * StockY. If the current spread is above the mean, short the spread (sell StockX and buy r of StockY) and wait for mean reversion. If the current spread is below the mean, go long on the spread and wait for mean reversion. From personal observations, it seems that the mean level of a spread lasts about 200 days, at that point a new mean is established. It is recommend to use this strategy during highly volatile markets or during earnings/news releases.

Strategy Basics:
1. Find correlated stock pairs on which to run search (best pairs come from the same industry) - you can run a correlation search, although not the best way.
2. Test to see if the individual price series are stationary, if not test the residuals of the spread using the Phillips-Perron test. You want to establish that the spread is stationary, if it's not move any further calcs are meaningless.
3. Create the spread (StockX - r * StockY) of the two stocks using linear regression (not the only way).
4. Check for deviations from the mean above a certain level and use those as triggers.
Bonus:
5. Create an ARMA model of the spread so that you can use standard stats tools like standard deviation and confidence intervals. In my experience most spreads can be mapped using an AR(2) process.
6. Once ARMA model is complete use 95-99% confidence interval as a trading trigger. You can also try to do forecasting using the model.


I might be willing to share the R source for this, but you must have something to offer in return :)

In addition I create some R code to do backtesting, comes in useful when exploring the possibilities for generating profits.

Stock Price Updater

I created a program for updating a mySql database with stock quotes from Yahoo finance. It can be run as a daemon so that it downloads all the data for a specified number of years the first time it's run, and updaes all the quotes an the end of every day after that. You may find it useful, if you do write back to let me know :)

I am offering the Eclipse project (just import it) - it will help if you know some Java. If there is enough demand I'll put together a binary for ease-of-use.

stockSaver.zip
- to configure the application look at the stocksaver.properties file, I've included the sql to create a basic table for all the data, the symbols for the S&P500 and some sql code to run correlations on all the pairs in the table - enjoy

P.S. to run it as a deamon check out the apache-daemon project

Evaluating Risk using the Merton Model

s mentioned previously, for my AMP466 Assignment, I'll be using the Merton Model to evaluate credit risk of corporate debt i.e. calculate the probability of default for a given company.

You can learn more about the Merton Model here.

Basically, the model uses a single debt and equity issue to represent the financing. The assets of the company is the total market capitalization and the debt is the market capitalization multiplied by the debt/equity ratio. Adding the two numbers gives the total value of the company. The model is used to calculate numbers for one year.

It is mostly an academic tool, since there are problems with its application in real world scenarios, a few short comings are:

  • the model can be used only for companies who have stock
  • governments cannot be evaluated
To compensate for these limitations a company, KMV, was created to commercialize Merton's work, it was later bought by Moodys.

I choose to evaluate First Solar (FSLR):

First you need to calculate the historical volatility of the stock, here and here is some more info on that. First Solar has been public since Nov 17th, 2006, so I used all of the available daily data.

logarithmic return: is the stock value on day i

sample variance: , is the mean of daily returns.

annualized volatility: multiply by 252 trading days since I use daily data

I calculated the historical volatility to be 70

Whenever necessary, I used the LIBOR risk free interest rate of 2.52%, it changes so look it up.

Credit Spread
S = Market Cap = 21,864.65 million
B = Current Debt = S * Debt/Equity = 21864.65e6 * 0.0986 = 2155.85 million
V = B + S = 2155.85e6 + 21864.65e6 = 24020.5 million

Finding Future Debt
K = 0.0986 * 2155.85e6 * e0.0252 = 2210.87 million this is the value of the debt discounted to one year into the future.

Using the Black-Scholes formula I find the volatility of the assets. John Hull has a B-S calculator on his website, I recommend using it or another of the B-S calculators floating around.
Treat the Future Debt as the strike price, and the Total Assets as the value of the equity. Use the historical volatility that was calculated previously.

Updating the volatility on each iteration, using the result is σv = 71.52% Asset Volatility

ln(K/B) = ln(2210.87/2155.85) = 0.0252  yield
2.52% - (risk free rate = 2.52%) = 0%  Credit Spread

Annual Risk Neutral Probability of Default

to be con't

Expected Credit Loss

to be con't


All the beautiful equations that you see are care of LATEX for blogger.

Ready, Set, Run

I'll try to use this blog to keep me honest in my pursuit of knowledge in Finance. I am a Computer Engineer, in my last month of M.Eng. My budding interest in finance as a area of study and profession has set me on a course to read many books, explore new computer systems and build some cool tools...

I plan to:

  • C++ : finish reading Primer, I need a better grasp
  • Read books on Finance
    • Paul Wilmott
    • John Hull
    • more...
  • Read books on Math
    • Stochastic Calculus
    • Optimization
    • more...
  • Learn Erlang
  • Read some books on Trading systems
  • Learn VBA: seems to be required
  • Python: this one is a maybe
  • Put together a nice trading system, allow for easy expansion through ready made components...
  • MAKE SOME MONEY :)
But first, need to finish my assignment on Credit Risk analysis (APM466) :)