2016-10-30 154 views
0

我試圖繪製兩個股票價格的滾動關聯。此功能用於工作,但由於某種原因,它現在不起作用。例如,我下載AAPL和TSLA股票數據,然後將其調整後的價格分爲兩個系列。例如,我下載AAPL和TSLA股票數據,然後將其調整後的價格分爲兩個系列。然後我嘗試運行一個滾動關聯圖。我收到以下錯誤:Python:Rolling Correlation Plot結果「ValueError:無法將字符串轉換爲浮點數:」

「ValueError異常:無法將字符串轉換爲float:「2013年1月2" 日從雅虎數據

import numpy as np 
randn = np.random.randn 
import pandas as pd 
import matplotlib.pyplot as plt 
import matplotlib as mpl 
import matplotlib.pylab as pylab 
%matplotlib inline 
from yahoo_finance import Share 

start = '2013-01-01' 
end = '2015-01-01' 
TSLA=pd.DataFrame(Share('TSLA').get_historical(start, end)) 
TSLA=TSLA.set_index('Date') 
AAPL=pd.DataFrame(Share('AAPL').get_historical(start, end)) 
AAPL=AAPL.set_index('Date') 

TSLA_px=TSLA['Adj_Close'] 
AAPL_px=AAPL['Adj_Close'] 

rolling_correlation = pd.rolling_corr(TSLA_px, AAPL_px, 60) 
plt.plot(rolling_correlation) 
plt.xlabel('Day') 
plt.ylabel('60-day Rolling Correlation') 
+0

難道你是*導入'pandas',但調用'pd.DataFrame'和'pd.rolling_corr'?請嘗試'將pandas導入爲pd'。即使它不能解決你的問題,這也是更好的做法。 – lanery

+0

謝謝Lanery,趕上!深夜編碼......不能解決問題,但你是對的! –

回答

1

愚蠢的小白錯誤...日期在作爲一個字符串,並需要轉換爲日期。

TSLA['Date']=pd.to_datetime(TSLA['Date']) 
+0

好的電話。我剛剛重新回顧了你的問題,並作出了相同的認識。 FWIW,'pandas_datareader'可以爲您提供比'yahoo_finance'包更好的服務,http://pandas-datareader.readthedocs.io/en/latest/remote_data.html。 – lanery

相關問題