SimoPape
SimoPape

Reputation: 47

How to plot Histrogram in a 3d plot with plot3 function

I am trying to plot histograms over the trajectories of a particular stochastic process using the plot3 function and a function to plot histograms.

I briefly explain the logic.

Focus on this is the important part.

y = @(x,T) lognpdf(x,log(S0)+(r-0.5*sigma^2)*T,sigma*sqrt(T));
T = linspace(0,T,5);
for i = 1:length(T)
    ind = find(t>=T(i),1,'first');
    x_arg = linspace(min(S(:,ind))-20, max(S(:,ind))+40, 100);
    plot3(T(i)*ones(length(x_arg),1),x_arg,y(x_arg,T(i)),'k','linewidth',2)
end

The idea would be to plot at certain time intervals the frequency histogram by taking an equispaced grid from the smallest value to the largest value.

To show what the result should look like I assumed that my process evolves with a log-normal distribution (completely meaningless but it is to give the idea of the result) and plotted the distribution at various time steps. Now I would like to do the same thing but with histograms (since I don't actually know this distribution) for both processes S(t) and V(t).

The output result should be similar to this (but with Histograms)

S(t) process

V(t) process

I leave below the code (it should also be compatible with GNU Octave, the Matlab clone).

I thank in advance anyone who wants to help me or give me a suggestion. Have a nice day everyone :)

%% Simulation of the Heston (1993) Stochastic Volatility Process
clear variables
close all
clc

% fixing seed of for replicability
rng(37,"twister")


%%% Parameters - Simulation dependent
M = 25; % number of paths
N = 252; % number of days
T = 1.0; % Time in years

% Parameters - Heston dependent
r = 0.02; % risk free rate
S0 = 100; % initial asset price value
V0 = 0.30; % initial variance value
kappa = 4; % rate of mean reversion of variance under risk-neutral dynamics 
theta = 0.04; % long-term mean of variance under risk-neutral dynamics 
eta = 0.45; % vol-of-vol
rho = -0.3; % correlation between returns and variances under risk-neutral dynamics     


%%% Heston simulation
[S,V] = pathsheston(S0,V0,r,kappa,theta,eta,rho,T,M,N);


%%% Plot Heston model paths for S(t)
t = 0:T/N:T;
% figure(1)
% plot(t,S,'linewidth',1.5)
% grid on
% xlabel('time')
% ylabel('S(t)')

%%% Plot Heston model paths for V(t)
% figure(2)
% plot(t,V,'linewidth',1.5)
% grid on
% xlabel('time')
% ylabel('V(t)')


%----------------------------------------------------
% Paths and PdF for S(t) and V(t)
%----------------------------------------------------
sigma = 0.4;

%%% for S(t)
figure3 = figure;
axes4 = axes('Parent',figure3);
hold(axes4,'on');

% density plot for S(t)
plot(t,S,'linewidth',1,'color',[0 0.45 0.74])
y = @(x,T) lognpdf(x,log(S0)+(r-0.5*sigma^2)*T,sigma*sqrt(T));
T = linspace(0,T,5);

for i = 1:length(T)
    ind = find(t>=T(i),1,'first');
    x_arg = linspace(min(S(:,ind))-20, max(S(:,ind))+40, 100);
    plot3(T(i)*ones(length(x_arg),1),x_arg,y(x_arg,T(i)),'k','linewidth',2)
end

axis([0,T(end),0,max(max(S))])
grid on;
xlabel('t')
ylabel('S(t)')
zlabel('density')
view(axes4,[-68.8 40.08]);


%%% for V(t)
figure4 = figure;
axes4 = axes('Parent',figure4);
hold(axes4,'on');

% density plot for S(t)
plot(t,V,'linewidth',1,'color',[0 0.45 0.74])
y = @(x,T) lognpdf(x,log(V0)+(r-0.5*sigma^2)*T,sigma*sqrt(T));

for i = 1:length(T)
    ind = find(t>=T(i),1,'first');
    x_arg = linspace(min(V(:,ind))-0.5, max(V(:,ind))+0.5, 100);
    plot3(T(i)*ones(length(x_arg),1),x_arg,y(x_arg,T(i)),'k','linewidth',2)
