2017-07-22 78 views
1

此代碼從Google財經中獲得一條直線的座標,並將第三個點放置在相同的距離上。有很多回溯ValueError:ordinal必須大於等於1

dt = datetime.datetime.fromordinal(ix).replace(tzinfo=UTC)
ValueError: ordinal must be >= 1

發生

import datetime as dt 
from datetime import timedelta as td 
import matplotlib.pyplot as plt 
from matplotlib import style 
import pandas as pd 
import pandas_datareader.data as web 
import numpy as np 

start = dt.datetime(2017, 7, 1) 
end = dt.datetime(2017, 3, 1) 

# retrieving data from google 
df = web.DataReader('TSLA', 'google', start,) 

Dates = df.index 
Highs = df['High'] # Getting only the values from the 'High' Column. 

Highest_high = np.amax(Highs) # returns the Highest value 
     for i, h in enumerate(Highs): 
      if h == Highest_high : 
       Highests_index = i 
#Highests_index = Highs.argmax() # returns the index of Highest value 

Highest_high_2 = sorted(Highs)[-2] 
for i, j in enumerate(Highs): 
     if j == Highest_high_2 : 
     Highests_index_2 = i 

#================Problem Maybe starting from here======================== 

x = [Highests_index, Highests_index_2] 
y = [Highest_high, Highest_high_2] 
coefficients = np.polyfit(x, y, 1) 

polynomial = np.poly1d(coefficients) 
# the np.linspace lets you set number of data points, line length. 
x_axis = np.linspace(3,Highests_index_2 + 1, 3) 
y_axis = polynomial(x_axis) 

plt.plot(x_axis, y_axis) 
plt.plot(x[0], y[0], 'go') 
plt.plot(x[1], y[1], 'go') 
plt.plot(Dates, Highs) 
plt.grid('on') 
plt.show() 

以下錯誤上面的代碼效果很好,當我剛繪製的數值,而無需使用datetime和大熊貓。我認爲這個問題可能在datetime或matplotlib中。

我知道這個問題可能看起來是重複的,但我無法將我的問題與其他任何解決方案聯繫在一起。

回答

0

對不起,其實錯誤發生是由於第三行。我刪除了plt.plot()Dates, Highs)而一切工作就像魅力!

1

錯誤是由於matplotlib無法找到沿x軸的x軸值的位置。

來自前兩行的圖表具有x軸的數值,而第三行試圖在同一軸上繪製datetime。在繪製第三行plt.plot(Dates, Highs)時,matplotlib會嘗試查找日期的x軸位置,並因錯誤而失敗。

相關問題