Created
May 24, 2018 14:55
-
-
Save tascrafts/2fba8e356df8338c6f1d1901090f1d8b to your computer and use it in GitHub Desktop.
Simple Moving Average function for PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Example | |
$sma_array = simple_sma(array(3,10,11,19,18,12,6,5,9,0), 5); | |
print_r($sma_array); // Outputs 8, 13.3333, 16, 16.3333, 12, 7.6667, 6.6667, 4.6667 | |
function simple_sma($array, $days) { | |
if($days < 0) die("Days have to be higher than 0 in the simple_sma function."); | |
$array = array_values($array); | |
$x = 0; | |
$sma_array = array(); | |
foreach($array as $key => $val) { | |
$x++; | |
for($y = 1; $y <= $days; $y++) { | |
$sma_array[$key + $y] += ($val / $days); | |
} | |
} | |
$sma_array = array_slice($sma_array, ($days-1), (count($array)-($days-1)) ); | |
return $sma_array; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment