File Exchange

## Algorithmic Trading with MATLAB - 2010

version 1.1.0.1 (1.87 MB) by

Files from the November 18, 2010 webinar.

51 Downloads

Updated

Files used in the webinar - Algorithmic Trading with MATLAB Products for Financial Applications broadcast on November 18, 2010. This webinar can be viewed at http://www.mathworks.com/videos/algorithmic-trading-with-matlab-for-financial-applications-81775.html
The download includes an additional demo, not shown in the webinar, that shows how to generate C-code from MATLAB.

Javier Garach

Nikos Rentoumis

Jana Juhaszova

Sergey Frolov

Charles

### Charles (view profile)

Further to my earlier comment the error message i receive when executing the parameter sweep of demo1, lines 135 through 148 is

Error in leadlagFun (line 19)
parfor i = 1:row

Error in @(x)leadlagFun(x,BundClose,annualScaling,cost)

Error in parameterSweep (line 66)
resp = fun(cell2mat(var));

Please note my matrix is a 500 x 4 double

Charles

### Charles (view profile)

Hello Stuart. Great Seminar and I like the code too. It will add alot to the current model I am enhancing. I used matlab 2015b. I ran your code successfully with your data, but had to change 'matlabpool' to 'parpool'. in this section

% Use my the cores on my laptop (a quadcore with hyperthreading, so 8
% virtual cores).
matlabpool local 8

I am having a challenge with the data file in your Bund1min.mat file.. It has over 4000 columns, and 4 rows I believe. I believe the parameter sweep is reading column 4 from the data file.

%% Determine best trading frequency (considering intraday)
% Load in 1-minute data and break into test/validation data sets
close all
load bund1min
testPts = floor(0.8*length(data));
BundClose = data(1:testPts,4);
BundCloseV = data(testPts+1:end,4);
cost=0.01; % bid/ask spread

I am using my own data here, which is a 500 x 5 matrix.
I get an error message which your help desk will have shared with you. Can you help? Let me know if you need more information.

Liang Seacom

Liang Seacom

Very cool code.
Thanks.

Vegeta

Vegeta

### Vegeta (view profile)

Hi I would like to ask a simple question.

For AlgoTradingDemo1, there is a leadlag function,
1:what is the difference from movavg function?
2:why you got 4 parameters in the function with last one is annualScaling? Since I search the doc leadlag, there are only 3 paremeters required. What this annualScaling for?

mom

good

Andoni Olaeta

thanks

srkn

### srkn (view profile)

I run the Algotrading1 and Algotrading2 with different data, but the result for the best ledlag is the same for different datas, such as 10:394 and 2:396.
why do my best estimators not change when I use different datas?

Andre Viana

Mark

### Mark (view profile)

Those following this thread my find the website: http://www.openAlgo.org interesting. Some of the work here inspired it.

Mirko

### Mirko (view profile)

This is a lot of stuff in very compact form. Thanks for this good example.

Just one comment: If you publish examples you should take the work to make them correct or even tell the user that it is delivering wrong results and can not be used (see Javier comment).

Chen

thanks

joseph Frank

### joseph Frank (view profile)

I am receiving the following error:
Error using -
Matrix dimensions must agree.

Error in filter2 (line 10)
diff=abs(X1(:,3)-cr);

Error in scribe.legend/methods>lscan (line 935)
newpop = filter2(ones(3),pop);

Error in scribe.legend/methods>get_best_location (line 700)
pos(1:2) = lscan(double(h.Axes),double(h.Plotchildren),pos(3),pos(4),0,1);

Error in scribe.legend/methods (line 19)
[varargout{1:nargout}] = feval(args{:});

Error in legendcolorbarlayout>doBestLegendLayout (line 1159)
pos = methods(handle(h),'get_best_location');

Error in legendcolorbarlayout (line 120)
doBestLegendLayout(ax,h);

Error in scribe.legend/init (line 137)
legendcolorbarlayout(ax,'addToLayoutList',double(h))

Error in scribe.legend (line 122)
h.init();

Error in legend>make_legend (line 386)
lh=scribe.legend(ha,orient,location,position,children,listen,strings,propargs{:});

Error in legend (line 284)
[h,msg] = make_legend(ha,varargin(arg:end));

Error in AlgoTradingDemo1 (line 21)
legend('Close','Lead','Lag','Location','Best')

Sumit

### Sumit (view profile)

Great explanation!

Mario

Javier

### Javier (view profile)

Hello Justinas: 250 days, 11 trading hours, 60 minutes in one hour.

Trading signal as exposed here, are wrong for the performance measure and sharpe calculation (lines 76 leadlag.m). In the same m file, plot result section, the signal helps to identify that you keep long or short.
It is important to differentiate variables definition with a graphical purpose and variables definition for calculation purpose.

Karamos

### Karamos (view profile)

Hi Stuart,

I used the AlgoTradingDemo1.m with SMA+RSI to find an optimal parametres for few currencies and I received the following error.
Error in @(x) marsiFun(x,BundClose,annualScaling,cost);
Error in parametersweep at 57
resp=fun(cell2mat(var));
Error in AlgoTradingDemo1 at 35
[maxSharpe,param,sh] = parameterSweep(fun,range);

The loop change the FX price and gives each time different parametres for each currency.

Could you please give me an idea of what could cause this error?

Thanks

Peter

### Peter (view profile)

The 2009 version of this has some sample stop code. Fwiw, I haven't found a good array way of doing it, as opposed to looping through the whole period. The biggest drawback being that you cannot use parallel computing.

Mate 2u

### Mate 2u (view profile)

Any thoughts on how to add a stop loss to RSI?

Peter

### Peter (view profile)

