## Introduction

The **Commodity Channel Index (CCI)** was pioneered by Donald R. Lambert. It was initially featured in an article titled, “*Commodity Channel Index: Tool for Trading Cyclic Trends*,” which was published in *Commodities Magazine* in 1980. Lambert primarily designed the CCI to pinpoint cyclical shifts in commodities but it is still appropriate to apply it to any cyclical market.

At its core, the CCI gauges the deviation of the current price relative to its average value. As an oscillator, the CCI revolves around a zero baseline, with positive values indicating prices above the mean and negative values suggesting prices below it. It’s particularly adept at detecting the acceleration or deceleration of prices as they diverge from their moving average.

The term “channel” can be somewhat misleading. When we think of channels in a trading context, we often visualize a range between two lines (like in the Bollinger Bands or Donchian channels).

However, the name “Commodity Channel Index” doesn’t refer to a visual channel on a chart. Instead, it reflects Lambert’s original intention for the CCI, which was to identify cyclical turns in commodities. The “channel” refers more abstractly to the typical price’s deviation from its average over a given period, and not to a bounded range or channel as in some other indicators.

It’s one of those instances where the naming convention in technical analysis can be somewhat non-intuitive or historical in nature.

## CCI Formula

The CCI is calculated using the following formula:

CCI = \frac{\text{Typical Price} - \text{SMA of Typical Price}}{0.015 \times \text{Mean Deviation}}

Where:

- SMA denotes the Simple Moving Average of the Typical Price.
- The Typical Price is calculated as:

\text{Typical Price} = \frac{\text{High} + \text{Low} + \text{Close}}{3}

- The Mean Deviation is the average of the absolute differences between the Typical Price and its SMA:

\text{Mean Deviation} = \text{Average}[\text{AbsoluteValue(Typical Price – SMA)}]

The constant factor, 0.015, ensures that about 85% of the data points lie between +100 and -100. Although there’s no strict boundary, values beyond +200 or -200 are typically seen as outliers.

The constant 0.015 is chosen to scale the denominator of the formula, which in turn affects how many data points fall within the ±100 range.

However, the relationship isn’t as direct as subtracting 15 from 100 to get 85%. The 0.015 constant is a scaling factor for the mean deviation in the denominator of the CCI formula. When the typical price’s deviation from the moving average is normalized by this scaled mean deviation, approximately 85% of the CCI values will fall within the ±100 range.

The logic behind this is related to statistical properties of data. Without going too deep into the maths, if we assume that price changes are normally distributed (a common assumption, though not always accurate in real-world markets), about 68% of data points will fall within one standard deviation, about 95% within two standard deviations, and about 99.7% within three standard deviations. The 0.015 constant effectively scales the CCI so that the ±100±100 values correspond roughly to these percentages (specifically, the 85% figure mentioned).

## Purpose of the CCI Indicator

The CCI is designed to be sensitive to market volatility. As the average deviation grows, the CCI becomes less reactive to price shifts. On the contrary, in a calm or stable market scenario, it will display heightened sensitivity. Its knack for identifying volatile market extremes makes it invaluable for spotting potential price trend reversals.

Traders often employ the CCI to discern overbought (OB) and oversold conditions (OS), which might hint at upcoming trading opportunities. A word of caution: in a dominant trend, the CCI can linger in overbought or oversold zones for prolonged periods, potentially leading to significant losses if not considered in a wider market context.

This indicator can also help traders recognize market breakouts, offering insights when the market is venturing beyond its usual range. It’s also handy for spotting divergence or affirming a fresh price peak, shedding light on market momentum and volatility shifts.

## How to Find Buy and Sell Signals with the Commodity Channel Index

The CCI is a dynamic tool that can be used to generate a variety of trading signals. Here are a few methods commonly used by traders:

