% Time series and trajectory animation of the 
% S&P 500 and NASDAQ data in the file SNindices.mat

% Set frame rate for playback:
framerate = 0.01;

load SNindices

Smin = min(S); Smax = max(S);
Nmin = min(N); Nmax = max(N);
ndates = datenum(dates);
dmin = min(ndates); dmax = max(ndates);
fig = figure;
subplot(2, 1, 1)
% Plot first point from each data set and set axes:
[hax, hS, hN] = plotyy(ndates(1), S(1), ndates(1), N(1));
   
set(hax(1), 'XGrid', 'on', 'YGrid', 'on')
set(hax(2), 'XGrid', 'on', 'YGrid', 'on')
set(hax(1), 'XLim', [dmin dmax], 'YLim', [Smin Smax])
set(hax(2), 'XLim', [dmin dmax], 'YLim', [Nmin Nmax])
set(hax(1), 'XTick', [datenum('01-Jan-1999'):365:datenum('01-Jan-2001')])
set(hax(2), 'XTick', [datenum('01-Jan-1999'):365:datenum('01-Jan-2001')])
set(hax(1), 'XTickLabel', {'1999'; '2000'; '2001'})
set(hax(2), 'XTickLabel', {'1999'; '2000'; '2001'})
set(hax(1), 'YTick', round([Smin:(Smax-Smin)/5:Smax]))
set(hax(2), 'YTick', round([Nmin:(Nmax-Nmin)/5:Nmax]))
h1 = legend(hax(1), 'S&P 500', 2);
set(h1, 'Color', 'w')
h2 = legend(hax(2), 'NASDAQ', 1);
set(h2, 'Color', 'w')

subplot(2, 1, 2)
% Plot first point and set axes:
ht = plot(N(1), S(1), 'co', 'MarkerFaceColor', 'c', 'MarkerSize', 2);

set(gca, 'XGrid', 'on', 'YGrid', 'on')
set(gca, 'XLim', [Nmin Nmax], 'YLim', [Smin Smax])
set(gca, 'XTick', round([Nmin:(Nmax-Nmin)/5:Nmax]))
set(gca, 'YTick', round([Smin:(Smax-Smin)/5:Smax]))
title('S&P 500 vs. NASDAQ')

% Prevent flickering in display:
set(gcf, 'DoubleBuffer', 'on');
ind = 1;
% Keep axes settings and display initial segments of data in order:
for t = 1:length(ndates)-1
    set(hS, 'Xdata', ndates(1:t), 'Ydata', S(1:t))
    set(hN, 'Xdata', ndates(1:t), 'Ydata', N(1:t))
    set(get(hax(1), 'Title'), 'String', ['\fontname{Courier New}{', '\bf{Date:} ', dates(t,:), '}'])
    set(ht, 'Xdata', N(1:t), 'Ydata', S(1:t))
    pause(framerate)     
    drawnow
    if ~mod(t,10)  % only capture every 10th frame
        F(ind) = getframe(fig);
        ind = ind+1;
    end
end
F(ind) = getframe(fig);
clear h1 h2 hS hN hax ht Smin Smax Nmin Nmax dmin dmax t ndates framerate

disp('To watch the movie, press return')
pause
hfig = figure; movie(hfig,F,1,[],[0 0 0 0]);

disp('To convert the movie to an AVI file, press return')
pause
movie2avi(F,'snmovie.avi')