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

#Author : Jeremy Morris
#Purpose : Calculate the value of an Asian option at time 0.
#Code works for the following set of parameters :
#	r = 1/4
#	p = q = 1/2
#
#Changes will have to be made for different sets of parameters.

sub optionAsian {
	my ($s,$y,$n,$c) = @_;
	my ($h,$t,$v) = 0;

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

	#return payoff function because we have hit the end of the tree
	if( $n == $c ){
		$v = (1/($n+1))*$y - 4;
		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
	$v = (4/5)*( (1/2)*$h + (1/2)*$t );
	print "\tv$c\t$v\n";
	return($v);

}

my $answer = optionAsian(4,16,2,0);
print "The price of the Asian option at time 0 : $answer\n";
