Skip to content

Instantly share code, notes, and snippets.

@shawntobin
Created June 22, 2013 15:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shawntobin/5841290 to your computer and use it in GitHub Desktop.
Save shawntobin/5841290 to your computer and use it in GitHub Desktop.
<?php
// Set up pre-established stock price changes and their corresponding probabilities
$chg[1] = -1;
$chg[2] = -0.15;
$chg[3] = -0.10;
$chg[4] = -0.05;
$chg[5] = 0;
$chg[6] = 0.05;
$chg[7] = 0.15;
$chg[8] = 0.5;
$p[1][1] = 0.0001;
$p[1][2] = 0.0099;
$p[1][3] = 0.15;
$p[1][4] = 0.25;
$p[1][5] = 0.18;
$p[1][6] = 0.25;
$p[1][7] = 0.15;
$p[1][8] = 0.01;
//Expected Return
$expReturn = 0;
for ($i=1; $i<=8; $i++) {
$expReturn = $chg[$i] * $p[1][$i] + $expReturn;
}
// Get cumulative probabilities
$cp[0] = 0;
for ($i=1;$i<=8;$i++) {
$cp[$i] = $cp[$i-1] + $p[1][$i];
}
// Set initial cash balance
$cashBalance[0] = 10000;
echo "Beginning Balance: ".$cashBalance[0];
echo "<br>";
// Enter loop for each day of the year
for ($d=1;$d<=365;$d++) {
// Get stock change for current day
$rand[$d] = rand(1,10000)/10000;
for ($i=1;$i<=8;$i++) {
if ($rand[$d] <= $cp[$i]) {
$stockChg[$d] = (1+$chg[$i]);
break;
}
}
// Apply current stock change to current cash balance
$cashBalance[$d] = round(($cashBalance[$d-1]*$stockChg[$d]),2);
echo "Day ".$d." Balance: ".$cashBalance[$d];
echo "<br>";
}
echo "<br>";
echo "<b>ENDING BALANCE: </b>".$cashBalance[365]."<br>";
echo "<b>TOTAL RETURN: </b>".round((100*(($cashBalance[365]/$cashBalance[0])-1)),2)."% <br>";
echo "<b> EXPECTED RETURN </b>".round(100*$expReturn,2)."% <br>";
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment