You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3.8环境下两个时间点价格间线性回归计算方法求教

实现方案

时间类型无法直接参与数值运算,只需将datetime对象转换为数值型的时间戳/时间差序列,即可直接使用numpy相关函数完成线性回归计算,完美适配Python3.8环境。

完整可运行代码

import yfinance as yf
import datetime
import numpy as np

start = datetime.datetime(2021,9,1)
end = datetime.datetime(2021,9,2)
test_point = datetime.datetime(2021,10,15)
Amazon = yf.Ticker("AMZN")
df = Amazon.history(start=start, end=end)

# 处理x轴:将时间索引转为数值,两种可选方式
# 方式1:转秒级时间戳
x = df.index.astype('int64') // 10**9
# 方式2:转距离第一个样本的天数,斜率含义更直观(每日价格变化)
# x = (df.index - df.index[0]).days

# y轴取低点价格
y = df['Low'].values

# numpy一阶多项式拟合,等价于两点线性回归,返回[斜率, 截距]
slope, intercept = np.polyfit(x, y, deg=1)

print(f"斜率: {slope}, 截距: {intercept}")

# 测试预测指定日期的价格
test_x = (test_point - datetime.datetime(1970,1,1)).total_seconds() # 对应方式1的x格式
# 如果用方式2的x,test_x = (test_point - df.index[0]).days
predict_low = slope * test_x + intercept
print(f"2021-10-15的预测低点价格: {predict_low}")

补充说明

  • 两点的线性回归本质上就是求两点连线的参数,你也可以直接用公式计算,不需要调用numpy接口:
x1, x2 = x[0], x[1]
y1, y2 = y[0], y[1]
slope = (y2 - y1) / (x2 - x1)
intercept = y1 - slope * x1
  • 两种x轴转换方式的计算结果可以互相换算,仅斜率的数值单位不同,最终预测的价格结果完全一致
  • 该方案也可扩展到大于2个样本的时间序列线性回归场景,仅需保持x为转换后的数值序列即可

内容的提问来源于stack exchange,提问作者luki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 09:36:03