**Overbought and Oversold Levels:**When the CCI moves above +100, it could be an indication that the asset is entering an overbought condition, and a price reversal may be imminent. When the CCI moves below -100, it could indicate an oversold condition, suggesting a potential upward price reversal. However, during strong trends, the CCI can remain overbought or oversold for extended periods, so it’s crucial to use other forms of analysis or indicators to confirm these signals.**Divergences:**Divergences occur when the price of an asset is moving in the opposite direction of the CCI. For example, if the price is making higher highs while the CCI is making lower highs, this is known as bearish divergence and could indicate a potential downward price reversal. Whereas, if the price is making lower lows while the CCI is making higher lows, this is known as bullish divergence and could signal a potential upward price reversal.**Zero Line Crosses:**Some traders use the indicator’s crossing of the zero line as a trading signal. A move above zero is viewed as bullish for prices, while a move below zero is seen as bearish.

## Pros and Cons

Like any technical indicator, the CCI has its strengths and weaknesses. Understanding these can help you make the most of this tool in your trading.

**Pros:**

**Adaptable:**The CCI’s multifaceted nature allows it to pinpoint overbought/oversold zones, detect divergences, and signal potential market breakouts.**Sensitivity to Volatility:**The CCI’s sensitivity to market volatility can make it a valuable tool for identifying market extremes and potential price reversals.

**Cons:**

**Potential False Alarms**: The CCI, like many indicators, might occasionally give misleading signals, especially in turbulent markets.**Requires Confirmation:**Because the CCI can remain overbought or oversold for extended periods during strong trends, it’s crucial to use other forms of analysis or indicators to confirm signals.

## Coding the Commodity Channel Index (CCI) in Python, R and MATLAB

The CCI can be found preloaded in many trading systems and technical analysis packages for your convenience but you may wish to custom code them or perhaps gain deeper understanding of how they are constructed. The CCI can be coded into popular trading languages such as Python, R, and MATLAB.

Here’s a basic example of how you might code the CCI in Python using the pandas library:

```
import pandas as pd
import numpy as np
def calculate_CCI(data, n):
TP = (data['High'] + data['Low'] + data['Close']) / 3
CCI = pd.Series((TP - TP.rolling(n).mean()) / (0.015 * TP.rolling(n).std()), name='CCI')
data = data.join(CCI)
return data
data = pd.read_csv('your_data.csv')
n = 20
calculate_CCI(data, n)
```

In this example, ‘your_data.csv’ should be replaced with the path to your data file, and ‘n’ is the number of periods to consider for the moving average and standard deviation calculations.

Here is the R code for the CCI Index:

```
# Installing and loading the TTR package
if (!require(TTR)) {
install.packages("TTR")
library(TTR)
}
# Load historical price data from CSV
# Ensure your CSV contains columns: 'High', 'Low', and 'Close'
data <- read.csv('your_data.csv')
# Calculate the typical price
data$TP <- (data$High + data$Low + data$Close) / 3
# Specify the lookback period for CCI
n <- 20
# Calculate CCI using the TTR package's function
# Note: This function might use a slightly different formula for CCI computation than the one provided.
data$CCI <- CCI(data$High, data$Low, data$Close, n)
# Display the data with the added CCI column
print(data)
```

The TTR package’s `CCI`

function calculates the CCI, but it uses the simple moving average (SMA) of the typical price and not the mean deviation of the typical price from its SMA. This might yield different results compared to the given formula.

Again as in Python, in this R example, ‘your_data.csv’ should be replaced with the path to your data file, and ‘n’ is the number of periods to consider for the moving average and standard deviation calculations.

Similarly to code the Commodity Channel Index (CCI) in MATLAB you would use:

```
% Load historical price data from CSV
% Ensure your CSV contains columns: 'High', 'Low', and 'Close'
data = readtable('your_data.csv');
% Calculate typical price
TP = (data.High + data.Low + data.Close) / 3;
% Specify the lookback period for CCI
n = 20;
% Calculate moving average of TP
MA = movmean(TP, n);
% Calculate mean deviation
MD = movmean(abs(TP - MA), n);
% Compute CCI
CCI = (TP - MA) ./ (0.015 * MD);
% Add CCI to data table
data.CCI = CCI;
% View data
disp(data)
```

Please note that the above MATLAB code uses the `movmean`

function, which was introduced in MATLAB R2016a. If you’re using an older version of MATLAB, you might need to use alternative methods or update your MATLAB.

## How to Plot CCI Using Python and VSCode

Suppose you want to plot this on a chart, you can do so using free data from Yahoo Finance and free software called Visual Studio Code from Microsoft. I’ll provide a step by step guide of how to do it below.

