
# set parameters
	X1_shares <- 10
	X2_shares <- -2
	P1_start <- 2
	P2_start <- 2
	s <- 100  # number of time periods in each trial
	numb_trials <- 100000
	
# create covariance matrix
	Sigma <- matrix(NA,2,2)
	Sigma[1,1] <- 0.03863539
	Sigma[2,2] <- 0.05585887
	Sigma[1,2] <- 0.02213511
	Sigma[2,1] <- Sigma[1,2]
	cat("\nSigma:\n")
	print(Sigma)

# function that does one trial version 5: has a useless trial number argument at beginning
do_trial_v5 <- function(trial_number,s,X1_shares,X2_shares,P1_start,P2_start,U) {
	# set up container to hold values of P1 and P2 over all time periods
	# one row for each time period, one column for each variable
		Price_matrix <- matrix(NA,s,2)
	# initial values for P1 and P2
		P1 <- P1_start
		P2 <- P2_start
	# create P1 and P2 series using single call to rnorm and no loop
		# draw all 2*s deviates simultaneously
		ISND <- rnorm(2*s)
		# dimension correctly for matric multiplecation
		dim(ISND) <- c(2,s)
		# correlate them (U is 2x2, ISDN is 2xs, CSND is 2xs; one row for each price series)
		CSND <- U%*%ISND 
		# cummulative products
		P1_cummulative_products <- cumprod(exp(CSND[1,]))	
		P2_cummulative_products <- cumprod(exp(CSND[2,]))	
		Price_matrix[,1] <- P1_start*P1_cummulative_products
		Price_matrix[,2] <- P2_start*P2_cummulative_products
	# loop through values, check for ruin
		ruin <- FALSE
		X <- matrix(NA,2,1)
		X[1,1] <- X1_shares
		X[2,1] <- X2_shares
		portfolio_value_vec <- Price_matrix %*% X
		if (min(portfolio_value_vec) < 0) ruin <- TRUE
	return(ruin)
	}

# do trials
	# get choleski decomp of covariance matrix
		U <- chol(Sigma)
	# initialize snowfall for using 7 cores
		library("snowfall")
		sfInit(parallel=TRUE, cpus=7, type="SOCK")
	# send all needed data to all cores
		sfExport("s")
		sfExport("X1_shares")
		sfExport("X2_shares")
		sfExport("P1_start")
		sfExport("P2_start")
		sfExport("U")	
	# setup network RNG
		sfClusterSetupRNG()
	# start profiling
		Rprof("profile_out_5.txt")
	# do simulation: "list apply" style
		results <- sfLapply(1:numb_trials,do_trial_v5,s,X1_shares,X2_shares,P1_start,P2_start,U)
		ruin_sum <- sum(unlist(results))
		cat("\nProbability of ruin:\n")
		print(ruin_sum/numb_trials)
	# stop profiling
		Rprof(NULL)
		summaryRprof("profile_out_5.txt")$by.self

