{"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":"2021-12-02T05:05:38.044255Z","iopub.execute_input":"2021-12-02T05:05:38.044609Z","iopub.status.idle":"2021-12-02T05:05:38.07641Z","shell.execute_reply.started":"2021-12-02T05:05:38.044501Z","shell.execute_reply":"2021-12-02T05:05:38.075366Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"![](https://miro.medium.com/max/964/0*tVCene42rgUTNv9Q.png)\n##### Prophet is a procedure for forecasting time series data based on an additive model where non-linear trends are fit with yearly, weekly, and daily seasonality, plus holiday effects. It works best with time series that have strong seasonal effects and several seasons of historical data. Prophet is robust to missing data and shifts in the trend, and typically handles outliers well.\n##### You can read more about it [here](https://facebook.github.io/prophet/docs/quick_start.html#python-api)","metadata":{}},{"cell_type":"markdown","source":"## Importing Required libraries","metadata":{}},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\nimport fbprophet\nfrom fbprophet import Prophet","metadata":{"execution":{"iopub.status.busy":"2021-12-02T05:05:38.078174Z","iopub.execute_input":"2021-12-02T05:05:38.078425Z","iopub.status.idle":"2021-12-02T05:05:38.296548Z","shell.execute_reply.started":"2021-12-02T05:05:38.078392Z","shell.execute_reply":"2021-12-02T05:05:38.295707Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Helper function","metadata":{}},{"cell_type":"code","source":"def reduce_memory_usage(df):\n    \"\"\" \n    iterate through all the columns of a dataframe and modify the data type to reduce memory usage.        \n    \"\"\"\n#     start_mem = df.memory_usage().sum() / 1024**2\n#     print('Memory usage of dataframe is {:.2f} MB'.format(start_mem))    \n\n    for col in df.columns:\n        col_type = df[col].dtype\n\n        if col_type != object:\n            c_min = df[col].min()\n            c_max = df[col].max()\n            if str(col_type)[:3] == 'int':\n                if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:\n                    df[col] = df[col].astype(np.int8)\n                elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:\n                    df[col] = df[col].astype(np.int16)\n                elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:\n                    df[col] = df[col].astype(np.int32)\n                elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:\n                    df[col] = df[col].astype(np.int64)  \n            else:\n                if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:\n                    df[col] = df[col].astype(np.float16)\n                elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:\n                    df[col] = df[col].astype(np.float32)\n                else:\n                    df[col] = df[col].astype(np.float64)\n        else:\n            df[col] = df[col].astype('category')\n\n    end_mem = df.memory_usage().sum() / 1024**2\n#     print('Memory usage after optimization is: {:.2f} MB'.format(end_mem))\n#     print('Decreased by {:.1f}%'.format(100 * (start_mem - end_mem) / start_mem))\n\n    return df","metadata":{"execution":{"iopub.status.busy":"2021-12-02T05:05:38.297853Z","iopub.execute_input":"2021-12-02T05:05:38.298106Z","iopub.status.idle":"2021-12-02T05:05:38.31401Z","shell.execute_reply.started":"2021-12-02T05:05:38.298073Z","shell.execute_reply":"2021-12-02T05:05:38.313183Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data = pd.read_csv('../input/g-research-crypto-forecasting/train.csv')\ndata.head()","metadata":{"execution":{"iopub.status.busy":"2021-12-02T05:05:38.316448Z","iopub.execute_input":"2021-12-02T05:05:38.316936Z","iopub.status.idle":"2021-12-02T05:06:32.383144Z","shell.execute_reply.started":"2021-12-02T05:05:38.3169Z","shell.execute_reply":"2021-12-02T05:06:32.382378Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"asset_id = pd.read_csv('../input/g-research-crypto-forecasting/asset_details.csv')","metadata":{"execution":{"iopub.status.busy":"2021-12-02T05:06:32.384789Z","iopub.execute_input":"2021-12-02T05:06:32.385309Z","iopub.status.idle":"2021-12-02T05:06:32.395697Z","shell.execute_reply.started":"2021-12-02T05:06:32.385269Z","shell.execute_reply":"2021-12-02T05:06:32.394814Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### We need to change the column name to - 'ds' and 'y'.","metadata":{}},{"cell_type":"code","source":"def model_building(df_data, asset_id):\n    data_set = df_data[df_data['Asset_ID'] == asset_id]\n    df = data_set[['timestamp', 'Target']]\n    df.columns = ['ds', 'y']\n    df = reduce_memory_usage(df)\n    df['ds'] = pd.to_datetime(df['ds'])\n    df = df.replace([np.inf, -np.inf], np.nan).dropna(how=\"any\")\n    \n    model = Prophet()\n    \n    model.fit(df)\n        \n    return model","metadata":{"execution":{"iopub.status.busy":"2021-12-02T05:06:32.397439Z","iopub.execute_input":"2021-12-02T05:06:32.397816Z","iopub.status.idle":"2021-12-02T05:06:32.405558Z","shell.execute_reply.started":"2021-12-02T05:06:32.397735Z","shell.execute_reply":"2021-12-02T05:06:32.404698Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Model Training","metadata":{}},{"cell_type":"code","source":"models = {}\nprint('Training Starting...')\n\nfor asset, asset_name in zip(asset_id[\"Asset_ID\"], asset_id[\"Asset_Name\"]):\n    print(f\"Training model for  {asset_name:<16} (ID={asset:<2})\")\n    model = model_building(data, asset)\n    models[asset] = model\n    \nprint('Training Completed !!!')","metadata":{"execution":{"iopub.status.busy":"2021-12-02T05:06:32.407375Z","iopub.execute_input":"2021-12-02T05:06:32.407695Z"},"trusted":true},"execution_count":null,"outputs":[]}]}