Sunteți pe pagina 1din 4

4/20/2014 File Exchange - MATLAB Central

http://www.mathworks.com/matlabcentral/fileexchange/37932-automated-trading-with-matlab-2012/content/html/Demo5_Pairs_Trading.html 1/4
Search: Fi l e Exchange
Nukul My Communi ty Profi l e Log Out
File Exchange Answers Newsgroup Link Exchange Blogs Trendy Cody Contest MathWorks.com
by Stuart Kozola
Automated Trading with MATLAB -
2012

31 Aug 2012 (Updated 04 Sep 2012)
Files f rom the Automated Trading webinar showing
X_Trader and QuickFIX/J integration.
Algorithmic Trading with MATLAB: Pairs trading
Download Submission
Code covered by the BSD License
Highlights from
Automated Trading with MATLAB - 2012
Algorithmic Trading with ...
Algorithmic Trading with ...
Algorithmic Trading with ...
Algorithmic Trading with ...
Algorithmic Trading with ...
Calibrate 3 Models
Integrating MATLAB with Q...
Utilize .NET Objects in M...
X_Trader Order Submission...
X_Trader Price Update Dep...
X_Trader Price Update exa...
createMSMQ() Copyright 2010-2012, The MathWorks, Inc.
crossover(parents,options...CROSSOVER generates kids from parents
dsample(HLC, factor) Downsamples our time series by a given factor, preserving the HIGH and
fitness(pop,indicator,pri...See also tradeSignal, initializePopulation
generateSpacedInts(lb, ub...GENERATESPACEDINTS Generates approximately NUMBER integers between LB and
generateTradeSignal(signa...GENERATETRADESIGNAL produces a buy/sell signal depending using parameters
getMinuteDataFromDB(table...Copyright 2010-2012, The MathWorks, Inc.
indicatorChartALL(price, ...INDICATORCHARTALL A chart showing prices and trading signals sent from
indicatorChartMA(YMatrix1) INDICATORCHARTMA(YMATRIX1)
indicatorChartWPR(w1) INDICATORCHARTWPR(W1)
initializePopulation(I,po...INITIALIZEPOPULATION generates an initial population of 1's and 0's
isoplot(xyz,u) Copyright 2010-2012, The MathWorks, Inc.
leadlag(P,N,M,scaling,cost) LEADLAG returns a trading signal for a simple lead/lag ema indicator
leadlagFun(x,data,scaling...define leadlag to accept vectorized inputs and return only sharpe ratio
locateConnectors(rule); LOCATECONNECTORS finds locations of connectors in RULE
mutation(parents,options,...MUTATION mutate childrend accordinlgy
pairs(series2, M, N, spre...PAIRS returns a trading signal for a simple pairs trading strategy
pairsChart(LCO, WTI) PAIRSCHART: Shows the full time history for LCO and WTI
pairsFun(x,data,scaling,c...define pairs to accept vectorized inputs and return only sharpe ratio
parameterSweep(fun,range) PARAMETERSWEEP performs a parameters sweep for a given function
plotRules(options, state,...
plotTrades(tradeSignal,se...Create plot
rsi(price,M,thresh,scalin...RSI returns a trading signal for a simple relative strength index
rsifun(x,data,scaling,cost) define rsi to accept vectorized inputs and return only sharpe ratio
ruleChartALL(prices, sh, ...RULECHARTALL Shows the performance of the combined model, after it has
ruleChartMA(YMatrix1, YMa...CREATEFIGURE(YMATRIX1,YMATRIX2)
runTradingAlgo() Copyright 2010-2012, The MathWorks, Inc.
sendOrder(signal, signalD...SENDORDER produces a message on a Microsoft Messaging Queue
sendOrderQuickFIX(signal) SENDORDERQUICKFIX submits an order to Banzai application
sendOrderXT(signal) SENDORDERXT submits an order to XTRADER
startBanzai(configFile) Copyright 2010-2012, The MathWorks, Inc.
sweepPlotMA(xdata, ydata,...SWEEPPLOTMA(XDATA, YDATA, ZDATA)
tradeSignal(pop,ind) TRADSIGNAL generates the trading signal from population
tradingSystem(varargin) This is for illustration purposes only.
validRule(rule) VALIDRULE determines if the rule is valid
wpr(price,N,scaling,cost) WPR returns a trading signal for a simple Williams %R indicator
wprFun(x,data,scaling,cost) WPR wrapper
helloWorldNET.mUtilize .NET Objects in MATLAB
View all files
4/20/2014 File Exchange - MATLAB Central
http://www.mathworks.com/matlabcentral/fileexchange/37932-automated-trading-with-matlab-2012/content/html/Demo5_Pairs_Trading.html 2/4
Algorithmic Trading with MATLAB: Pairs trading
This demo shows how f unctionality within Econometric Toolbox can be used to identif y and calibrate a simple, intraday pairs trading
strategy.
Copyright 2010-2012, The MathWorks, Inc. All rights reserved.
Contents
Load intraday data f rom a database
The cointegration test f ramework
The pairs trading strategy
Load intraday data from a database
As bef ore, we will download intraday data f or Brent Crude (LCO) f rom our database. We will also download data corresponding to West
Texas Intermediate (WTI).
% Rather than forcing the customer to define and populate a database, we
% will instead read from a prepared data file. If you wish, you may write
% the data from this file to a database of your choosing and adapt the
% GETMINUTEDATAFROMDB command to connect to and read from it.
% LCO = getMinuteDataFromDB('LCO');
% WTI = getMinuteDataFromDB('WTI');
load oilData
LCO = double(brent);
WTI = double(light);
clearvars -except LCO WTI
pairsChart(LCO, WTI)
% These two time series have historically tracked each other, but since
% December 2010, LCO has consistently traded higher than WTI. It would
% seem that a pairs trading strategy would not work in 2011, but if we are
% willing to actively recalibrate our model on an intraday basis, we may
% find profitable opportunities.
% Let's focus on the last 11 days' of data:
series = [LCO(end-4619 : end, 4) WTI(end-4619 : end, 4)];
The cointegration test framework
Econometrics Toolbox supports both the Engle-Granger and the Johansen cointegration f rameworks. Engle-Granger is the older model,
and Johansen is particularly usef ul f or analyzing more than two time series at a time. We will use Engle-Granger f or our trading model.
% First, we note that the last 11 days are not cointegrated as a whole
egcitest(series)
% (A zero indicates failure to reject the null hypothesis that no
% cointegrating relationship exists.)
ans =
0
Even so, there are smaller windows of time where a cointegrating relationship does exist.
[h, ~, ~, ~, reg1] = egcitest(series(1700:2000, :));
display(h)
h =
1
The test estimates the coef f icients of the cointegrating regression as well as the residuals and the standard errors of the residuals: all
usef ul inf ormation f or any pairs trading strategy.
4/20/2014 File Exchange - MATLAB Central
http://www.mathworks.com/matlabcentral/fileexchange/37932-automated-trading-with-matlab-2012/content/html/Demo5_Pairs_Trading.html 3/4
display(reg1)
reg1 =
num: 301
size: 301
names: {2x1 cell}
coeff: [2x1 double]
se: [2x1 double]
Cov: [2x2 double]
tStats: [1x1 struct]
FStat: [1x1 struct]
yMu: 110.7448
ySigma: 0.3043
yHat: [301x1 double]
res: [301x1 double]
DWStat: 0.1891
SSR: 13.0123
SSE: 14.7666
SST: 27.7789
MSE: 0.0494
RMSE: 0.2222
RSq: 0.4684
aRSq: 0.4666
LL: 26.6152
AIC: -49.2304
BIC: -41.8162
HQC: -46.2636
The pairs trading strategy
The f ollowing f unction describes our pairs strategy. It is basically a copy of our other existing strategy f iles, with signif icant changes to
only about 7 lines of code.
edit pairs
We may test this strategy as we do our other rules:
pairs(series, 420, 60)
% Note that this strategy will not trade if the most recent minutes do not
% show signs of cointegration and that the size of the long/short positions
% are dynamically scaled with the volatility of the cointegrating
% relationship. Many other customizations can be made.
We can use our existing parameter sweep f ramework to identif y the best combination of calibration window and rebalancing f requency.
This builds of f of existing code and takes advantage of parallel computing:
if matlabpool('size') == 0
matlabpool local
end
window = 120:60:420;
freq = 10:10:60;
range = {window, freq};
annualScaling = sqrt(250*7*60);
cost = 0.01;
pfun = @(x) pairsFun(x, series, annualScaling, cost);
tic
[~,param] = parameterSweep(pfun,range);
toc
pairs(series, param(1), param(2), 1, annualScaling, cost)
Elapsed time is 37.228054 seconds.
4/20/2014 File Exchange - MATLAB Central
http://www.mathworks.com/matlabcentral/fileexchange/37932-automated-trading-with-matlab-2012/content/html/Demo5_Pairs_Trading.html 4/4

Si te Hel p Patents Trademarks Pri vacy Pol i cy Preventi ng Pi racy Terms of Use
Featured MathWorks.com Topi cs: New Products Support Documentati on Trai ni ng Webi nars Newsl etters MATLAB Tri al s Careers
Despite the f act that these historically-tracking time series have diverged, we can still create a prof itable pairs trading strategy by
f requently recalibrating.
Published with MATLAB 7.14
Contact us
1994-2014 The MathWorks, Inc.

S-ar putea să vă placă și