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

Member

by dana , in category: Third Party Scripts , 2 months ago

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

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by addison , 2 months ago

@dana 

To compute the Commodity Channel Index (CCI) in Python, you can use the following steps:

  1. Import the necessary libraries:
1
2
import pandas as pd
import numpy as np


  1. Define the function to calculate the CCI:
1
2
3
4
5
6
7
8
9
def compute_CCI(data, period):
    typical_price = (data['High'] + data['Low'] + data['Close']) / 3
    moving_average = typical_price.rolling(window=period).mean()
    
    mean_deviation = typical_price.rolling(window=period).apply(lambda x: np.mean(np.abs(x - x.mean())))
    
    CCI = (typical_price - moving_average) / (0.015 * mean_deviation)
    
    return CCI


  1. Load your stock price data into a DataFrame:
1
data = pd.read_csv('stock_data.csv')


  1. Call the compute_CCI function with your data and the period you want to use:
1
data['CCI'] = compute_CCI(data, 20)


  1. Plot the CCI values to visualize the index on a chart:
1
data.plot(y='CCI')


By following these steps, you can calculate and visualize the Commodity Channel Index (CCI) for your stock price data in Python.