python - 值错误 : ordinal must be >= 1

标签 python pandas matplotlib dataframe quantitative-finance

此代码从 google finance 获取一条直线的 2 个坐标,并将第三个点放在同一条直线上一定距离处。

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

大量Traceback出现如下错误

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

当我不使用 datetime 和 pandas 只绘制数值时,上面的代码运行良好。我认为问题可能出在日期时间或 matplotlib 中。

我知道这个问题可能看起来重复,但我无法将我的问题与此处的任何其他解决方案联系起来。

最佳答案

错误是由于matplotlib无法找到x轴值沿x轴的位置。

前两行的绘图具有 x 轴的数值,而第三行试图在同一轴上绘制 datetime。在绘制第三行 plt.plot(Dates, Highs) 时,matplotlib 试图找到日期的 x 轴位置,但失败并出现错误。

关于python - 值错误 : ordinal must be >= 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45257475/

相关文章:

python - 二元对数损失是否排除了基于 y 的方程的一部分?

python - 多索引 pandas 数据帧的最高和最低列值

python - 修改matplotlib内置颜色

python - pandas groupby,只保留第一次出现的行

python - 如何为图形级函数编辑 seaborn 图例标题和标签

python - 概率标准化的二维直方图

python - 在 matplotlib 中创建堆叠柱面条形图

python - 有效地将数据从 CSV 读取到具有多个分隔符的数据框中

python - 二维 numpy.take 快吗?

python - 如何使用 Pandas 样式器根据给定列为整行着色?