0

试图从 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'

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

4

1 回答 1

0

原来在保存本地文件的过程中出现错误关闭情况,谢谢大家

于 2020-12-08T01:06:13.063 回答