2015-12-14 88 views
0

我想繪製一個簡單的時間序列圖,看看收盤價如何在一天中發生變化。這是我的代碼:使用熊貓繪製簡單的時間序列

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方法,我會得到相同的錯誤) 。

在此先感謝您的任何幫助,並歡迎您提出任何有關簡化此方法的建議。

回答

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() 
+0

謝謝!去圖,當然熊貓有一個內置的方法來轉換爲日期時間哈哈 – ploo