% Export binary beliefs to CSV for Stata
%
% Computes excess movement (M-R) for each contract-bin pair and assembles
% export matrix with dates, M, R, probabilities, contract length, and pi0
%
% Assumes in workspace: binaryProbs, binaryProbStartOfContract,
%   binaryDates, exDates, last_ex

clear am_exp ans baseIndex binaryProb binIndexes bothLessThan date4 datesToUse diffFinalEnd dtm exDate exDateIndex finalObservationIndex firstObservationIndex i initPriceDateIndex* opt_dtm opt_ytm pctIndex priceDateIndexes probData returnDiff select_zc_indices startDate startPrice temp_zc_date tmp zc_curve* zc_interp;

binaryProbsUse = binaryProbs;
binaryProbM = NaN(size(binaryProbsUse));
binaryProbR = NaN(size(binaryProbsUse));
binaryProbMRFull = NaN(size(binaryProbsUse,1),size(binaryProbsUse,2));
binaryProbMFull = NaN(size(binaryProbsUse,1),size(binaryProbsUse,2));
binaryProbRFull = NaN(size(binaryProbsUse,1),size(binaryProbsUse,2));
contractLength = NaN(size(binaryProbsUse,1),size(binaryProbsUse,2));
pi0 = binaryProbStartOfContract;

for t_exp=1:size(binaryProbsUse,1)
    
    bin_inds = find(~isnan(max(binaryProbsUse(t_exp,:,:),[],3)));
    
    for bin=bin_inds
        
        t=1;
        while t<size(binaryProbsUse,3)
           
            t_next = t+find(~isnan(binaryProbsUse(t_exp,bin,t+1:end)),1,'first');
            if isempty(t_next)
                contractLength(t_exp,bin) = t-1;
                break
            end
            binaryProbM(t_exp,bin,t) = (binaryProbsUse(t_exp,bin,t)-binaryProbsUse(t_exp,bin,t_next))^2;
            binaryProbR(t_exp,bin,t) = binaryProbsUse(t_exp,bin,t_next)*(1-binaryProbsUse(t_exp,bin,t_next))-binaryProbsUse(t_exp,bin,t)*(1-binaryProbsUse(t_exp,bin,t));
            t = t_next;
            
        end
        
        binaryProbMRFull(t_exp,bin) = nansum(binaryProbM(t_exp,bin,:))-nansum(binaryProbR(t_exp,bin,:));
        binaryProbMFull(t_exp,bin) = nansum(binaryProbM(t_exp,bin,:));
        binaryProbRFull(t_exp,bin) = nansum(binaryProbR(t_exp,bin,:));
        
    end
    
end

binaryProbMR = binaryProbM-binaryProbR;

binaryDatesTemp = NaT(size(binaryDates,1),1,size(binaryDates,2));
binaryDatesTemp(:,1,:) = binaryDates;
binaryDates = repmat(binaryDatesTemp,1,size(binaryProbMR,2),1);
binaryMonth = month(binaryDates);
binaryDay = day(binaryDates);
binaryYear = year(binaryDates);
if length(exDates)>last_ex
    exDates = exDates(1:last_ex); 
end
exDates = repmat(exDates,1,size(binaryProbMR,2),size(binaryProbMR,3));
exDateMonth = month(exDates);
exDateDay = day(exDates);
exDateYear = year(exDates);

contractLength = repmat(contractLength,1,1,size(binaryProbMR,3));
pi0 = repmat(pi0,1,1,size(binaryProbMR,3));
bin = 1:size(binaryProbs,2);
bin = repmat(bin,size(binaryProbs,1),1,size(binaryProbs,3));

exportMat = [binaryYear(:) binaryMonth(:) binaryDay(:) exDateYear(:) exDateMonth(:) exDateDay(:) binaryProbM(:) binaryProbR(:) binaryProbMR(:) binaryProbs(:) contractLength(:) pi0(:) bin(:)];