%% example of how to use MDobj.m and MDestim.m

%% figure formatting

set(0,'DefaultTextInterpreter','latex')
set(0,'DefaultAxesTickLabelInterpreter','latex');
set(0,'DefaultLegendInterpreter', 'latex')

set(0,'DefaultTextFontSize', 14)
set(0,'DefaultAxesFontSize', 14)
set(0,'DefaultLineLineWidth',2)

set(0,'DefaultTextFontSize', 14)
set(0,'DefaultAxesFontSize', 14)
set(0,'DefaultLineLineWidth',2)

close all

data = xlsread('TabFig2017prel.xls','Table A3','A10:G110');
% Table A1: excluding capital gains
% Table A3: including capital gains

year = data(:,1);
T = length(year);
TopShares = fliplr(data(:,2:end));
percent = [0.01 0.1 0.5 1 5 10];

p = percent/100;
S = TopShares(end,:)/100;

N = 101;
xigrid = linspace(0.01,0.99,N);
Ggrid = zeros(N,1);
for n=1:N
    G = MDobj(xigrid(n),p,S);
    Ggrid(n) = G;
end

figure(1)
plot(xigrid,Ggrid)
ylim([0,0.1])
xlabel('$\xi=1/\alpha$')
ylabel('Objective function')

fun = @(xi)MDobj(xi,p,S);
alpha0 = 2;
xi0 = 1/alpha0;
tic
xi = fmincon(fun,xi0,[],[],[],[],0.01,0.99);
toc

n = 1e5; % sample size

tic
[alpha,G,xi,sigma_xi,alphaCI] = MDestim(p,S,[],n);
toc
