function cov = ReMeDI2(logprice, jvec, kn)
%%
%  cov = ReMeDI2(logprice, jvec, kn)
% 
%  Estimating the (co)variance of noise by Realized Moments of Disjoint Increaments
%  (ReMeDI) of observed (noisy) prices. 
% 
%  Inputs:  logprice --- the logarithmic price
%           jvec--- a vector containing targeted parameters of 2nd mmt of
%           noise, e.g., jvec =[0, 2, 5], ReMeDI2 will returns tthe
%           estimated variance of noise, 2nd and 5th-order covariances
%           kn --- tuning parameters of the estimator
% 
%  Outputs: covs --- the estimated covariances up to order covorder
% 
%  
%  References:
% 
%  Li, Z. Merrick and Oliver Linton (2018):
%  "A ReMeDI for microstructure noise."
% 
%  Authors : Z. Merrick Li and Oliver Linton
% 
%  Date : 01 July 2018
%%
y = logprice(~isnan(logprice));
Numvec = length(jvec);
cov = zeros(Numvec,1);
for i = 1:Numvec
    cov(i) = ReMeDI2j(y,jvec(i),kn);
end
end


function secondmmt = ReMeDI2j(logprice, j, kn)
%%
%  secondmmt = ReMeDI2j(logprice, j, kn)
%
%  Estimating the (co)variance of noise by Realized Moments of Disjoint Increaments
%  of observed prices. 
%
%  Inputs:  logprice --- the logarithmic price
%           j --- the maximum order of covariances
%           kn --- tuning parameters of the estimator
%
%  Outputs: covs --- the estimated covariances up to order covorder
%
%
%  References: 
%
%  Li, Z. Merrick and Oliver Linton. "Robust measures of microstructure noise."
%
%  Authors : Z. Merrick Li and Oliver Linton
%
%  Date : 01 July 2018
%%
y = logprice;
n = length(y);
s = 0;
for i = 1:n- 3*kn - j
   s = s + (y(i+2*kn)-y(i))*(y(i+3*kn+j) - y(i+2*kn+j));
end
secondmmt = -s/(n-3*kn-j);
end
