I am using PHP and recently started using the technical analysis extension TA-LIB to calculate indicators on stock price data. I am getting what I consider a strange result on one of the simplest indicators there is, the simple moving average, and I have not figured out the reason. I have posted a similar question on the TA-LIB forum, but the activity there is very low and I suspect I might not get an answer in a long time, if at all.
The SMA calculates the average based on a given number of previous price datapoints. The problem I am having is best illustrated by an example. Let us say I have a set of 10 price datapoints and I would like to calculate the SMA. For simplicity let us use an average of 4. When calculating this we would expect a new set of 7 averagevalues. However, TA-LIB returns 4 as seen below:
$sma=trader_sma($close,4);
echo"<pre>";
print_r($sma);
Array
(
[0] => Array
(
[0] =>
[1] => 0
[2] =>
)
[1] => Array
(
[0] =>
[1] => 1
[2] =>
)
[2] => Array
(
[0] =>
[1] => 2
[2] =>
)
[3] => Array
(
[0] =>
[1] => 3
[2] => 573.267
)
[4] => Array
(
[0] =>
[1] => 4
[2] => 565.307
)
[5] => Array
(
[0] =>
[1] => 5
[2] => 560.552
)
[6] => Array
(
[0] =>
[1] => 6
[2] => 557.382
)
)
As you can see we get nulls at the beginning of the set, as expected. However, we are missing datapoints at the end and the number of missing datapoints always corresponds to the number of datapoints I am averaging over. This causes an unatural gap at the end when I plot the moving average against my price data.
Any ideas on what is going on?
Turns out that I`ve done a silly mistake, not surprisingly. I actually wrote my own function:
function sma($array,$averagenr){
$length=count($array);
if($length<$averagenr)return(null);
$sma_result=array();
for ($x=1;$x<$averagenr;$x++){
array_push($sma_result,array('',$x,null));
}
for ($x=$averagenr;$x<$length+1;$x++){
$sum=0;
for ($counter=$x-$averagenr;$counter<$x;$counter++){
$sum=$sum+$array[$counter];
}
$avg=$sum/$averagenr;
array_push($sma_result,array('',$x,$avg));
}
return($sma_result);}
echo "<pre>";
print_r(sma($close,4));
Works fine, but when comparing it`s results with the results of TA-LIB I realized that the problem is a parse-error I have done with TA-LIBs results. The question I originally asked is thus invalid. Simple error, waiste of time, but good to know TA-LIB works as I want it to.