n=50
T=1
delta_t=T/n
r=0.25
sigma=0.4
S0=120
K=120
up=exp(sigma*sqrt(delta_t))
down=1/up
R=exp(r*delta_t)
p=(R-down)/(up-down)

// EXERCICE 1

SS=zeros(n+1,n+1)
SS(1,1)=S0
for i=1:n
    SS(i+1,1)=SS(i,1)*down
    for j=1:i
        SS(i+1,j+1)=SS(i,j)*up
    end
end


function fi=phi(x)
    fi=max(0,x-K)
endfunction

function psu=psi(x)
    psu=max(0,K-x)
endfunction

CC=zeros(n+1,n+1)
for j=1:(n+1)
	CC(1+n,j)=phi(SS(1+n,j))
end
for i=n-1:-1:0
    for j=0:i
        CC(i+1,j+1)=(p*CC(i+2,j+2)+(1-p)*CC(i+2,j+1))/R;
	end
end

PP=zeros(n+1,n+1)
for j=1:(n+1)
	PP(1+n,j)=psi(SS(1+n,j))
end
for i=n-1:-1:0
    for j=0:i
        PP(i+1,j+1)=(p*PP(i+2,j+2)+(1-p)*PP(i+2,j+1))/R;
	end
end

// EXERCICE 3
CCamer=zeros(n+1,n+1)
for j=1:(n+1)
	CCamer(1+n,j)=phi(SS(1+n,j))
end
for i=n-1:-1:0
    for j=0:i
        CCamer(i+1,j+1)=max(phi(SS(i+1,j+1)),(p*CCamer(i+2,j+2)+(1-p)*CCamer(i+2,j+1))/R);
	end
end


// EXERCICE 6

PPamer=zeros(n+1,n+1)
for j=1:(n+1)
	PPamer(1+n,j)=psi(SS(1+n,j))
end
for i=n-1:-1:0
    for j=0:i
        PPamer(i+1,j+1)=max(psi(SS(i+1,j+1)),(p*PPamer(i+2,j+2)+(1-p)*PPamer(i+2,j+1))/R);
	end
end

//disp(PPamer(1,1)-PP(1,1))


// EXERCICE 8 


function p=phie(x,t)
    p=max(0,x-t)
endfunction


t1=209
t2=215
N=10
for k=1:N
    t3=(t1+t2)/2
    CC=zeros(n+1,n+1)
    for j=1:(n+1)
        CC(1+n,j)=phie(SS(1+n,j),t3)
    end
    for i=n-1:-1:0
        for j=0:i
            CC(i+1,j+1)=(p*CC(i+2,j+2)+(1-p)*CC(i+2,j+1))/R;
        end
    end
    if (CC(1,1)>PP(1,1)) then
        t1=t3;
    else
        t2=t3;
    end
    disp(t2,CC(1,1))
end
disp(t3)
disp(CC(1,1))

