/////////TP3_19.sce 
//Question 1
clear;
n=100;T=1;deltat=T/n;S0=140;sigma=0.3;
up=exp(sigma/sqrt(n));down=1/up;r=0.15;R=exp(r*deltat);
//Calcul des valeurs de S(reprise du TP1)////////////
function s=S(i,j); // on doit avoir 0<=j<=i<=n
  s=S0*up.^j.*down.^(i-j);
endfunction;
//Calcul de la prime du Call et du Put (reprise du TP2)
p=(R-down)/(up-down);K=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)
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)
//Question 2
binomial(p,n)'
max(S(n,0:n)-K,0)*binomial(p,n)'
//Question 3
(max(S(n,0:n)-K,0)*binomial(p,n)')/R^n
CC(1,1)
(max(S(n,0:n)-K,0)*binomial(p,n)')/R^n-CC(1,1)

(max(K-S(n,0:n),0)*binomial(p,n)')/R^n
PP(1,1)
//Questions 4 et 5
CC(1+n,1:1+n)-PP(1+n,1:1+n)-(S(n,0:n)-K)


CC(1,1)-PP(1,1)
S(0,0)-K/R^n
CC(1,1)-PP(1,1)-(S(0,0)-K/R^n)
//Questions 6 et 7
function cal=C(i,j)
    if i==n then cal=max(S(n,j)-K,0)// payoff
        else cal=(max(S(n,j:j+n-i)-K,0)*binomial(p,n-i)')/R^(n-i);
   end
endfunction;
function put=P(i,j)
    if i==n then put=max(K-S(n,j),0)// payoff
        else
    put=(max(K-S(n,j:j+n-i),0)*binomial(p,n-i)')/R^(n-i)
    end
endfunction;
P(50,0)
//P(50,30)
//Question 8
scf(0);
Abs=zeros(1+n,1+n);Ord=zeros(1+n,1+n);
for k=0:n
    for m=0:n-k
        Abs(1+m,1+k)=(k+m)*deltat;
        Ord(1+m,1+k)=S(k+m,k);
    end;
    for m=1:k
        Abs(1+n-k+m,1+k)=(n-m)*deltat;
        Ord(1+n-k+m,1+k)=S(n-m,k-m);
     end;   
end;
plot(Abs,Ord)
image="arbreCox100.eps";xs2eps(0,image);
//Question 9
scf(1);
Abs=zeros(1+n,1+n);OrdC=zeros(1+n,1+n);
for k=0:n
    for m=0:n-k
        Abs(1+m,1+k)=(k+m)*deltat;
        OrdC(1+m,1+k)=C(k+m,k);
    end;
    for m=1:k
        Abs(1+n-k+m,1+k)=(n-m)*deltat;
        OrdC(1+n-k+m,1+k)=C(n-m,k-m);
     end;   
end;
plot(Abs,OrdC)
image="arbreCall100.eps";xs2eps(1,image);


scf(2);
Abs=zeros(1+n,1+n);OrdC=zeros(1+n,1+n);
for k=0:n
    for m=0:n-k
        Abs(1+m,1+k)=(k+m)*deltat;
        OrdP(1+m,1+k)=P(k+m,k);
    end;
    for m=1:k
        Abs(1+n-k+m,1+k)=(n-m)*deltat;
        OrdP(1+n-k+m,1+k)=P(n-m,k-m);
     end;   
end;
plot(Abs,OrdP)
image="arbrePut100.eps";xs2eps(2,image);