### Step 1: Setup and Preparing the Environment

**Open VSCode:**Make sure you have Python and the necessary VSCode Python extension installed. If not, you can download it from the extensions pane on the left sidebar.**Open a New File:**Click`File`

>`New File`

from the top menu.**Set the Language to Python:**Click on the bottom right where it says`Plain Text`

and change it to`Python`

.**Paste the following code into your file**:

```
import yfinance as yf
import pandas as pd
import mplfinance as mpf
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
```

5. **Save the File:** Click `File`

> `Save As`

and save it as `cci_chart.py`

(or any name with a `.py`

extension).

### Step 2: Define the CCI Calculation Function

Below the imports you’ve added in the previous step, paste the following function. This function will help us calculate the Commodity Channel Index (CCI) for the given data:

```
def calculate_cci(data, n):
TP = (data['High'] + data['Low'] + data['Close']) / 3
MA = TP.rolling(window=n).mean()
MD = TP.rolling(window=n).apply(lambda x: (abs(x - x.mean())).mean())
CCI = (TP - MA) / (0.015 * MD)
return CCI
```

### Step 3: Fetching Data and Preparing the Chart

Continue in the `cci_chart.py`

file. Below the function you added in the last step, paste the following:

```
# Fetch the data
data = yf.download('6B=F', start='2022-07-01', end='2023-07-01')
# Calculate the CCI
lookback = 20
data['CCI'] = calculate_cci(data, lookback)
# Add zero, +200, and -200 lines
data['Zero Line'] = 0
data['+200'] = 200
data['-200'] = -200
# Ensure the index is a DatetimeIndex
data.index = pd.DatetimeIndex(data.index)
```

### Step 4: Plotting the Data

To finish off the script and visualize the data, paste the following code below the previous section:

```
# Define the additional plots as a list of dictionaries
apd = [
mpf.make_addplot(data['CCI'], panel=2, color='b', secondary_y=False, ylabel='CCI'),
mpf.make_addplot(data['Zero Line'], panel=2, color='black', secondary_y=False, linestyle='dashed'),
mpf.make_addplot(data['+200'], panel=2, color='r', secondary_y=False, linestyle='dashed'),
mpf.make_addplot(data['-200'], panel=2, color='g', secondary_y=False, linestyle='dashed')
]
# Set the panel sizes. The first panel (candles) is 5 times the size of the second and third panels (volume and CCI)
panel_sizes = (5, 1, 3)
# Create a subplot for the CCI and add the additional plot
fig, axes = mpf.plot(data, type='candle', style='yahoo', addplot=apd, volume=True, panel_ratios=panel_sizes, title='British Pound Futures and CCI', returnfig=True)
# Create legend using dummy lines
legend_lines = [Line2D([0], [0], color=c, lw=1.5, linestyle=ls) for c, ls in zip(['b', 'black', 'r', 'g'], ['solid', 'dashed', 'dashed', 'dashed'])]
axes[2].legend(legend_lines, ['CCI', 'Zero Line', 'Overbought +200', 'Oversold -200'], loc='lower left')
# Show the plot
mpf.show()
```

Now, save your file (`File`

> `Save`

).

### Step 5. Running the Script

**Open the Terminal in VSCode:**You can do this by clicking on`View`

>`Terminal`

in the top menu.- Ensure you are in the correct directory where you saved your
`cci_chart.py`

script. If not, use the`cd`

command to navigate to the directory. **Install Required Libraries:**In the terminal, type the following commands one by one and hit`Enter`

:

`pip install yfinance pandas mplfinance matplotlib`

**Run the Script:** After installing the required libraries, in the terminal, type:

`python cci_chart.py`

And hit `Enter`

. This will execute the script and display the chart.

That’s it! You should now see a chart displaying the British Pound Futures with the CCI plotted below it the same as mine below:

You can see if you had bought and sold when the CCI line turns back after crossing to 200 level extremes you wouldn’t have done too badly on some occasions but others don’t look great. This why you should never solely rely on a single indicator but combine the signals perhaps with candle patterns and other considerations such as fundamentals as well as tying in with other indicators.

