2011/10/25

Pair trading strategy : how to use "PairTrading" package

Mr.Ishikawa(my old friend) and I developed "PairTrading" package, and uploaded it on CRAN.
This article shows you how you can use it.


The pair trading is a market neutral trading strategy and gives traders a chance to profit regardless of market conditions. The idea of this strategy is quite simple.
 1 : Select two stocks(or any assets) moving similarly
 2 : Short out-performing stock, buy under-performing one
 3 : If "spread"(price difference between two stocks) converge, close your position.


So, Let's start to explain how to use this package.
(This example is in PDF manual of this package)

0: Install & load package
You can install and load "PairTrading" package via CRAN in the same way as other packages.


> install.packages("PairTrading")
> library(PairTrading)


1: Load sample data
We prepared sample stock price data in our package. You can load it by using "data" command.


> #load sample stock price data
> data(stock.price)


2: Estimate parameters
Next, We extract two stock prices(from 31 Mar, 2008) and estimate parameters.

> #select 2 stocks
> price.pair <- stock.price[,1:2]["2008-03-31::"]
> #Estimate parameters & plot spread
> reg <- EstimateParameters(price.pair, method = lm)

At the moment, we have only normal linear regression method to estimate parameters, but we will develop more sophisticated method in the future.The estimation result contains the following contents.

> str(reg)
List of 3
 $ spread     :An ‘xts’ object from 2008-03-31 to 2011-08-05 containing:
  Data: num [1:821, 1] 0.26 0.271 0.294 0.275 0.255 ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr "7203"
  Indexed by objects of class: [Date] TZ: 
  xts Attributes:  
 NULL
 $ hedge.ratio: num 0.285
 $ premium    : num 6.34
The most important thing in this estimation is "spread", then we try to plot it.


> plot(reg$spread)




And, you can check the stationarity of that by using "IsStationary" function.
This function return the result of two types unit root test.

> #check stationarity
> IsStationary(reg$spread, 0.1)
 PP.test adf.test 
    TRUE     TRUE 
( augmented Dickey–Fuller test (ADF) and Phillips-Perron test)


3: Estimate parameters for back-test
To run back-test, you have to estimate parameters historically by using "EstimateParametersHistorically"function. This function do something like "rolling regression" to estimate parameters. This point is different from "EstimateParameter" function.


> #estimate parameters for back test
> params <- EstimateParametersHistorically(price.pair, period = 180)
> #create & plot trading signals
> str(params)
An ‘xts’ object from 2008-12-18 to 2011-08-05 containing:
  Data: num [1:642, 1:3] 0.065 0.0577 0.0396 0.0136 0.021 ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr [1:3] "spread" "hedge.ratio" "premium"
  Indexed by objects of class: [Date] TZ: 
  xts Attributes:  
 NULL



4: Create trading signal
Next, you create trading singal using estimated spread. "Simple" function give a very simple trading strategy(If The spread is more(less) than specified value, you will buy(sell))


> #create & plot trading signals
> signal <- Simple(params$spread, 0.05)
> barplot(signal,col="blue",space = 0, border = "blue",xaxt="n",yaxt="n",xlab="",ylab="")
> par(new=TRUE)
> plot(params$spread)

In this case, The trading signal is drawn as below.


Last, you can check the performance of pair trading by using "Return" function.


> #performance
> return.pairtrading <- Return(price.pair, lag(signal), lag(params$hedge.ratio))
> plot(100 * cumprod(1 + return.pairtrading))

In this case, our strategy seems to work correctly :-)



6: Conclusion and remarks
Pair trading is well-known trading strategy, and I introduced "PairTrading" package in this article.
We would like to modify this package to be more useful and fit in real-market.
If you have any suggestion, please let me know.

And we created a presentation slide to explain the basic concept of pair trading.
It may be useful for you to understand the basic concept of pair trading if you are interested in it.


Enjoy!

2011/07/06

Yet another way to use R in Excel for .NET programmer

I wrote the article whose title is "Another way to use R in Excel for .NET programmer" last night.
In that article, We need to use IDE to write C# program.

