import pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom statsmodels.tsa.arima_model import ARIMAfrom sklearn.metrics import mean_squared_errorimport pymysqlimport time, osimport reimport requestsimport urllibfrom datetime import datetimefrom statsmodels.graphics.tsaplots import plot_acf, plot_pacf# 导入模块import pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom statsmodels.tsa.arima_model import ARIMAfrom sklearn.metrics import mean_squared_errorimport pymysqlfrom datetime import datetimefrom statsmodels.graphics.tsaplots import plot_acf, plot_pacf# 连接数据库connect = pymysql.connect(host='localhost', # 本地数据库 user='root', password='123456', port=3306, charset='utf8', database='sheji') # 数据库名称cur = connect.cursor()# 读取数据try: select_sqli = "SELECT time,xiaoliang FROM sale where chexing='海豚';" cur.execute(select_sqli) data = pd.DataFrame(cur.fetchall(), columns=['time', 'xiaoliang'])except Exception as e: print("读取数据失败:", e)else: print("读取数据成功")# 转换时间格式data['time'] = pd.to_datetime(data['time'], format='%Y-%m')data = data.set_index('time')diff_data = data.diff().dropna()# 绘制自相关图和偏自相关图plot_acf(diff_data)plot_pacf(diff_data)# 确定 ARIMA 模型的参数p = 1d = 1q = 1model = ARIMA(data, order=(p, d, q))model_fit = model.fit(disp=0)# 预测销量y_pred = model_fit.predict(len(data), len(data) + 11, typ='levels')# 绘制预测结果plt.plot(data)plt.plot(y_pred, color='red')plt.show()# 关闭数据库连接cur.close()connect.close()请将这段代码改为移动平均模型
时间: 2024-01-28 10:04:33 浏览: 156
下面是将上述代码改为移动平均模型的示例:
```python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from statsmodels.tsa.arima_model import ARIMA
from sklearn.metrics import mean_squared_error
import pymysql
from datetime import datetime
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
# 连接数据库
connect = pymysql.connect(host='localhost', # 本地数据库
user='root',
password='123456',
port=3306,
charset='utf8',
database='sheji')
# 数据库查询语句
select_sql = "SELECT time, xiaoliang FROM sale WHERE chexing='海豚';"
# 读取数据
try:
data = pd.read_sql(select_sql, connect, index_col='time', parse_dates=True)
except Exception as e:
print("读取数据失败:", e)
else:
print("读取数据成功")
# 移动平均模型
window_size = 3
data_ma = data.rolling(window_size).mean()
data_ma.dropna(inplace=True)
# 绘制自相关图和偏自相关图
plot_acf(data_ma)
plot_pacf(data_ma)
# 选择移动平均模型的滞后阶数
q = 1
# 构建移动平均模型并拟合数据
model = ARIMA(data_ma, order=(0, 0, q))
model_fit = model.fit(disp=False)
# 预测销量并绘图
y_pred = model_fit.predict(len(data_ma), len(data_ma) + 11, typ='levels')
plt.plot(data_ma, label='Original Data')
plt.plot(y_pred, color='red', label='Predicted Data')
plt.legend()
plt.show()
# 关闭数据库连接
connect.close()
```
以上代码通过 rolling() 函数进行滑动窗口处理,计算移动平均值,并选择滞后阶数,然后构建移动平均模型,拟合数据,并进行预测和绘图。需要注意的是,移动平均模型需要对数据进行平稳化处理,否则预测结果可能会出现误差。
阅读全文