kit12_31
kit12_31

Reputation: 99

Key error message when calculating variables using pandas and yfinance

trying to calculate some variables from yfinance from the column df['Close']. But im getting this error which i have not seen before. and heres are the code:

 import os 
 import pandas as pd
 import plotly.graph_objects as go

 symbols = 'AAPL'

for filename in os.listdir('datasets/'):
#print(filename)
symbol = filename.split('.')[0]
#print(symbol)

df = pd.read_csv('datasets/{}'.format(filename))
if df.empty:
    continue 

df['20_sma'] = df['Close'].rolling(window=20).mean()
df['stddev'] = df['Close'].rolling(window=20).std()
df['lowerband'] = df['20_sma'] + (2* df['stddev'])
df['upperband'] = df['20_sma'] - (2* df['stddev'])

if symbol in symbols:
    print(df)

and heres are the error message:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pandas/core/indexes/base.py", line 2895, in get_loc
    return self._engine.get_loc(casted_key)
  File "pandas/_libs/index.pyx", line 70, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/index.pyx", line 101, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/hashtable_class_helper.pxi", line 1675, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas/_libs/hashtable_class_helper.pxi", line 1683, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'Close'

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

Traceback (most recent call last):
  File "/Users/Kit/Documents/TTM_squeezer/squeeze.py", line 16, in <module>
    df['20_sma'] = df['Close'].rolling(window=20).mean()
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pandas/core/frame.py", line 2906, in __getitem__
    indexer = self.columns.get_loc(key)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pandas/core/indexes/base.py", line 2897, in get_loc
    raise KeyError(key) from err
KeyError: 'Close'

Seems like the 'Close' column has contributed to this error but i just cant figure out why? Many thanks

Upvotes: 0

Views: 526

Answers (1)

kit12_31
kit12_31

Reputation: 99

turns out there was an error in the process where the local file was saved case closed, thanks all

Upvotes: 1

Related Questions