On ther other hand, Excel-DNA give us easier way to create XLL.
Let me show you one example.

In last post, I downloaded two libraries.

  1. Excel-DNA
  2. R.NET

If you don't download these files yet, please do it.
And, put the files which I showed below together into some folder.
I changed the file name of ExcelDna.xll and ExcelDna.dna to SimpleExample.xll and SimpleExample.dna.
It is no problem for you to change these names as you like.

Next, Please copy and paste below codes to SimpleExample.dna by notepad or such a editor and save & close dna file.

<DnaLibrary RuntimeVersion="v4.0" Name="My First XLL" Language="CS">
<ExternalLibrary Path="R.NET.dll" />
<Reference Name="R.NET" />
<![CDATA[

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ExcelDna.Integration;
using RDotNet;

namespace CSLib
{
    public class CSLib
    {
        static REngine rengine = null;
        static CSLib()
        {
            // Set the folder in which R.dll locates.
            REngine.SetDllDirectory(@"C:\Program Files\R\R-2.13.0\bin\i386");
            rengine = REngine.CreateInstance("RDotNet", new[] { "-q" });
        }            
        [ExcelFunction(Description = "get random numbers obey to normal distribution")]
        public static double [] MyRnorm(int number)
        {
            return (rengine.EagerEvaluate("rnorm(" + number + ")").AsNumeric().ToArray<double>());
        }
    }
}

]]>
</DnaLibrary>



If you use or install another version R, modify "SetDllDirectory" function call.

Lanch SimpleExample.xll and create new Excel sheet. As you'll see below, you can use your own function defined in C# language !



Enjoy !

*R.NET seems to be compiled with .NET framework 4.0. you may have to install these to try this example.

2011/07/05

Another way to use R in Excel for .NET programmer

As you know, RExcel give us a way to combine R with Excel.
But, It just bothering to install some COMs and maybe not be programming but excel manipulation!

If you are a .NET programmer, there is another way to call R from Excel.
I would like to show you simple example.
We need to two libraries to do that.
  1. Excel-DNA
  2. R.NET
First, you download ExcelDNA from here.
And, go to "Distribution" folder.



you just need only three files(ExcelDna.dna, ExcelDna.xll, ExcelDna.Integration.dll) in this folder.
(I assume that your OS is 32bit windows.)
Second, you download R.NET from here.

you can set(or copy) these files any folder as you like.

Next, you start up your IDE. I used VC# this time.
Of-course, you can use other .NET languages like a VB.NET.

Create new project, choice "Class library" as template and wrote program as below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ExcelDna.Integration;
using RDotNet;

namespace CSLib
{
    public class CSLib
    {
        static REngine rengine = null;
        static CSLib()
        {
            // Set the folder in which R.dll locates.
            REngine.SetDllDirectory(@"C:\Program Files\R\R-2.13.0\bin\i386");
            rengine = REngine.CreateInstance("RDotNet", new[] { "-q" });
        }            
        [ExcelFunction(Description = "get random numbers obey to normal distribution")]
        public static double [] MyRnorm(int number)
        {
            return (rengine.EagerEvaluate("rnorm(" + number + ")").AsNumeric().ToArray());
        }
    }
}

In this case, I defined the function which generates random numbers obey standard normal  distribution. If you use or install another version R, modify "SetDllDirectory" function call.
All source code and solution files are here(github).

Next, Add R.NET.dll and ExcelDna.Integration.dll to your project as reference.
Now, Everything is ready. Let's compile !

After compile, you have to modify your ExcelDna.dna file.
Edit this file with notepad like below.
















(v4.0 means your version of .NET framework. modify this number if you need)
(If your DLL's relative-path is not "CSLib.dll" from ExcelDNA.xll, you have to correct this name)
(I deployed CSLib.dll, ExcelDna.xll, ExcelDna.dna in the same folder)

After that, double-click your ExcelDna.xll and create new Excel sheet.
As you'll see below, you can use your own function defined in C# language !



Enjoy !