我一直在尝试绘制一些价格与时间的数据,但我无法在此处找到绘制趋势线的方法。日期是日期时间对象。该图很好。但是,像我下面那样使用polyfit会引发错误。
import matplotlib.pyplot as plt
import pandas as pd
import datetime as dt
from datetime import datetime
import numpy as np
import matplotlib.pylab as plb
notes = pd.read_csv("tsla.csv")
notes.dropna(inplace=True)
date_list = notes['x']
price_list = notes['Close']
date_list = date_list.tolist()
price_list = price_list.tolist()
for i in range(len(date_list)):
date_list[i] = (date_list[i][:-8])
date_list[i] = date_list[i][:-5] + date_list[i][-3:-1]
##print(len(date_list[i]))
date_list[i] = datetime.strptime(date_list[i], "%m/%d/%y")
##print(date_list[i])
##print(date_list)
price_list = list(map(lambda x: int(x), price_list))
plt.plot(date_list, price_list)
plt.ylabel("Prices")
plt.xlabel("Dates")
# calc the trendline (it is simply a linear fitting)
z = np.polyfit(date_list, price_list, 1)
p = np.poly1d(z)
plb.plot(x,p(x),"r--")
##### Showing time series line graph below
plt.show()
下面的错误
Traceback (most recent call last):
File "/Users/ramapriyansrivatsanpd/Documents/Python for finance - fintech soc.py", line 42, in <module>
z = np.polyfit(date_list, price_list, 1)
File "<__array_function__ internals>", line 5, in polyfit
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/numpy/lib/polynomial.py", line 590, in polyfit
x = NX.asarray(x) + 0.0
TypeError: unsupported operand type(s) for +: 'datetime.datetime' and 'float'
答案 0 :(得分:0)
我知道它是 10 个月,但也许你或其他一些人
您可以在 int()
之后将 Y 轴转换为 datetime
,将 X 轴转换为 x = mdates.date2num(x)
-Object。
在这之后它对我有用。