Code covered by the BSD License

# Automated Trading with MATLAB - 2012

### Stuart Kozola (view profile)

31 Aug 2012 (Updated )

```function varargout = leadlag(P,N,M,scaling,cost)
%   moving-average technical indicator.
%
%   S = LEADLAG(PRICE) returns a trading signal based upon a 12-period
%   lead and a 26-period lag.  This is the default value used in a MACD
%   indicator.  S is the trading signal of values -1, 0, 1 where -1 denotes
%   a sell (short), 0 is neutral, and 1 is buy (long).
%
%   a M-period lag.
%
%   absolute return in R, the Sharpe Ratio in SH calculated using R, and
%   the LEAD or LAG series.
%
%   EXAMPLE:
%   % IBM
%     ax(1) = subplot(2,1,1);
%     title('IBM Price Series')
%     ax(2) = subplot(2,1,2);
%     plot(s)
%     set(gca,'YLim',[-1.2 1.2])
%
%   % Disney
%     dis_CLOSE(isnan(dis_CLOSE)) = [];
%     ax(1) = subplot(2,1,1);
%     title('Disney Price Series')
%     ax(2) = subplot(2,1,2);
%     plot(s)
%     set(gca,'YLim',[-1.2 1.2])
%

%%
% Copyright 2010-2012, The MathWorks, Inc.

%% Process input args
if ~exist('scaling','var')
scaling = 1;
end

if ~exist('cost','var')
cost = 0;
end

if nargin < 2
% default values
M = 26;
N = 12;
elseif nargin < 3
'When defining a leading window, the lag must be defined too')
end

if nargin > 0
s = zeros(size(P));

pandl   = [0; s(1:end-1)].*P + cash;
r = diff(pandl);
sh = scaling*sharpe(r,0);

if nargout == 0 % Plot
%% Plot results
ax(1) = subplot(2,1,1);
title(['Lead/Lag EMA Results, Annual Sharpe Ratio = ',num2str(sh,3)])
ax(2) = subplot(2,1,2);
plot([s,pandl]); grid on
legend('Position','Cumulative Return','Location','Best')
title(['Final Return = ',num2str(sum(r),3),' (',num2str(sum(r)/P(1)*100,3),'%)'])
xlabel(ax(1), 'Serial day number');
xlabel(ax(2), 'Serial day number');
ylabel(ax(1), 'Price (\$)');
ylabel(ax(2), 'Returns (\$)');
else
for i = 1:nargout
switch i
case 1
varargout{1} = s;
case 2
varargout{2} = r;
case 3
varargout{3} = sh;
case 4
case 5
varargout{5} = lag;
otherwise
'Too many output arguments requested, ignoring last ones');
end %switch
end %for
end %if
else
%% Run Example
example(1:2)
end %if

%% Examples
function example(ex)
for e = 1:length(ex)
for e = 1:length(ex)
switch ex(e)
case 1
figure(1), clf
ax(1) = subplot(2,1,1);
title('IBM Price Series')
ax(2) = subplot(2,1,2);
plot(s)
set(gca,'YLim',[-1.2 1.2])
xlabel(ax(1), 'Serial day number');
xlabel(ax(2), 'Serial day number');
ylabel(ax(1), 'Price (\$)');
ylabel(ax(2), 'Returns (\$)');
case 2
figure(2),clf
dis_CLOSE(isnan(dis_CLOSE)) = [];
ax(1) = subplot(2,1,1);
title('Disney Price Series')
ax(2) = subplot(2,1,2);
plot(s)