Jhanvi
Jhanvi

Reputation: 15

AttributeError: 'dict' object has no attribute 'plot'

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'

I am trying to get the plot for the dataframe created with the different prices from the start and end date. I tried reading different blogs but none seem to solve it. I am sure I am making a very basic error. Although, I am not able to figure out what am I doing wrong here, any suggestions to fix it?

Upvotes: 1

Views: 8232

Answers (1)

Sid Narayanan
Sid Narayanan

Reputation: 49

You cannot directly plot a dictionary in matplotlib. It needs x values and y values.

You can see that type(df) will be a <class 'dict'> which contains the value something like this:

{'TSLA': {'2017-02-09': {'open': 266.25, 'high': 271.18, 'low': 266.15, 'close': 269.2, 'volume': 7820222}}}

so, if you want to get it graphed, you need to convert it into pandas dataFrame

your code has to change like this:

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();

You will get a graph like this:

Graph

Upvotes: 1

Related Questions