How To Compute Commodity Channel Index (CCI) in Perl?

Member

by ethelyn , in category: General Help , 10 months ago

How To Compute Commodity Channel Index (CCI) in Perl?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by aliya.yundt , 10 months ago

@ethelyn 

To compute the Commodity Channel Index (CCI) in Perl, 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
sub calculate_CCI {
    my ($high_prices, $low_prices, $close_prices, $period) = @_;

    my @typical_prices = map { ($high_prices->[$_] + $low_prices->[$_] + $close_prices->[$_]) / 3 } 0..$#close_prices;
    my @CCI_values;

    for (my $i = $period - 1; $i <= $#close_prices; $i++) {
        my @TP_slice = @typical_prices[$i - $period + 1 .. $i];
        my $TP_avg = (reduce { $a + $b } @TP_slice) / $period;
        my $TP_stddev = sqrt((reduce { $a + $b**2 } map { $_ - $TP_avg } @TP_slice) / $period);
        
        my $CCI = ($typical_prices[$i] - $TP_avg) / (0.015 * $TP_stddev);
        push @CCI_values, $CCI;
    }

    return @CCI_values;
}

# Example usage
my @high_prices = (10, 12, 15, 14, 16);
my @low_prices = (8, 10, 12, 11, 14);
my @close_prices = (9, 11, 14, 12, 15);
my $CCI_period = 3;

my $CCI_values = calculate_CCI(@high_prices, @low_prices, @close_prices, $CCI_period);

print "CCI values: " . join(", ", @$CCI_values) . "
";


In this code snippet, the calculate_CCI function takes four input parameters - arrays of high prices, low prices, close prices, and the CCI period. It calculates the typical prices, then iterates through the closing prices to calculate the CCI values using the formula for CCI. The function returns an array reference containing the CCI values.


You can adjust the input parameters (prices and CCI period) and use this function to compute the CCI values for your specific data set.