使用SARIMA模型进行辣椒类销售预测

本代码实现使用SARIMA模型对辣椒类销售数据进行预测,并将预测结果与实际数据进行可视化比较。具体功能如下:

  1. 读取数据:从名为'data_v6_1.csv'的文件中读取数据。
  2. 选择辣椒类数据:从整个数据集中选择分类为'辣椒类'的数据。
  3. 使用过去4个月的数据:选择最近4个月的数据进行模型训练和预测。
  4. 拆分数据为训练集和测试集:将80%的数据作为训练集,20%的数据作为测试集。
  5. 使用ACF和PACF确定SARIMA模型的参数:通过绘制自相关函数(ACF)和偏自相关函数(PACF)的图形,确定SARIMA模型的参数。
  6. 拟合SARIMA模型:使用训练集数据拟合销量和利润的SARIMA模型。
  7. 使用模型预测接下来的7天:使用拟合好的模型对未来7天的销量和利润进行预测。
  8. 进行可视化:将实际销量和利润数据以及预测结果进行可视化比较,包括绘制实际数据和预测数据的线图,以及绘制置信区间。
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from datetime import timedelta
from statsmodels.tsa.statespace.sarimax import SARIMAX
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
from sklearn.metrics import mean_squared_error, mean_absolute_error

# 读取数据
chili_data = pd.read_csv('./ProcessedData/data_v6_1.csv')
chili_data['销售日期'] = pd.to_datetime(chili_data['销售日期'])

# 选择辣椒类数据
chili_data = chili_data[chili_data['分类名称'] == '辣椒类']

# 使用过去4个月的数据
four_months_data = chili_data[chili_data['销售日期'] > (chili_data['销售日期'].max() - timedelta(days=4*30))]

# 拆分数据为80%训练集和20%测试集
train_size_4m = int(len(four_months_data) * 0.8)
train_4m = four_months_data.iloc[:train_size_4m]

# 使用ACF和PACF确定SARIMA模型的参数
# plot_acf(train_4m['销量(千克)'])
# plot_pacf(train_4m['销量(千克)'])

# 根据ACF和PACF的图形,选择SARIMA模型的参数
order = (1, 1, 1)
seasonal_order = (1, 1, 1, 7)

# 为销量和利润分别拟合SARIMA模型
model_sales_train_4m = SARIMAX(train_4m['销量(千克)'], order=order, seasonal_order=seasonal_order)
results_sales_train_4m = model_sales_train_4m.fit(disp=False)

model_profit_train_4m = SARIMAX(train_4m['利润'], order=order, seasonal_order=seasonal_order)
results_profit_train_4m = model_profit_train_4m.fit(disp=False)

# 使用模型预测接下来的7天
forecast_length = len(four_months_data) - len(train_4m)
sales_forecast_full_4m = results_sales_train_4m.get_forecast(steps=forecast_length).predicted_mean
profit_forecast_full_4m = results_profit_train_4m.get_forecast(steps=forecast_length).predicted_mean

# 进行可视化
forecast_length_7d = forecast_length + 7

sales_forecast_7d = results_sales_train_4m.get_forecast(steps=forecast_length_7d).predicted_mean
profit_forecast_7d = results_profit_train_4m.get_forecast(steps=forecast_length_7d).predicted_mean

# Confidence intervals for the forecasts
sales_conf_int = results_sales_train_4m.get_forecast(steps=forecast_length_7d).conf_int()
profit_conf_int = results_profit_train_4m.get_forecast(steps=forecast_length_7d).conf_int()

# Generate date range for the next 7 days
last_date = four_months_data['销售日期'].max()
date_range_7d = pd.date_range(start=last_date + timedelta(days=1), periods=7)

# Correcting the error: Concatenating train data and forecast for visualization
sales_combined_7d = pd.concat([train_4m['销量(千克)'], sales_forecast_7d])
profit_combined_7d = pd.concat([train_4m['利润'], profit_forecast_7d])
all_dates = pd.concat([four_months_data['销售日期'], pd.Series(date_range_7d)])

# Visualization
fig, ax = plt.subplots(2, 1, figsize=(15, 12))
# Plot sales
ax[0].plot(all_dates, four_months_data['销量(千克)'].append(pd.Series(sales_forecast_7d[-7:].values)),
           label='Actual Sales', color='blue')
ax[0].plot(all_dates, sales_combined_7d, label='Forecast Sales', color='red', linestyle='--')
ax[0].fill_between(all_dates[-forecast_length_7d:], sales_conf_int.iloc[-forecast_length_7d:]['lower 销量(千克)'],
                   sales_conf_int.iloc[-forecast_length_7d:]['upper 销量(千克)'], color='pink', alpha=0.3)
ax[0].axvspan(date_range_7d[0], date_range_7d[-1], alpha=0.2, color='yellow', label='Highlighted Forecast for 1 Week')
ax[0].set_title('Sales (Actual vs Forecast)')
ax[0].set_xlabel('Date')
ax[0].set_ylabel('Sales (kg)')
ax[0].legend()

# Plot profit
ax[1].plot(all_dates, four_months_data['利润'].append(pd.Series(profit_forecast_7d[-7:].values)),
           label='Actual Profit', color='blue')
ax[1].plot(all_dates, profit_combined_7d, label='Forecast Profit', color='red', linestyle='--')
ax[1].fill_between(all_dates[-forecast_length_7d:], profit_conf_int.iloc[-forecast_length_7d:]['lower 利润'],
                   profit_conf_int.iloc[-forecast_length_7d:]['upper 利润'], color='pink', alpha=0.3)
ax[1].axvspan(date_range_7d[0], date_range_7d[-1], alpha=0.2, color='yellow', label='Highlighted Forecast for 1 Week')
ax[1].set_title('Profit (Actual vs Forecast)')
ax[1].set_xlabel('Date')
ax[1].set_ylabel('Profit')
ax[1].legend()


plt.tight_layout()
plt.show()

该代码利用SARIMA模型对辣椒类销售数据进行预测,并对预测结果与实际数据进行可视化比较,帮助用户了解未来7天的销量和利润趋势。

使用方法:

  1. 将代码中的'data_v6_1.csv'替换为实际销售数据的CSV文件路径。
  2. 运行代码,观察可视化结果。

需要注意的是:

  • 本代码仅提供一个预测模型的示例,实际应用中可能需要根据具体数据情况调整模型参数。
  • 预测结果仅供参考,实际销量和利润可能存在偏差。

其他

  • 该代码可以作为论文的一部分,用于展示时间序列分析和预测模型的应用。
  • 代码中注释部分可以用于解释模型参数和可视化结果。
  • 还可以添加其他指标,例如预测误差,以评估模型的性能。
使用SARIMA模型进行辣椒类销售预测 - 预测未来7天销量和利润

原文地址: https://www.cveoy.top/t/topic/nBjt 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录