Skip to content

Commit

Permalink
change return to array instead of int
Browse files Browse the repository at this point in the history
  • Loading branch information
romulodl committed Nov 13, 2020
1 parent 7f0c53b commit f3b740c
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 9 deletions.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ or add `romulodl/ema` to your `composer.json`. Please check the latest version i

```php
$ema = new Romulodl\Ema();
$ema->calculate(array $values, int $period = 9);
$values = $ema->calculate(array $values, int $period = 9);
// return array, $values[0] being the last one
```

For example:
Expand Down
12 changes: 5 additions & 7 deletions src/Ema.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,26 +7,24 @@ class Ema
/**
* Calculate the EMA based on this formula
* (Close - previous EMA) * (2 / n+1) + previous EMA
*
* The previous values options exists to try to smooth the current calculation
* if it is empty, it will calculate the SMA for the first round.
*/
public function calculate(array $values, int $period = 9) : float
public function calculate(array $values, int $period = 9) : array
{
if (empty($values) || count($values) < $period) {
throw new \Exception('[' . __METHOD__ . '] $values parameters is empty');
}

$mult = 2 / ($period + 1);
$ema = 0;
$ema[] = 0;
foreach ($values as $value) {
if ( !is_numeric($value)) {
throw new \Exception('[' . __METHOD__ . '] invalid value: '. $value);
}

$ema = ($value - $ema) * $mult + $ema;
$prev = array_slice($ema, -1)[0];
$ema[] = ($value - $prev) * $mult + $prev;
}

return $ema;
return array_reverse($ema);
}
}
2 changes: 1 addition & 1 deletion tests/TestEma.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public function testCalculateWithMorePreviousValues(): void
}

$ema = new Ema();
$this->assertSame(9101.36, round($ema->calculate($values), 2));
$this->assertSame(9101.36, round($ema->calculate($values)[0], 2));
}

public function testCalculateWithEmptyArray(): void
Expand Down

0 comments on commit f3b740c

Please sign in to comment.