{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":30894,"databundleVersionId":3147400,"sourceType":"competition"}],"dockerImageVersionId":30587,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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":"2023-11-24T09:11:12.742150Z","iopub.execute_input":"2023-11-24T09:11:12.742792Z","iopub.status.idle":"2023-11-24T09:11:13.100708Z","shell.execute_reply.started":"2023-11-24T09:11:12.742757Z","shell.execute_reply":"2023-11-24T09:11:13.099041Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# G-Research Crypto Forecasting\n\n## 1.Problem Definiton\n> We need to use a machine learning model to forecast short term returns in 14 popular cryptocurrencies?\n  Our dataset contains information on historic trades for several cryptoassets, such as Bitcoin and Ethereum and our challenge is to predict their future returns.\n    \n## 2.Data\nThe data is dowloaded from the Kaggle's G-Research Crypto Forecasting competition.\n\nThere are 3 main datasets:\n\n* train.csv - The training set, which contains data through the\n* asset_details.csv - Provides the real name and of the cryptoasset for each Asset_ID and the weight each cryptoasset receives in the metric.\n* example_test.csv - An example of the data that will be delivered by the time series API.\n* supplemental_train.csv - After the submission period is over this file's data will be replaced with cryptoasset prices from the entire submission period.\n\n## 3.Evaluation\n\n* Submissions are evaluated on a weighted version of the Pearson correlation coefficient.\n\nFor more one evaluation of this project check:\n`www.kaggle.com/competitions/g-research-crypto-forecasting/overview/evaluation`\n\n**Note:** The goal for most regression evaluation metrics is to minimize the error. For example, our goal for this project will be to build a machine learning model which minimises RMSLE.\n\n## 4.Features\n\nKaggle provides a data dicitionary detailing all of the  features of the dataset.\nEach row of the data setin the train.csv has the trading data for an asset, at a given minute timestamp, described in detail below.\n\n* timestamp: All timestamps are returned as second Unix timestamps (the number of seconds elapsed since 1970-01-01 00:00:00.000 UTC). Timestamps in this dataset are multiple of 60, indicating minute-by-minute data.\n* Asset_ID: The asset ID corresponding to one of the crytocurrencies (e.g. Asset_ID = 1 for Bitcoin). The mapping from Asset_ID to crypto asset is contained in asset_details.csv.\n* Count: Total number of trades in the time interval (last minute).\n* Open: Opening price of the time interval (in USD).\n* High: Highest price reached during time interval (in USD).\n* Low: Lowest price reached during time interval (in USD).\n* Close: Closing price of the time interval (in USD).\n* Volume: Quantity of asset bought or sold, displayed in base currency USD.\n* VWAP: The average price of the asset over the time interval, weighted by volume. VWAP is an aggregated form of trade data.\n* Target: Residual log-returns for the asset over a 15 minute horizon.\n\nThe first two columns define the time and asset indexes for this data row. The 6 middle columns are feature columns with the trading data for this asset and minute in time. The last column is the prediction target, which we will get to later in more detail.\n\nWe also view the asset information, including the list of all assets, the Asset_ID to asset mapping, and the weight of each asset used to weigh their relative importance in the evaluation metric.\n","metadata":{"execution":{"iopub.status.busy":"2023-11-24T09:12:08.549555Z","iopub.execute_input":"2023-11-24T09:12:08.550021Z","iopub.status.idle":"2023-11-24T09:12:08.572590Z","shell.execute_reply.started":"2023-11-24T09:12:08.549997Z","shell.execute_reply":"2023-11-24T09:12:08.570729Z"}}},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport seaborn as sns\nfrom tqdm.auto import tqdm\nimport time\nfrom datetime import datetime\n\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split\n\nfrom lightgbm import LGBMRegressor\nfrom scipy.stats import pearsonr\n\nimport warnings\nimport lightgbm as lgb\nwarnings.simplefilter(\"ignore\")\npd.set_option(\"display.max_columns\", None)\n\ncut_type = 'peryear'\ntrain_type = 'scilearn'\ndata_type = 'all'\n\n\nbegin_test_date = '2021-06-13  00:00:00'\nend_test_date = '2021-09-21  00:00:00'\ntrain_instant = True\nmodelpath = './catM'","metadata":{"execution":{"iopub.status.busy":"2023-11-24T09:14:14.498495Z","iopub.execute_input":"2023-11-24T09:14:14.498892Z","iopub.status.idle":"2023-11-24T09:14:14.508576Z","shell.execute_reply.started":"2023-11-24T09:14:14.498862Z","shell.execute_reply":"2023-11-24T09:14:14.507527Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Load the training set","metadata":{}},{"cell_type":"code","source":"data_folder = \"../input/g-research-crypto-forecasting/\"\n!ls $data_folder","metadata":{"execution":{"iopub.status.busy":"2023-11-24T09:14:23.243321Z","iopub.execute_input":"2023-11-24T09:14:23.243713Z","iopub.status.idle":"2023-11-24T09:14:23.555961Z","shell.execute_reply.started":"2023-11-24T09:14:23.243675Z","shell.execute_reply":"2023-11-24T09:14:23.554466Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"crypto_df = pd.read_csv(data_folder + 'train.csv')","metadata":{"execution":{"iopub.status.busy":"2023-11-24T09:14:41.689284Z","iopub.execute_input":"2023-11-24T09:14:41.689642Z","iopub.status.idle":"2023-11-24T09:15:31.936468Z","shell.execute_reply.started":"2023-11-24T09:14:41.689610Z","shell.execute_reply":"2023-11-24T09:15:31.934506Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"crypto_df.head(10)","metadata":{"execution":{"iopub.status.busy":"2023-11-24T09:17:00.053906Z","iopub.execute_input":"2023-11-24T09:17:00.054303Z","iopub.status.idle":"2023-11-24T09:17:00.074538Z","shell.execute_reply.started":"2023-11-24T09:17:00.054272Z","shell.execute_reply":"2023-11-24T09:17:00.072795Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"asset_details = pd.read_csv(data_folder + 'asset_details.csv')\nasset_details","metadata":{"execution":{"iopub.status.busy":"2023-11-24T09:17:00.261817Z","iopub.execute_input":"2023-11-24T09:17:00.262237Z","iopub.status.idle":"2023-11-24T09:17:00.277613Z","shell.execute_reply.started":"2023-11-24T09:17:00.262208Z","shell.execute_reply":"2023-11-24T09:17:00.276455Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Candlestick charts \nThe trading data format is an aggregated form of market data including for Open,\nHigh, Low and Close. We can visualize this data through the commonly used \ncandlestick bar chart, which allows traders to perform technical analysis on intraday values. \nThe bar's body length represents the price range between the open and close of that day's trading.\nWhen the bar is red, it means the close was lower than the open, and green otherwise. These are also referred to as bullish and bearish candlesticks. \nThe wicks above and below the bars show the high and low prices of that interval's trading.","metadata":{}},{"cell_type":"code","source":"btc = crypto_df[crypto_df[\"Asset_ID\"]==1].set_index(\"timestamp\") # Asset_ID = 1 is for Bitcoin\nbtc_mini = btc.iloc[-200:] # Select recent data rows","metadata":{"execution":{"iopub.status.busy":"2023-11-24T09:18:24.548781Z","iopub.execute_input":"2023-11-24T09:18:24.551150Z","iopub.status.idle":"2023-11-24T09:18:24.833651Z","shell.execute_reply.started":"2023-11-24T09:18:24.551072Z","shell.execute_reply":"2023-11-24T09:18:24.831357Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import plotly.graph_objects as go\n\nfig = go.Figure(data=[go.Candlestick(x=btc_mini.index, open=btc_mini['Open'], high=btc_mini['High'], low=btc_mini['Low'], close=btc_mini['Close'])])\nfig.show()","metadata":{"execution":{"iopub.status.busy":"2023-11-24T09:35:56.741216Z","iopub.execute_input":"2023-11-24T09:35:56.741652Z","iopub.status.idle":"2023-11-24T09:35:57.233965Z","shell.execute_reply.started":"2023-11-24T09:35:56.741619Z","shell.execute_reply":"2023-11-24T09:35:57.232119Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Data Precrocessing\n\n#### Dealing with missing data\n\n","metadata":{"execution":{"iopub.status.busy":"2023-11-24T09:37:00.226832Z","iopub.execute_input":"2023-11-24T09:37:00.227379Z","iopub.status.idle":"2023-11-24T09:37:00.234436Z","shell.execute_reply.started":"2023-11-24T09:37:00.227337Z","shell.execute_reply":"2023-11-24T09:37:00.232551Z"}}},{"cell_type":"code","source":"# inspecting ethereum which is yet another important asset.\neth = crypto_df[crypto_df[\"Asset_ID\"]==6].set_index(\"timestamp\") # Asset_ID = 6 for Ethereum\neth.info(show_counts =True)\n","metadata":{"execution":{"iopub.status.busy":"2023-11-24T09:37:53.738200Z","iopub.execute_input":"2023-11-24T09:37:53.738618Z","iopub.status.idle":"2023-11-24T09:37:53.999955Z","shell.execute_reply.started":"2023-11-24T09:37:53.738586Z","shell.execute_reply":"2023-11-24T09:37:53.998659Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# We can see the number of rows in the training set,\n# and that there are missing values for the targets columns, which we will address later.\neth.isna().sum()","metadata":{"execution":{"iopub.status.busy":"2023-11-24T09:39:28.614238Z","iopub.execute_input":"2023-11-24T09:39:28.614651Z","iopub.status.idle":"2023-11-24T09:39:28.641378Z","shell.execute_reply.started":"2023-11-24T09:39:28.614619Z","shell.execute_reply":"2023-11-24T09:39:28.640359Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Let's check the time range for Bitcoin and Ethereum data, using the coversion from timestamp to datetime.\n","metadata":{"execution":{"iopub.status.busy":"2023-11-24T09:40:47.143530Z","iopub.execute_input":"2023-11-24T09:40:47.143952Z","iopub.status.idle":"2023-11-24T09:40:47.160068Z","shell.execute_reply.started":"2023-11-24T09:40:47.143917Z","shell.execute_reply":"2023-11-24T09:40:47.158645Z"}}},{"cell_type":"code","source":"btc.head()","metadata":{"execution":{"iopub.status.busy":"2023-11-24T09:42:37.527415Z","iopub.execute_input":"2023-11-24T09:42:37.527864Z","iopub.status.idle":"2023-11-24T09:42:37.549035Z","shell.execute_reply.started":"2023-11-24T09:42:37.527826Z","shell.execute_reply":"2023-11-24T09:42:37.546843Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"beg_btc = btc.index[0].astype('datetime64[s]')\nend_btc = btc.index[-1].astype('datetime64[s]')\nbeg_eth = eth.index[0].astype('datetime64[s]')\nend_eth = eth.index[-1].astype('datetime64[s]')\n\nprint('BTC data goes from ', beg_btc, 'to ', end_btc)\nprint('Ethereum data goes from ', beg_eth, 'to ', end_eth)","metadata":{"execution":{"iopub.status.busy":"2023-11-24T09:41:33.221775Z","iopub.execute_input":"2023-11-24T09:41:33.222173Z","iopub.status.idle":"2023-11-24T09:41:33.230345Z","shell.execute_reply.started":"2023-11-24T09:41:33.222145Z","shell.execute_reply":"2023-11-24T09:41:33.229329Z"},"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":"eth.head(5)","metadata":{"execution":{"iopub.status.busy":"2023-11-24T09:43:50.092593Z","iopub.execute_input":"2023-11-24T09:43:50.092975Z","iopub.status.idle":"2023-11-24T09:43:50.112028Z","shell.execute_reply.started":"2023-11-24T09:43:50.092944Z","shell.execute_reply":"2023-11-24T09:43:50.110090Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"(eth.index[1:] - eth.index[:-1]).value_counts().head()","metadata":{"execution":{"iopub.status.busy":"2023-11-24T09:48:59.512530Z","iopub.execute_input":"2023-11-24T09:48:59.512960Z","iopub.status.idle":"2023-11-24T09:48:59.540939Z","shell.execute_reply.started":"2023-11-24T09:48:59.512928Z","shell.execute_reply":"2023-11-24T09:48:59.540079Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"We can see that there are many gaps in the data. To work with most time series models, we should preprocess our data into a format without time gaps. To fill the gaps, we can use the `.reindex()` method for forward filling, filling gaps with the previous valid value.","metadata":{"execution":{"iopub.status.busy":"2023-11-24T09:51:44.758798Z","iopub.execute_input":"2023-11-24T09:51:44.759448Z","iopub.status.idle":"2023-11-24T09:51:44.767154Z","shell.execute_reply.started":"2023-11-24T09:51:44.759416Z","shell.execute_reply":"2023-11-24T09:51:44.765402Z"}}},{"cell_type":"code","source":"eth = eth.reindex(range(eth.index[0],eth.index[-1]+60,60),method='pad')","metadata":{"execution":{"iopub.status.busy":"2023-11-24T09:52:12.503797Z","iopub.execute_input":"2023-11-24T09:52:12.504156Z","iopub.status.idle":"2023-11-24T09:52:12.791491Z","shell.execute_reply.started":"2023-11-24T09:52:12.504129Z","shell.execute_reply":"2023-11-24T09:52:12.790005Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Checking again for the time gaps","metadata":{"execution":{"iopub.status.busy":"2023-11-24T09:52:35.676897Z","iopub.execute_input":"2023-11-24T09:52:35.677325Z","iopub.status.idle":"2023-11-24T09:52:35.685295Z","shell.execute_reply.started":"2023-11-24T09:52:35.677295Z","shell.execute_reply":"2023-11-24T09:52:35.683261Z"}}},{"cell_type":"code","source":"(eth.index[1:] - eth.index[:-1]).value_counts().head()","metadata":{"execution":{"iopub.status.busy":"2023-11-24T09:52:42.493655Z","iopub.execute_input":"2023-11-24T09:52:42.494076Z","iopub.status.idle":"2023-11-24T09:52:42.533680Z","shell.execute_reply.started":"2023-11-24T09:52:42.494043Z","shell.execute_reply":"2023-11-24T09:52:42.532331Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### Data visualisation \nWe will start by visualising the Close prices for the two assets we have selected","metadata":{}},{"cell_type":"code","source":"# plot vwap time series for both chosen assets\nf = plt.figure(figsize=(15,4))\n\n# fill missing values for BTC\nbtc = btc.reindex(range(btc.index[0],btc.index[-1]+60,60),method='pad')\n\nax = f.add_subplot(121)\nplt.plot(btc['Close'], label='BTC')\nplt.legend()\nplt.xlabel('Time')\nplt.ylabel('Bitcoin')\n\nax2 = f.add_subplot(122)\nax2.plot(eth['Close'], color='red', label='ETH')\nplt.legend()\nplt.xlabel('Time')\nplt.ylabel('Ethereum')\n\nplt.tight_layout()\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2023-11-24T09:53:53.691453Z","iopub.execute_input":"2023-11-24T09:53:53.691816Z","iopub.status.idle":"2023-11-24T09:53:57.308862Z","shell.execute_reply.started":"2023-11-24T09:53:53.691789Z","shell.execute_reply":"2023-11-24T09:53:57.307494Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Looks like these assets have quite different history, no direct corelation is visible in graphs, but we can check if they correlate in recent times(We will check for the last months upto which data is available)","metadata":{}},{"cell_type":"code","source":"# helper function for conversion from datetime to timestamp\ntotimestamp = lambda s: np.int32(time.mktime(datetime.strptime(s, \"%d/%m/%Y\").timetuple()))\n\n# creating intervals\nbtc_mini_2021 = btc.loc[totimestamp('01/06/2021'):totimestamp('01/07/2021')]\neth_mini_2021 = eth.loc[totimestamp('01/06/2021'):totimestamp('01/07/2021')]","metadata":{"execution":{"iopub.status.busy":"2023-11-24T09:56:34.640242Z","iopub.execute_input":"2023-11-24T09:56:34.640654Z","iopub.status.idle":"2023-11-24T09:56:34.647371Z","shell.execute_reply.started":"2023-11-24T09:56:34.640622Z","shell.execute_reply":"2023-11-24T09:56:34.646112Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# plotting time series for both chosen assets\nf = plt.figure(figsize=(7,8))\n\nax = f.add_subplot(211)\nplt.plot(btc_mini_2021['Close'], label='btc')\nplt.legend()\nplt.xlabel('Time')\nplt.ylabel('Bitcoin Close')\n\nax2 = f.add_subplot(212)\nax2.plot(eth_mini_2021['Close'], color='red', label='eth')\nplt.legend()\nplt.xlabel('Time')\nplt.ylabel('Ethereum Close')\n\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-11-24T09:56:46.467594Z","iopub.execute_input":"2023-11-24T09:56:46.467989Z","iopub.status.idle":"2023-11-24T09:56:46.953169Z","shell.execute_reply.started":"2023-11-24T09:56:46.467957Z","shell.execute_reply":"2023-11-24T09:56:46.951097Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"On shorter intervals we can visually see some potential correlation between both assets, with some simultaneous ups and downs. A better format for analyzing such mmovements is by calculating asset returns.","metadata":{"execution":{"iopub.status.busy":"2023-11-24T09:57:07.375719Z","iopub.execute_input":"2023-11-24T09:57:07.376239Z","iopub.status.idle":"2023-11-24T09:57:07.384125Z","shell.execute_reply.started":"2023-11-24T09:57:07.376171Z","shell.execute_reply":"2023-11-24T09:57:07.382380Z"}}},{"cell_type":"markdown","source":"#### Log returns\nIn order to analyze price changes for an asset we can deal with the price difference. However, different assets exhibit different price scales, so that the their returns are not readily comparable. We can solve this problem by computing the percentage change in price instead, also known as the return. This return coincides with the percentage change in our invested capital.\n\nReturns are widely used in finance, however log returns are preferred for mathematical modelling of time series, as they are additive across time. Also, while regular returns cannot go below -100%, log returns are not bounded.\n\nTo compute the log return, we can simply take the logarithm of the ratio between two consecutive prices. The first row will have an empty return as the previous value is unknown, therefore the empty return data point will be dropped.\n\n**Source**: Tutorial to the G-Research Crypto Competition","metadata":{}},{"cell_type":"code","source":"# we are making a function which will  compute log returns\ndef log_return(series, periods=1):\n    return np.log(series).diff(periods=periods)","metadata":{"execution":{"iopub.status.busy":"2023-11-24T09:58:50.940781Z","iopub.execute_input":"2023-11-24T09:58:50.941420Z","iopub.status.idle":"2023-11-24T09:58:50.947093Z","shell.execute_reply.started":"2023-11-24T09:58:50.941388Z","shell.execute_reply":"2023-11-24T09:58:50.945793Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"We can know visualize the log return for our two assets. ","metadata":{}},{"cell_type":"code","source":"import scipy.stats as stats\n\nlret_btc = log_return(btc_mini_2021.Close)[1:]\nlret_eth = log_return(eth_mini_2021.Close)[1:]\nlret_btc.rename('lret_btc', inplace=True)\nlret_eth.rename('lret_eth', inplace=True)\n\nplt.figure(figsize=(8,4))\nplt.plot(lret_btc);\nplt.plot(lret_eth);\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-11-24T10:00:01.467868Z","iopub.execute_input":"2023-11-24T10:00:01.468266Z","iopub.status.idle":"2023-11-24T10:00:01.744320Z","shell.execute_reply.started":"2023-11-24T10:00:01.468237Z","shell.execute_reply":"2023-11-24T10:00:01.743033Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Now we can see how the signal now looks more like white noise, with less drift than the time series for prices.","metadata":{}},{"cell_type":"markdown","source":"#### Correlation between assets¶\nWe hypothesized before that crypto asset returns may exhibit some correlation. we will try to look this in more detail now.\n\nWe can check how the correlation between Bitcoin and Ethereum change over time for the 2021 period we selected.","metadata":{}},{"cell_type":"code","source":"# join two asset in single DataFrame\n\nlret_btc_long = log_return(btc.Close)[1:]\nlret_eth_long = log_return(eth.Close)[1:]\nlret_btc_long.rename('lret_btc', inplace=True)\nlret_eth_long.rename('lret_eth', inplace=True)\ntwo_assets = pd.concat([lret_btc_long, lret_eth_long], axis=1)\n\n# group consecutive rows and use .corr() for correlation between columns\ncorr_time = two_assets.groupby(two_assets.index//(10000*60)).corr().loc[:,\"lret_btc\"].loc[:,\"lret_eth\"]\n\ncorr_time.plot();\nplt.xticks([])\nplt.ylabel(\"Correlation\")\nplt.title(\"Correlation between BTC and ETH over time\");","metadata":{"execution":{"iopub.status.busy":"2023-11-24T10:01:00.009940Z","iopub.execute_input":"2023-11-24T10:01:00.010396Z","iopub.status.idle":"2023-11-24T10:01:00.407855Z","shell.execute_reply.started":"2023-11-24T10:01:00.010363Z","shell.execute_reply":"2023-11-24T10:01:00.406489Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"We will now check the correlation between all assets visualizing the correlation matrix. Note how some assets have much higher pairwise correlation than others.","metadata":{}},{"cell_type":"code","source":"# creating dataframe with returns for all assets\nall_assets_2021 = pd.DataFrame([])\nfor asset_id, asset_name in zip(asset_details.Asset_ID, asset_details.Asset_Name):\n  asset = crypto_df[crypto_df[\"Asset_ID\"]==asset_id].set_index(\"timestamp\")\n  asset = asset.loc[totimestamp('01/01/2021'):totimestamp('01/05/2021')]\n  asset = asset.reindex(range(asset.index[0],asset.index[-1]+60,60),method='pad')\n  lret = log_return(asset.Close.fillna(0))[1:]\n  all_assets_2021 = all_assets_2021.join(lret, rsuffix=asset_name, how=\"outer\")","metadata":{"execution":{"iopub.status.busy":"2023-11-24T10:07:18.609167Z","iopub.execute_input":"2023-11-24T10:07:18.609670Z","iopub.status.idle":"2023-11-24T10:07:21.621278Z","shell.execute_reply.started":"2023-11-24T10:07:18.609632Z","shell.execute_reply":"2023-11-24T10:07:21.619767Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"asset_details.Asset_ID, asset_details.Asset_Name\n","metadata":{"execution":{"iopub.status.busy":"2023-11-24T10:07:29.727267Z","iopub.execute_input":"2023-11-24T10:07:29.727630Z","iopub.status.idle":"2023-11-24T10:07:29.737855Z","shell.execute_reply.started":"2023-11-24T10:07:29.727599Z","shell.execute_reply":"2023-11-24T10:07:29.736376Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.imshow(all_assets_2021.corr());\nplt.yticks(range(14), asset_details.Asset_Name.values);\nplt.xticks(range(14), asset_details.Asset_Name.values, rotation='vertical');\nplt.colorbar();","metadata":{"execution":{"iopub.status.busy":"2023-11-24T10:08:21.364177Z","iopub.execute_input":"2023-11-24T10:08:21.364676Z","iopub.status.idle":"2023-11-24T10:08:21.792647Z","shell.execute_reply.started":"2023-11-24T10:08:21.364642Z","shell.execute_reply":"2023-11-24T10:08:21.790805Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Building our prediction model\n### Feature design\nFirst we will design few relevant features to input into our model.","metadata":{"execution":{"iopub.status.busy":"2023-11-24T10:13:06.955459Z","iopub.execute_input":"2023-11-24T10:13:06.955905Z","iopub.status.idle":"2023-11-24T10:13:06.963661Z","shell.execute_reply.started":"2023-11-24T10:13:06.955868Z","shell.execute_reply":"2023-11-24T10:13:06.961978Z"}}},{"cell_type":"code","source":"# Select some input features from the trading data: \n# 5 min log return, abs(5 min log return), upper shadow, and lower shadow.\nupper_shadow = lambda asset: asset.High - np.maximum(asset.Close,asset.Open)\nlower_shadow = lambda asset: np.minimum(asset.Close,asset.Open)- asset.Low\n\nX_btc = pd.concat([log_return(btc.VWAP,periods=5), log_return(btc.VWAP,periods=1).abs(), \n               upper_shadow(btc), lower_shadow(btc)], axis=1)\ny_btc = btc.Target\n\nX_eth = pd.concat([log_return(eth.VWAP,periods=5), log_return(eth.VWAP,periods=1).abs(), \n               upper_shadow(eth), lower_shadow(eth)], axis=1)\ny_eth = eth.Target","metadata":{"execution":{"iopub.status.busy":"2023-11-24T10:13:36.771201Z","iopub.execute_input":"2023-11-24T10:13:36.771594Z","iopub.status.idle":"2023-11-24T10:13:36.891229Z","shell.execute_reply.started":"2023-11-24T10:13:36.771565Z","shell.execute_reply":"2023-11-24T10:13:36.889961Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### Preparing the data for building predictive models\nThe first model we are going to try is the basic Linear Regression. As we will train linear regression parameters, we need to separate training and test sets. To do so, we will compute X and y and split this data into train and test splits.","metadata":{}},{"cell_type":"code","source":"# select training and test periods\ntrain_window = [totimestamp(\"01/05/2021\"), totimestamp(\"30/05/2021\")]\ntest_window = [totimestamp(\"01/06/2021\"), totimestamp(\"30/06/2021\")]\n\n# divide data into train and test, compute X and y\n# we aim to build simple regression models using a window_size of 1\nX_btc_train = X_btc.loc[train_window[0]:train_window[1]].fillna(0).to_numpy()  # filling NaN's with zeros\ny_btc_train = y_btc.loc[train_window[0]:train_window[1]].fillna(0).to_numpy()  \n\nX_btc_test = X_btc.loc[test_window[0]:test_window[1]].fillna(0).to_numpy() \ny_btc_test = y_btc.loc[test_window[0]:test_window[1]].fillna(0).to_numpy() \n\nX_eth_train = X_eth.loc[train_window[0]:train_window[1]].fillna(0).to_numpy()  \ny_eth_train = y_eth.loc[train_window[0]:train_window[1]].fillna(0).to_numpy()  \n\nX_eth_test = X_eth.loc[test_window[0]:test_window[1]].fillna(0).to_numpy() \ny_eth_test = y_eth.loc[test_window[0]:test_window[1]].fillna(0).to_numpy() ","metadata":{"execution":{"iopub.status.busy":"2023-11-24T10:16:09.081792Z","iopub.execute_input":"2023-11-24T10:16:09.082205Z","iopub.status.idle":"2023-11-24T10:16:09.097021Z","shell.execute_reply.started":"2023-11-24T10:16:09.082156Z","shell.execute_reply":"2023-11-24T10:16:09.095302Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"We will now standarize the input data. Standarization is the process of putting different variables on the same scale. In regression analysis, it is often crucial to standarize our independent variables or we may risk obtaining misleading results.","metadata":{}},{"cell_type":"code","source":"from sklearn.preprocessing import StandardScaler\n# simple preprocessing of the data \nscaler = StandardScaler()#using StandardScalar() as it is Robust scalar\nX_btc_train_scaled = scaler.fit_transform(X_btc_train)\nX_btc_test_scaled = scaler.transform(X_btc_test)\n\nX_eth_train_scaled = scaler.fit_transform(X_eth_train)\nX_eth_test_scaled = scaler.transform(X_eth_test)","metadata":{"execution":{"iopub.status.busy":"2023-11-24T10:17:50.693674Z","iopub.execute_input":"2023-11-24T10:17:50.694228Z","iopub.status.idle":"2023-11-24T10:17:50.708578Z","shell.execute_reply.started":"2023-11-24T10:17:50.694164Z","shell.execute_reply":"2023-11-24T10:17:50.706490Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"We wil try simple Linear Regression on the features we designed, first we will consider each asset independently and then one multiple inputs that models all assets together.\nWe will also compare both of them.","metadata":{"execution":{"iopub.status.busy":"2023-11-24T10:20:00.600586Z","iopub.execute_input":"2023-11-24T10:20:00.601404Z","iopub.status.idle":"2023-11-24T10:20:00.608121Z","shell.execute_reply.started":"2023-11-24T10:20:00.601363Z","shell.execute_reply":"2023-11-24T10:20:00.606320Z"}}},{"cell_type":"code","source":"from sklearn.linear_model import LinearRegression\n\n# implementing basic ML baseline (one per asset)\nlr = LinearRegression()\nlr.fit(X_btc_train_scaled,y_btc_train)\ny_pred_lr_btc = lr.predict(X_btc_test_scaled)\n\nlr.fit(X_eth_train_scaled,y_eth_train)\ny_pred_lr_eth = lr.predict(X_eth_test_scaled)","metadata":{"execution":{"iopub.status.busy":"2023-11-24T10:20:03.925077Z","iopub.execute_input":"2023-11-24T10:20:03.925467Z","iopub.status.idle":"2023-11-24T10:20:04.098433Z","shell.execute_reply.started":"2023-11-24T10:20:03.925438Z","shell.execute_reply":"2023-11-24T10:20:04.097441Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# implementing more complex baseline (multiple input/output regression model)\nfrom sklearn.multioutput import MultiOutputRegressor\n\n# we concatenate X and y for both assets\nX_both_train = np.concatenate((X_btc_train_scaled, X_eth_train_scaled), axis=1)\nX_both_test = np.concatenate((X_btc_test_scaled, X_eth_test_scaled), axis=1)\ny_both_train = np.column_stack((y_btc_train, y_eth_train))\ny_both_test = np.column_stack((y_btc_test, y_eth_test))\n\n# define the direct multioutput model and fit it\nmlr = MultiOutputRegressor(LinearRegression())\nmlr.fit(X_both_train,y_both_train)\ny_pred_lr_both = mlr.predict(X_both_test)","metadata":{"execution":{"iopub.status.busy":"2023-11-24T10:20:53.362531Z","iopub.execute_input":"2023-11-24T10:20:53.362908Z","iopub.status.idle":"2023-11-24T10:20:53.399821Z","shell.execute_reply.started":"2023-11-24T10:20:53.362881Z","shell.execute_reply":"2023-11-24T10:20:53.398978Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### Evaluating our models\nHere we are using a simple correlation metric to evaluate the two baseline models built.","metadata":{"execution":{"iopub.status.busy":"2023-11-24T10:21:51.419115Z","iopub.execute_input":"2023-11-24T10:21:51.419516Z","iopub.status.idle":"2023-11-24T10:21:51.423626Z","shell.execute_reply.started":"2023-11-24T10:21:51.419488Z","shell.execute_reply":"2023-11-24T10:21:51.422711Z"}}},{"cell_type":"code","source":"print('Test score for LR baseline: BTC', f\"{np.corrcoef(y_pred_lr_btc, y_btc_test)[0,1]:.2f}\", \n                                ', ETH', f\"{np.corrcoef(y_pred_lr_eth, y_eth_test)[0,1]:.2f}\")\nprint('Test score for multiple output LR baseline: BTC', f\"{np.corrcoef(y_pred_lr_both[:,0], y_btc_test)[0,1]:.2f}\", \n                                                ', ETH', f\"{np.corrcoef(y_pred_lr_both[:,1], y_eth_test)[0,1]:.2f}\")","metadata":{"execution":{"iopub.status.busy":"2023-11-24T10:22:04.485630Z","iopub.execute_input":"2023-11-24T10:22:04.485997Z","iopub.status.idle":"2023-11-24T10:22:04.497612Z","shell.execute_reply.started":"2023-11-24T10:22:04.485973Z","shell.execute_reply":"2023-11-24T10:22:04.496035Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"We can see that, for the training and test periods selected, the multiple asset LR model performs better than simply modelling each asset separately. Note that because the data is highly non-stationary, these results might vary a lot for different periods.","metadata":{}},{"cell_type":"code","source":"","metadata":{"execution":{"iopub.status.busy":"2023-11-24T10:31:02.021535Z","iopub.execute_input":"2023-11-24T10:31:02.021929Z","iopub.status.idle":"2023-11-24T10:31:03.131411Z","shell.execute_reply.started":"2023-11-24T10:31:02.021901Z","shell.execute_reply":"2023-11-24T10:31:03.130221Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}