Any thoughts on the best way to make this a long/short/flat system, ie you can be 1=long, 0=flat, -1=short? So far you're either long or short, ie always in the market. Any thoughts on what the best way is to run the L/S conditions through the tradesignal file using bit operations?

Peter

### Peter (view profile)

Interesting approach, still working through this. Bring on the curve fitting!

The tradeSignal.m definitely has a mistake. Couldn't quite get Ivan's solution to work. I fixed it as follows: change to idx = indLoc(:); and add
if (ind2use(iInd)==0) sigC=sigB;
elseif (ind2use(iInd+1)==0) sigC=sigA;

I also renamed some vars and got rid of that eval business, seems to work faster. Full code below, if there are more mistakes feel free to comment.

Re the Sharpe annualization - OMG guys! When you use that Sharpe maximization, you should also realize that you're not really maximizing the Sharpe ratio unless you are working with indexed prices. The PnL function gives prices differences (not returns), Sharpe ratio works with returns!

function sigOut = tradeSignal(pop,ind)
%% BitString Length
cntBString = size(pop,2);

%% Calculate Indicators
% Length = 4*NoIndicators - 2
cntInd = (cntBString+2)/4;
% indicator locations
indLoc = 1:3:cntBString-cntInd;
indLocEnd = max(indLoc);
%% Generate Signal
sigOut = zeros(size(ind,1),size(pop,1));
for iPop = 1:size(pop,1)
ind2use = logical(pop(iPop,cntBString-cntInd+1:end));
idx = indLoc(:);
for iInd = 1:length(idx)-1
% indicator 1
if (iInd == 1) %evaluate first indicator
sigA=[ind(:,iInd)==pop(iPop,idx(iInd))];
else %for all other indicators, combine with the results generated so far
sigA = sigC;
end

% indicator 2
sigB=[ind(:,iInd+1)==pop(iPop,idx(iInd+1))];

% connector
if (ind2use(iInd)==0) sigC=sigB; %I1 inactive
elseif (ind2use(iInd+1)==0) sigC=sigA; %I2 inactive
else
conValue = bin2dec(num2str(pop(iPop,(1:2)+idx(iInd))));
switch conValue
case 0
sigC = bitand(sigA,sigB);
case 1
sigC = bitor(sigA,sigB);
case 2
sigC = bitxor(sigA,sigB);
end
end
end %for
sigOut(:,iPop) = sigC;
end

Fuzhi Cheng

### Fuzhi Cheng (view profile)

Following Ivan, it seems that we need to transform raw signal -1/+1 into 0/1 in order to use tradeSignal.m accurately. suppose pop=[1 0 0 0 1 1], tradeSignal(pop,[1 -1])=0 while tradeSignal(pop, [1 0])=1, the latter being the correct signal given the rule.

Ivan

### Ivan (view profile)

I have some problems with tradeSignal.m function

It seems to be a mistake there: le assume we have

pop = [ 1 0 0 1 0 0 0 0 1 1]
,which means not to use indicator1, and return True if indicator2 == 1 and indicator3 == 0

signals = [ 0 1 0], which must satisfy the conditions of pop.

Now, I run tradeSignal(pop, signals) and get 0.

So there is a mistake. I'm thinking of line 50 and 57. But first we should declare
line 46: filteredSignals = ind(:,ind2use);

line 51: A = eval(['(filteredSignals(:,1) == pop(r,',idxstr,'));']);
line 57: B = eval(['(filteredSignals(:,',num2str(i+1),') == pop(r,',idxstr,'));']);

Now, test of corrected function

signals =
[0 0 0;
0 0 1;
0 1 0;
0 1 1;
1 0 0;
1 0 1;
1 1 0;
1 1 1];
s = tradeSignal(pop, signals)
s =

0
0
1
0
0
0
1
0

Paul Wesson

Paul Wesson

### Paul Wesson (view profile)

60 minutes in 1 hour.
11 trading hours of 1-minute data in a day.

Trader

### Trader (view profile)

I was wondering the same thing, could someone please explain why he is multiplying by 60 and 11?

Justinas Barauskas

### Justinas Barauskas (view profile)

Hi is just wanted a sharpe question :)

%%
% Develop a trading signal and performance measures. We'll assume 250
% trading days per year.
s = zeros(size(BundClose));
s(lead>lag) = 1; % Buy (long)
s(lead<lag) = -1; % Sell (short)
r = [0; s(1:end-1).*diff(BundClose)]; % Return
sh = sqrt(250)*sharpe(r,0); % Annual Sharpe Ratio

Hi Stuart,

if I am to use minute data(NOT DAILY as used in the example) does that mean i have to adjust the sharpe annual scaling as well?

i.e. sqrt(250*60*11)

imad kachacha

Jorge

### Jorge (view profile)

I am having difficulty trying to load my own high frequency data in line 181 of AlgoTradingDemo1.m. I get the following error message:
??? Error using ==> movavg at 41
Lead and lag arguments must be positive <= 23.
I believe the error stems from line 39 of movavg.m:
r = length(asset);
somehow, input 'asset' is being passed as zero to function movavg. I notice that when bund1min.mat is loaded using the load function, it automatically generates a variable 'data'. When I load my own .mat file, it does not generate a 'data' variable. Could this be the problem?

zhang

Artik Crazy

### Artik Crazy (view profile)

Great Webinar and usefull code.
Only how can I get the PP slides that were used in the webinar?

Fabrice

### Fabrice (view profile)

Really Amazing !!

### Updates

 1 Sep 2016 1.1.0.1 Updated license 6 Dec 2010 1.1 Updated link to recorded version of the webinar.
##### MATLAB Release
MATLAB 7.11 (R2010b)
##### Acknowledgements

Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.