%% mat_05run_all_matlab_indexvol.m
% Export non-binary (full histogram) RN probabilities to CSV for Table V
% (Option-Implied Excess Index Variance) analysis in Stata
%
% Loads 2ppt RN probability distributions and exports to CSV format for
% constructing the tail-free index S_alt and computing excess movement
%
% Input:  Output/rnProbsBinary_2ppt.mat (from mat_03run_all_matlab_2ppt)
% Output: ../Stata/Input/rnProbAggReshaped2ppt.csv
%         ../Stata/Input/priceDates2ppt.csv
%         ../Stata/Input/exDates2ppt.csv
%         ../Stata/Input/xCdfPctAgg2ppt.csv

%% Part 1: Load and reshape data
load('Output/rnProbsBinary_2ppt.mat');

n = size(rnProbAgg, 1);
nBins = size(rnProbAgg, 2);
nStreams = size(rnProbAgg, 3);

fprintf('Processing %d dates, %d bins, %d streams\n', n, nBins, nStreams);

% Reshape: rows = date*bin, columns = stream values
rnProbAggReshape = zeros(n * nBins, nStreams + 2);
for i = 1:nBins
    s = n * (i - 1) + 1;
    e = n * i;
    % Column 1 = bin index from 1-nBins
    % Column 2 = date index from 1-n
    rnProbAggReshape(s:e, 1) = ones(n, 1) * i;
    rnProbAggReshape(s:e, 2) = 1:n;
    rnProbAggReshape(s:e, 3:nStreams+2) = squeeze(rnProbAgg(:, i, :));
end

% Reshape to long format: stream, bin, date, probability
rnProbAggReshape2 = zeros(n * nBins * nStreams, 4);
for i = 1:nStreams
    s = n * nBins * (i - 1) + 1;
    e = n * nBins * i;
    % Column 1 = stream (expiration date)
    % Column 2 = bin
    % Column 3 = date
    % Column 4 = probability
    rnProbAggReshape2(s:e, 1) = ones(n * nBins, 1) * i;
    rnProbAggReshape2(s:e, 2) = rnProbAggReshape(:, 1);
    rnProbAggReshape2(s:e, 3) = rnProbAggReshape(:, 2);
    rnProbAggReshape2(s:e, 4) = rnProbAggReshape(:, (i + 2));
end

% Remove NaN entries
rnProbAggReshape2(isnan(rnProbAggReshape2(:, 4)), :) = [];

%% Part 2: Export data

% Export probs
csvwrite('Output/rnProbAggReshaped2ppt.csv',rnProbAggReshape2);
csvwrite('../Stata/Input/rnProbAggReshaped2ppt.csv', rnProbAggReshape2);

% Export dates in Unix timestamp format
priceDatesNum = posixtime(priceDates);
dlmwrite('Output/priceDates2ppt.csv', priceDatesNum, 'precision', 12);
dlmwrite('../Stata/Input/priceDates2ppt.csv', priceDatesNum, 'precision', 12);

exDatesNum = posixtime(exDates);
dlmwrite('Output/exDates2ppt.csv', exDatesNum, 'precision', 12);
dlmwrite('../Stata/Input/exDates2ppt.csv', exDatesNum, 'precision', 12);

% Export bin boundaries
csvwrite('Output/xCdfPctAgg2ppt.csv', xCdfPctAgg');
csvwrite('../Stata/Input/xCdfPctAgg2ppt.csv', xCdfPctAgg');