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

by shanie.wisozk , in category: SEO Tools , 9 months ago

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

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

Member

by julio , 9 months ago

@shanie.wisozk 

Here is an example of how you can calculate Moving Average Convergence Divergence (MACD) in F#:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
open System

let calculate_moving_average_convergence_divergence (prices: float []) (short_period: int) (long_period: int) (signal_period: int) =
    let calculate_ema (data: float []) (period: int) =
        let alpha = 2.0 / (float(period) + 1.0)
        let rec calculate_ema_helper (data: float []) (period: int) (prev_ema: float) (index: int) =
            if index >= Array.length data then prev_ema
            else
                let current_ema = (data.[index] * alpha) + (prev_ema * (1.0 - alpha))
                calculate_ema_helper data period current_ema (index + 1)
        calculate_ema_helper data period data.[period] 1

    let short_ema = calculate_ema prices short_period
    let long_ema = calculate_ema prices long_period
    let macd = short_ema - long_ema

    let signal_line = calculate_ema (Array.append [|0.0|] (Array.map (fun x -> x - macd) prices)) signal_period

    macd, signal_line
    
// Example usage
let prices = [|100.0; 105.0; 110.0; 115.0; 120.0; 125.0; 130.0; 135.0; 140.0; 145.0|]
let short_period = 12
let long_period = 26
let signal_period = 9

let macd, signal_line = calculate_moving_average_convergence_divergence prices short_period long_period signal_period

printfn "MACD: %f, Signal Line: %f" macd signal_line


In this code snippet, we define a function calculate_moving_average_convergence_divergence that takes in an array of prices, short period, long period, and signal period as parameters. Inside the function, we calculate the exponential moving averages (EMAs) for the short and long periods, then calculate the MACD as the difference between the short EMA and long EMA. Finally, we calculate the signal line using the MACD values and the signal period.


You can then test this function with example data as shown in the example usage section where we calculate the MACD and Signal Line for a given array of prices.