Я просматриваю учебник по Python для финансов на YouTube, но застреваю с ошибкой Matplotlib. Мой код очищает имена S & P 500 из Википедии, а затем использует Pandas data_reader для получения информации об акциях из Yahoo Finance для каждого тикера.
В возвращаемом фрейме данных есть столбец даты и столбцы для каждого имени тикера.
Все это, по-видимому, работает нормально, используя функцию compile_data()
, но я получаю ValueError: view limit minimum 0.0 is less than 1 and is an invalid Matplotlib date value.
после попытки построить график данных csv с visualize_data
, используя Pandas .plot () для данного символа (т.е. AAPL). В столбце даты и символа отсутствуют пропущенные значения.
Пожалуйста, помогите мне!
Полный код учебника можно найти здесь (pythonprogramming.net).
Вот код:
def compile_data():
with open('sp500tickers.pickle','rb') as f:
tickers = pickle.load(f)
main_df = pd.DataFrame()
for count, ticker in enumerate(tickers):
df = pd.read_csv('stock_dfs/{}.csv'.format(ticker))
df.set_index('Date', inplace=True)
df.rename(columns={'Adj Close': ticker}, inplace=True)
df.drop(['Open', 'High', 'Low', 'Close', 'Volume'], axis=1, inplace=True)
if main_df.empty: # boolean for if empty or not
main_df = df
else:
main_df = main_df.join(df, how='outer')
if count % 100 == 0:
print(count)
#print(main_df.head())
main_df.to_csv('sp500_joined_closes.csv')
compile_data()
def visualize_data():
df = pd.read_csv('sp500_joined_closes.csv')
df['AAPL'].plot()
plt.show()
visualize_data()
Вот полное сообщение об ошибке:
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
//anaconda3/lib/python3.7/site-packages/pandas/plotting/_tools.py in _handle_shared_axes(axarr, nplots, naxes, nrows, ncols, sharex, sharey)
306 for ax in axarr:
--> 307 layout[ax.rowNum, ax.colNum] = ax.get_visible()
308
IndexError: index 5 is out of bounds for axis 0 with size 3
During handling of the above exception, another exception occurred:
ValueError Traceback (most recent call last)
<ipython-input-87-55ac2958f267> in <module>
4 plt.show()
5
----> 6 visualize_data()
<ipython-input-87-55ac2958f267> in visualize_data()
1 def visualize_data():
2 df = pd.read_csv('sp500_joined_closes.csv')
----> 3 df['AAPL'].plot(x='Date')
4 plt.show()
5
//anaconda3/lib/python3.7/site-packages/pandas/plotting/_core.py in __call__(self, kind, ax, figsize, use_index, title, grid, legend, style, logx, logy, loglog, xticks, yticks, xlim, ylim, rot, fontsize, colormap, table, yerr, xerr, label, secondary_y, **kwds)
2740 colormap=colormap, table=table, yerr=yerr,
2741 xerr=xerr, label=label, secondary_y=secondary_y,
-> 2742 **kwds)
2743 __call__.__doc__ = plot_series.__doc__
2744
//anaconda3/lib/python3.7/site-packages/pandas/plotting/_core.py in plot_series(data, kind, ax, figsize, use_index, title, grid, legend, style, logx, logy, loglog, xticks, yticks, xlim, ylim, rot, fontsize, colormap, table, yerr, xerr, label, secondary_y, **kwds)
1996 yerr=yerr, xerr=xerr,
1997 label=label, secondary_y=secondary_y,
-> 1998 **kwds)
1999
2000
//anaconda3/lib/python3.7/site-packages/pandas/plotting/_core.py in _plot(data, x, y, subplots, ax, kind, **kwds)
1799 plot_obj = klass(data, subplots=subplots, ax=ax, kind=kind, **kwds)
1800
-> 1801 plot_obj.generate()
1802 plot_obj.draw()
1803 return plot_obj.result
//anaconda3/lib/python3.7/site-packages/pandas/plotting/_core.py in generate(self)
252 self._add_table()
253 self._make_legend()
--> 254 self._adorn_subplots()
255
256 for ax in self.axes:
//anaconda3/lib/python3.7/site-packages/pandas/plotting/_core.py in _adorn_subplots(self)
429 naxes=nrows * ncols, nrows=nrows,
430 ncols=ncols, sharex=self.sharex,
--> 431 sharey=self.sharey)
432
433 for ax in self.axes:
//anaconda3/lib/python3.7/site-packages/pandas/plotting/_tools.py in _handle_shared_axes(axarr, nplots, naxes, nrows, ncols, sharex, sharey)
325 if sharex or len(ax.get_shared_x_axes()
326 .get_siblings(ax)) > 1:
--> 327 _remove_labels_from_axis(ax.xaxis)
328
329 if ncols > 1:
//anaconda3/lib/python3.7/site-packages/pandas/plotting/_tools.py in _remove_labels_from_axis(axis)
278
279 def _remove_labels_from_axis(axis):
--> 280 for t in axis.get_majorticklabels():
281 t.set_visible(False)
282
//anaconda3/lib/python3.7/site-packages/matplotlib/axis.py in get_majorticklabels(self)
1251 def get_majorticklabels(self):
1252 'Return a list of Text instances for the major ticklabels.'
-> 1253 ticks = self.get_major_ticks()
1254 labels1 = [tick.label1 for tick in ticks if tick.label1.get_visible()]
1255 labels2 = [tick.label2 for tick in ticks if tick.label2.get_visible()]
//anaconda3/lib/python3.7/site-packages/matplotlib/axis.py in get_major_ticks(self, numticks)
1406 'Get the tick instances; grow as necessary.'
1407 if numticks is None:
-> 1408 numticks = len(self.get_majorticklocs())
1409
1410 while len(self.majorTicks) < numticks:
//anaconda3/lib/python3.7/site-packages/matplotlib/axis.py in get_majorticklocs(self)
1323 def get_majorticklocs(self):
1324 """Get the array of major tick locations in data coordinates."""
-> 1325 return self.major.locator()
1326
1327 def get_minorticklocs(self):
//anaconda3/lib/python3.7/site-packages/matplotlib/dates.py in __call__(self)
1432 def __call__(self):
1433 'Return the locations of the ticks'
-> 1434 self.refresh()
1435 return self._locator()
1436
//anaconda3/lib/python3.7/site-packages/matplotlib/dates.py in refresh(self)
1452 def refresh(self):
1453 'Refresh internal information based on current limits.'
-> 1454 dmin, dmax = self.viewlim_to_dt()
1455 self._locator = self.get_locator(dmin, dmax)
1456
//anaconda3/lib/python3.7/site-packages/matplotlib/dates.py in viewlim_to_dt(self)
1203 'often happens if you pass a non-datetime '
1204 'value to an axis that has datetime units'
-> 1205 .format(vmin))
1206 return num2date(vmin, self.tz), num2date(vmax, self.tz)
1207
ValueError: view limit minimum 0.0 is less than 1 and is an invalid Matplotlib date value. This often happens if you pass a non-datetime value to an axis that has datetime units