Skip to content

Instantly share code, notes, and snippets.

@quantra-go-algo
Created December 25, 2021 11:59
Show Gist options
  • Save quantra-go-algo/1b37bfb74d69148f0dfbdb5a2c7bdb25 to your computer and use it in GitHub Desktop.
Save quantra-go-algo/1b37bfb74d69148f0dfbdb5a2c7bdb25 to your computer and use it in GitHub Desktop.
Build Technical Indicators In Python - CCI
# Commodity Channel Index Python Code
# Load the necessary libraries
from pandas_datareader import data as pdr
import matplotlib.pyplot as plt
import yfinance
import pandas as pd
# Commodity Channel Index
def CCI(df, ndays):
df['TP'] = (data['High'] + data['Low'] + data['Close']) / 3
df['sma'] = df['TP'].rolling(ndays).mean()
df['mad'] = df['TP'].rolling(ndays).apply(lambda x: pd.Series(x).mad())
df['CCI'] = (df['TP'] - df['sma']) / (0.015 * df['mad'])
return df
# Get the NIFTY data from Yahoo finance:
data = pdr.get_data_yahoo("^NSEI", start="2014-01-01", end="2016-01-01")
data = pd.DataFrame(data)
# Compute the Commodity Channel Index (CCI) for NIFTY based on the 14-day moving average
n = 14
NIFTY_CCI = CCI(data, n)
# Plot the price series chart and the Commodity Channel index
fig = plt.figure(figsize=(7,5))
ax = fig.add_subplot(2, 1, 1)
ax.set_xticklabels([])
plt.plot(data['Close'],lw=1)
plt.title('NIFTY Price Chart')
plt.ylabel('Close Price')
plt.grid(True)
bx = fig.add_subplot(2, 1, 2)
plt.plot(NIFTY_CCI['CCI'],'k',lw=0.75,linestyle='-',label='CCI')
plt.title('CCI Values for NIFTY')
plt.legend(loc=2,prop={'size':9.5})
plt.ylabel('CCI values')
plt.grid(True)
plt.setp(plt.gca().get_xticklabels(), rotation=30)
plt.tight_layout()
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment