//  Filets.sce code pour TP01 et TP02 sur le filet d'une 
//option;
//d'un modele a n etapes
//A.1 et 2 du poly
clear;
n=40;T=1;delta_t=T/n;S0=120;sigma=0.40;K=S0;
up=exp(sigma/sqrt(n));down=1/up;
r=0;R=exp(r*delta_t);
function phi=phi(S);
phi=max(S-K,0);
endfunction;
p=(R-down)/(up-down);
SS=zeros(n+1,n+1);
SS(1+0,1+0)=S0;
for i=1:n
  SS(i+1,0+1)=SS(i,0+1)*down;
  for j=1:i
    SS(i+1,j+1)=SS(i,j)*up;
  end;
end;
// La matrice CC
CC=zeros(n+1,n+1);
for jj=1:n+1    //jj=j+1
  CC(n+1,jj)=phi(SS(n+1,jj)); //ici ii=n+1 c'est le payoff
end;
for ii=n:-1:1
  for jj=1:ii
    CC(ii,jj)=(p*CC(ii+1,jj+1)+(1-p)*CC(ii+1,jj))/R;
  end;
end;
//////// trace du filet des SS /////
///   La fonction  filet   ////
function [Abs,Ord]=filet(SS);
[nl,nc]=size(SS);n=max(nl,nc)-1; //en principe nl=nc: sinon bug dans le dessin! 
Abs=zeros(n+1,n+1);
Ord=zeros(n+1,n+1);
for k=0:n
  for m=0:n-k
    Abs(m+1,k+1)=(k+m)*delta_t;
    Ord(m+1,k+1)=SS(k+m+1,k+1);
  end;
  for m=1:k
    Abs(n-k+m+1,k+1)=(n-m)*delta_t;
    Ord(n-k+m+1,k+1)=SS(n-m+1,k-m+1);
  end;
end;
endfunction;
////// Utilisation de la fonction filet  ///
[Abs,Ord]=filet(SS);
xset("window",1);
plot2d(Abs,Ord)
xs2eps(1,'ArbreCox.eps');
//xs2gif(0,'ArbreCox.gif');

//////// trace du filet des CC /////
[Abs,Cot]=filet(CC);
xset("window",2);
plot2d(Abs,Cot)
//xs2eps(2,'ArbreCoxCall.eps');

//////// trace du filet des SS CC /////
xset("window",3);
//set("figure_style","new"); //create a figure
   a=get("current_axes");//get the handle of the newly created axes
   a.cube_scaling="on"; // [GED] Axes->Aspect->cube_scaling=on
//C=hotcolormap(32);
//xset("colormap",C);
//xset("hidden3d",30); //choix de la couleur 30 pour les faces negatives
//ATTENTION: choisir flag=[1 4] pour prendre en compte "ebox"
param3d1(Abs,Ord,Cot,alpha=46,theta=-52,flag=[1 4],ebox=[0,T,0,1.5*S0,0,S0/2])

//// ajout de la fonction de payoff phi ///
AbsLignePayOff=ones(1:n+1)*T;
OrdLignePayOff=SS(n+1,:);
CotLignePayOff=CC(n+1,:);
param3d1(AbsLignePayOff,OrdLignePayOff,CotLignePayOff,alpha=46,theta=-52,flag=[1 4])

////////// ajout des Ligne intermediaire I et II
AbsLigneI=ones(1:n/2+1)*T/2;
OrdLigneI=SS(n/2+1,1:n/2+1);
CotLigneI=CC(n/2+1,1:n/2+1);
param3d1(AbsLigneI,OrdLigneI,CotLigneI,alpha=46,theta=-52,flag=[1 4])
//
AbsLigneII=ones(1:n/4+1)*T/4;
OrdLigneII=SS(n/4+1,1:n/4+1);
CotLigneII=CC(n/4+1,1:n/4+1);
param3d1(AbsLigneII,OrdLigneII,CotLigneII,alpha=46,theta=-52,flag=[1 4])
xs2eps(3,'FiletCoxCall.eps');
