我试图将趋势线添加到S&P500的历史值中,但是当我尝试添加趋势线时,它没有出现,只有S&P500值出现在图表中。 (“ Dato”在挪威语中意为“日期”。)

这是我的代码:

##################### Load the data

df = pd.read_csv("SP500.csv", delimiter=r",", names = ["Date","Open", "High",
                                      "Low", "Close", "S&P500",
                                      "Volume"])

df = df.drop(columns=['Open', 'High', 'Low', 'Close', 'Volume'])

df["Dato"] = df["Date"]

df2 = pd.read_excel("OSEBX.xlsx", names = ["Date", "OSEBX"])

df.set_index('Date', inplace=True)
df2.set_index('Date', inplace=True)

df3 = df.join(df2)
df["Dato"] = pd.to_datetime(df3["Dato"])

################################ Graph


t = np.array(range(0, len(df["Dato"])))

x = np.array(df3["OSEBX"])
y = np.array(df3["S&P500"])

plt.scatter(t,x, s=1)

z = np.polyfit(x, t, 1)

p = np.poly1d(z)

plt.plot(x,p(x),"bs", linewidth=20)


plt.show()

最佳答案

#Thanks to Andreas Deak I found a solution:

t = np.array(range(0, len(df3["Dato"])))

x = np.array(df3["OSEBX"])
y = np.array(df3["S&P500"])

plt.plot(t, x, linewidth=0.5, color="b")

z = np.polyfit(t, x, 1)
p = np.poly1d(z)
plt.plot(t, p(t),"r--", linewidth=0.5)
plt.show()

关于python - 趋势线缺失,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50209037/

10-14 17:46