Skip to content

Commit

Permalink
improve calculation
Browse files Browse the repository at this point in the history
  • Loading branch information
romulodl committed Oct 29, 2020
1 parent 97bd9ef commit 7f0c53b
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 28 deletions.
15 changes: 3 additions & 12 deletions src/Ema.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
19 changes: 3 additions & 16 deletions tests/TestEma.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [];
Expand All @@ -31,15 +18,15 @@ 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);

$ema = new Ema();
$ema->calculate([]);
}

public function testCalculateEmaWithInvalidArray(): void
public function testCalculateWithInvalidArray(): void
{
$values = [
9148.27,
Expand Down

0 comments on commit 7f0c53b

Please sign in to comment.