View License

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

» Watch video

Highlights from
Algorithmic Trading with MATLAB - 2010

5.0 | 16 ratings Rate this file 70 Downloads (last 30 days) File Size: 1.87 MB File ID: #29489 Version:
image thumbnail

Algorithmic Trading with MATLAB - 2010


Stuart Kozola (view profile)


22 Nov 2010 (Updated )

Files from the November 18, 2010 webinar.

| Watch this File

File Information

Files used in the webinar - Algorithmic Trading with MATLAB Products for Financial Applications broadcast on November 18, 2010. This webinar can be viewed at
The download includes an additional demo, not shown in the webinar, that shows how to generate C-code from MATLAB.


This file inspired Algorithmic Trading With Bloomberg Emsx And Matlab, Automated Trading With Matlab 2012, and Commodities Trading With Matlab.

Required Products Financial Toolbox
Global Optimization Toolbox
Optimization Toolbox
Statistics and Machine Learning Toolbox
MATLAB release MATLAB 7.11 (R2010b)
Other requirements To run AlgoTradingDemo5.m you will also need a compatible compiler and Real-Time Workshop
Tags for This File   Please login to tag files.
Please login to add a comment or rating.
Comments and Ratings (36)
16 Feb 2017 Nikos Rentoumis

19 Oct 2016 Jana Juhaszova

28 Aug 2016 Sergey Frolov

04 Aug 2016 Charles

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

Comment only
04 Aug 2016 Charles

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.

Comment only
11 Jul 2016 Liang Seacom

11 Jul 2016 Liang Seacom

Very cool code.

23 Mar 2016 Vegeta

Vegeta (view profile)

23 Feb 2016 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?

05 Dec 2014 mom

mom (view profile)


01 Oct 2014 Andoni Olaeta


Comment only
23 May 2014 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?

Comment only
22 Dec 2013 Andre Viana

08 Jul 2013 Mark

Mark (view profile)

Those following this thread my find the website: interesting. Some of the work here inspired it.

Comment only
25 Mar 2013 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).

Comment only
07 Mar 2013 Chen

Chen (view profile)


04 Mar 2013 joseph Frank

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

Error in filter2 (line 10)

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)

Error in scribe.legend/init (line 137)

Error in scribe.legend (line 122)

Error in legend>make_legend (line 386)

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

Error in AlgoTradingDemo1 (line 21)

Comment only
12 Feb 2013 Sumit

Sumit (view profile)

Great explanation!

14 Oct 2012 Mario

Mario (view profile)

29 Sep 2012 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.

Comment only
04 Sep 2012 Karamos

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
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?


Comment only
13 Jun 2012 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.

Comment only
10 Jun 2012 Mate 2u

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

Comment only
09 Jun 2012 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?

Comment only
09 Jun 2012 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
else %for all other indicators, combine with the results generated so far
sigA = sigC;

% indicator 2

% connector
if (ind2use(iInd)==0) sigC=sigB; %I1 inactive
elseif (ind2use(iInd+1)==0) sigC=sigA; %I2 inactive
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 %for
sigOut(:,iPop) = sigC;

Comment only
06 Jun 2012 Fuzhi Cheng

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.

Comment only
23 Apr 2012 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 =


Comment only
09 Apr 2012 Paul Wesson

Comment only
09 Apr 2012 Paul Wesson

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

Comment only
09 Apr 2012 Trader

Trader (view profile)

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

Comment only
17 Mar 2012 Justinas Barauskas

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)

Comment only
29 Dec 2011 imad kachacha

20 Oct 2011 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?

Comment only
26 May 2011 zhang

zhang (view profile)

09 Dec 2010 Artik Crazy

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

06 Dec 2010 Fabrice

Really Amazing !!

06 Dec 2010 1.1

Updated link to recorded version of the webinar.

01 Sep 2016

Updated license

Contact us