【问题标题】:Unsupported operand type(s) for +: 'int' and 'datetime.timedelta'+ 不支持的操作数类型:“int”和“datetime.timedelta”
【发布时间】:2021-12-01 18:26:23
【问题描述】:

在尝试绘制图表时遇到此错误。我正在尝试使用提供的值绘制图表。我正在使用 yahoo Finance,并想使用 python 绘制阻力线。

    for index in range(len(pivots)):
    print(str(pivots[index])+": "+str(dates[index]))

    plt.plot_date([dates[index],dates[index]+timeD,
        pivots[index],pivots[index]], linestyle="-", linewidth=2, marker="none")

这是整个代码

import pandas
import yfinance as yf
import datetime as dt
import pandas as pd
from pandas_datareader import data as pdr
import matplotlib.pyplot as plt

yf.pdr_override()
start= dt.datetime(2019,1,1)
now= dt.datetime.now()

stock = input("Enter the stock symbol: ")

while stock !="quit":

df=pdr.get_data_yahoo(stock, start, now)

df["Low"].plot(Label="low")

pivots=[]
dates=[]
counter=0
lastPivot=0

Range=[0,0,0,0,0,0,0,0,0,0]
dateRange=[0,0,0,0,0,0,0,0,0,0]

for i in df.index:
    currentMin=min(Range, default=0)
    value=round(df["Low"][i],2)

    Range=Range[1:9]
    Range.append(value)
    dateRange=dateRange[1:9]
    dateRange.append(i)

    if currentMin==min(Range, default=0):
        counter-=1
    else:
        counter=0
    if counter==-5:
        lastPivot=currentMin
        dateloc=Range.index(lastPivot)
        lastDate=dateRange[dateloc]
        pivots.append(lastPivot)
        dates.append(lastDate)

print()

# print(str(pivots))
# print(str(dates))
timeD=dt.timedelta(days=30)

for index in range(len(pivots)):
    print(str(pivots[index])+": "+str(dates[index]))

    plt.plot_date([dates[index],dates[index]+timeD,
        pivots[index],pivots[index]], linestyle="-", linewidth=2, marker="none")

plt.show()

stock= input ("Enter the stock symbol : ")

我收到的错误是

Traceback(最近一次调用最后一次): 文件“Low.py”,第 57 行,在

plt.plot_date([dates[index],dates[index]+timeD,
TypeError: unsupported operand type(s) for +: 'int' and 'datetime.timedelta'

谢谢

【问题讨论】:

    标签: python matplotlib plot finance stock


    【解决方案1】:

    问题在于plt.plot_date中的这个表达式:

    dates[index]+timeD
    

    如果你打印日期,你会得到这个输出:

    [0,
     Timestamp('2019-02-08 00:00:00'),
     Timestamp('2019-03-08 00:00:00'),
     ...
     ...
     ...
     Timestamp('2021-09-20 00:00:00'),
     Timestamp('2021-10-04 00:00:00')]
    

    如您所见,列表包含 Int 和 Timestamp 值。所以当你添加timeDwitch is a timedelta 时,这个操作是非法的。

    我不明白您是如何构造 dates 的,但您需要检查该部分中的逻辑并检查为什么您会获得 Int 和 Timestamp 值。

    【讨论】:

      猜你喜欢
      • 2022-01-03
      • 1970-01-01
      • 2021-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-12
      • 2018-11-08
      • 2015-01-17
      相关资源
      最近更新 更多