Python Function for Bollinger Bands

I am working on building a Python function for Bollinger Bands on my local jupyter nb but it's giving me a key error here's the code

 

def Bollinger_Bands(data, n):

    # Calculating the moving average
    MA = data['Close'].rolling(window=n).mean()

    # Calculating the standard deviation
    SD = data['Close'].rolling(window=n).std()

    data['Lower_BB'] = MA - (2 * SD)  # Lower Bollinger Band
    data['Upper_BB'] = MA + (2 * SD)  # Upper Bollinger Band

    return data


# Load and view Nifty data
import pandas as pd
nifty = pd.read_csv('nifty.csv')
nifty.head()


n = 21  
nifty_bb = Bollinger_Bands(nifty, n)

This is the error I am getting

 

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
File ~/anaconda3/lib/python3.11/site-packages/pandas/core/indexes/base.py:3653, in Index.get_loc(self, key)
   3652 try:
-> 3653     return self._engine.get_loc(casted_key)
   3654 except KeyError as err:

File ~/anaconda3/lib/python3.11/site-packages/pandas/_libs/index.pyx:147, in pandas._libs.index.IndexEngine.get_loc()

File ~/anaconda3/lib/python3.11/site-packages/pandas/_libs/index.pyx:176, in pandas._libs.index.IndexEngine.get_loc()

File pandas/_libs/hashtable_class_helper.pxi:7080, in pandas._libs.hashtable.PyObjectHashTable.get_item()

File pandas/_libs/hashtable_class_helper.pxi:7088, in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 'Close'

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
Cell In[4], line 6
      3 n = 21  # We have kept the window of the moving average as 21 days
      5 # Calling the Bollinger Bands function cerated by us
----> 6 nifty_bb = Bollinger_Bands(nifty, n)
      8 nifty_bb.tail()

Cell In[2], line 4, in Bollinger_Bands(data, n)
      1 def Bollinger_Bands(data, n):
      2 
      3     # Calculating the moving average
----> 4     MA = data['Close'].rolling(window=n).mean()
      6     # Calculating the standard deviation
      7     SD = data['Close'].rolling(window=n).std()

File ~/anaconda3/lib/python3.11/site-packages/pandas/core/frame.py:3761, in DataFrame.__getitem__(self, key)
   3759 if self.columns.nlevels > 1:
   3760     return self._getitem_multilevel(key)
-> 3761 indexer = self.columns.get_loc(key)
   3762 if is_integer(indexer):
   3763     indexer = [indexer]

File ~/anaconda3/lib/python3.11/site-packages/pandas/core/indexes/base.py:3655, in Index.get_loc(self, key)
   3653     return self._engine.get_loc(casted_key)
   3654 except KeyError as err:
-> 3655     raise KeyError(key) from err
   3656 except TypeError:
   3657     # If we have a listlike key, _check_indexing_error will raise
   3658     #  InvalidIndexError. Otherwise we fall through and re-raise
   3659     #  the TypeError.
   3660     self._check_indexing_error(key)

KeyError: 'Close'

Can anybody tell me what I am doing wrong



I am getting the data from https://www.nseindia.com/reports-indices-historical-index-data

Hello Abhijit,

The error you are encountering indicates that the column 'Close' does not exist in the DataFrame "nifty." This could be due to a typo in the column name or if the column is not present in the CSV file you are loading. Please check if the data file has the column 'Close.'

If the closing prices are stored in any other column, such as 'close' or 'price,' use the corresponding column name in the code instead of 'Close.'

Please let us know if you need any additional assistance.