使用pandas和yfinance计算变量时的关键错误消息

2024-05-31 23:02:13 发布

您现在位置:Python中文网/ 问答频道 /正文

试图从df['Close']列的yfinance计算一些变量。 但是我犯了一个我以前从未见过的错误。代码如下:

 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)

下面是错误消息:

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'

上述异常是以下异常的直接原因:

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'

似乎是“关闭”列导致了这个错误,但我就是不明白为什么? 非常感谢


Tags: inpypandasdfclosegetindex错误