#!/usr/bin/perl -w
use strict;

#Author : Jeremy Morris
#Purpose : Calculate the value of a European option with differing u/d
#Code works for the following set of parameters :
#	r = 0
#	q = Determined at each step so that u_{n}S_{n} = S_{n-1} - 10
#
#Changes will have to be made for different sets of parameters.

sub optionEuro {
	my ($s,$n,$c) = @_;
	my ($h,$t,$v,$u,$d,$p,$q) = 0;

	$u = ($s + 10) / $s;
	$d = ($s - 10) / $s;

	#do the recursive step since we haven't hit the end of the tree
	if( $n > $c ){
		$h = optionEuro($s*$u,$n,$c+1);
		$t = optionEuro($s*$d,$n,$c+1);
	}

	#return payoff function because we have hit the end of the tree
	if( $n == $c ){
		$v = $s - 80;
		if( $v < 0 ){
			$v = 0;
		}
		print "\tv$c\t$v\n";
		return($v);
	}

	#add up the correct prices, we are going back down the tree
	$p = (1 - $d) / ($u - $d);
	$q = ($u - 1) / ($u - $d);
	$v = ( $p*$h + $q*$t );
	print "\tv$c\t$v\n";
	return($v);

}

my $answer = optionEuro(80,5,0);
print "The price of the European option at time 0 : $answer\n";
