How To Calculate Moving Average Convergence Divergence (MACD) in Erlang?

Member

by lonzo , in category: General Help , 3 months ago

How To Calculate Moving Average Convergence Divergence (MACD) in Erlang?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by georgiana.senger , 2 months ago

@lonzo 

To calculate the Moving Average Convergence Divergence (MACD) in Erlang, you can follow these steps:

  1. Calculate the 12-period Exponential Moving Average (EMA) of the closing prices. You can use the following formula for this:
1
2
3
4
ema([], _, _) -> [];
ema([X | Xs], PrevEMA, K) -> 
    EMA = K*X + (1-K)*PrevEMA,
    [EMA | ema(Xs, EMA, K)].


  1. Calculate the 26-period Exponential Moving Average (EMA) of the closing prices using the same formula as above.
  2. Subtract the 26-period EMA from the 12-period EMA to get the MACD line:
1
2
3
4
5
6
7
8
9
calculate_macd(Closes) ->
    K = 2/(12 + 1),
    ShortEMA = ema(Closes, lists:nth(1, Closes), K),
    
    K = 2/(26 + 1),
    LongEMA = ema(Closes, lists:nth(1, Closes), K),
    
    MACD = lists:zipWith(fun(A,B) -> A - B end, ShortEMA, LongEMA),
    MACD.


  1. Calculate the 9-period EMA of the MACD line to get the Signal line:
1
2
3
4
5
6
7
8
9
ema_signals([], _, _) -> [];
ema_signals([X | Xs], PrevEMA, K) -> 
    EMA = K*X + (1-K)*PrevEMA,
    [EMA | ema_signals(Xs, EMA, K)].

calculate_signal(MACD) ->
    K = 2/(9 + 1),
    Signal = ema_signals(MACD, lists:nth(1, MACD), K),
    Signal.


  1. Plot the MACD line and the Signal line on the chart to identify buy and sell signals based on crossovers.


By following these steps, you can calculate and visualize the Moving Average Convergence Divergence (MACD) in Erlang.