{"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-21T12:23:20.192692Z","iopub.execute_input":"2021-11-21T12:23:20.193065Z","iopub.status.idle":"2021-11-21T12:23:20.223968Z","shell.execute_reply.started":"2021-11-21T12:23:20.192975Z","shell.execute_reply":"2021-11-21T12:23:20.223144Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport plotly.express as px\nfrom sklearn import preprocessing \nfrom category_encoders import *\nfrom sklearn.preprocessing import LabelEncoder\n%matplotlib inline\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom catboost import CatBoostRegressor\nfrom sklearn.metrics import r2_score,mean_squared_error\nfrom sklearn import datasets, linear_model, metrics\nfrom sklearn.metrics import  confusion_matrix\nfrom sklearn import preprocessing \nfrom sklearn.impute import SimpleImputer\nfrom datetime import datetime\nimport lightgbm as ltb","metadata":{"execution":{"iopub.status.busy":"2021-11-21T12:49:02.502057Z","iopub.execute_input":"2021-11-21T12:49:02.502872Z","iopub.status.idle":"2021-11-21T12:49:02.516243Z","shell.execute_reply.started":"2021-11-21T12:49:02.502821Z","shell.execute_reply":"2021-11-21T12:49:02.515344Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_asset = pd.read_csv('../input/g-research-crypto-forecasting/asset_details.csv')\ndf_asset","metadata":{"execution":{"iopub.status.busy":"2021-11-21T12:46:35.943454Z","iopub.execute_input":"2021-11-21T12:46:35.943753Z","iopub.status.idle":"2021-11-21T12:46:35.973226Z","shell.execute_reply.started":"2021-11-21T12:46:35.943711Z","shell.execute_reply":"2021-11-21T12:46:35.972333Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = pd.read_csv('../input/g-research-crypto-forecasting/train.csv')","metadata":{"execution":{"iopub.status.busy":"2021-11-21T12:46:43.040264Z","iopub.execute_input":"2021-11-21T12:46:43.040535Z","iopub.status.idle":"2021-11-21T12:47:43.833072Z","shell.execute_reply.started":"2021-11-21T12:46:43.040508Z","shell.execute_reply":"2021-11-21T12:47:43.831937Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.head()","metadata":{"execution":{"iopub.status.busy":"2021-11-21T12:46:39.339656Z","iopub.execute_input":"2021-11-21T12:46:39.340413Z","iopub.status.idle":"2021-11-21T12:46:39.50175Z","shell.execute_reply.started":"2021-11-21T12:46:39.340376Z","shell.execute_reply":"2021-11-21T12:46:39.500493Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.dtypes","metadata":{"execution":{"iopub.status.busy":"2021-11-21T11:59:45.869657Z","iopub.execute_input":"2021-11-21T11:59:45.86995Z","iopub.status.idle":"2021-11-21T11:59:45.882897Z","shell.execute_reply.started":"2021-11-21T11:59:45.869911Z","shell.execute_reply":"2021-11-21T11:59:45.882004Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.isnull().sum()","metadata":{"execution":{"iopub.status.busy":"2021-11-21T11:59:45.884715Z","iopub.execute_input":"2021-11-21T11:59:45.884929Z","iopub.status.idle":"2021-11-21T11:59:46.359536Z","shell.execute_reply.started":"2021-11-21T11:59:45.884903Z","shell.execute_reply":"2021-11-21T11:59:46.35865Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.dropna(axis = 0, inplace = True)","metadata":{"execution":{"iopub.status.busy":"2021-11-21T12:47:43.835303Z","iopub.execute_input":"2021-11-21T12:47:43.83559Z","iopub.status.idle":"2021-11-21T12:47:45.565803Z","shell.execute_reply.started":"2021-11-21T12:47:43.835555Z","shell.execute_reply":"2021-11-21T12:47:45.564889Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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']\n# A utility function to build features from the original df\n# It works for rows to, so we can reutilize it.\ndef get_features(df, row=False):\n    df_feat = df[['Count', 'Open', 'High', 'Low', 'Close', 'Volume', 'VWAP']].copy()\n    df_feat['Upper_Shadow'] = upper_shadow(df_feat)\n    df_feat['Lower_Shadow'] = lower_shadow(df_feat)\n    \n    \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    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    ## possible seasonality, datetime  features (unlikely to me meaningful, given very short time-frames)\n    ### to do: add cyclical features for seasonality\n    df['datetime'] = pd.to_datetime(df['timestamp'], unit='s')\n    df_feat['year'] = df['datetime'].dt.year\n    df_feat['month'] = df['datetime'].dt.month\n    df_feat['week'] = df['datetime'].dt.week\n    df_feat['day'] = df['datetime'].dt.day\n    df_feat['hour'] = df['datetime'].dt.hour\n    df_feat['minute'] = df['datetime'].dt.minute\n    df_feat['dayofweek'] = df['datetime'].dt.dayofweek\n    return df_feat\n\n\ndef get_Xy_and_model_for_asset(df_train, asset_id):\n    df = df_train[df_train[\"Asset_ID\"] == asset_id]\n    \n    # TODO: Try different features here!\n    df_proc = get_features(df)\n    df_proc['y'] = df['Target']\n    df_proc = df_proc.replace([np.inf, -np.inf], np.nan).dropna(how=\"any\")\n    \n    X = df_proc.drop(\"y\", axis=1)\n    y = df_proc[\"y\"]\n\n    # TODO: Try different models here!\n    model = ltb.LGBMRegressor(n_estimators=50,learning_rate=0.01)\n    model.fit(X, y)\n    return X, y, model","metadata":{"execution":{"iopub.status.busy":"2021-11-21T12:49:28.722822Z","iopub.execute_input":"2021-11-21T12:49:28.723747Z","iopub.status.idle":"2021-11-21T12:49:28.74177Z","shell.execute_reply.started":"2021-11-21T12:49:28.723691Z","shell.execute_reply":"2021-11-21T12:49:28.740868Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Xs = {}\nys = {}\nmodels = {}\n\nfor asset_id, asset_name in zip(df_asset['Asset_ID'], df_asset['Asset_Name']):\n    print(f\"Training model for {asset_name:<16} (ID={asset_id:<2})\")\n    X, y, model = get_Xy_and_model_for_asset(df, asset_id)    \n    Xs[asset_id], ys[asset_id], models[asset_id] = X, y, model","metadata":{"execution":{"iopub.status.busy":"2021-11-21T12:49:33.245288Z","iopub.execute_input":"2021-11-21T12:49:33.245956Z","iopub.status.idle":"2021-11-21T12:51:32.639647Z","shell.execute_reply.started":"2021-11-21T12:49:33.245922Z","shell.execute_reply":"2021-11-21T12:51:32.638906Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test = pd.read_csv('../input/g-research-crypto-forecasting/example_test.csv')","metadata":{"execution":{"iopub.status.busy":"2021-11-21T12:58:13.728587Z","iopub.execute_input":"2021-11-21T12:58:13.72889Z","iopub.status.idle":"2021-11-21T12:58:13.744818Z","shell.execute_reply.started":"2021-11-21T12:58:13.72886Z","shell.execute_reply":"2021-11-21T12:58:13.743873Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import gresearch_crypto\n#env = gresearch_crypto.make_env()\n#iter_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)\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        \n        # Print just one sample row to get a feeling of what it looks like\n        if i == 0 and j == 0:\n            display(x_test)\n\n    # Display the first prediction dataframe\n    if i == 0:\n        display(df_pred)\n\n    # Send submissions\n    env.predict(df_pred)","metadata":{"execution":{"iopub.status.busy":"2021-11-21T13:01:03.347074Z","iopub.execute_input":"2021-11-21T13:01:03.347507Z","iopub.status.idle":"2021-11-21T13:01:03.353895Z","shell.execute_reply.started":"2021-11-21T13:01:03.347477Z","shell.execute_reply":"2021-11-21T13:01:03.353182Z"},"trusted":true},"execution_count":null,"outputs":[]}]}