How To Calculate Parabolic SAR (Stop and Reverse) using F#?

by bridie_mante , in category: Technical Analysis , 2 months ago

How To Calculate Parabolic SAR (Stop and Reverse) using F#?

Facebook Twitter LinkedIn Whatsapp

1 answer

by beryl_kshlerin , 2 months ago

@bridie_mante 

To calculate the Parabolic SAR indicator in F#, you can use the following code snippet:

 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
let calculateSAR (highs: float list) (lows: float list) (acc: float) (acc2: float) (sar: float) (ep: float) (af: float) =
    let sar' = sar + af * (ep - sar)
    
    if acc < List.length highs - 2 then
        let newEP = max (List.item (acc + 1) highs) ep
        let newAF = min 0.20 (af + 0.02)
        
        let newSAR = 
            if sar' < List.item acc highs then max (List.item (acc - 1) lows) sar'
            else if sar' > List.item acc lows then min (List.item (acc - 1) highs) sar'
            else sar'
        
        calculateSAR highs lows (acc + 1) (acc2) newSAR newEP newAF
    else if acc2 < List.length highs - 2 then
        calculateSAR highs lows acc (acc2 + 1) sar' ep af
    else sar', ep, af

let initializeSAR (highs: float list) (lows: float list) =
    let startSAR = List.nth highs 0
    let startEP = List.nth lows 1
    let startAF = 0.02
    
    calculateSAR highs lows 1 1 startSAR startEP startAF

// Usage example
let highs = [10.0; 12.0; 11.0; 15.0; 14.0; 16.0]
let lows = [8.0; 10.0; 9.0; 13.0; 12.0; 14.0]

let sar, _, _ = initializeSAR highs lows

printfn "Initial SAR: %.2f" sar


In this code snippet, the calculateSAR function recursively calculates the Parabolic SAR value based on the previous SAR value, Extreme Point (EP), and Acceleration Factor (AF). The initializeSAR function initializes the SAR calculation with the first SAR value, EP, and AF.


You can customize the input data and print out the calculated SAR value using this code snippet.