{"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-11-27T11:48:26.540311Z","iopub.execute_input":"2021-11-27T11:48:26.540647Z","iopub.status.idle":"2021-11-27T11:48:26.564919Z","shell.execute_reply.started":"2021-11-27T11:48:26.540564Z","shell.execute_reply":"2021-11-27T11:48:26.564247Z"},"_kg_hide-input":true,"_kg_hide-output":true,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"![](https://www.cointribune.com/wp-content/uploads/2021/06/to-the-moon-and-bitcoin-stock-growth-concept-strong-increase-of-bitcoin-prices-shown-at-candlestick-bull-market-chart-lightning-hitting-the-bitcoin-investment-in-cryptocurrency-world-stockpack-deposit-photos-scaled.jpg)","metadata":{}},{"cell_type":"markdown","source":"## Importing Required Libraries","metadata":{}},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set_style('darkgrid')\nimport plotly\nimport plotly.express as px\nimport plotly.graph_objects as go\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split\n\nfrom lightgbm import LGBMRegressor","metadata":{"execution":{"iopub.status.busy":"2021-11-27T11:48:26.566544Z","iopub.execute_input":"2021-11-27T11:48:26.567266Z","iopub.status.idle":"2021-11-27T11:48:29.690483Z","shell.execute_reply.started":"2021-11-27T11:48:26.56722Z","shell.execute_reply":"2021-11-27T11:48:29.689695Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-11-27T11:48:29.691784Z","iopub.execute_input":"2021-11-27T11:48:29.692183Z","iopub.status.idle":"2021-11-27T11:48:29.709043Z","shell.execute_reply.started":"2021-11-27T11:48:29.69214Z","shell.execute_reply":"2021-11-27T11:48:29.708249Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Files\ntrain.csv - The training set\n\n> timestamp - A timestamp for the minute covered by the row.\n\n> Asset_ID - An ID code for the cryptoasset.\n\n> Count - The number of trades that took place this minute.\n\n> Open - The USD price at the beginning of the minute.\n\n> High - The highest USD price during the minute.\n\n> Low - The lowest USD price during the minute.\n\n> Close - The USD price at the end of the minute.\n\n> Volume - The number of cryptoasset units traded during the minute.\n\n> VWAP - The volume weighted average price for the minute.\n\n> Target - 15 minute residualized returns. See the 'Prediction and Evaluation' section of this notebook for details of how the target is calculated.\n\nexample_test.csv - An example of the data that will be delivered by the time series API.\n\nexample_sample_submission.csv - An example of the data that will be delivered by the time series API. The data is just copied from train.csv.\n\nasset_details.csv - Provides the real name and of the cryptoasset for each Asset_ID and the weight each cryptoasset receives in the metric.\n\ngresearch_crypto - An unoptimized version of the time series API files for offline work. You may need Python 3.7 and a Linux environment to run it without errors.\n\nsupplemental_train.csv - After the submission period is over this file's data will be replaced with cryptoasset prices from the submission period. In the Evaluation phase, the train, train supplement, and test set will be contiguous in time, apart from any missing data. The current copy, which is just filled approximately the right amount of data from train.csv is provided as a placeholder.","metadata":{}},{"cell_type":"code","source":"data = pd.read_csv('../input/g-research-crypto-forecasting/train.csv')\ndata.head()","metadata":{"execution":{"iopub.status.busy":"2021-11-27T11:48:29.710378Z","iopub.execute_input":"2021-11-27T11:48:29.71068Z","iopub.status.idle":"2021-11-27T11:49:18.563515Z","shell.execute_reply.started":"2021-11-27T11:48:29.710598Z","shell.execute_reply":"2021-11-27T11:49:18.562778Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"asset_id = pd.read_csv('../input/g-research-crypto-forecasting/asset_details.csv')\nasset = asset_id.set_index('Asset_ID').sort_index()\nasset","metadata":{"execution":{"iopub.status.busy":"2021-11-27T11:49:18.566198Z","iopub.execute_input":"2021-11-27T11:49:18.567137Z","iopub.status.idle":"2021-11-27T11:49:18.588486Z","shell.execute_reply.started":"2021-11-27T11:49:18.56709Z","shell.execute_reply":"2021-11-27T11:49:18.587845Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(12,5))\nsns.countplot(data['Asset_ID'], palette='cool')","metadata":{"execution":{"iopub.status.busy":"2021-11-27T11:49:18.589568Z","iopub.execute_input":"2021-11-27T11:49:18.589827Z","iopub.status.idle":"2021-11-27T11:49:21.361738Z","shell.execute_reply.started":"2021-11-27T11:49:18.589792Z","shell.execute_reply":"2021-11-27T11:49:21.361068Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Let's have a look at the most famous crypto - BITCOIN","metadata":{}},{"cell_type":"code","source":"btc = data[data['Asset_ID'] == 1].set_index(\"timestamp\")\nbtc_range = btc.iloc[-500:]  # Since we cannot plot the entire btc, so selecting the latest 500 points.\nbtc_range.head()","metadata":{"execution":{"iopub.status.busy":"2021-11-27T11:49:21.363054Z","iopub.execute_input":"2021-11-27T11:49:21.363449Z","iopub.status.idle":"2021-11-27T11:49:21.690114Z","shell.execute_reply.started":"2021-11-27T11:49:21.363411Z","shell.execute_reply":"2021-11-27T11:49:21.689287Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig = go.Figure(data=[go.Candlestick(x=btc_range.index, \n                                     open=btc_range['Open'], \n                                     high=btc_range['High'], \n                                     low=btc_range['Low'], \n                                     close=btc_range['Close'])])\nprint('Use the slider to Adjust and Zoom')\nfig.show()","metadata":{"execution":{"iopub.status.busy":"2021-11-27T11:49:21.691534Z","iopub.execute_input":"2021-11-27T11:49:21.692019Z","iopub.status.idle":"2021-11-27T11:49:21.760956Z","shell.execute_reply.started":"2021-11-27T11:49:21.691975Z","shell.execute_reply":"2021-11-27T11:49:21.760212Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Let's have a look at another crypto - ETHEREUM","metadata":{}},{"cell_type":"code","source":"eth = data[data['Asset_ID'] == 1].set_index(\"timestamp\")\neth_range = eth.iloc[-500:]  # Since we cannot plot the entire btc, so selecting the latest 500 points.\n\n\nfig = go.Figure(data=[go.Candlestick(x=eth_range.index, \n                                     open=eth_range['Open'], \n                                     high=eth_range['High'], \n                                     low=eth_range['Low'], \n                                     close=eth_range['Close'])])\nfig.show()","metadata":{"execution":{"iopub.status.busy":"2021-11-27T11:49:21.762069Z","iopub.execute_input":"2021-11-27T11:49:21.762512Z","iopub.status.idle":"2021-11-27T11:49:22.086047Z","shell.execute_reply.started":"2021-11-27T11:49:21.762477Z","shell.execute_reply":"2021-11-27T11:49:22.085378Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Data Preprocessing","metadata":{}},{"cell_type":"code","source":"data.isnull().sum()","metadata":{"execution":{"iopub.status.busy":"2021-11-27T11:49:22.087079Z","iopub.execute_input":"2021-11-27T11:49:22.087445Z","iopub.status.idle":"2021-11-27T11:49:22.497464Z","shell.execute_reply.started":"2021-11-27T11:49:22.087413Z","shell.execute_reply":"2021-11-27T11:49:22.496459Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Many missing values in target variable.","metadata":{}},{"cell_type":"code","source":"btc.isnull().sum()","metadata":{"execution":{"iopub.status.busy":"2021-11-27T11:49:22.498832Z","iopub.execute_input":"2021-11-27T11:49:22.499165Z","iopub.status.idle":"2021-11-27T11:49:22.536792Z","shell.execute_reply.started":"2021-11-27T11:49:22.499128Z","shell.execute_reply":"2021-11-27T11:49:22.536003Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Missing asset data, for a given minute, is not represented by NaN's, but instead by the absence of those rows. We can check the timestamp difference between consecutive rows to see if there is missing data.","metadata":{}},{"cell_type":"code","source":"(btc.index[1:]-btc.index[:-1]).value_counts().head()","metadata":{"execution":{"iopub.status.busy":"2021-11-27T11:49:22.538152Z","iopub.execute_input":"2021-11-27T11:49:22.53842Z","iopub.status.idle":"2021-11-27T11:49:22.564026Z","shell.execute_reply.started":"2021-11-27T11:49:22.538384Z","shell.execute_reply":"2021-11-27T11:49:22.563283Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Notice that there are many gaps in the data. \n\nLet's now see Ethereum.","metadata":{}},{"cell_type":"code","source":"eth.isnull().sum()","metadata":{"execution":{"iopub.status.busy":"2021-11-27T11:49:22.565326Z","iopub.execute_input":"2021-11-27T11:49:22.566169Z","iopub.status.idle":"2021-11-27T11:49:22.60668Z","shell.execute_reply.started":"2021-11-27T11:49:22.56613Z","shell.execute_reply":"2021-11-27T11:49:22.605999Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"(eth.index[1:]-eth.index[:-1]).value_counts().head()","metadata":{"execution":{"iopub.status.busy":"2021-11-27T11:49:22.609738Z","iopub.execute_input":"2021-11-27T11:49:22.610384Z","iopub.status.idle":"2021-11-27T11:49:22.634878Z","shell.execute_reply.started":"2021-11-27T11:49:22.610347Z","shell.execute_reply":"2021-11-27T11:49:22.634182Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"As expected it also has large gaps.\n\nTo work with most time series models, we should preprocess our data into a format without time gaps. \n\nTo fill the gaps, we can use the `.reindex()` method for forward filling, filling gaps with the previous valid value.","metadata":{}},{"cell_type":"code","source":"btc = btc.reindex(range(btc.index[0],btc.index[-1]+60,60),method='pad')\neth = eth.reindex(range(eth.index[0],eth.index[-1]+60,60),method='pad')","metadata":{"execution":{"iopub.status.busy":"2021-11-27T11:49:22.636117Z","iopub.execute_input":"2021-11-27T11:49:22.636536Z","iopub.status.idle":"2021-11-27T11:49:23.251883Z","shell.execute_reply.started":"2021-11-27T11:49:22.636497Z","shell.execute_reply":"2021-11-27T11:49:23.25115Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"(btc.index[1:]-btc.index[:-1]).value_counts().head()\n(eth.index[1:]-eth.index[:-1]).value_counts().head()","metadata":{"execution":{"iopub.status.busy":"2021-11-27T11:49:23.253339Z","iopub.execute_input":"2021-11-27T11:49:23.253593Z","iopub.status.idle":"2021-11-27T11:49:23.33379Z","shell.execute_reply.started":"2021-11-27T11:49:23.253559Z","shell.execute_reply":"2021-11-27T11:49:23.332981Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Clearly, their is no time gap now.","metadata":{}},{"cell_type":"markdown","source":"### Feature Enginnering","metadata":{}},{"cell_type":"code","source":"def upper_shadow(df):\n    return df[\"High\"] - np.maximum(df[\"Close\"], df[\"Open\"])\n\ndef lower_shadow(df):\n    return np.minimum(df[\"Close\"], df[\"Open\"]) - df[\"Low\"]","metadata":{"execution":{"iopub.status.busy":"2021-11-27T11:49:23.335277Z","iopub.execute_input":"2021-11-27T11:49:23.335541Z","iopub.status.idle":"2021-11-27T11:49:23.34066Z","shell.execute_reply.started":"2021-11-27T11:49:23.335507Z","shell.execute_reply":"2021-11-27T11:49:23.339971Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_features(dataframe, row=False):\n    df_feat = dataframe.copy()\n    \n    df_feat[\"Upper_Shadow\"] = upper_shadow(df_feat)\n    df_feat[\"Lower_Shadow\"] = lower_shadow(df_feat)\n\n    ## Adding some more features\n    df_feat[\"Close/Open\"] = df_feat[\"Close\"] / df_feat[\"Open\"] \n    df_feat[\"Close-Open\"] = df_feat[\"Close\"] - df_feat[\"Open\"] \n    df_feat[\"High-Low\"] = df_feat[\"High\"] - df_feat[\"Low\"] \n    df_feat[\"High/Low\"] = df_feat[\"High\"] / df_feat[\"Low\"]\n    \n    if row:\n        df_feat['Mean'] = df_feat[['Open', 'High', 'Low', 'Close']].mean()\n    else:\n        df_feat['Mean'] = df_feat[['Open', 'High', 'Low', 'Close']].mean(axis=1)\n\n    df_feat[\"High/Mean\"] = df_feat[\"High\"] / df_feat[\"Mean\"]\n    df_feat[\"Low/Mean\"] = df_feat[\"Low\"] / df_feat[\"Mean\"]\n    df_feat[\"Volume/Count\"] = df_feat[\"Volume\"] / (df_feat[\"Count\"] + 1)\n\n    times = pd.to_datetime(df_feat[\"timestamp\"],unit=\"s\",infer_datetime_format=True)\n    if row:\n        df_feat[\"hour\"] = times.hour  # .dt\n        df_feat[\"dayofweek\"] = times.dayofweek \n        df_feat[\"day\"] = times.day \n    else:\n        df_feat[\"hour\"] = times.dt.hour  # .dt\n        df_feat[\"dayofweek\"] = times.dt.dayofweek \n        df_feat[\"day\"] = times.dt.day \n    \n    if row:\n        df_feat[\"Median\"] = df_feat[[\"Open\", \"High\", \"Low\", \"Close\"]].median()\n    else:\n        df_feat[\"Median\"] = df_feat[[\"Open\", \"High\", \"Low\", \"Close\"]].median(axis=1)\n    df_feat[\"High/Median\"] = df_feat[\"High\"] / df_feat[\"Median\"]\n    df_feat[\"Low/Median\"] = df_feat[\"Low\"] / df_feat[\"Median\"]\n\n    for col in ['Open', 'High', 'Low', 'Close', 'VWAP']:\n        df_feat[f\"Log_1p_{col}\"] = np.log1p(df_feat[col])\n        \n    if row:\n        df_feat.drop(['row_id', 'Asset_ID'], inplace=True)\n    else:\n        df_feat.drop(['Asset_ID'], axis=1, inplace=True)\n    \n    return df_feat","metadata":{"execution":{"iopub.status.busy":"2021-11-27T11:49:23.352832Z","iopub.execute_input":"2021-11-27T11:49:23.353178Z","iopub.status.idle":"2021-11-27T11:49:23.369253Z","shell.execute_reply.started":"2021-11-27T11:49:23.353141Z","shell.execute_reply":"2021-11-27T11:49:23.368467Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Model Building","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 = get_features(data_set)\n    df = df.replace([np.inf, -np.inf], np.nan).dropna(how=\"any\")\n    \n    df = reduce_memory_usage(df)\n    \n    X = df.drop(['Target'], axis=1)\n    y = df[\"Target\"]\n    \n    X_train, X_valid, y_train, y_valid = train_test_split(X, y, test_size=0.25, random_state=24, shuffle=False)\n    \n    scaler = StandardScaler()\n    X_train = scaler.fit_transform(X_train)\n    X_valid = scaler.transform(X_valid)\n    \n    model = LGBMRegressor(\n        n_estimators=1500, \n        num_leaves=700,\n        objective=\"regression\",\n        metric=\"rmse\",\n        boosting_type=\"gbdt\",\n        learning_rate=0.01,\n        random_state=24,\n        verbose=0,\n        force_col_wise=True,\n    )\n    \n    model.fit(X_train, y_train)\n        \n    return X_train, y_train, model","metadata":{"execution":{"iopub.status.busy":"2021-11-27T11:49:23.370659Z","iopub.execute_input":"2021-11-27T11:49:23.371355Z","iopub.status.idle":"2021-11-27T11:49:23.383038Z","shell.execute_reply.started":"2021-11-27T11:49:23.371318Z","shell.execute_reply":"2021-11-27T11:49:23.382285Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Xs = {}\nys = {}\nmodels = {}\nprint('Training Starting...')\n\nfor asset, asset_name in zip(asset_id[\"Asset_ID\"], asset_id[\"Asset_Name\"]):\n    X, y, model = model_building(data, asset)\n    Xs[asset], ys[asset], models[asset] = X, y, model\n    \nprint('Training Completed !!!')","metadata":{"execution":{"iopub.status.busy":"2021-11-27T11:49:23.385579Z","iopub.execute_input":"2021-11-27T11:49:23.3858Z","iopub.status.idle":"2021-11-27T11:51:14.875381Z","shell.execute_reply.started":"2021-11-27T11:49:23.385776Z","shell.execute_reply":"2021-11-27T11:51:14.874816Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Prediction","metadata":{}},{"cell_type":"code","source":"import gresearch_crypto\n\nenv = gresearch_crypto.make_env()\niter_test = env.iter_test()\n\nfor i, (df_test, df_pred) in enumerate(iter_test):\n    for j , row in df_test.iterrows():\n        \n        model = models[row[\"Asset_ID\"]]\n        x_test = get_features(row, row=True)\n        y_pred = model.predict([x_test])[0]\n        \n        df_pred.loc[df_pred[\"row_id\"] == row[\"row_id\"], \"Target\"] = y_pred\n\n    # Send submissions\n    env.predict(df_pred)","metadata":{"execution":{"iopub.status.busy":"2021-11-27T11:51:14.878614Z","iopub.execute_input":"2021-11-27T11:51:14.88016Z","iopub.status.idle":"2021-11-27T11:51:15.671908Z","shell.execute_reply.started":"2021-11-27T11:51:14.880127Z","shell.execute_reply":"2021-11-27T11:51:15.671266Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}