From 7f0c53b702b820c69f94539b9ad774637f6f2970 Mon Sep 17 00:00:00 2001 From: Romulo De Lazzari Date: Thu, 29 Oct 2020 07:31:24 +0000 Subject: [PATCH] improve calculation --- src/Ema.php | 15 +++------------ tests/TestEma.php | 19 +++---------------- 2 files changed, 6 insertions(+), 28 deletions(-) diff --git a/src/Ema.php b/src/Ema.php index 37d9784..3774cef 100644 --- a/src/Ema.php +++ b/src/Ema.php @@ -18,24 +18,15 @@ public function calculate(array $values, int $period = 9) : float } $mult = 2 / ($period + 1); - $prev_close = []; - $prev_ema = false; + $ema = 0; foreach ($values as $value) { if ( !is_numeric($value)) { throw new \Exception('[' . __METHOD__ . '] invalid value: '. $value); } - if (count($prev_close) < $period) { - $prev_close[] = $value; - if (count($prev_close) === $period) { - $prev_ema = array_sum($prev_close) / $period; - } - continue; - } - - $prev_ema = ($value - $prev_ema) * $mult + $prev_ema; + $ema = ($value - $ema) * $mult + $ema; } - return $prev_ema; + return $ema; } } diff --git a/tests/TestEma.php b/tests/TestEma.php index becd51f..04a2850 100644 --- a/tests/TestEma.php +++ b/tests/TestEma.php @@ -6,20 +6,7 @@ final class EmaTest extends TestCase { - public function testCalculateEmaWithEmptyPreviousValues(): void - { - $val = require(__DIR__ . '/values.php'); - $values = []; - foreach ($val as $v) { - $values[] = $v[2]; - } - $values = array_slice($values, -9); - - $ema = new Ema(); - $this->assertSame(9147.33, round($ema->calculate($values), 2)); - } - - public function testCalculateEmaWithMorePreviousValues(): void + public function testCalculateWithMorePreviousValues(): void { $val = require(__DIR__ . '/values.php'); $values = []; @@ -31,7 +18,7 @@ public function testCalculateEmaWithMorePreviousValues(): void $this->assertSame(9101.36, round($ema->calculate($values), 2)); } - public function testCalculateEmaWithEmptyArray(): void + public function testCalculateWithEmptyArray(): void { $this->expectException(Exception::class); @@ -39,7 +26,7 @@ public function testCalculateEmaWithEmptyArray(): void $ema->calculate([]); } - public function testCalculateEmaWithInvalidArray(): void + public function testCalculateWithInvalidArray(): void { $values = [ 9148.27,