{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-08-13T05:19:04.283375Z","iopub.execute_input":"2022-08-13T05:19:04.283774Z","iopub.status.idle":"2022-08-13T05:19:04.292946Z","shell.execute_reply.started":"2022-08-13T05:19:04.283739Z","shell.execute_reply":"2022-08-13T05:19:04.291848Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **Introduction**","metadata":{}},{"cell_type":"code","source":"# Setup feedback system\nfrom learntools.core import binder\nbinder.bind(globals())\nfrom learntools.time_series.ex3 import *\n\n# Setup notebook\nfrom pathlib import Path\nfrom learntools.time_series.style import *  # plot style settings\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sns\nfrom sklearn.linear_model import LinearRegression\n\ncomp_dir = Path('../input/store-sales-time-series-forecasting')\n\ntransactions_sales = pd.read_csv(\n    comp_dir / \"transactions.csv\",\n    parse_dates=['date'],\n    index_col='date',\n).to_period('D')\ntransaction_sales = transactions_sales.loc[:, 'transactions']\n\ndtype = {\n    'store_nbr': 'category',\n    'family': 'category',\n    'sales': 'float32',\n    'onpromotion': 'uint64',\n}\ntrain_sales = pd.read_csv(\n    comp_dir / 'train.csv',\n    dtype=dtype,\n    parse_dates=['date'],\n    infer_datetime_format=True,\n)\ntrain_sales = train_sales.set_index('date').to_period('D')\ntrain_sales = train_sales.set_index(['store_nbr', 'family'], append=True)\naverage_sales = train_sales.groupby('date').mean()['sales']\naverage_transactions = transactions_sales.groupby('date').mean()['transactions']","metadata":{"execution":{"iopub.status.busy":"2022-08-13T05:19:04.402180Z","iopub.execute_input":"2022-08-13T05:19:04.402558Z","iopub.status.idle":"2022-08-13T05:19:07.081242Z","shell.execute_reply.started":"2022-08-13T05:19:04.402525Z","shell.execute_reply":"2022-08-13T05:19:07.079977Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **1) Determine trend with a moving average plot**","metadata":{}},{"cell_type":"code","source":"ax = transaction_sales.plot(**plot_params)\nax.set(title=\"Transactions\", ylabel=\"Number of Transactions\");","metadata":{"execution":{"iopub.status.busy":"2022-08-13T05:19:07.083529Z","iopub.execute_input":"2022-08-13T05:19:07.084069Z","iopub.status.idle":"2022-08-13T05:19:08.067859Z","shell.execute_reply.started":"2022-08-13T05:19:07.084022Z","shell.execute_reply":"2022-08-13T05:19:08.066882Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Add methods to `transaction_sales` to compute a moving average with appropriate parameters for trend estimation.\ntrend = transaction_sales.rolling(\n    window=12,\n    center=True,\n    min_periods=6,\n).mean()\n\n# Make a plot\nax = transaction_sales.plot(**plot_params, alpha=0.5)\nax = trend.plot(ax=ax, linewidth=3)","metadata":{"execution":{"iopub.status.busy":"2022-08-13T05:19:08.069017Z","iopub.execute_input":"2022-08-13T05:19:08.069811Z","iopub.status.idle":"2022-08-13T05:19:08.830040Z","shell.execute_reply.started":"2022-08-13T05:19:08.069776Z","shell.execute_reply":"2022-08-13T05:19:08.829159Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **2) Identify trend**","metadata":{}},{"cell_type":"code","source":"trend = average_transactions.rolling(\n    window=365,\n    center=True,\n    min_periods=183,\n).mean()\n\nax = average_transactions.plot(**plot_params, alpha=0.5)\nax = trend.plot(ax=ax, linewidth=3)","metadata":{"execution":{"iopub.status.busy":"2022-08-13T05:19:08.832012Z","iopub.execute_input":"2022-08-13T05:19:08.832749Z","iopub.status.idle":"2022-08-13T05:19:09.131935Z","shell.execute_reply.started":"2022-08-13T05:19:08.832715Z","shell.execute_reply":"2022-08-13T05:19:09.130732Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **3) Create a Trend Feature**","metadata":{}},{"cell_type":"code","source":"from statsmodels.tsa.deterministic import DeterministicProcess\n\ny = average_transactions.copy()  # the target\n\n# Instantiate `DeterministicProcess` with arguments appropriate for a cubic trend model\ndp = DeterministicProcess(index=y.index, order=3)\n\n# Create the feature set for the dates given in y.index\nX = dp.in_sample()\n\n# Create features for a 90-day forecast.\nX_fore = dp.out_of_sample(steps=90)","metadata":{"execution":{"iopub.status.busy":"2022-08-13T05:19:09.133600Z","iopub.execute_input":"2022-08-13T05:19:09.134672Z","iopub.status.idle":"2022-08-13T05:19:09.145409Z","shell.execute_reply.started":"2022-08-13T05:19:09.134629Z","shell.execute_reply":"2022-08-13T05:19:09.144278Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = LinearRegression()\nmodel.fit(X, y)\n\ny_pred = pd.Series(model.predict(X), index=X.index)\ny_fore = pd.Series(model.predict(X_fore), index=X_fore.index)\n\nax = y.plot(**plot_params, alpha=0.5, title=\"Average Transactions\", ylabel=\"Number of Transactions\")\nax = y_pred.plot(ax=ax, linewidth=3, label=\"Trend\", color='C0')\nax = y_fore.plot(ax=ax, linewidth=3, label=\"Trend Forecast\", color='C3')\nax.legend();","metadata":{"execution":{"iopub.status.busy":"2022-08-13T05:19:09.147117Z","iopub.execute_input":"2022-08-13T05:19:09.147750Z","iopub.status.idle":"2022-08-13T05:19:09.505987Z","shell.execute_reply.started":"2022-08-13T05:19:09.147697Z","shell.execute_reply":"2022-08-13T05:19:09.504901Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from statsmodels.tsa.deterministic import DeterministicProcess\n\ndp = DeterministicProcess(index=y.index, order=11) #Using an order 11 polynomial\nX = dp.in_sample()\n\nmodel = LinearRegression()\nmodel.fit(X, y)\n\ny_pred = pd.Series(model.predict(X), index=X.index)\n\nax = y.plot(**plot_params, alpha=0.5, title=\"Average Transactions\", ylabel=\"Number of Transactions\")\nax = y_pred.plot(ax=ax, linewidth=3, label=\"Trend\", color='C0')\nax.legend();","metadata":{"execution":{"iopub.status.busy":"2022-08-13T05:19:09.507390Z","iopub.execute_input":"2022-08-13T05:19:09.507749Z","iopub.status.idle":"2022-08-13T05:19:09.957811Z","shell.execute_reply.started":"2022-08-13T05:19:09.507714Z","shell.execute_reply":"2022-08-13T05:19:09.956660Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **4) Understand risks of forecasting with high-order polynomials**","metadata":{}},{"cell_type":"code","source":"X_fore = dp.out_of_sample(steps=90)\ny_fore = pd.Series(model.predict(X_fore), index=X_fore.index)\n\nax = y.plot(**plot_params, alpha=0.5, title=\"Average Transactions\", ylabel=\"Number of Transactions\")\nax = y_pred.plot(ax=ax, linewidth=3, label=\"Trend\", color='C0')\nax = y_fore.plot(ax=ax, linewidth=3, label=\"Trend Forecast\", color='C3')\nax.legend();","metadata":{"execution":{"iopub.status.busy":"2022-08-13T05:19:09.959712Z","iopub.execute_input":"2022-08-13T05:19:09.960488Z","iopub.status.idle":"2022-08-13T05:19:10.315761Z","shell.execute_reply.started":"2022-08-13T05:19:09.960438Z","shell.execute_reply":"2022-08-13T05:19:10.314997Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **Submission**","metadata":{}},{"cell_type":"code","source":"data_path = comp_dir / \"sample_submission.csv\"\ndata = pd.read_csv(data_path)\n\npred_data = pd.DataFrame({'pred':y_pred}).reset_index()\n\noutput = pd.DataFrame({'id': data.id, 'sales': pred_data.pred})\noutput['sales'].fillna(float(output['sales'].mean()), inplace=True)\n\noutput.to_csv('submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2022-08-13T05:19:10.317079Z","iopub.execute_input":"2022-08-13T05:19:10.317560Z","iopub.status.idle":"2022-08-13T05:19:10.404289Z","shell.execute_reply.started":"2022-08-13T05:19:10.317530Z","shell.execute_reply":"2022-08-13T05:19:10.403145Z"},"trusted":true},"execution_count":null,"outputs":[]}]}