我试图绘制一个简单的时间序列图表,看看收盘价格是如何变化的。这是我的代码:
from yahoo_finance import Share
from datetime import datetime
import pandas as pd
import matplotlib.pyplot as plt
yahoo = Share('YHOO')
stock = yahoo
start_date = '2015-12-01'
end_date = '2015-12-10'
historical_table = pd.DataFrame(stock.get_historical(start_date, end_date))
historical_table = historical_table[['Date','Symbol','Close','High','Low','Open']]
def convert_dates(date):
date = datetime.strptime(date, "%Y-%m-%d")
return date
historical_table['Date'].apply(convert_dates)
print historical_table['Date']
x = historical_table['Date']
y = historical_table['Close']
plt.plot(x,y)
plt.show()
这是我收到的错误消息:
Traceback (most recent call last):
File "finance.py", line 45, in <module>
plt.plot(x,y)
File "/Users/paulzovighian/anaconda/lib/python2.7/site-packages/matplotlib/pyplot.py", line 3099, in plot
ret = ax.plot(*args, **kwargs)
File "/Users/paulzovighian/anaconda/lib/python2.7/site-packages/matplotlib/axes/_axes.py", line 1373, in plot
for line in self._get_lines(*args, **kwargs):
File "/Users/paulzovighian/anaconda/lib/python2.7/site-packages/matplotlib/axes/_base.py", line 304, in _grab_next_args
for seg in self._plot_args(remaining, kwargs):
File "/Users/paulzovighian/anaconda/lib/python2.7/site-packages/matplotlib/axes/_base.py", line 263, in _plot_args
linestyle, marker, color = _process_plot_format(tup[-1])
File "/Users/paulzovighian/anaconda/lib/python2.7/site-packages/matplotlib/axes/_base.py", line 85, in _process_plot_format
if fmt.find('--') >= 0:
File "/Users/paulzovighian/anaconda/lib/python2.7/site-packages/pandas/core/generic.py", line 2246, in __getattr__
(type(self).__name__, name))
AttributeError: 'Series' object has no attribute 'find'
在线查看时,我倾向于看到“硬编码”的示例。变量,但我不知道如何将其应用于数据框列 - 我发现我应该使用strptime来确定我的日期列的格式,但我不知道这是否有任何影响(我如果我注释掉convert_dates apply方法,会得到相同的错误。
在此提前感谢您提供任何帮助,并欢迎提出任何简化此方法的建议。
答案 0 :(得分:1)
看起来像格式问题,试试这个:
# %matplotlib inline # Use this if you are using Jupyter notebook and want plots inline
from yahoo_finance import Share
from datetime import datetime
import pandas as pd
import matplotlib.pyplot as plt
yahoo = Share('YHOO')
stock = yahoo
start_date = '2015-12-01'
end_date = '2015-12-10'
historical_table = pd.DataFrame(stock.get_historical(start_date, end_date))
historical_table = historical_table[['Date','Symbol','Close','High','Low','Open']]
historical_table['Date'] = pd.to_datetime(historical_table['Date']) #date to datetime format
historical_table['Close'] = [float(x) for x in historical_table['Close']] #close price to floats
x = historical_table['Date']
y = historical_table['Close']
plt.plot(x,y)
plt.show()