from iexfinance import Stock
import matplotlib.pyplot as plt
tsla = Stock('TSLA')
tsla.get_close()
tsla.get_price()
from iexfinance import get_historical_data
from datetime import datetime
import pandas as pd
pd.set_option('display.max_rows', 1000)
start = datetime(2017, 2, 9)
end = datetime(2017, 5, 24)
df = get_historical_data("TSLA", start=start, end=end, output_format='json')
df.plot()
plt.show()
---------------------------------------------------------------------------
AttributeError Traceback (most recent call
last)
<ipython-input-16-77b5455be846> in <module>()
8
9 df = get_historical_data("TSLA", start=start, end=end,
output_format='json')
---> 10 df.plot()
11 plt.show()
12 df
AttributeError: 'dict' object has no attribute 'plot'
我试图获取从开始和结束日期以不同价格创建的数据框的图。我尝试阅读其他博客,但似乎都无法解决。我确定我犯了一个非常基本的错误。虽然,我无法弄清楚我在做什么错,但有什么建议可以解决?
答案 0 :(得分:2)
您不能直接在matplotlib中绘制字典。它需要x值和y值。
您会看到type(df)
将是<class 'dict'>
,其中包含类似以下内容的值:
{'TSLA': {'2017-02-09': {'open': 266.25, 'high': 271.18, 'low': 266.15, 'close': 269.2, 'volume': 7820222}}}
因此,如果要绘制图形,则需要将其转换为pandas dataFrame
您的代码必须像这样更改:
from iexfinance import Stock
import matplotlib.pyplot as plt
tsla = Stock('TSLA')
tsla.get_close()
tsla.get_price()
from iexfinance import get_historical_data
from datetime import datetime
import pandas as pd
pd.set_option('display.max_rows', 1000)
start = datetime(2017, 2, 9)
end = datetime(2017, 5, 24)
df = get_historical_data("TSLA", start=start, end=end, output_format='json')
df = pd.DataFrame(df["TSLA"]).transpose() #transpose to get dates as x
df = df.drop(columns = "volume") #deleted volume column, else it make other graphs smaller
df.index = pd.to_datetime(df.index) #change string to date format
df.plot()
plt.show();
您将获得如下图: