%% Distributed Marginal Value-at-Risk Simulation
% This example uses the Parallel Computing Toolbox(TM) to perform a Monte Carlo
% simulation of a number of stocks in a
% portfolio. At a given confidence level, we predict the value at risk (VaR) 
% of the portfolio as well as the marginal value at risk (mVaR) of each of
% the stocks in the portfolio.  We also provide confidence intervals for our 
% estimates.
%
% For details about the computations, 
% <matlab:edit(fullfile(matlabroot, 'examples', 'distcomp', 'pctdemo_setup_mvar.m')) view the code for pctdemo_setup_mvar>.
%
% Prerequisites:
% 
% * <docid:distcomp_examples.example-ex53988799
% Customizing the Settings for the Examples in the Parallel Computing Toolbox> 
% * <docid:distcomp_examples.example-ex17307408
% Dividing MATLAB(R) Computations into Tasks>
% * <docid:distcomp_examples.example-ex92578668 Writing Task Functions>
%
% Related examples:
%
% * <docid:distcomp_examples.example-ex32863272 Sequential Marginal Value-at-Risk Simulation>

%   Copyright 2007-2012 The MathWorks, Inc.

%% Analyze the Sequential Problem
% First, we look at how the computations in the sequential example fit into the
% model introduced in the <docid:distcomp_examples.example-ex17307408 Dividing MATLAB
% Computations into Tasks> example.  The main computations in the sequential example
% consist of calling |pctdemo_task_mvar| to perform repeated simulations. 
% Each simulation takes only a few seconds, so we have each task perform many 
% such simulations.  Because the function |pctdemo_task_mvar| can already
% perform many simulations in a single function call, we can use it directly as 
% our task function.

%% Load the Example Settings and the Data
% The example uses the default profile when identifying the cluster to use.
% The
% <matlab:helpview(fullfile(docroot,'toolbox','distcomp','distcomp_ug.map'),'profiles_help')
% profiles documentation> 
% explains how to create new profiles and how to change the default 
% profile.  See 
% <docid:distcomp_examples.example-ex53988799
% Customizing the Settings for the Examples in the Parallel Computing Toolbox> 
% for instructions on how to change the example difficulty level or the number of
% tasks created.
[difficulty, myCluster, numTasks] = pctdemo_helper_getDefaults();

%%
% We obtain the performance of the stocks, their weights in our portfolio, and
% other input data from |pctdemo_setup_mvar|.  The number of repetitions,
% |numTimes|, is determined by the |difficulty| parameter.
% You can 
% <matlab:edit(fullfile(matlabroot, 'examples', 'distcomp', 'pctdemo_setup_mvar.m')) view the code for pctdemo_setup_mvar> 
% for full details.
[fig, numSims, numTimes, stock, names, weights, time, confLevel] = ...
    pctdemo_setup_mvar(difficulty); 
%%
% Let's look at the confidence level at which we are calculating the VaR and
% mVaR.
fprintf('Calculating VaR and mVaR at the %3.1f%% confidence level.\n', ...
        confLevel);
startTime = clock;

%% Divide the Work into Smaller Tasks
% We divide the |numTimes| repetitions of the simulations among the |numTasks| 
% tasks. 
[splitTimes, numTasks] = pctdemo_helper_split_scalar(numTimes, numTasks);
fprintf(['This example will submit a job with %d task(s) ' ...
         'to the cluster.\n'], numTasks);

%% Create and Submit the Job
% We create the job and the tasks in the job.  We let the task function in task
% |i| perform |splitTimes(i)| repetitions of the simulations.
% You can 
% <matlab:edit(fullfile(matlabroot, 'examples', 'distcomp', 'pctdemo_task_mvar.m')) view the code for pctdemo_task_mvar> 
% for full details.
job = createJob(myCluster);
for i = 1:numTasks
    createTask(job, @pctdemo_task_mvar, 2, ...
               {splitTimes(i), stock, weights, time, numSims, confLevel});
end

%%
% We can now submit the job and wait for it to finish.
submit(job);
wait(job);

%% Retrieve the Results
% Let us obtain the job results, verify that all the tasks finished
% successfully, and then delete the job.  |fetchOutputs| will throw an
% error if the tasks did not complete successfully, in which case we need
% to delete the job before throwing the error.
try
    jobResults = fetchOutputs(job);
catch err
    delete(job);
    rethrow(err);
end

%%
% We collect the task results. 
VaR = cat(1, jobResults{:, 1});
mVaR = cat(1, jobResults{:, 2});

%%
% We have now finished all the verifications, so we can delete the job.
delete(job);

%% Measure the Elapsed Time
% The time used for the distributed computations should be compared
% against the time it takes to perform the same set of calculations
% in the <docid:distcomp_examples.example-ex32863272 
% Sequential Marginal Value-at-Risk Simulation> example.
% The elapsed time varies with the underlying hardware and network infrastructure.
elapsedTime = etime(clock, startTime);
fprintf('Elapsed time is %2.1f seconds\n', elapsedTime);

%% Plot the Results
% We use |pctdemo_plot_mvar| to create a graph of the value at risk of our
% portfolio at the given confidence level.  The graph also shows the marginal
% value at risk of the individual stocks in our portfolio at that same
% confidence level. You can 
% <matlab:edit(fullfile(matlabroot, 'examples', 'distcomp', 'pctdemo_plot_mvar.m')) view the code for pctdemo_plot_mvar> for
% full details.
pctdemo_plot_mvar(fig, VaR, mVaR, time, names);
