{"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":"markdown","source":"# **Crypto forecasting tutorial**","metadata":{"id":"8PNZS8gF3CVN"}},{"cell_type":"markdown","source":"# Dataset description\n\nNow, let's dive into the data! We start by loading the competition's dataset and inspecting its basic properties. ","metadata":{"id":"4e6OA0qc6x9h"}},{"cell_type":"markdown","source":"## Load the training set","metadata":{"id":"OevdFjmtar0j"}},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nfrom datetime import datetime","metadata":{"id":"90fqnpNQ2wd8","execution":{"iopub.status.busy":"2022-01-10T14:05:04.181146Z","iopub.execute_input":"2022-01-10T14:05:04.181502Z","iopub.status.idle":"2022-01-10T14:05:04.206365Z","shell.execute_reply.started":"2022-01-10T14:05:04.181400Z","shell.execute_reply":"2022-01-10T14:05:04.205684Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_folder = \"../input/g-research-crypto-forecasting/\"\n!ls $data_folder","metadata":{"id":"Zw_oi4NETkKv","outputId":"e6fe292d-721e-4c6a-bc70-9026cfd5b915","execution":{"iopub.status.busy":"2022-01-10T14:05:04.207984Z","iopub.execute_input":"2022-01-10T14:05:04.208498Z","iopub.status.idle":"2022-01-10T14:05:05.010228Z","shell.execute_reply.started":"2022-01-10T14:05:04.208456Z","shell.execute_reply":"2022-01-10T14:05:05.009171Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"crypto_df = pd.read_csv(data_folder + 'train.csv')","metadata":{"id":"La0-ivRAUopA","scrolled":true,"execution":{"iopub.status.busy":"2022-01-10T14:05:05.013263Z","iopub.execute_input":"2022-01-10T14:05:05.013942Z","iopub.status.idle":"2022-01-10T14:05:57.633971Z","shell.execute_reply.started":"2022-01-10T14:05:05.013893Z","shell.execute_reply":"2022-01-10T14:05:57.633358Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"crypto_df.head(10)","metadata":{"id":"14ZSPE6daadW","outputId":"b6a4f262-4071-4c2f-dd42-12a253452297","execution":{"iopub.status.busy":"2022-01-10T14:05:57.635785Z","iopub.execute_input":"2022-01-10T14:05:57.636040Z","iopub.status.idle":"2022-01-10T14:05:57.663680Z","shell.execute_reply.started":"2022-01-10T14:05:57.636009Z","shell.execute_reply":"2022-01-10T14:05:57.662782Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"We can see that each row of the data set has the trading data for an asset, at a given minute timestamp, described in detail below. ","metadata":{"id":"ZUPxDsW8bCh1"}},{"cell_type":"markdown","source":"## Data features\nWe can see the different features included in the dataset. Specifically, the features included per asset are the following:\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**:\tOpening price of the time interval (in USD).\n*   **High**:\tHighest price reached during time interval (in USD).\n*   **Low**: Lowest price reached during time interval (in USD).\n*   **Close**:\tClosing price of the time interval (in USD).\n*   **Volume**:\tQuantity 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.","metadata":{"id":"YjN-TfBUx2ml"}},{"cell_type":"code","source":"asset_details = pd.read_csv(data_folder + 'asset_details.csv')\nasset_details","metadata":{"execution":{"iopub.status.busy":"2022-01-10T14:05:57.664903Z","iopub.execute_input":"2022-01-10T14:05:57.665188Z","iopub.status.idle":"2022-01-10T14:05:57.680585Z","shell.execute_reply.started":"2022-01-10T14:05:57.665156Z","shell.execute_reply":"2022-01-10T14:05:57.679721Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Candlestick charts\n\nThe trading data format is an aggregated form of market data including for Open, High, Low and Close. We can visualize this data through the commonly used candlestick bar chart, which allows traders to perform technical analysis on intraday values. The bar's body length represents the price range between the open and close of that day's trading. When 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. The wicks above and below the bars show the high and low prices of that interval's trading.","metadata":{"id":"QNWAfs_O0hyf"}},{"cell_type":"markdown","source":"We can visualize a slice of the Bitcoin prices using the `plotly` library. The bottom part of the plot shows a rangeslider, which you can use to zoom in the plot.","metadata":{"id":"570DeXQa0skY"}},{"cell_type":"code","source":"import plotly.graph_objects as go","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Binance Coin**","metadata":{}},{"cell_type":"code","source":"btc = crypto_df[crypto_df[\"Asset_ID\"]==0].set_index(\"timestamp\") # Asset_ID = 1 for Bitcoin\nbtc_mini = btc.iloc[-200:] # Select recent data rows\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_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Bitcoin**","metadata":{}},{"cell_type":"code","source":"btc = crypto_df[crypto_df[\"Asset_ID\"]==1].set_index(\"timestamp\") # Asset_ID = 1 for Bitcoin\nbtc_mini = btc.iloc[-200:] # Select recent data rows\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":{"id":"tMxYx8ZO3fuy","execution":{"iopub.status.busy":"2022-01-10T14:05:57.681690Z","iopub.execute_input":"2022-01-10T14:05:57.682068Z","iopub.status.idle":"2022-01-10T14:05:57.983248Z","shell.execute_reply.started":"2022-01-10T14:05:57.682036Z","shell.execute_reply":"2022-01-10T14:05:57.982457Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Bitcoin Cash**","metadata":{}},{"cell_type":"code","source":"btc = crypto_df[crypto_df[\"Asset_ID\"]==2].set_index(\"timestamp\") # Asset_ID = 1 for Bitcoin\nbtc_mini = btc.iloc[-200:] # Select recent data rows\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":{"id":"tMxYx8ZO3fuy","execution":{"iopub.status.busy":"2022-01-10T14:05:57.681690Z","iopub.execute_input":"2022-01-10T14:05:57.682068Z","iopub.status.idle":"2022-01-10T14:05:57.983248Z","shell.execute_reply.started":"2022-01-10T14:05:57.682036Z","shell.execute_reply":"2022-01-10T14:05:57.982457Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Cardano**","metadata":{}},{"cell_type":"code","source":"btc = crypto_df[crypto_df[\"Asset_ID\"]==3].set_index(\"timestamp\") # Asset_ID = 1 for Bitcoin\nbtc_mini = btc.iloc[-200:] # Select recent data rows\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":{"id":"tMxYx8ZO3fuy","execution":{"iopub.status.busy":"2022-01-10T14:05:57.681690Z","iopub.execute_input":"2022-01-10T14:05:57.682068Z","iopub.status.idle":"2022-01-10T14:05:57.983248Z","shell.execute_reply.started":"2022-01-10T14:05:57.682036Z","shell.execute_reply":"2022-01-10T14:05:57.982457Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Dogecoin**","metadata":{}},{"cell_type":"code","source":"btc = crypto_df[crypto_df[\"Asset_ID\"]==4].set_index(\"timestamp\") # Asset_ID = 1 for Bitcoin\nbtc_mini = btc.iloc[-200:] # Select recent data rows\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":{"id":"tMxYx8ZO3fuy","execution":{"iopub.status.busy":"2022-01-10T14:05:57.681690Z","iopub.execute_input":"2022-01-10T14:05:57.682068Z","iopub.status.idle":"2022-01-10T14:05:57.983248Z","shell.execute_reply.started":"2022-01-10T14:05:57.682036Z","shell.execute_reply":"2022-01-10T14:05:57.982457Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**EOS.IO**","metadata":{}},{"cell_type":"code","source":"btc = crypto_df[crypto_df[\"Asset_ID\"]==5].set_index(\"timestamp\") # Asset_ID = 1 for Bitcoin\nbtc_mini = btc.iloc[-200:] # Select recent data rows\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":{"id":"tMxYx8ZO3fuy","execution":{"iopub.status.busy":"2022-01-10T14:05:57.681690Z","iopub.execute_input":"2022-01-10T14:05:57.682068Z","iopub.status.idle":"2022-01-10T14:05:57.983248Z","shell.execute_reply.started":"2022-01-10T14:05:57.682036Z","shell.execute_reply":"2022-01-10T14:05:57.982457Z"}},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Ethereum**","metadata":{}},{"cell_type":"code","source":"btc = crypto_df[crypto_df[\"Asset_ID\"]==6].set_index(\"timestamp\") # Asset_ID = 1 for Bitcoin\nbtc_mini = btc.iloc[-200:] # Select recent data rows\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":{"id":"tMxYx8ZO3fuy","execution":{"iopub.status.busy":"2022-01-10T14:05:57.681690Z","iopub.execute_input":"2022-01-10T14:05:57.682068Z","iopub.status.idle":"2022-01-10T14:05:57.983248Z","shell.execute_reply.started":"2022-01-10T14:05:57.682036Z","shell.execute_reply":"2022-01-10T14:05:57.982457Z"}},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Ethereum Classic**","metadata":{}},{"cell_type":"code","source":"btc = crypto_df[crypto_df[\"Asset_ID\"]==7].set_index(\"timestamp\") # Asset_ID = 1 for Bitcoin\nbtc_mini = btc.iloc[-200:] # Select recent data rows\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":{"id":"tMxYx8ZO3fuy","execution":{"iopub.status.busy":"2022-01-10T14:05:57.681690Z","iopub.execute_input":"2022-01-10T14:05:57.682068Z","iopub.status.idle":"2022-01-10T14:05:57.983248Z","shell.execute_reply.started":"2022-01-10T14:05:57.682036Z","shell.execute_reply":"2022-01-10T14:05:57.982457Z"}},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**IOTA**","metadata":{}},{"cell_type":"code","source":"btc = crypto_df[crypto_df[\"Asset_ID\"]==8].set_index(\"timestamp\") # Asset_ID = 1 for Bitcoin\nbtc_mini = btc.iloc[-200:] # Select recent data rows\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":{"id":"tMxYx8ZO3fuy","execution":{"iopub.status.busy":"2022-01-10T14:05:57.681690Z","iopub.execute_input":"2022-01-10T14:05:57.682068Z","iopub.status.idle":"2022-01-10T14:05:57.983248Z","shell.execute_reply.started":"2022-01-10T14:05:57.682036Z","shell.execute_reply":"2022-01-10T14:05:57.982457Z"}},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Litecoin**","metadata":{}},{"cell_type":"code","source":"btc = crypto_df[crypto_df[\"Asset_ID\"]==9].set_index(\"timestamp\") # Asset_ID = 1 for Bitcoin\nbtc_mini = btc.iloc[-200:] # Select recent data rows\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":{"id":"tMxYx8ZO3fuy","execution":{"iopub.status.busy":"2022-01-10T14:05:57.681690Z","iopub.execute_input":"2022-01-10T14:05:57.682068Z","iopub.status.idle":"2022-01-10T14:05:57.983248Z","shell.execute_reply.started":"2022-01-10T14:05:57.682036Z","shell.execute_reply":"2022-01-10T14:05:57.982457Z"}},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Maker**","metadata":{}},{"cell_type":"code","source":"btc = crypto_df[crypto_df[\"Asset_ID\"]==10].set_index(\"timestamp\") # Asset_ID = 1 for Bitcoin\nbtc_mini = btc.iloc[-200:] # Select recent data rows\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":{"id":"tMxYx8ZO3fuy","execution":{"iopub.status.busy":"2022-01-10T14:05:57.681690Z","iopub.execute_input":"2022-01-10T14:05:57.682068Z","iopub.status.idle":"2022-01-10T14:05:57.983248Z","shell.execute_reply.started":"2022-01-10T14:05:57.682036Z","shell.execute_reply":"2022-01-10T14:05:57.982457Z"}},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Monero**","metadata":{}},{"cell_type":"code","source":"btc = crypto_df[crypto_df[\"Asset_ID\"]==11].set_index(\"timestamp\") # Asset_ID = 1 for Bitcoin\nbtc_mini = btc.iloc[-200:] # Select recent data rows\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":{"id":"tMxYx8ZO3fuy","execution":{"iopub.status.busy":"2022-01-10T14:05:57.681690Z","iopub.execute_input":"2022-01-10T14:05:57.682068Z","iopub.status.idle":"2022-01-10T14:05:57.983248Z","shell.execute_reply.started":"2022-01-10T14:05:57.682036Z","shell.execute_reply":"2022-01-10T14:05:57.982457Z"}},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Stellar**","metadata":{}},{"cell_type":"code","source":"btc = crypto_df[crypto_df[\"Asset_ID\"]==12].set_index(\"timestamp\") # Asset_ID = 1 for Bitcoin\nbtc_mini = btc.iloc[-200:] # Select recent data rows\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":{"id":"tMxYx8ZO3fuy","execution":{"iopub.status.busy":"2022-01-10T14:05:57.681690Z","iopub.execute_input":"2022-01-10T14:05:57.682068Z","iopub.status.idle":"2022-01-10T14:05:57.983248Z","shell.execute_reply.started":"2022-01-10T14:05:57.682036Z","shell.execute_reply":"2022-01-10T14:05:57.982457Z"}},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**TRON**","metadata":{}},{"cell_type":"code","source":"btc = crypto_df[crypto_df[\"Asset_ID\"]==13].set_index(\"timestamp\") # Asset_ID = 1 for Bitcoin\nbtc_mini = btc.iloc[-200:] # Select recent data rows\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":{"id":"tMxYx8ZO3fuy","execution":{"iopub.status.busy":"2022-01-10T14:05:57.681690Z","iopub.execute_input":"2022-01-10T14:05:57.682068Z","iopub.status.idle":"2022-01-10T14:05:57.983248Z","shell.execute_reply.started":"2022-01-10T14:05:57.682036Z","shell.execute_reply":"2022-01-10T14:05:57.982457Z"}},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Preprocessing","metadata":{"id":"S-oceNYiivUi"}},{"cell_type":"markdown","source":"## Dealing with missing data\n","metadata":{"id":"K9ce7eWddHfM"}},{"cell_type":"markdown","source":"Let us inspect the data for another important asset, Ethereum.","metadata":{"id":"AOpyJzKgFuYb"}},{"cell_type":"code","source":"eth = crypto_df[crypto_df[\"Asset_ID\"]==6].set_index(\"timestamp\") # Asset_ID = 6 for Ethereum\neth.info(show_counts =True)","metadata":{"id":"cuWT1Suxzjvb","outputId":"04ff726c-8858-4d87-b592-ee1b036f0996","execution":{"iopub.status.busy":"2022-01-10T14:05:58.117764Z","iopub.execute_input":"2022-01-10T14:05:58.117970Z","iopub.status.idle":"2022-01-10T14:05:58.461700Z","shell.execute_reply.started":"2022-01-10T14:05:58.117945Z","shell.execute_reply":"2022-01-10T14:05:58.460883Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"We can see the number of rows in the training set, and that there are missing values for the targets columns, which we will address later. Let's confirm that:\n","metadata":{"id":"3qryFWzMgXgo"}},{"cell_type":"code","source":"eth.isna().sum()","metadata":{"id":"0hVTUf1LflPM","outputId":"4c3c1993-1594-44c2-8457-52e94c199a5f","execution":{"iopub.status.busy":"2022-01-10T14:05:58.462709Z","iopub.execute_input":"2022-01-10T14:05:58.462912Z","iopub.status.idle":"2022-01-10T14:05:58.502912Z","shell.execute_reply.started":"2022-01-10T14:05:58.462887Z","shell.execute_reply":"2022-01-10T14:05:58.502166Z"},"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`.","metadata":{"id":"sJ_CF60EfpQS"}},{"cell_type":"code","source":"btc.head()","metadata":{"execution":{"iopub.status.busy":"2022-01-10T14:05:58.505166Z","iopub.execute_input":"2022-01-10T14:05:58.505398Z","iopub.status.idle":"2022-01-10T14:05:58.520540Z","shell.execute_reply.started":"2022-01-10T14:05:58.505370Z","shell.execute_reply":"2022-01-10T14:05:58.519579Z"},"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":{"id":"YrVaTbdtZ6Qv","outputId":"c640691c-075f-4573-e3a4-ad24ae468f72","execution":{"iopub.status.busy":"2022-01-10T14:05:58.521753Z","iopub.execute_input":"2022-01-10T14:05:58.522347Z","iopub.status.idle":"2022-01-10T14:05:58.531929Z","shell.execute_reply.started":"2022-01-10T14:05:58.522283Z","shell.execute_reply":"2022-01-10T14:05:58.531352Z"},"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":{"id":"4PIgY9dtZ7BX"}},{"cell_type":"code","source":"(eth.index[1:]-eth.index[:-1]).value_counts().head()","metadata":{"id":"KOrD8uIked2c","outputId":"51d9c340-a88c-4476-fdca-cffa8edc5c39","execution":{"iopub.status.busy":"2022-01-10T14:05:58.532989Z","iopub.execute_input":"2022-01-10T14:05:58.533333Z","iopub.status.idle":"2022-01-10T14:05:58.564396Z","shell.execute_reply.started":"2022-01-10T14:05:58.533283Z","shell.execute_reply":"2022-01-10T14:05:58.563595Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Notice 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":{"id":"GFLjIGONhN9s"}},{"cell_type":"code","source":"eth = eth.reindex(range(eth.index[0],eth.index[-1]+60,60),method='pad')","metadata":{"id":"8h29S-1Hhp3Y","execution":{"iopub.status.busy":"2022-01-10T14:05:58.565763Z","iopub.execute_input":"2022-01-10T14:05:58.566456Z","iopub.status.idle":"2022-01-10T14:05:58.878749Z","shell.execute_reply.started":"2022-01-10T14:05:58.566414Z","shell.execute_reply":"2022-01-10T14:05:58.877850Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"And check that are no time gaps now.","metadata":{"id":"4sX6uvcQiCC5"}},{"cell_type":"code","source":"(eth.index[1:]-eth.index[:-1]).value_counts().head()","metadata":{"id":"UDUygkngiBKT","outputId":"c9f12e5c-f07d-4063-c35e-2eec6d692438","execution":{"iopub.status.busy":"2022-01-10T14:05:58.880001Z","iopub.execute_input":"2022-01-10T14:05:58.880261Z","iopub.status.idle":"2022-01-10T14:05:58.913062Z","shell.execute_reply.started":"2022-01-10T14:05:58.880226Z","shell.execute_reply":"2022-01-10T14:05:58.912199Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Data visualisation\n\nWe  will start by visualising the Close prices for the two assets we have selected.","metadata":{"id":"_TcwTqisePHB"}},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n# 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()","metadata":{"id":"PtVHC0YTxq-l","outputId":"525bc0d9-9673-42d0-ab73-aadc5e6afdad","execution":{"iopub.status.busy":"2022-01-10T14:05:58.914203Z","iopub.execute_input":"2022-01-10T14:05:58.914442Z","iopub.status.idle":"2022-01-10T14:06:02.144611Z","shell.execute_reply.started":"2022-01-10T14:05:58.914415Z","shell.execute_reply":"2022-01-10T14:06:02.143678Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"The assets have quite different history, but we could check if they correlate in recent times.","metadata":{"id":"ECfuzVHyzEF2"}},{"cell_type":"code","source":"import time\n\n# auxiliary function, from datetime to timestamp\ntotimestamp = lambda s: np.int32(time.mktime(datetime.strptime(s, \"%d/%m/%Y\").timetuple()))\n\n# create 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":{"id":"mcfpDT6vNzpT","execution":{"iopub.status.busy":"2022-01-10T14:06:02.146150Z","iopub.execute_input":"2022-01-10T14:06:02.146645Z","iopub.status.idle":"2022-01-10T14:06:02.154789Z","shell.execute_reply.started":"2022-01-10T14:06:02.146602Z","shell.execute_reply":"2022-01-10T14:06:02.153768Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# plot 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":{"id":"EfZiXb74zQsK","outputId":"5039e885-cb14-487f-fe06-3a30e4cf7270","execution":{"iopub.status.busy":"2022-01-10T14:06:02.155897Z","iopub.execute_input":"2022-01-10T14:06:02.156154Z","iopub.status.idle":"2022-01-10T14:06:02.621819Z","shell.execute_reply.started":"2022-01-10T14:06:02.156123Z","shell.execute_reply":"2022-01-10T14:06:02.621241Z"},"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 movements is by calculating asset returns. ","metadata":{"id":"O2-jEU3wPnNV"}},{"cell_type":"markdown","source":"## Log returns\n\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.","metadata":{"id":"6WpWqQ-EReg2"}},{"cell_type":"code","source":"# define function to compute log returns\ndef log_return(series, periods=1):\n    return np.log(series).diff(periods=periods)","metadata":{"id":"DBg185h-SOwI","execution":{"iopub.status.busy":"2022-01-10T14:06:02.622844Z","iopub.execute_input":"2022-01-10T14:06:02.623154Z","iopub.status.idle":"2022-01-10T14:06:02.626784Z","shell.execute_reply.started":"2022-01-10T14:06:02.623125Z","shell.execute_reply":"2022-01-10T14:06:02.626316Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"We can visualize the log return for our two assets. See how the signal now looks more like white noise, with less drift than the time series for prices.","metadata":{"id":"pdAR2fjIrCge"}},{"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":{"id":"9WYTbi-LrDOM","outputId":"797d73c3-a320-4376-c1ff-4607a1adea29","execution":{"iopub.status.busy":"2022-01-10T14:06:02.627813Z","iopub.execute_input":"2022-01-10T14:06:02.628100Z","iopub.status.idle":"2022-01-10T14:06:03.709299Z","shell.execute_reply.started":"2022-01-10T14:06:02.628075Z","shell.execute_reply":"2022-01-10T14:06:03.708671Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Correlation between assets\n\nWe hypothesized before that crypto asset returns may exhibit some correlation. Let's check 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":{"id":"DnAM1L8dj5ir"}},{"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":{"id":"pDB4cVz2u_kC","outputId":"7c483562-4cbd-46a1-d16d-94b3bc69d2c3","execution":{"iopub.status.busy":"2022-01-10T14:06:03.710453Z","iopub.execute_input":"2022-01-10T14:06:03.710809Z","iopub.status.idle":"2022-01-10T14:06:04.223154Z","shell.execute_reply.started":"2022-01-10T14:06:03.710767Z","shell.execute_reply":"2022-01-10T14:06:04.222281Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Note the high but variable correlation between the assets. Here we can see that there is some changing dynamics over time, and this would be critical for this time series challenge, that is, how to perform forecasts in a highly non-stationary environment.\n\nA stationary behaviour of a system or a process is characterized by non-changing statistical properties over time such as the mean, variance and autocorrelation. On the other hand, a non-stationary behaviour is characterized by a continuous change of statistical properties over time. Stationarity is important because many useful analytical tools and statistical tests and models rely on it.\n\nWe can also check the correlation between all assets visualizing the correlation matrix. Note how some assets have much higher pairwise correlation than others.","metadata":{"id":"oc7qBUdszXZf"}},{"cell_type":"code","source":"# create 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":{"id":"Dzv6CD3nz57z","execution":{"iopub.status.busy":"2022-01-10T14:06:04.224666Z","iopub.execute_input":"2022-01-10T14:06:04.225233Z","iopub.status.idle":"2022-01-10T14:06:04.604771Z","shell.execute_reply.started":"2022-01-10T14:06:04.225183Z","shell.execute_reply":"2022-01-10T14:06:04.603507Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.imshow(all_assets_2021.corr());\nplt.yticks(asset_details.Asset_ID.values, asset_details.Asset_Name.values);\nplt.xticks(asset_details.Asset_ID.values, asset_details.Asset_Name.values, rotation='vertical');\nplt.colorbar();","metadata":{"execution":{"iopub.status.busy":"2022-01-10T14:06:04.605544Z","iopub.status.idle":"2022-01-10T14:06:04.605838Z","shell.execute_reply.started":"2022-01-10T14:06:04.605685Z","shell.execute_reply":"2022-01-10T14:06:04.605701Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"We encourage participants to perform additional statistical analyses to have a stronger grasp on the dataset, including autocorrelation, time-series decomposition and stationarity tests.","metadata":{}}]}