Commodity Channel Index ( CCI ) Using Python

The CCI compares the current price to an average price over a period of time. The indicator fluctuates above or below zero, moving into positive or negative territory. While most values, approximately 75%, fall between -100 and +100, about 25% of the values fall outside this range, indicating a lot of weakness or strength in the price movement.

CCI is calculated with the following formula:

(Typical Price - Simple Moving Average) / (0.015 x Mean Deviation)

When the CCI is above +100, this means the price is well above the average price as measured by the indicator. When the indicator is below -100, the price is well below the average price.

A basic CCI strategy is used to track the CCI for movement above +100, which generates buy signals, and movements below -100, which generates sell or short trade signals.

Investors may only want to take the buy signals, exit when the sell signals occur, and then re-invest when the buy signal occurs again.

Here I've used Python to build a CCI indicator. 

# Load the necessary packages and modules
from pandas_datareader import data as pdr
import matplotlib.pyplot as plt
import yfinance
import pandas as pd


# Commodity Channel Index 
def CCI(datandays): 
    TP = (data['High'] + data['Low'] + data['Close']) / 3 
    CCI = pd.Series((TP - TP.rolling(ndays).mean()) / (0.015 * TP.rolling(ndays).std()),
                    name = 'CCI'
    data = data.join(CCI) 
    return data


# Retrieve the Nifty data from Yahoo finance:
data = pdr.get_data_yahoo("^NSEI", start="2018-01-01", end="2021-01-24"
data = pd.DataFrame(data)


# Compute the Commodity Channel Index(CCI) for NIFTY based on the 20-day Moving average
n = 20
NIFTY_CCI = CCI(data, n)  
CCI = NIFTY_CCI['CCI']


# Plotting the Price Series chart and the Commodity Channel index below
fig = plt.figure(figsize=(10,8))
ax = fig.add_subplot(211)
ax.set_xticklabels([])
plt.plot(data['Close'],lw=1)
plt.title('NSE Price Chart')
plt.ylabel('Close Price')
plt.grid(True)
bx = fig.add_subplot(212)
plt.plot(CCI,'k',lw=0.75,linestyle='-',label='CCI')
plt.legend(loc=2,prop={'size':9.5})
plt.ylabel('CCI values')
plt.grid(True)







Comments

Popular posts from this blog

Net Present Value (NPV) On Python Using Numpy

SMA Trading Strategy Using Python