From f3b740c71f1fa49c0bdb524c0ee846cc756a97a5 Mon Sep 17 00:00:00 2001 From: Romulo De Lazzari Date: Fri, 13 Nov 2020 16:22:19 +0000 Subject: [PATCH] change return to array instead of int --- README.md | 3 ++- src/Ema.php | 12 +++++------- tests/TestEma.php | 2 +- 3 files changed, 8 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 97056be..8911031 100644 --- a/README.md +++ b/README.md @@ -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: diff --git a/src/Ema.php b/src/Ema.php index 3774cef..2ae65c3 100644 --- a/src/Ema.php +++ b/src/Ema.php @@ -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); } } diff --git a/tests/TestEma.php b/tests/TestEma.php index 04a2850..821de0f 100644 --- a/tests/TestEma.php +++ b/tests/TestEma.php @@ -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