How To Compute Moving Average Convergence Divergence (MACD) using F#?

by margarett , in category: General Help , 9 months ago

How To Compute Moving Average Convergence Divergence (MACD) using F#?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by aglae_feil , 9 months ago

@margarett 

Here is an example of how you can compute Moving Average Convergence Divergence (MACD) using 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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
open System

// Function to calculate EMA of a list of values
let calculateEMA (values: float list) (n: int) =
    let alpha = 2.0 / (float (n + 1))
    
    let rec calcEMA (values: float list) (prevEMA: float) =
        match values with
        | [] -> prevEMA
        | x::xs -> 
            let newEMA = alpha * x + (1.0 - alpha) * prevEMA
            calcEMA xs newEMA
            
    calcEMA values (List.average values)

// Function to calculate MACD values
let calculateMACD (prices: float list) (shortPeriod: int) (longPeriod: int) (signalPeriod: int) =
    let shortEMA = calculateEMA prices shortPeriod
    let longEMA = calculateEMA prices longPeriod
    
    let macdLine = shortEMA - longEMA
    
    let signalLineValues = List.scan (fun prevValue price ->
        let shortEMA = calculateEMA [price] shortPeriod
        let longEMA = calculateEMA [price] longPeriod
        let macdLine = shortEMA - longEMA
        let signalEMA = calculateEMA [macdLine] signalPeriod
        signalEMA
    ) 0.0 prices
    
    let signalLine = List.tail signalLineValues
    
    macdLine, signalLine

// Example usage
let prices = [100.0; 105.0; 110.0; 115.0; 120.0; 125.0]
let shortPeriod = 10
let longPeriod = 20
let signalPeriod = 9

let macdLine, signalLine = calculateMACD prices shortPeriod longPeriod signalPeriod

printfn "MACD Line values: %A" macdLine
printfn "Signal Line values: %A" signalLine


In this code snippet, we define a function calculateEMA to calculate the Exponential Moving Average (EMA) of a list of values. Then, we define a function calculateMACD that calculates the MACD and signal line values based on the input prices and parameters for short, long, and signal periods. Finally, we provide an example of how to use the calculateMACD function with sample prices and parameters.


You can run this F# code in an F# interactive environment to compute the MACD values for a given set of prices.