我正在尝试将趋势线添加到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()
答案 0 :(得分:1)
#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()