%% Figure 5.4  Selling share by market state
% Immediate vs Proposed (with JPX) vs Proposed (no JPX)

clear; clc;

% ---- File paths
f_jpx   = 'weekly_decisions.csv';
f_nojpx = 'weekly_decisions_noJPX.csv';

% ---- Read tables
Tj = readtable(f_jpx);
Tn = readtable(f_nojpx);

% ---- Ensure numeric (robust to CSV quirks)
Tj.state_id  = double(Tj.state_id);
Tj.sell_frac = double(Tj.sell_frac);

Tn.state_id  = double(Tn.state_id);
Tn.sell_frac = double(Tn.sell_frac);

% ---- Compute average selling share by state
states = unique([Tj.state_id; Tn.state_id]);
states = sort(states);

avgSell_JPX   = nan(size(states));
avgSell_noJPX = nan(size(states));
avgSell_Imm   = ones(size(states));   % Immediate sale = sell 100%

for i = 1:numel(states)
    s = states(i);

    idxJ = (Tj.state_id == s);
    if any(idxJ)
        avgSell_JPX(i) = mean(Tj.sell_frac(idxJ), 'omitnan');
    end

    idxN = (Tn.state_id == s);
    if any(idxN)
        avgSell_noJPX(i) = mean(Tn.sell_frac(idxN), 'omitnan');
    end
end

% ---- Plot
figure('Color','w');
plot(states, avgSell_Imm,  '-o', 'LineWidth',1.5); hold on;
plot(states, avgSell_JPX,  '-s', 'LineWidth',1.5);
plot(states, avgSell_noJPX,'-^', 'LineWidth',1.5);
grid on;

xlabel('Market state');
ylabel('Average selling share');
%title('Figure 2 Selling share by market state');

legend({'Immediate sale', ...
        'Proposed rule (with JPX)', ...
        'Proposed rule (no JPX)'}, ...
        'Location','best');

% ---- Optional export
% exportgraphics(gcf,'Figure_5_4_selling_share_by_state.png','Resolution',300);
