How To Compute Commodity Channel Index (CCI) in F#?

by edmond_brakus , in category: Third Party Scripts , 9 months ago

How To Compute Commodity Channel Index (CCI) in F#?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lew , 9 months ago

@edmond_brakus 

To compute the Commodity Channel Index (CCI) in F#, you can create a function that takes in a list of closing prices for a specific period and calculates the CCI value. Here is an example implementation of the CCI calculation in F#:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
let calculateCCI (prices: float list) (period: int) =
    let tp = List.map (fun price -> (price + price + price) / 3.0) prices
    let sma n (lst: float list) =
        List.windowed n lst
        |> List.map (fun window -> List.average window)
    let meanDev = List.mapi (fun i price ->
                        let avg = sma period tp |> List.item i
                        let sum = List.take (i+1) tp |> List.sum
                        let meanDev = sum / float (i+1)
                        abs(meanDev - avg) / period
                    ) tp
    let cci = List.map2 (fun price md -> (price - sma period tp |> List.head) / (0.015 * md)) prices meanDev
    cci


In this implementation, the calculateCCI function takes in a list of closing prices and a period value as parameters. It first calculates the typical price (tp) for each closing price, then calculates the simple moving average (sma) for the typical prices over the specified period.


Next, it calculates the mean deviation for each price, which is used to compute the CCI value for each price. Finally, the function returns a list of CCI values for each closing price.


You can call this function with a list of closing prices and a period value to calculate the CCI values, like this:

1
2
3
let closingPrices = [10.0; 11.0; 12.0; 11.5; 12.5; 13.0; 12.5; 13.5]
let period = 5
let cciValues = calculateCCI closingPrices period


This will calculate the CCI values for the provided closing prices and period, and store them in the cciValues list.