{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "SAMDFdMvszup"
      },
      "source": [
        "# SARIMAX modelを用いたブドウトレンドの予測\n"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "## ライブラリのインポート\n",
        "\n",
        "使用するpmdarimaライブラリのインストールにnumpy 1.26.4が必要となるため、最初にインストールする。セッションの再起動が求められることがある。<br>\n",
        "セッションを再起動した後は、numpyのインストールをせずに、pmdarimaのインストールから進める。"
      ],
      "metadata": {
        "id": "HEjXkN7l4Xwl"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "!pip install numpy==1.26.4"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 532
        },
        "id": "VAnmtYIx4Vdr",
        "outputId": "77ea6b90-3e24-4e98-d538-0457387ddeca"
      },
      "execution_count": 1,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Collecting numpy==1.26.4\n",
            "  Downloading numpy-1.26.4-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (61 kB)\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m61.0/61.0 kB\u001b[0m \u001b[31m1.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hDownloading numpy-1.26.4-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (18.0 MB)\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m18.0/18.0 MB\u001b[0m \u001b[31m35.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hInstalling collected packages: numpy\n",
            "  Attempting uninstall: numpy\n",
            "    Found existing installation: numpy 2.0.2\n",
            "    Uninstalling numpy-2.0.2:\n",
            "      Successfully uninstalled numpy-2.0.2\n",
            "\u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n",
            "rasterio 1.5.0 requires numpy>=2, but you have numpy 1.26.4 which is incompatible.\n",
            "jaxlib 0.7.2 requires numpy>=2.0, but you have numpy 1.26.4 which is incompatible.\n",
            "xarray-einstats 0.10.0 requires numpy>=2.0, but you have numpy 1.26.4 which is incompatible.\n",
            "opencv-contrib-python 4.13.0.92 requires numpy>=2; python_version >= \"3.9\", but you have numpy 1.26.4 which is incompatible.\n",
            "tobler 0.13.0 requires numpy>=2.0, but you have numpy 1.26.4 which is incompatible.\n",
            "opencv-python 4.13.0.92 requires numpy>=2; python_version >= \"3.9\", but you have numpy 1.26.4 which is incompatible.\n",
            "shap 0.51.0 requires numpy>=2, but you have numpy 1.26.4 which is incompatible.\n",
            "pytensor 2.38.2 requires numpy>=2.0, but you have numpy 1.26.4 which is incompatible.\n",
            "opencv-python-headless 4.13.0.92 requires numpy>=2; python_version >= \"3.9\", but you have numpy 1.26.4 which is incompatible.\n",
            "jax 0.7.2 requires numpy>=2.0, but you have numpy 1.26.4 which is incompatible.\u001b[0m\u001b[31m\n",
            "\u001b[0mSuccessfully installed numpy-1.26.4\n"
          ]
        },
        {
          "output_type": "display_data",
          "data": {
            "application/vnd.colab-display-data+json": {
              "pip_warning": {
                "packages": [
                  "numpy"
                ]
              },
              "id": "64bfb0ad40bc4072a837cc002620ac2d"
            }
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "!pip install pmdarima"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "37COv6jA4hia",
        "outputId": "621a0758-37a9-490b-d84a-869bde48beb9"
      },
      "execution_count": 1,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Collecting pmdarima\n",
            "  Downloading pmdarima-2.1.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl.metadata (8.5 kB)\n",
            "Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.12/dist-packages (from pmdarima) (1.5.3)\n",
            "Requirement already satisfied: Cython!=0.29.18,!=0.29.31,>=0.29 in /usr/local/lib/python3.12/dist-packages (from pmdarima) (3.0.12)\n",
            "Requirement already satisfied: numpy>=1.21.6 in /usr/local/lib/python3.12/dist-packages (from pmdarima) (1.26.4)\n",
            "Requirement already satisfied: pandas>=0.19 in /usr/local/lib/python3.12/dist-packages (from pmdarima) (2.2.2)\n",
            "Requirement already satisfied: scikit-learn>=0.22 in /usr/local/lib/python3.12/dist-packages (from pmdarima) (1.6.1)\n",
            "Requirement already satisfied: scipy>=1.13.0 in /usr/local/lib/python3.12/dist-packages (from pmdarima) (1.16.3)\n",
            "Requirement already satisfied: statsmodels>=0.14.5 in /usr/local/lib/python3.12/dist-packages (from pmdarima) (0.14.6)\n",
            "Requirement already satisfied: urllib3 in /usr/local/lib/python3.12/dist-packages (from pmdarima) (2.5.0)\n",
            "Requirement already satisfied: setuptools!=50.0.0,>=42 in /usr/local/lib/python3.12/dist-packages (from pmdarima) (75.2.0)\n",
            "Requirement already satisfied: packaging>=17.1 in /usr/local/lib/python3.12/dist-packages (from pmdarima) (26.0)\n",
            "Requirement already satisfied: python-dateutil>=2.8.2 in /usr/local/lib/python3.12/dist-packages (from pandas>=0.19->pmdarima) (2.9.0.post0)\n",
            "Requirement already satisfied: pytz>=2020.1 in /usr/local/lib/python3.12/dist-packages (from pandas>=0.19->pmdarima) (2025.2)\n",
            "Requirement already satisfied: tzdata>=2022.7 in /usr/local/lib/python3.12/dist-packages (from pandas>=0.19->pmdarima) (2025.3)\n",
            "Requirement already satisfied: threadpoolctl>=3.1.0 in /usr/local/lib/python3.12/dist-packages (from scikit-learn>=0.22->pmdarima) (3.6.0)\n",
            "Requirement already satisfied: patsy>=0.5.6 in /usr/local/lib/python3.12/dist-packages (from statsmodels>=0.14.5->pmdarima) (1.0.2)\n",
            "Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.12/dist-packages (from python-dateutil>=2.8.2->pandas>=0.19->pmdarima) (1.17.0)\n",
            "Downloading pmdarima-2.1.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl (689 kB)\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m689.1/689.1 kB\u001b[0m \u001b[31m10.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hInstalling collected packages: pmdarima\n",
            "Successfully installed pmdarima-2.1.1\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "#日本語環境の設定\n",
        "!pip install japanize_matplotlib\n",
        "import matplotlib.pyplot as plt\n",
        "import japanize_matplotlib"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "zAch6iI45Dz6",
        "outputId": "8d7a34b5-5b93-4648-91b8-98d32794b49d"
      },
      "execution_count": 2,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Collecting japanize_matplotlib\n",
            "  Downloading japanize-matplotlib-1.1.3.tar.gz (4.1 MB)\n",
            "\u001b[?25l     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m0.0/4.1 MB\u001b[0m \u001b[31m?\u001b[0m eta \u001b[36m-:--:--\u001b[0m\r\u001b[2K     \u001b[91m━━\u001b[0m\u001b[91m╸\u001b[0m\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m0.3/4.1 MB\u001b[0m \u001b[31m9.9 MB/s\u001b[0m eta \u001b[36m0:00:01\u001b[0m\r\u001b[2K     \u001b[91m━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m\u001b[91m╸\u001b[0m\u001b[90m━━━━━━━━━━━━━\u001b[0m \u001b[32m2.7/4.1 MB\u001b[0m \u001b[31m37.5 MB/s\u001b[0m eta \u001b[36m0:00:01\u001b[0m\r\u001b[2K     \u001b[91m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m\u001b[91m╸\u001b[0m \u001b[32m4.1/4.1 MB\u001b[0m \u001b[31m47.7 MB/s\u001b[0m eta \u001b[36m0:00:01\u001b[0m\r\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m4.1/4.1 MB\u001b[0m \u001b[31m34.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25h  Preparing metadata (setup.py) ... \u001b[?25l\u001b[?25hdone\n",
            "Requirement already satisfied: matplotlib in /usr/local/lib/python3.12/dist-packages (from japanize_matplotlib) (3.10.0)\n",
            "Requirement already satisfied: contourpy>=1.0.1 in /usr/local/lib/python3.12/dist-packages (from matplotlib->japanize_matplotlib) (1.3.3)\n",
            "Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.12/dist-packages (from matplotlib->japanize_matplotlib) (0.12.1)\n",
            "Requirement already satisfied: fonttools>=4.22.0 in /usr/local/lib/python3.12/dist-packages (from matplotlib->japanize_matplotlib) (4.62.1)\n",
            "Requirement already satisfied: kiwisolver>=1.3.1 in /usr/local/lib/python3.12/dist-packages (from matplotlib->japanize_matplotlib) (1.5.0)\n",
            "Requirement already satisfied: numpy>=1.23 in /usr/local/lib/python3.12/dist-packages (from matplotlib->japanize_matplotlib) (1.26.4)\n",
            "Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.12/dist-packages (from matplotlib->japanize_matplotlib) (26.0)\n",
            "Requirement already satisfied: pillow>=8 in /usr/local/lib/python3.12/dist-packages (from matplotlib->japanize_matplotlib) (11.3.0)\n",
            "Requirement already satisfied: pyparsing>=2.3.1 in /usr/local/lib/python3.12/dist-packages (from matplotlib->japanize_matplotlib) (3.3.2)\n",
            "Requirement already satisfied: python-dateutil>=2.7 in /usr/local/lib/python3.12/dist-packages (from matplotlib->japanize_matplotlib) (2.9.0.post0)\n",
            "Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.12/dist-packages (from python-dateutil>=2.7->matplotlib->japanize_matplotlib) (1.17.0)\n",
            "Building wheels for collected packages: japanize_matplotlib\n",
            "  Building wheel for japanize_matplotlib (setup.py) ... \u001b[?25l\u001b[?25hdone\n",
            "  Created wheel for japanize_matplotlib: filename=japanize_matplotlib-1.1.3-py3-none-any.whl size=4120257 sha256=6459d2358d0bff8b4a80dfde265c9f3a7ac55bde4743ae2265e24e4436d03091\n",
            "  Stored in directory: /root/.cache/pip/wheels/c1/f7/9b/418f19a7b9340fc16e071e89efc379aca68d40238b258df53d\n",
            "Successfully built japanize_matplotlib\n",
            "Installing collected packages: japanize_matplotlib\n",
            "Successfully installed japanize_matplotlib-1.1.3\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "metadata": {
        "id": "Kg3XJLgcszur"
      },
      "outputs": [],
      "source": [
        "import numpy as np\n",
        "import pandas as pd\n",
        "import statsmodels.api as sm\n",
        "import pmdarima as pm\n",
        "\n",
        "import seaborn as sns\n",
        "\n",
        "from sklearn.model_selection import train_test_split\n",
        "\n",
        "from scipy import stats\n",
        "\n",
        "np.random.seed(0)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "metadata": {
        "scrolled": true,
        "id": "2C9pT9XPszus",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 521
        },
        "outputId": "bd3f3694-3a44-40e3-8125-2bafbb3beca9"
      },
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<Figure size 1200x600 with 1 Axes>"
            ],
            "image/png": "[encoded data, 83924 characters]\n"
          },
          "metadata": {}
        }
      ],
      "source": [
        "df = pd.read_csv('dataBudou.csv', index_col='月', parse_dates=True, comment='#')\n",
        "\n",
        "#直近36か月をテストデータとする\n",
        "#それ以前を訓練データとする。\n",
        "df_train = df[:-36]\n",
        "df_test = df[-36:]\n",
        "\n",
        "\n",
        "fig, ax = plt.subplots(figsize=(12,6))\n",
        "\n",
        "plt.plot(df_train.index, df_train, label='学習データ', c='k')\n",
        "plt.plot(df_test.index, df_test, label='テストデータ', c='k', linestyle='dashed')\n",
        "\n",
        "ax.grid()\n",
        "plt.legend()\n",
        "plt.savefig('grape1.png')\n",
        "plt.savefig('grape1.pdf')\n",
        "plt.savefig('grape1.svg')\n",
        "plt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "## 周期性があるかどうかを調べる"
      ],
      "metadata": {
        "id": "5u4w_IWnAGV0"
      }
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "metadata": {
        "id": "0h_mwqWDszut",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 309
        },
        "outputId": "090a9d30-731d-4483-b414-22bb4dbcf306"
      },
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<Figure size 600x300 with 1 Axes>"
            ],
            "image/png": "[encoded data, 33276 characters]\n"
          },
          "metadata": {}
        }
      ],
      "source": [
        "acf = sm.tsa.stattools.acf(df, nlags=60)\n",
        "fig, ax = plt.subplots(figsize=(6,3))\n",
        "plt.plot(acf, marker='o', c='k')\n",
        "plt.xlabel('lag')\n",
        "plt.ylabel('acf')\n",
        "plt.grid()\n",
        "ax.set_xticks(np.arange(0, 61, 12))\n",
        "plt.savefig('grape_acf.png')\n",
        "plt.savefig('grape_acf.pdf')\n",
        "plt.savefig('grape_acf.svg')\n",
        "plt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "xdkLjDUKszut"
      },
      "source": [
        "## 自動構築（auto_arima関数）によるパラメータ探索"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 7,
      "metadata": {
        "id": "VmsUlRHOszut",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "0c3d5d59-4c88-43f0-c2a2-add79ba824fa"
      },
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Performing stepwise search to minimize aic\n",
            " ARIMA(2,1,2)(1,1,1)[12]             : AIC=inf, Time=2.26 sec\n",
            " ARIMA(0,1,0)(0,1,0)[12]             : AIC=1081.174, Time=0.05 sec\n",
            " ARIMA(1,1,0)(1,1,0)[12]             : AIC=1032.432, Time=0.18 sec\n",
            " ARIMA(0,1,1)(0,1,1)[12]             : AIC=1035.854, Time=0.32 sec\n",
            " ARIMA(1,1,0)(0,1,0)[12]             : AIC=1071.928, Time=0.07 sec\n",
            " ARIMA(1,1,0)(2,1,0)[12]             : AIC=1033.256, Time=0.36 sec\n",
            " ARIMA(1,1,0)(1,1,1)[12]             : AIC=1033.832, Time=0.30 sec\n",
            " ARIMA(1,1,0)(0,1,1)[12]             : AIC=1044.002, Time=0.27 sec\n",
            " ARIMA(1,1,0)(2,1,1)[12]             : AIC=1029.339, Time=2.48 sec\n",
            " ARIMA(1,1,0)(2,1,2)[12]             : AIC=1025.825, Time=6.78 sec\n",
            " ARIMA(1,1,0)(1,1,2)[12]             : AIC=1029.346, Time=2.82 sec\n",
            " ARIMA(0,1,0)(2,1,2)[12]             : AIC=1031.561, Time=3.98 sec\n",
            " ARIMA(2,1,0)(2,1,2)[12]             : AIC=1012.956, Time=3.41 sec\n",
            " ARIMA(2,1,0)(1,1,2)[12]             : AIC=1014.262, Time=3.02 sec\n",
            " ARIMA(2,1,0)(2,1,1)[12]             : AIC=1012.865, Time=2.29 sec\n",
            " ARIMA(2,1,0)(1,1,1)[12]             : AIC=1018.516, Time=0.43 sec\n",
            " ARIMA(2,1,0)(2,1,0)[12]             : AIC=1017.849, Time=0.54 sec\n",
            " ARIMA(2,1,0)(1,1,0)[12]             : AIC=1017.268, Time=0.25 sec\n",
            " ARIMA(3,1,0)(2,1,1)[12]             : AIC=1013.799, Time=2.51 sec\n",
            " ARIMA(2,1,1)(2,1,1)[12]             : AIC=981.547, Time=3.34 sec\n",
            " ARIMA(2,1,1)(1,1,1)[12]             : AIC=986.150, Time=1.00 sec\n",
            " ARIMA(2,1,1)(2,1,0)[12]             : AIC=985.800, Time=3.15 sec\n",
            " ARIMA(2,1,1)(2,1,2)[12]             : AIC=982.540, Time=4.84 sec\n",
            " ARIMA(2,1,1)(1,1,0)[12]             : AIC=984.582, Time=0.71 sec\n",
            " ARIMA(2,1,1)(1,1,2)[12]             : AIC=984.105, Time=2.86 sec\n",
            " ARIMA(1,1,1)(2,1,1)[12]             : AIC=982.320, Time=2.01 sec\n",
            " ARIMA(3,1,1)(2,1,1)[12]             : AIC=982.822, Time=6.00 sec\n",
            " ARIMA(2,1,2)(2,1,1)[12]             : AIC=inf, Time=7.37 sec\n",
            " ARIMA(1,1,2)(2,1,1)[12]             : AIC=980.260, Time=3.46 sec\n",
            " ARIMA(1,1,2)(1,1,1)[12]             : AIC=984.907, Time=1.53 sec\n",
            " ARIMA(1,1,2)(2,1,0)[12]             : AIC=984.558, Time=1.88 sec\n",
            " ARIMA(1,1,2)(2,1,2)[12]             : AIC=982.154, Time=3.72 sec\n",
            " ARIMA(1,1,2)(1,1,0)[12]             : AIC=983.381, Time=0.60 sec\n",
            " ARIMA(1,1,2)(1,1,2)[12]             : AIC=983.117, Time=2.50 sec\n",
            " ARIMA(0,1,2)(2,1,1)[12]             : AIC=979.794, Time=2.09 sec\n",
            " ARIMA(0,1,2)(1,1,1)[12]             : AIC=984.758, Time=0.77 sec\n",
            " ARIMA(0,1,2)(2,1,0)[12]             : AIC=984.386, Time=2.15 sec\n",
            " ARIMA(0,1,2)(2,1,2)[12]             : AIC=982.749, Time=3.43 sec\n",
            " ARIMA(0,1,2)(1,1,0)[12]             : AIC=983.278, Time=0.39 sec\n",
            " ARIMA(0,1,2)(1,1,2)[12]             : AIC=983.121, Time=1.64 sec\n",
            " ARIMA(0,1,1)(2,1,1)[12]             : AIC=1018.624, Time=1.44 sec\n",
            " ARIMA(0,1,3)(2,1,1)[12]             : AIC=980.751, Time=2.47 sec\n",
            " ARIMA(1,1,3)(2,1,1)[12]             : AIC=981.805, Time=6.04 sec\n",
            " ARIMA(0,1,2)(2,1,1)[12] intercept   : AIC=inf, Time=4.79 sec\n",
            "\n",
            "Best model:  ARIMA(0,1,2)(2,1,1)[12]          \n",
            "Total fit time: 102.639 seconds\n"
          ]
        }
      ],
      "source": [
        "# 3分くらいかかる\n",
        "sarima_model = pm.arima.auto_arima(df_train,seasonal=True,m=12,trace=True,stepwise=True,maxiter=50)"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "## 自動探索したモデルの表示"
      ],
      "metadata": {
        "id": "opedVDLH_JAK"
      }
    },
    {
      "cell_type": "code",
      "execution_count": 8,
      "metadata": {
        "id": "Ykrfxvlbszuu",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 494
        },
        "outputId": "61c8e2a8-11b8-4bc2-bad2-c477ec22bdf1"
      },
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<class 'statsmodels.iolib.summary.Summary'>\n",
              "\"\"\"\n",
              "                                      SARIMAX Results                                       \n",
              "============================================================================================\n",
              "Dep. Variable:                                    y   No. Observations:                  221\n",
              "Model:             SARIMAX(0, 1, 2)x(2, 1, [1], 12)   Log Likelihood                -483.897\n",
              "Date:                              Sat, 04 Apr 2026   AIC                            979.794\n",
              "Time:                                      20:06:46   BIC                            999.820\n",
              "Sample:                                  04-01-2004   HQIC                           987.891\n",
              "                                       - 08-01-2022                                         \n",
              "Covariance Type:                                opg                                         \n",
              "==============================================================================\n",
              "                 coef    std err          z      P>|z|      [0.025      0.975]\n",
              "------------------------------------------------------------------------------\n",
              "ma.L1         -0.4496      0.037    -12.021      0.000      -0.523      -0.376\n",
              "ma.L2         -0.4828      0.048    -10.107      0.000      -0.576      -0.389\n",
              "ar.S.L12       0.4190      0.222      1.884      0.060      -0.017       0.855\n",
              "ar.S.L24       0.4777      0.084      5.667      0.000       0.313       0.643\n",
              "ma.S.L12      -0.8431      0.244     -3.458      0.001      -1.321      -0.365\n",
              "sigma2         5.9264      0.452     13.104      0.000       5.040       6.813\n",
              "===================================================================================\n",
              "Ljung-Box (L1) (Q):                   0.19   Jarque-Bera (JB):               206.84\n",
              "Prob(Q):                              0.66   Prob(JB):                         0.00\n",
              "Heteroskedasticity (H):               3.35   Skew:                             1.11\n",
              "Prob(H) (two-sided):                  0.00   Kurtosis:                         7.36\n",
              "===================================================================================\n",
              "\n",
              "Warnings:\n",
              "[1] Covariance matrix calculated using the outer product of gradients (complex-step).\n",
              "\"\"\""
            ],
            "text/html": [
              "<table class=\"simpletable\">\n",
              "<caption>SARIMAX Results</caption>\n",
              "<tr>\n",
              "  <th>Dep. Variable:</th>                   <td>y</td>                <th>  No. Observations:  </th>    <td>221</td>  \n",
              "</tr>\n",
              "<tr>\n",
              "  <th>Model:</th>           <td>SARIMAX(0, 1, 2)x(2, 1, [1], 12)</td> <th>  Log Likelihood     </th> <td>-483.897</td>\n",
              "</tr>\n",
              "<tr>\n",
              "  <th>Date:</th>                    <td>Sat, 04 Apr 2026</td>         <th>  AIC                </th>  <td>979.794</td>\n",
              "</tr>\n",
              "<tr>\n",
              "  <th>Time:</th>                        <td>20:06:46</td>             <th>  BIC                </th>  <td>999.820</td>\n",
              "</tr>\n",
              "<tr>\n",
              "  <th>Sample:</th>                     <td>04-01-2004</td>            <th>  HQIC               </th>  <td>987.891</td>\n",
              "</tr>\n",
              "<tr>\n",
              "  <th></th>                           <td>- 08-01-2022</td>           <th>                     </th>     <td> </td>   \n",
              "</tr>\n",
              "<tr>\n",
              "  <th>Covariance Type:</th>                <td>opg</td>               <th>                     </th>     <td> </td>   \n",
              "</tr>\n",
              "</table>\n",
              "<table class=\"simpletable\">\n",
              "<tr>\n",
              "      <td></td>        <th>coef</th>     <th>std err</th>      <th>z</th>      <th>P>|z|</th>  <th>[0.025</th>    <th>0.975]</th>  \n",
              "</tr>\n",
              "<tr>\n",
              "  <th>ma.L1</th>    <td>   -0.4496</td> <td>    0.037</td> <td>  -12.021</td> <td> 0.000</td> <td>   -0.523</td> <td>   -0.376</td>\n",
              "</tr>\n",
              "<tr>\n",
              "  <th>ma.L2</th>    <td>   -0.4828</td> <td>    0.048</td> <td>  -10.107</td> <td> 0.000</td> <td>   -0.576</td> <td>   -0.389</td>\n",
              "</tr>\n",
              "<tr>\n",
              "  <th>ar.S.L12</th> <td>    0.4190</td> <td>    0.222</td> <td>    1.884</td> <td> 0.060</td> <td>   -0.017</td> <td>    0.855</td>\n",
              "</tr>\n",
              "<tr>\n",
              "  <th>ar.S.L24</th> <td>    0.4777</td> <td>    0.084</td> <td>    5.667</td> <td> 0.000</td> <td>    0.313</td> <td>    0.643</td>\n",
              "</tr>\n",
              "<tr>\n",
              "  <th>ma.S.L12</th> <td>   -0.8431</td> <td>    0.244</td> <td>   -3.458</td> <td> 0.001</td> <td>   -1.321</td> <td>   -0.365</td>\n",
              "</tr>\n",
              "<tr>\n",
              "  <th>sigma2</th>   <td>    5.9264</td> <td>    0.452</td> <td>   13.104</td> <td> 0.000</td> <td>    5.040</td> <td>    6.813</td>\n",
              "</tr>\n",
              "</table>\n",
              "<table class=\"simpletable\">\n",
              "<tr>\n",
              "  <th>Ljung-Box (L1) (Q):</th>     <td>0.19</td> <th>  Jarque-Bera (JB):  </th> <td>206.84</td>\n",
              "</tr>\n",
              "<tr>\n",
              "  <th>Prob(Q):</th>                <td>0.66</td> <th>  Prob(JB):          </th>  <td>0.00</td> \n",
              "</tr>\n",
              "<tr>\n",
              "  <th>Heteroskedasticity (H):</th> <td>3.35</td> <th>  Skew:              </th>  <td>1.11</td> \n",
              "</tr>\n",
              "<tr>\n",
              "  <th>Prob(H) (two-sided):</th>    <td>0.00</td> <th>  Kurtosis:          </th>  <td>7.36</td> \n",
              "</tr>\n",
              "</table><br/><br/>Warnings:<br/>[1] Covariance matrix calculated using the outer product of gradients (complex-step)."
            ],
            "text/latex": "\\begin{center}\n\\begin{tabular}{lclc}\n\\toprule\n\\textbf{Dep. Variable:}          &                y                 & \\textbf{  No. Observations:  } &    221      \\\\\n\\textbf{Model:}                  & SARIMAX(0, 1, 2)x(2, 1, [1], 12) & \\textbf{  Log Likelihood     } &  -483.897   \\\\\n\\textbf{Date:}                   &         Sat, 04 Apr 2026         & \\textbf{  AIC                } &  979.794    \\\\\n\\textbf{Time:}                   &             20:06:46             & \\textbf{  BIC                } &  999.820    \\\\\n\\textbf{Sample:}                 &            04-01-2004            & \\textbf{  HQIC               } &  987.891    \\\\\n\\textbf{}                        &           - 08-01-2022           & \\textbf{                     } &             \\\\\n\\textbf{Covariance Type:}        &               opg                & \\textbf{                     } &             \\\\\n\\bottomrule\n\\end{tabular}\n\\begin{tabular}{lcccccc}\n                  & \\textbf{coef} & \\textbf{std err} & \\textbf{z} & \\textbf{P$> |$z$|$} & \\textbf{[0.025} & \\textbf{0.975]}  \\\\\n\\midrule\n\\textbf{ma.L1}    &      -0.4496  &        0.037     &   -12.021  &         0.000        &       -0.523    &       -0.376     \\\\\n\\textbf{ma.L2}    &      -0.4828  &        0.048     &   -10.107  &         0.000        &       -0.576    &       -0.389     \\\\\n\\textbf{ar.S.L12} &       0.4190  &        0.222     &     1.884  &         0.060        &       -0.017    &        0.855     \\\\\n\\textbf{ar.S.L24} &       0.4777  &        0.084     &     5.667  &         0.000        &        0.313    &        0.643     \\\\\n\\textbf{ma.S.L12} &      -0.8431  &        0.244     &    -3.458  &         0.001        &       -1.321    &       -0.365     \\\\\n\\textbf{sigma2}   &       5.9264  &        0.452     &    13.104  &         0.000        &        5.040    &        6.813     \\\\\n\\bottomrule\n\\end{tabular}\n\\begin{tabular}{lclc}\n\\textbf{Ljung-Box (L1) (Q):}     & 0.19 & \\textbf{  Jarque-Bera (JB):  } & 206.84  \\\\\n\\textbf{Prob(Q):}                & 0.66 & \\textbf{  Prob(JB):          } &  0.00   \\\\\n\\textbf{Heteroskedasticity (H):} & 3.35 & \\textbf{  Skew:              } &  1.11   \\\\\n\\textbf{Prob(H) (two-sided):}    & 0.00 & \\textbf{  Kurtosis:          } &  7.36   \\\\\n\\bottomrule\n\\end{tabular}\n%\\caption{SARIMAX Results}\n\\end{center}\n\nWarnings: \\newline\n [1] Covariance matrix calculated using the outer product of gradients (complex-step)."
          },
          "metadata": {},
          "execution_count": 8
        }
      ],
      "source": [
        "sarima_model.summary()"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "SARIMAXを用いた予測"
      ],
      "metadata": {
        "id": "jYK2YGiYKCaL"
      }
    },
    {
      "cell_type": "code",
      "execution_count": 9,
      "metadata": {
        "id": "Y67F7u3Tszuu"
      },
      "outputs": [],
      "source": [
        "# 学習データの期間の予測値\n",
        "train_pred = sarima_model.predict_in_sample()\n",
        "\n",
        "# テストデータの期間の予測値, 予測区間\n",
        "test_pred, test_pred_ci = sarima_model.predict(n_periods=df_test.shape[0], return_conf_int=True)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 10,
      "metadata": {
        "id": "skl9r0Rgszuu",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 521
        },
        "outputId": "1e4bcf63-541f-499e-d1cf-3cfa32f3e869"
      },
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<Figure size 1200x600 with 1 Axes>"
            ],
            "image/png": "[encoded data, 112224 characters]\n"
          },
          "metadata": {}
        }
      ],
      "source": [
        "fig, ax = plt.subplots(figsize=(12,6))\n",
        "\n",
        "ax.plot(df_train.index, df_train, label='学習データ（実データ）', c='k')\n",
        "ax.plot(df_test.index, df_test, label='テストデータ（実データ）', c='k', linestyle='dashed')\n",
        "\n",
        "ax.scatter(train_pred.index, train_pred, label='学習データがある期間の推定', color='k')\n",
        "ax.scatter(test_pred.index, test_pred, label='学習していない期間の予測', color='dimgray')\n",
        "\n",
        "ax.fill_between(df_test.index, test_pred_ci[:,0], test_pred_ci[:,1], color='gray', alpha=0.3)\n",
        "ax.grid()\n",
        "plt.legend()\n",
        "plt.savefig('grape2.png')\n",
        "plt.savefig('grape2.pdf')\n",
        "plt.savefig('grape2.svg')\n",
        "plt.show()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 14,
      "metadata": {
        "id": "VQ0bO4PEszuu",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 521
        },
        "outputId": "740efa4e-6738-4925-f760-662ffc435703"
      },
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<Figure size 1200x600 with 1 Axes>"
            ],
            "image/png": "[encoded data, 112120 characters]\n"
          },
          "metadata": {}
        }
      ],
      "source": [
        "fig, ax = plt.subplots(figsize=(12,6))\n",
        "\n",
        "ax.plot(df_train.index, df_train, label='学習データ（実データ）', c='k')\n",
        "ax.plot(df_test.index, df_test, label='テスト・データ（実データ）', c='k', linestyle='dashed')\n",
        "\n",
        "ax.scatter(train_pred.index, train_pred, label='学習データがある期間の推定', color='k')\n",
        "ax.scatter(test_pred.index, test_pred, label='学習していない期間の予測', color='dimgray',marker='^')\n",
        "\n",
        "ax.fill_between(df_test.index, test_pred_ci[:,0], test_pred_ci[:,1], color='gray', alpha=0.3)\n",
        "ax.grid()\n",
        "plt.legend()\n",
        "plt.savefig('grape3.png')\n",
        "plt.savefig('grape3.pdf')\n",
        "plt.savefig('grape3.svg')\n",
        "plt.show()"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3 (ipykernel)",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.9.16"
    },
    "colab": {
      "provenance": []
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}