辣椒销售预测:使用SARIMA模型预测销量和利润
import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom datetime import timedelta\nfrom statsmodels.tsa.statespace.sarimax import SARIMAX\nfrom statsmodels.graphics.tsaplots import plot_acf, plot_pacf\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error\n\n# 读取数据\nchili_data = pd.read_csv("./ProcessedData/data_v6_1.csv")\nchili_data['销售日期'] = pd.to_datetime(chili_data['销售日期'])\n\n# 选择辣椒类数据\nchili_data = chili_data[chili_data['分类名称'] == '辣椒类']\n\n# 使用过去4个月的数据\nfour_months_data = chili_data[chili_data['销售日期'] > (chili_data['销售日期'].max() - timedelta(days=4*30))]\n\n# 拆分数据为80%训练集和20%测试集\ntrain_size_4m = int(len(four_months_data) * 0.8)\ntrain_4m = four_months_data.iloc[:train_size_4m]\n\n# 使用ACF和PACF确定SARIMA模型的参数\n# plot_acf(train_4m['销量(千克)'])\n# plot_pacf(train_4m['销量(千克)'])\n\n# 根据ACF和PACF的图形,选择SARIMA模型的参数\norder = (1, 1, 1)\nseasonal_order = (1, 1, 1, 7)\n\n# 为销量和利润分别拟合SARIMA模型\nmodel_sales_train_4m = SARIMAX(train_4m['销量(千克)'], order=order, seasonal_order=seasonal_order)\nresults_sales_train_4m = model_sales_train_4m.fit(disp=False)\n\nmodel_profit_train_4m = SARIMAX(train_4m['利润'], order=order, seasonal_order=seasonal_order)\nresults_profit_train_4m = model_profit_train_4m.fit(disp=False)\n\n# 使用模型预测接下来的7天\nforecast_length = len(four_months_data) - len(train_4m)\nsales_forecast_full_4m = results_sales_train_4m.get_forecast(steps=forecast_length).predicted_mean\nprofit_forecast_full_4m = results_profit_train_4m.get_forecast(steps=forecast_length).predicted_mean\n\n# 进行可视化\nforecast_length_7d = forecast_length + 7\n\nsales_forecast_7d = results_sales_train_4m.get_forecast(steps=forecast_length_7d).predicted_mean\nprofit_forecast_7d = results_profit_train_4m.get_forecast(steps=forecast_length_7d).predicted_mean\n\n# Confidence intervals for the forecasts\nsales_conf_int = results_sales_train_4m.get_forecast(steps=forecast_length_7d).conf_int()\nprofit_conf_int = results_profit_train_4m.get_forecast(steps=forecast_length_7d).conf_int()\n\n# Generate date range for the next 7 days\nlast_date = four_months_data['销售日期'].max()\ndate_range_7d = pd.date_range(start=last_date + timedelta(days=1), periods=7)\n\n# Correcting the error: Concatenating train data and forecast for visualization\nsales_combined_7d = pd.concat([train_4m['销量(千克)'], sales_forecast_7d])\nprofit_combined_7d = pd.concat([train_4m['利润'], profit_forecast_7d])\nall_dates = pd.concat([four_months_data['销售日期'], pd.Series(date_range_7d)])\n\n# Visualization\nfig, ax = plt.subplots(2, 1, figsize=(15, 12))\n# Plot sales\nax[0].plot(all_dates, four_months_data['销量(千克)'].append(pd.Series(sales_forecast_7d[-7:].values)),\n label='Actual Sales', color='blue')\nax[0].plot(all_dates, sales_combined_7d, label='Forecast Sales', color='red', linestyle='--')\nax[0].fill_between(all_dates[-forecast_length_7d:], sales_conf_int.iloc[-forecast_length_7d:]['lower 销量(千克)'],\n sales_conf_int.iloc[-forecast_length_7d:]['upper 销量(千克)'], color='pink', alpha=0.3)\nax[0].axvspan(date_range_7d[0], date_range_7d[-1], alpha=0.2, color='yellow', label="Highlighted Forecast for 1 Week")\nax[0].set_title('Sales (Actual vs Forecast)')\nax[0].set_xlabel('Date')\nax[0].set_ylabel('Sales (kg)')\nax[0].legend()\n\n# Plot profit\nax[1].plot(all_dates, four_months_data['利润'].append(pd.Series(profit_forecast_7d[-7:].values)),\n label='Actual Profit', color='blue')\nax[1].plot(all_dates, profit_combined_7d, label='Forecast Profit', color='red', linestyle='--')\nax[1].fill_between(all_dates[-forecast_length_7d:], profit_conf_int.iloc[-forecast_length_7d:]['lower 利润'],\n profit_conf_int.iloc[-forecast_length_7d:]['upper 利润'], color='pink', alpha=0.3)\nax[1].axvspan(date_range_7d[0], date_range_7d[-1], alpha=0.2, color='yellow', label="Highlighted Forecast for 1 Week")\nax[1].set_title('Profit (Actual vs Forecast)')\nax[1].set_xlabel('Date')\nax[1].set_ylabel('Profit')\nax[1].legend()\n\n\nplt.tight_layout()\nplt.show()\n\n解释这段代码实现了什么功能内容:这段代码实现了使用SARIMA模型进行销量和利润的预测,并通过可视化展示了预测结果。具体功能如下:\n\n1. 读取数据:从csv文件中读取数据。\n2. 选择辣椒类数据:筛选出分类名称为"辣椒类"的数据。\n3. 使用过去4个月的数据:选择最近4个月的数据作为模型训练的数据。\n4. 拆分数据为训练集和测试集:将80%的数据作为训练集,20%的数据作为测试集。\n5. 使用ACF和PACF确定SARIMA模型的参数:通过自相关图和偏自相关图确定SARIMA模型的参数。\n6. 拟合SARIMA模型:根据训练集数据拟合销量和利润的SARIMA模型。\n7. 使用模型预测接下来的7天:使用训练好的模型预测接下来7天的销量和利润。\n8. 进行可视化:将实际销量和利润数据与预测结果进行可视化展示,包括预测结果的置信区间。
原文地址: https://www.cveoy.top/t/topic/nBjR 著作权归作者所有。请勿转载和采集!