gpt4 book ai didi

python - Pandas 时间序列的线性回归

转载 作者:行者123 更新时间:2023-11-28 20:39:41 27 4
gpt4 key购买 nike

我有一个数据框对象,其中包含 1 秒间隔的 EUR_USD 货币对。但理论上它可以是任何间隔,在这种情况下它可能看起来像这样:

2015-11-10 01:00:00+01:00    1.07616
2015-11-10 01:01:00+01:00 1.07605
2015-11-10 01:02:00+01:00 1.07590
2015-11-10 01:03:00+01:00 1.07592
2015-11-10 01:04:00+01:00 1.07583

我想使用线性回归从 dataframe 中的数据绘制趋势线,但我不确定对时间序列,甚至如此小的时间序列间隔来说,最好的方法是什么。

到目前为止,我已经将时间替换为(这只是为了显示我想用它去哪里)范围从 0 到时间序列列表长度的列表。

x = list(range(0, len(df.index.tolist()), 1))
y = df["closeAsk"].tolist()

使用 numpy 做数学魔术

fit = np.polyfit(x,y,1)
fit_fn = np.poly1d(fit)

最后,我将函数与 df["closeAsk"] 一起绘制,以了解趋势。

plt.plot(x,df["closeAsk"], '-')
plt.plot(x,y, 'yo', x, fit_fn(x), '--k')
plt.show()

但是现在 x 轴只是无意义的数字,相反我希望它们显示时间序列。

最佳答案

详细说明我的评论:

假设您有一些均匀分布时间序列数据time,以及一些相关数据data,正如您在你的问题。

time = pd.date_range('9:00', '10:00', freq='1s')
data = np.cumsum(np.random.randn(time.size))

df = pd.DataFrame({'time' : time,
'data' : data})

如您所示,您可以使用 np.polyfit 对数据进行线性拟合,并使用 np.poly1d 创建趋势线。

x = np.arange(time.size) # = array([0, 1, 2, ..., 3598, 3599, 3600])
fit = np.polyfit(x, df['data'], 1)
fit_fn = np.poly1d(fit)

然后以 df['time'] 作为 x 轴绘制数据和拟合。

plt.plot(df['time'], fit_fn(x), 'k-')
plt.plot(df['time'], df['data'], 'go', ms=2)

enter image description here

关于python - Pandas 时间序列的线性回归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37337836/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com