%% Stratified Sampling
%% Set assumptions

rng(10203,'twister')
dt       = 1 / 252;        % 1 day = 1/252 years
nPeriods = 63;             % 3 months = 63 trading days
T        = nPeriods * dt;  % 3 months = 0.25 years
nPaths   = 10;            % # of simulated paths
obj      = bm(0, 1, 'StartState', 0);
sampleTimes = cumsum([obj.StartTime; ...
    dt(ones(nPeriods,1))]);
z        = Example_StratifiedRNG(nPaths, sampleTimes);

%
%% Simulate the standard Brownian paths

X = obj.simulate(nPeriods, 'DeltaTime', dt, ...
    'nTrials', nPaths, 'Z', z);

%
%% Reorder the output sample paths

X = squeeze(X);

%
%% Verify the stratification (Recreate the uniform draws)

rng(10203,'twister')
U  = ((1:nPaths)' - 1 + rand(nPaths,1))/nPaths;

%
%% Verify the stratification (obtain the terminal values)

WT = norminv(U) * sqrt(T);  % Stratified Brownian motion.

%
%% Verify the stratification (plot the terminal values)

plot(sampleTimes, X), hold('on')
xlabel('Time (Years)'), ylabel('Brownian State')
title('Terminal Stratification: Standard Brownian Motion')
plot(T, WT, '. black', T, WT, 'o black')
hold('off')

%
%% Load and process the data

load Data_GlobalIdx2
returns = tick2ret(Dataset.FTSE);
sigma   = std(returns) * sqrt(252);
rate    = Dataset.EB3M;
rate    = mean(360 * log(1 + rate));

%
%% Create the GBM model

obj = gbm(rate, sigma, 'StartState', 100);

%
%% Determine the sample time and simulate the price paths

nSteps      = 1;
sampleTimes = cumsum([obj.StartTime ; ...
dt(ones(nPeriods * nSteps,1))/nSteps]);
z           = Example_StratifiedRNG(nPaths, sampleTimes);
rng(10203,'twister')
[Y, Times]  = obj.simBySolution(nPeriods, 'nTrials', nPaths,...
'DeltaTime', dt, 'nSteps', nSteps,  'Z', z);
Y = squeeze(Y);   % Reorder to a 2-D array
plot(Times, Y)
xlabel('Time (Years)'), ylabel('Index Level')
title('FTSE 100 Terminal Stratification:Geometric Brownian Motion')

% Copyright 2015 The MathWorks, Inc.