Wednesday, February 27, 2013

Algorithmic Trading System Update 02/27/2013

I've just hit an enormous milestone with my ATS project. I'm currently building my ATS using C#. I'm not a fan of making small scripts and then running them repeatedly by hand, so I would ideally like to use C# to do everything. Unfortunately, I came to a standstill for statistics. I wasn't able to find any C# code for doing the Augmented Dickey Fuller test. This is used to determine whether or not two series are cointegrated, and is a key piece in datamining. There was a C library available called gretl, and my attempt to port it turned out to be a nightmare. Attempting to use marshalling was equally daunting. R Project has libraries which do the ADF test, but well... it's R. It's messy if you want to do something other than performing a couple of calculations. This means I can't do say... automate a daily download of new prices and then perform tests to find out the new hedge ratios. Finally, I came a cross a project called RDotNet.  This is basically a C# wrapper around the R Project interpreter so that you can feed lines of R code into it from C# code. After a lot of struggling, I finally got this working.

            string[] v1 = sec1bars.Select(r => r.dt.ToString("yyyyMMdd")).ToArray();
            string[] v2 = sec2bars.Select(r => r.dt.ToString("yyyyMMdd")).ToArray();

            CharacterVector sec1dates = mEngine.CreateCharacterVector(v1);
            NumericVector sec1prices = mEngine.CreateNumericVector(sec1bars.Select(r => (double)r.adjc));
            CharacterVector sec2dates = mEngine.CreateCharacterVector(v2);
            NumericVector sec2prices = mEngine.CreateNumericVector(sec2bars.Select(r => (double)r.adjc));

            mEngine.SetSymbol("sec1dates", sec1dates);
            mEngine.SetSymbol("sec1prices", sec1prices);
            mEngine.SetSymbol("sec2dates", sec2dates);
            mEngine.SetSymbol("sec2prices", sec2prices);

            mEngine.Evaluate("sec1zoo <- zoo(sec1prices, as.Date(as.character(sec1dates), format=\"%Y%m%d\"))");
            mEngine.Evaluate("sec2zoo <- zoo(sec2prices, as.Date(as.character(sec2dates), format=\"%Y%m%d\"))");
            mEngine.Evaluate("t.zoo <- merge(sec1zoo, sec2zoo, all=FALSE)");
            mEngine.Evaluate("t <-");
            mEngine.Evaluate("m <- lm(sec1zoo ~ sec2zoo + 0, data=t)");
            mEngine.Evaluate("beta <- coef(m)[1]");
            mEngine.Evaluate("sprd <- t$sec1zoo - beta*t$sec2zoo");
            mEngine.Evaluate("ht <- adf.test(sprd, alternative=\"stationary\", k=0)");
            mEngine.Evaluate("pvalue <- ht$p.value");

            DynamicVector beta = mEngine.GetSymbol("beta").AsVector();
            DynamicVector pvalue = mEngine.GetSymbol("pvalue").AsVector();

After that, you end up with your beta and pvalue for your pair.

No comments:

Post a Comment