| [T,H,L,O,C,V]=Tick2Bar(t,p,v,g)
|
function [T,H,L,O,C,V]=Tick2Bar(t,p,v,g)
% [T,H,L,O,C,V]=Tick2Bar(t,p,v,g)
% Divides a time series into periods of g days
% (may be less than one day).
% It is useful in conjunction with HIGHLOW
% [T,H,L,O,C,V]=Tick2Bar(t,p,v,g);
% highlow(H(:),L(:),C(:),O(:),'k',T(:));
%
% It returns:
%
% T date/time of the period
% H high of the period
% L low of the period
% O open (first datum of the period)
% C close (last datum of the period)
% V volume of the period
%
% given
%
% t date/time
% p price
% v volume
% g time granularity [days]
%
% USAGE
%
% % test data
% N=1e4;
% g=1/(24*60*60); % 1 minute granularity
% t=([1:N]+rand(1,N)).*g; % time
% p=100+rand(1,N).*10; % price
% v=1e4.*rand(1,N); % volume
% % add some test-NANs
% a=randperm(N);
% v(a(1:10))=nan;
%
% g=1/(24*60*60); % 1 minute granularity
% [T,H,L,O,C,V]=Tick2Bar(t,p,v,g);
%
% subplot(6,1,1:2);
% plot(t,p,'k');
% datetick;
% title('plot(t,p,''k'');')
%
% subplot(6,1,3);
% plot(t,v,'k');
% datetick;
% title('plot(t,v,''k'');');
%
% subplot(6,1,4:5);
% highlow(H(:),L(:),C(:),O(:),'k',T(:));
% datetick;
% title('highlow(H(:),L(:),C(:),O(:),''k'',T(:));');
%
% subplot(6,1,6);
% plot(T,V,'k');
% datetick;
% title('plot(T,V,''k'');');
%
% h=suptitle('[T,H,L,O,C,V]=Tick2Bar(t,p,v,g);');
% set(h,'FontSize',get(h,'FontSize').*2,'FontWeight','Bold');
%
%
% IT'S NOT FANCY BUT IT WORKS
% Michael Robbins
% robbins@bloomberg.net
% michael.robbins@us.cibc.com
% Thanks to: us (us@neurol.unizh.ch) for helping to speed up
% also to Loren Shure(loren@mathworks.com)
% ORIENT INPUTS
t=t(:).';
p=p(:).';
v=v(:).';
% CHECK SIZE
if all(size(t)==size(p)) & all(size(t)==size(v))
% THE FUNCTION
%-----------------------------------------
% pre-condition
% ... sort for smart indexing
[t,tix]=sort(t);
p=p(tix);
v=v(tix);
% ... remove NANs for smart summing
vix=~isnan(v);
t=t(vix);
p=p(vix);
v=v(vix);
% create bins
edges=[floor(min(t)):g:ceil(max(t))];
[n,bin]=histc(t,edges);
[ubin,i]=unique(bin);
T=edges(ubin+1);
% ... and bin-indices
ix=[[1 cumsum(n(ubin))+1]; ...
[cumsum(n(ubin)) length(bin)]];
ix=ix(:,1:end-1);
n=size(ix,2);
% pre-allocate
tt.H=zeros(n,1);
tt.L=zeros(n,1);
tt.O=zeros(n,1);
tt.C=zeros(n,1);
tt.V=zeros(n,1);
for i=1:n
k=ix(1,i):ix(2,i);
tt.H(i)=max(p(k));
tt.L(i)=min(p(k));
[temp,j]=min(t(k));
tt.O(i)=p(k(j));
[temp,j]=max(t(k));
tt.C(i)=p(k(j));
tt.V(i)=sum(v(k));
end
tt.T=T;
H=tt.H;
L=tt.L;
O=tt.O;
C=tt.C;
V=tt.V;
else
error('TICK2BAR:: Input sizes don''t match');
end;
|
|