Browse Source

Add basic MACD

pull/2/head
Arthur POULET 4 years ago
parent
commit
b66cec9d8b
No known key found for this signature in database GPG Key ID: FC154EA63FF5D8BC
  1. 11
      README.md
  2. 5
      spec/math/macd.cr
  3. 22
      src/lib/math/macd.cr

11
README.md

@ -66,11 +66,12 @@ Math.factorial(4) # => 24
```crystal
[1, 2, 3].mean # => 2.0
[1, 2, 3].variance.round(4) # => 0.6667
[1, 2, 3].standard_deviation.round(4) # => 0.8165
[1, 2, 3].quadratic_mean.round(2) # => 2.16
[2, 32].geometric_mean # => 8
[40, 60].harmonic_mean.round # => 48
[1, 2, 3].variance # => 0.6667
[1, 2, 3].standard_deviation # => 0.8165
[1, 2, 3].quadratic_mean # => 2.16
[2, 32].geometric_mean # => 8.0
[40, 60].harmonic_mean # => 48.0
[1,2,3,2,1].macd 3 # => [2.0, 2.333, 2.0]
```
## Development

5
spec/math/macd.cr

@ -0,0 +1,5 @@
describe Math::MACD do
it "test basic macd" do
[1, 2, 3, 2, 1].macd(3).map { |e| e.round(3) }.should eq [2, 2.333, 2]
end
end

22
src/lib/math/macd.cr

@ -0,0 +1,22 @@
module Math::MACD
def macd(n : Int)
((n.odd?) ? macd_odd(n) : macd_pair(n)).compact
end
private def macd_odd(n)
map_with_index do |_, i|
next if i < n / 2
next if i + n / 2 >= size
range = (i - n / 2)..(i + n / 2)
self[range].mean
end
end
private def macd_pair(n)
raise ArgumentError.new "The MACD should be computed for an odd window"
end
end
module Enumerable(T)
include Math::MACD
end
Loading…
Cancel
Save