%% Figure A: ECDF (left-tail zoom) + VaR(5%) + tau
clear; clc;

% --- Inputs ---
fileWith  = 'weekly_decisions.csv';
fileNo    = 'weekly_decisions_noJPX.csv';
fileLocal = 'DPRC_up_clean_merged.csv';

alpha = 0.05;      % VaR/CVaR level
zoomQ = 0.25;      % zoom to left tail up to 25th percentile of baseline

% --- Read data ---
W = readtable(fileWith);
N = readtable(fileNo);
L = readtable(fileLocal);

% --- Out-of-sample alignment (243 weeks): rows 21..263 (MATLAB 1-indexed) ---
pLocal = L.LOCAL(21:263);

% --- Build unconditional price series ---
pImm  = pLocal;

pWith = pLocal;
saleW = (W.sell_qty > 0) & (W.rev_local > 0);
pWith(saleW) = W.rev_local(saleW) ./ W.sell_qty(saleW);

pNo = pLocal;
saleN = (N.sell_qty > 0) & (N.rev_local > 0);
pNo(saleN) = N.rev_local(saleN) ./ N.sell_qty(saleN);

% --- Compute VaR(5%) for each series ---
VaR_imm  = quantile(pImm,  alpha);
VaR_with = quantile(pWith, alpha);
VaR_no   = quantile(pNo,   alpha);

% --- Threshold tau: median of baseline (Immediate sale) ---
tau = median(pImm);

% --- ECDF (use ecdf if Statistics Toolbox exists; otherwise manual fallback) ---
hasECDF = exist('ecdf','file') == 2;

if hasECDF
    [F_imm,  X_imm]  = ecdf(pImm);
    [F_with, X_with] = ecdf(pWith);
    [F_no,   X_no]   = ecdf(pNo);
else
    % manual ECDF
    X_imm  = sort(pImm(:));  F_imm  = (0:numel(X_imm)-1)'/(numel(X_imm)-1);
    X_with = sort(pWith(:)); F_with = (0:numel(X_with)-1)'/(numel(X_with)-1);
    X_no   = sort(pNo(:));   F_no   = (0:numel(X_no)-1)'/(numel(X_no)-1);
end

% --- Left-tail zoom range ---
xMin = min([pImm; pWith; pNo]);
xMax = quantile(pImm, zoomQ);

% --- Plot ---
figure('Color','w','Position',[120 120 900 520]); hold on;

plot(X_imm,  F_imm,  'LineWidth',1.6, 'DisplayName','Immediate sale (Local)');
plot(X_with, F_with, 'LineWidth',1.6, 'DisplayName','Proposed (with JPX)');
plot(X_no,   F_no,   'LineWidth',1.6, 'DisplayName','Proposed (no JPX)');

% Vertical lines: VaR(5%)
xline(VaR_imm,  '--', 'LineWidth',1.2, 'HandleVisibility','off');
xline(VaR_with, '--', 'LineWidth',1.2, 'HandleVisibility','off');
xline(VaR_no,   '--', 'LineWidth',1.2, 'HandleVisibility','off');

% Vertical line: tau
xline(tau, ':', 'LineWidth',1.4, 'HandleVisibility','off');

% Annotations (minimal but clear)
yl = ylim;
text(VaR_with, yl(2)*0.15, sprintf('VaR(5%%) with JPX = %.2f', VaR_with), ...
    'HorizontalAlignment','left','VerticalAlignment','bottom','FontSize',10);

text(tau, yl(2)*0.80, sprintf('\\tau (median baseline) = %.2f', tau), ...
    'HorizontalAlignment','left','VerticalAlignment','bottom','FontSize',10);

xlim([xMin xMax]);
ylim([0 1]);

xlabel('Realised local price (THB/kg) — left-tail zoom');
ylabel('ECDF  F(p) = Pr(Price ≤ p)');
%title('Figure 3 ECDF (left tail) and VaR(5%) illustration (unconditional series)');
legend('Location','southeast');
grid on; box on;

exportgraphics(gcf,'Figure 3_ECDF_lefttail.png','Resolution',200);
