//////////////////// Exercice 1
clear;
n=100;T=1; deltat=T/n;S0=120; sigma=0.3;
up=exp(sigma*sqrt(deltat));down=1/up;
function s=S(i,j); // on doit avoir 0<=j<=i<=n
  s=S0*up.^j.*down.^(i-j);
endfunction;
S(10,6)
S(50,46)
/////////////////// Exercice 3
r=0.1;R=exp(r*deltat);K=S0;p=(R-down)/(up-down);
CC=zeros(n+1,n+1);
for j=0:n CC(n+1,j+1)=max(S(n,j)-K,0);
end;
for i=n-1:-1:0
    for j=0:i CC(i+1,j+1)=(p*CC(i+1+1,j+1+1)+(1-p)*CC(i+1+1,j+1))/R;  
    end;
end;
CC(1,1)
CC(101,:)
CC(n+1,81)-max(S(n,80)-K,0)//vérification du payoff quand j=80
CC(n+1,61)-max(S(n,60)-K,0)//vérification du payoff quand j=60
CC(n+1,31)-max(S(n,30)-K,0)//vérification du payoff quand j=30 (il doit être nul!)
/////////////////// Exercice 4
CC(5,5)
CC(5,4)
/////////////////// Exercice 5
for K=S0/2:2*S0
PP=zeros(n+1,n+1);
for j=0:n PP(n+1,j+1)=max(K-S(n,j),0);
end;
for i=n-1:-1:0
    for j=0:i PP(i+1,j+1)=(p*PP(i+1+1,j+1+1)+(1-p)*PP(i+1+1,j+1))/R;  
    end;
end;
PP(1,1)    
end
PP=zeros(n+1,n+1);
for j=0:n PP(n+1,j+1)=max(K-S(n,j),0);
end;
for i=n-1:-1:0
    for j=0:i PP(i+1,j+1)=(p*PP(i+1+1,j+1+1)+(1-p)*PP(i+1+1,j+1))/R;  
    end;
end;
PP(1,1)
//////////////////// Exercice 6
for K=S0/2:2*S0
PP=zeros(n+1,n+1);
for j=0:n PP(n+1,j+1)=max(K-S(n,j),0);
end;
for i=n-1:-1:0
    for j=0:i PP(i+1,j+1)=(p*PP(i+1+1,j+1+1)+(1-p)*PP(i+1+1,j+1))/R;  
    end;
end;
PP(1,1)    
end
///////////////
for K=S0/2:2*S0
CC=zeros(n+1,n+1);
for j=0:n CC(n+1,j+1)=max(S(n,j)-K,0);
end;
for i=n-1:-1:0
    for j=0:i CC(i+1,j+1)=(p*CC(i+1+1,j+1+1)+(1-p)*CC(i+1+1,j+1))/R;  
    end;
end;
CC(1,1)    
end


/////////////////// Exercice 7
K=S0;
for sigma=0.05:0.05:0.6;
    up=exp(sigma*sqrt(deltat));down=1/up;
CC=zeros(n+1,n+1);
for j=0:n CC(n+1,j+1)=max(S(n,j)-K,0);
end;
for i=n-1:-1:0
    for j=0:i CC(i+1,j+1)=(p*CC(i+1+1,j+1+1)+(1-p)*CC(i+1+1,j+1))/R;  
    end;
end;
CC(1,1)    
end
for sigma=0.05:0.05:0.6;
    up=exp(sigma*sqrt(deltat));down=1/up;
PP=zeros(n+1,n+1);
for j=0:n PP(n+1,j+1)=max(K-S(n,j),0);
end;
for i=n-1:-1:0
    for j=0:i PP(i+1,j+1)=(p*PP(i+1+1,j+1+1)+(1-p)*PP(i+1+1,j+1))/R;  
    end;
end;
PP(1,1)    
end    
/////////////////// Exercice 8
n=20;T=1; deltat=T/n;S0=120; sigma=0.3;
up=exp(sigma*sqrt(deltat));down=1/up;
function c=Callrec(i,j)
   if i==n then c=max(S(n,j)-K,0)
   else c=(p*Callrec(i+1,j+1)+(1-p)*Callrec(i+1,j))/R
    end;
endfunction;
disp(Callrec(0,0),"la prime vaut", n, "Pour n=")