end

axis([0,T(end),0,max(max(V))])
grid on;
xlabel('t')
ylabel('V(t)')
zlabel('density')
view(axes4,[-68.8 40.08]);


%% Generate Paths from Heston
function [S,V] = pathsheston(s0,v0,r,kappa,theta,eta,rho,T,nPaths,nSteps)

dt = T/nSteps; % time step

% Cholesky decomposition
Corr = [1, rho; rho, 1]; 
A = chol(Corr,"Upper");     % Corr = A x A^(T)  

TT = randn(nPaths,nSteps,2);  
Z = zeros(nPaths,nSteps+1); % for log(S) increments
V = zeros(nPaths,nSteps+1); % for variance increments
V(:,1) = v0;            

for i = 2 : nSteps+1
    C = squeeze(TT(:,i-1,:))*A;
    V(:,i) = abs(V(:,i-1) + kappa*(theta-V(:,i-1))*dt + eta*sqrt(V(:,i-1)*dt).*C(:,1));
    Z(:,i) = Z(:,i-1)+(r-V(:,i-1)/2)*dt + sqrt(dt*V(:,i-1)).*C(:,2);
end

S = s0*exp(Z);

end

(Very Optional) If you know how to use colors in MatLab; It would be great to have the histogram more in front with a lot of transparency than the one further back (I write really bad but I hope you understand what I am saying anyway it is not necessary I just need to be able to plot the histograms over the paths)

Upvotes: 1

Views: 82

Answers (1)

Hoki
Hoki

Reputation: 11812

You can use histogram2 for this.

I do not have the Statistics and Machine Learning Toolbox. Without this I do not have access to the function lognpdf so I cannot use your exact data. I can run your code until line 56 where you call for the first plot of S(t):

plot(t,S,'linewidth',1,'color',[0 0.45 0.74])

From there, instead of using lognpdf to generate the histograms I have to use mock-up data, loosely adjusted to your data range so the visualisation stays relevant.

%% Generate 5 datasets at different t (called xs to not interfere)
xs = 0:.25:1;
nx = numel(xs) ;
np = 5000 ;
y = zeros( nx , np ) ;
for k=1:nx
    y(k,:) = ( randn(1,5000) * 20*k/nx ) + 100 ;
end

Once I have data I can generate an histogram on, you can display them in 3D in a slice way like so:

hold on
for k = 1:nx
    alphaLevel = k/nx/2+0.25 ; % Will vary alpha from 0.25 to 0.75    
    hh(k) = histogram2( repmat(xs(k),1,np), y(k,:) , xs(k)+[-0.01 0.01] , 0:2:200, ...
        'FaceColor',[.7 .7 .7], 'FaceAlpha',alphaLevel, 'EdgeAlpha',alphaLevel );     
end
% hold off
view(-60,30)

This will get you the following display:

histo3d

As you can see my distribution do not exactly represent your data but you should get the idea. The important points to "slice" your histograms are in the way you call the function. I used the call syntax: histogram2(X,Y,Xedges,Yedges, ...):

  • The first parameters X is a vector containing only the t value at which this histogram should sit. This value is repeated so the vector has the same number of point than y.
  • The second parameter Y is your actual data to be binned in an histogram (use your data for this instead of my sample data).
  • The third parameter Xedges will define the position and thickness of your histogram slice. In this example it has a thickness of 0.02, centered on each t value. Adjust this as necessary for your data.
  • The fourth parameter Yedges is less critical but we have to provide something in this call syntax and it insures all the histograms are bound the same way.

The last few parameters control your optional transparencies, FaceAlpha and EdgeAlpha. The alpha value has to be from 0 (=fully transparent) to 1 (=fully opaque). I made the alpha level vary from 0.25 (first histogram, quite transparent), to 0.75 for the last histogram (almost opaque). Again, feel free to adjust these levels for a nicer visualisation (specially if you use another color for the histograms, then the transparency levels needed to keep the figure clear are to be adjusted).

Upvotes: 1

Related Questions