The Commodity Channel Index (CCI) is a versatile indicator that can be adjusted to fit the your specific needs. Here are some parameters and considerations:

### Parameters to Adjust:

**Lookback Period:**The most direct parameter to adjust is the lookback period*n*. Typically, a 20-day period is used, but this can be shortened or lengthened depending on the trader’s preferences. A shorter period will make the CCI more sensitive, while a longer period will make it less so.**Threshold Levels:**While the traditional overbought and oversold levels for the CCI are +100 and -100 respectively, these can be adjusted. You might use +200 and -200 for a more conservative approach as we did in the chart we created above. These levels dictate when you might consider a market to be overbought or oversold.**Constant Multiplier:**The 0.015 constant in the CCI formula ensures that about 85% of CCI values fall between +100 and -100. However, this constant can be adjusted if the trader wants to change the percentage of value encapsulation. I explained in more detail how this works earlier in the post in the formula section.

### Complementary Indicator: Parabolic SAR

The Parabolic Stop and Reverse (Parabolic SAR) can be a good indicator to use alongside the CCI.

**How it Works:**The Parabolic SAR provides entry and exit points. When the price is above the Parabolic SAR dots, it indicates an uptrend, and when it’s below the dots, it indicates a downtrend.**Combination with CCI:****Trend Confirmation:**The Parabolic SAR can help confirm the trend that the CCI might be indicating. For instance, if the CCI shows an overbought condition and the price is below the Parabolic SAR dots, it might be a strong indication of a potential downturn.**Entry/Exit Points:**While the CCI can indicate overbought or oversold conditions, the Parabolic SAR can provide specific entry and exit points. For example, if the CCI indicates an oversold condition and the price switches to being above the Parabolic SAR dots, it might be a good buying opportunity.

### Why the Combination Works:

The CCI is primarily a momentum oscillator, while the Parabolic SAR is a trend-following indicator. By combining the two, a trader gets both a sense of the momentum behind price moves and a confirmation of the prevailing trend. This dual approach can help in filtering out false signals from either indicator when used alone.

## Conclusion

The Commodity Channel Index (CCI) can be powerful tool that traders can use to identify potential trading opportunities. Its sensitivity to market volatility makes it a valuable addition to any trader’s charts or screener.

However, like all technical indicators, the CCI is not infallible and should not be used in isolation. It’s important to use the CCI in conjunction with other forms of technical analysis and to always consider the broader market context. Furthermore, while the CCI can provide valuable insights, it’s ultimately up to each trader to interpret these insights in the context of their own trading strategy and risk tolerance.

## Related Indicators

If you found the CCI useful, you might also want to check out these related indicators:

**Relative Strength Index (RSI):**Like the CCI, the RSI is an oscillator that can help identify overbought and oversold conditions.**Moving Average Convergence Divergence (MACD):**The MACD is a trend-following momentum indicator that can help identify potential buy and sell signals.**Bollinger Bands:**Bollinger Bands are a volatility indicator that can provide insights into potential price levels at which to buy or sell.

## Leave a Comment

We hope you found this guide to the Commodity Channel Index (CCI) helpful! If you have any questions, comments, or insights you’d like to share, please leave a comment below. We’d love to hear from you!

Remember, successful trading involves more than just understanding technical indicators. It also requires discipline, patience, and a solid understanding of your own risk tolerance. Happy trading!

### Further Reading

- “
*Commodity Channel Index: Tool for Trading Cyclic Trends*,” published in Commodities Magazine in 1980. The article provides a detailed explanation of the CCI and how it can be used to identify cyclical trends in commodity prices. At the time of writing this post, it appears that the article is available for purchase as a PDF from the Technical Analysis of Stocks & Commodities magazine’s online store. However, I’d recommend checking their website directly as availability and terms might change.

You can find it here

2. Park, Cheol-Ho and Irwin, Scott, *The Profitability of Technical Analysis: A Review* (October 2004). AgMAS Project Research Report No. 2004-04, Available at SSRN: https://ssrn.com/abstract=603481 or http://dx.doi.org/10.2139/ssrn.603481 – This paper reviews a large number of studies on the profitability of technical analysis. We review this paper in this article.

## Leave a Reply