/ Simulations / src / ema.jl
ema.jl
 1  @doc """ Find the index of the first valid real number in an array
 2  
 3  $(TYPEDSIGNATURES)
 4  
 5  This function returns the index of the first valid real number in an array. 
 6  If there are no valid real numbers in the array, it returns 0.
 7  
 8  """
 9  function first_valid(x::Array{<:Real})::Int
10      if !isnan(x[1])
11          return 1
12      else
13          @inbounds for i in 2:length(x)
14              if !isnan(x[i])
15                  return i
16              end
17          end
18      end
19      return 0
20  end
21  @doc """ Compute the exponential moving average (EMA) 
22  
23  $(TYPEDSIGNATURES)
24  
25  This function calculates the exponential moving average (EMA) for a vector of real numbers. The EMA is a type of weighted moving average that gives more importance to the latest data.
26  The number of periods `n` and the smoothing factor `alpha` can be specified. 
27  By default, `n` is set to 6 and `alpha` is set to 2.0 / 7.0.
28  
29  """
30  @views function ema(x::Vector{<:Real}; n::Int=6, alpha::Real=2.0 / 7.0)
31      @assert n < size(x, 1) && n > 0 "Argument n out of bounds."
32      out = zeros(size(x))
33      i = first_valid(x)
34      i = 2n
35      out[1:(n + i - 2)] .= NaN
36      out[n + i - 1] = mean(x[i:(n + i - 1)])
37      @inbounds for i in (n + i):size(x, 1)
38          out[i] = ema(x[i], out[i - 1]; n, alpha)
39      end
40      return out
41  end
42  
43  @doc """ Compute the exponential moving average (EMA) for a new value 
44  
45  $(TYPEDSIGNATURES)
46  
47  This function calculates the exponential moving average (EMA) for a new value, given the previous EMA value.
48  The EMA is a type of moving average that places a greater weight on the most recent data.
49  The number of periods `n` and the smoothing factor `alpha` can be specified. 
50  By default, `n` is set to 6 and `alpha` is set to 2.0 / (n + 1).
51  
52  """
53  function ema(val::T, prev::T; n::Int=6, alpha::T=2.0 / n + 1) where {T<:Real}
54      alpha * (val - prev) + prev
55  end