{"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":"!pip -q install mplfinance\n!pip -q install --upgrade ta\n\n\nfrom IPython.core.display import display, HTML, Javascript\nfrom datetime import datetime\nimport os\nfrom IPython.core.display import display, HTML\nfrom sklearn.preprocessing import StandardScaler, RobustScaler, MinMaxScaler\n\nimport matplotlib.ticker as mtick\nimport warnings\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom pandas_profiling import ProfileReport\nimport warnings\nwarnings.simplefilter(action='ignore', category=FutureWarning)\n\nimport mplfinance as mpf\n\n\nfrom inspect import getmembers\nfrom pprint import pprint\nfrom ta import add_all_ta_features\n\n\n\n%matplotlib inline\nplt.rcParams['figure.figsize'] = (10, 8)\nplt.style.use('bmh')\n\n\n\n\nwarnings.simplefilter(action='ignore', category=FutureWarning)\n\ndisplay(HTML(\"<style>.container { width:100% !important; }</style>\"))\npd.set_option('display.max_rows', 500)  # Max. number of rows to display    ","metadata":{"execution":{"iopub.status.busy":"2021-11-21T17:30:49.617687Z","iopub.execute_input":"2021-11-21T17:30:49.618223Z","iopub.status.idle":"2021-11-21T17:31:05.833523Z","shell.execute_reply.started":"2021-11-21T17:30:49.618191Z","shell.execute_reply":"2021-11-21T17:31:05.832844Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<br><br>\n<div>    \n<!--     <div style = \"float:left; width:55%; overflow:hidden;\">         -->\n        <center><img src=\"https://storage.googleapis.com/kaggle-competitions/kaggle/30894/logos/header.png\" style = \"max-height:300px;\"></center> \n<!--     </div> -->\n<!--     <div style = \"float:right; width:35%; overflow:hidden;\"> -->\n<!--         <img src=\"img/meditation/Meditation3.gif\">  -->\n<!--     </div> -->\n</div>","metadata":{}},{"cell_type":"markdown","source":"# Utils","metadata":{}},{"cell_type":"code","source":"def reduce_mem_usage(df):\n    \"\"\" iterate through all the columns of a dataframe and modify the data type\n        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.float32)\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\n\ndef search_null(data):\n    n=data.isnull().sum().where(lambda _ : _ > 0).dropna()\n    df = pd.DataFrame({'columns':n.index, 'count nulls':n.values})\n    df[\"% Total\"] = (df[\"count nulls\"] /  data.shape[0]).round(4)*100.00\n    return df    \n\ndef group_trading_timeseries(df, time_step_size):\n    df = df.sort_index()\n    df = df.resample('{}'.format(time_step_size)).agg({\n            'Count': lambda df: df.sum(),\n            'Open': lambda s: s.iloc[0] ,\n            'High': lambda df: df.max(), \n            'Low': lambda df: df.min(),\n            'Close': lambda df: df.iloc[-1], \n            'Volume': lambda df: df.sum(),\n            'VWAP' : lambda df: df.mean(),\n            'Target' : lambda df: df.mean()\n            }) \n    return df \n\ndef open_resampler(arraylike):\n    nrows = arraylike.shape[0]\n    if nrows == 0:\n        return np.nan\n    else:\n        return arraylike.iloc[0]\n\ndef close_resampler(arraylike):\n    nrows = arraylike.shape[0]\n    if nrows == 0:\n        return np.nan\n    else:\n        return arraylike.iloc[-1]\n\ndef group_trading_timeseries_all(df, time_step_size):\n    df = df.sort_values([\"Asset_ID\", \"timestamp\"], ascending = (False, True))\n    df = df.groupby(\"Asset_ID\").resample('{}'.format(time_step_size)).agg({\n            'Count': lambda df: df.sum(),\n            'Open': open_resampler,\n            'High': lambda df: df.max(), \n            'Low': lambda df: df.min(),\n             'Close': close_resampler,\n            'Volume': lambda df: df.sum(),\n            'VWAP' : lambda df: df.mean(),\n            'Target' : lambda df: df.mean()\n            }) \n    return df \n\ndef update_indicator_property(indicators, name, prop, value):\n    for indicator in indicators:\n        if indicator.name == name:\n            indicator.__setattr__(prop, value)\n            break\n\ndef filter_indicators(indicators, filter_list=[], filter_wildcard=\"*\"):\n    if filter_wildcard != \"*\" and len(filter_list) ==0:\n        return [indicator for indicator in indicators if (indicator.name.startswith(filter_wildcard) and (indicator.is_support_indicator == False) )   ]\n    elif filter_wildcard != \"*\" and len(filter_list) >0:\n        return [indicator for indicator in indicators if (indicator.name.startswith(filter_wildcard) and (indicator.is_support_indicator == False) and \n                                                         ((indicator.name in filter_list) and (indicator.is_support_indicator == False) ) )   ]\n    else:\n        return [indicator for indicator in indicators if ((indicator.name in filter_list)  )   ]\n\ndef plot_candle_indicators(df, indicators,coin, step_size=10):\n\n    part_no = 1\n    for i in range(0,len(indicators),step_size):\n        indicators_step = indicators[i:i+step_size]\n        ap0 = []\n        start=2\n        panel_ratios_list=[]\n        panel_ratios_list.append(4)\n        panel_ratios_list.append(2)\n\n        for indicator in indicators_step:\n\n            ap0.append(mpf.make_addplot(df[indicator.name], color=indicator.color, panel=start, type=indicator.chart, ylabel=\"_\".join(indicator.name.split(\"_\")[1:])))\n            ap0.append(mpf.make_addplot(df.VWAP,panel=0,color='fuchsia',secondary_y=True))\n            #plot limits \n            if str(indicator.lower_limit) != \"nan\":\n                lower_limit= df[indicator.name].copy(deep=True)\n                lower_limit.values[:] = indicator.lower_limit\n                ap0.append(mpf.make_addplot(lower_limit, color=\"r\", panel=start, type=\"line\"))\n\n                \n            if str(indicator.upper_limit) != \"nan\":\n                upper_limit= df[indicator.name].copy(deep=True)\n                upper_limit.values[:] = indicator.upper_limit\n                ap0.append(mpf.make_addplot(upper_limit, color=\"r\", panel=start, type=\"line\"))\n\n\n            for support_indicator in indicator.support_indicators:\n                #print(support_indicator.color)\n                ap0.append(mpf.make_addplot(df[support_indicator.name], color=support_indicator.color, panel=start, secondary_y=support_indicator.secondary_y, type=support_indicator.chart, ylabel=\"_\".join(support_indicator.name.split(\"_\")[1:])))\n                \n            start+=1\n            panel_ratios_list.append(2)\n        #print(\"panels ratios: \", panel_ratios_list)\n        mpf.plot(df, type='candle', figscale=3.2, style='nightclouds', title=coin+\"- part \"+str(part_no),addplot=ap0,  volume=True,main_panel=0,volume_panel=1)#, panel_ratios=tuple(panel_ratios_list))\n        part_no+=1","metadata":{"execution":{"iopub.status.busy":"2021-11-21T17:31:05.835313Z","iopub.execute_input":"2021-11-21T17:31:05.83562Z","iopub.status.idle":"2021-11-21T17:31:05.86786Z","shell.execute_reply.started":"2021-11-21T17:31:05.835586Z","shell.execute_reply":"2021-11-21T17:31:05.867122Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Load dataset","metadata":{}},{"cell_type":"code","source":"data_folder = \"../input/g-research-crypto-forecasting/\"\nset_parameter_csv = {'sep': ',', 'encoding': 'ISO-8859-1', 'low_memory': True}\ncrypto_df = pd.read_csv('{}'.format(data_folder + 'train.csv'),      **set_parameter_csv)\ncrypto_df = reduce_mem_usage(crypto_df)\nasset_details = pd.read_csv(data_folder + 'asset_details.csv')\ncrypto_df = crypto_df.merge(asset_details, how='left', left_on=\"Asset_ID\", right_on=\"Asset_ID\").copy(deep=True)\nasset_names_dict = {row[\"Asset_ID\"]:row[\"Asset_Name\"] for ind, row in asset_details.iterrows()}\ncrypto_df[\"date\"] = crypto_df[\"timestamp\"].astype('datetime64[s]')\ncrypto_df.set_index(\"date\", inplace=True)   # Set index to timestamp    \n\ndisplay(crypto_df.head(3))\n","metadata":{"execution":{"iopub.status.busy":"2021-11-21T17:31:05.870094Z","iopub.execute_input":"2021-11-21T17:31:05.870411Z","iopub.status.idle":"2021-11-21T17:32:10.232999Z","shell.execute_reply.started":"2021-11-21T17:31:05.870371Z","shell.execute_reply":"2021-11-21T17:32:10.232079Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Data Dictionary","metadata":{}},{"cell_type":"markdown","source":"<div class=\"alert alert-block alert-warning\">\n<b>References:</b>\n<ul>\n    <li><a href = \"https://www.kaggle.com/c/g-research-crypto-forecasting/data\">Crypto-forecasting data dictionary</a></li>\n</ul>\n</div>","metadata":{}},{"cell_type":"markdown","source":"# Data Profiling","metadata":{}},{"cell_type":"code","source":"profile_crypto = ProfileReport(crypto_df, title=\"Crypto -  Data Integrity & Profiling Report_df\" , minimal=True)\nprofile_crypto.to_notebook_iframe()","metadata":{"execution":{"iopub.status.busy":"2021-11-21T17:43:31.36597Z","iopub.execute_input":"2021-11-21T17:43:31.366712Z","iopub.status.idle":"2021-11-21T17:43:32.579785Z","shell.execute_reply.started":"2021-11-21T17:43:31.366682Z","shell.execute_reply":"2021-11-21T17:43:32.578703Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Nulls","metadata":{}},{"cell_type":"code","source":"search_null(crypto_df).sort_values(by='% Total', ascending=False)","metadata":{"execution":{"iopub.status.busy":"2021-11-21T17:34:46.323512Z","iopub.execute_input":"2021-11-21T17:34:46.323698Z","iopub.status.idle":"2021-11-21T17:34:47.515934Z","shell.execute_reply.started":"2021-11-21T17:34:46.323673Z","shell.execute_reply":"2021-11-21T17:34:47.515098Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Data Exploration","metadata":{}},{"cell_type":"markdown","source":"## Mean Close Price by Asset","metadata":{}},{"cell_type":"markdown","source":"BTC is by far the best valued currency\n","metadata":{}},{"cell_type":"code","source":"fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(8, 5))\n\ndata_agg=crypto_df[[\"Asset_Name\",\"Close\"]].groupby(\"Asset_Name\")[\"Close\"].agg([\"mean\"])\ndata_agg=data_agg.sort_values(by='mean',ascending=False)\ndata_agg.plot(kind=\"bar\", ax=ax, color=\"blue\", title=\"Mean Close Price by Asset\")","metadata":{"execution":{"iopub.status.busy":"2021-11-21T17:34:47.517012Z","iopub.execute_input":"2021-11-21T17:34:47.517253Z","iopub.status.idle":"2021-11-21T17:34:50.425513Z","shell.execute_reply.started":"2021-11-21T17:34:47.517221Z","shell.execute_reply":"2021-11-21T17:34:50.424399Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Boxplot by Asset and Year","metadata":{}},{"cell_type":"markdown","source":"We can see a high pump in 2020-2021 in all assets","metadata":{}},{"cell_type":"code","source":"\nstart = 0\n\nfig, ax = plt.subplots(nrows=5, ncols=3, figsize=(30, 25))\n\nfor j in range(5):\n    for i in range(3):\n        if start == len(asset_names_dict):\n            break \n        crypto_df_filtered = crypto_df[crypto_df[\"Asset_ID\"]==start]\n        crypto_df_filtered = crypto_df_filtered[\"Close\"].groupby(pd.Grouper(freq='A'))\n        years = pd.DataFrame()\n\n        for name, group in crypto_df_filtered:\n            years[name.year] = pd.Series( group.values )\n\n        g= sns.boxplot( data=years, ax=ax[j,i])\n        g.set_title(asset_names_dict[start])    \n        start += 1\nfig.tight_layout(pad=0.2)","metadata":{"execution":{"iopub.status.busy":"2021-11-21T17:34:50.427219Z","iopub.execute_input":"2021-11-21T17:34:50.427544Z","iopub.status.idle":"2021-11-21T17:35:01.725227Z","shell.execute_reply.started":"2021-11-21T17:34:50.427514Z","shell.execute_reply":"2021-11-21T17:35:01.724109Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## BTC VS ALT Coins","metadata":{}},{"cell_type":"markdown","source":"It seems BTC has been the pump driver over  years , as a result we can see how the other assets follow the btc trend.","metadata":{}},{"cell_type":"code","source":"groups_assets =  crypto_df[[\"Asset_Name\",\"Close\"]].groupby([pd.Grouper(\"Asset_Name\"),pd.Grouper(freq='M')]).max().reset_index()\nbtc = groups_assets[groups_assets[\"Asset_Name\"]==\"Bitcoin\"]   # BTC   \nlowprice_assets = ['Stellar','TRON', 'Cardano', 'IOTA', 'Dogecoin','EOS.IO']\nothers =  groups_assets[(~groups_assets[\"Asset_Name\"].isin(lowprice_assets)) & (groups_assets[\"Asset_Name\"]!=\"Bitcoin\")]   # Others\nfig, ax = plt.subplots(nrows=1, ncols=1, figsize=(25, 10))\nax2 = ax.twinx()\npalette ={\"Bitcoin\": \"#000000\"}\ng=sns.lineplot(data=btc, x=\"date\", y=\"Close\", hue=\"Asset_Name\",err_style=\"bars\", ci=68,ax=ax, palette=palette)\nsns.move_legend(g, \"upper left\")\ng=sns.lineplot(data=others, x=\"date\", y=\"Close\", hue=\"Asset_Name\",err_style=\"bars\", ci=68,ax=ax2)","metadata":{"execution":{"iopub.status.busy":"2021-11-21T17:35:01.72723Z","iopub.execute_input":"2021-11-21T17:35:01.727739Z","iopub.status.idle":"2021-11-21T17:35:06.836085Z","shell.execute_reply.started":"2021-11-21T17:35:01.727702Z","shell.execute_reply":"2021-11-21T17:35:06.835121Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"lowprice_assets = ['Cardano', 'IOTA', 'EOS.IO']\nothers =  groups_assets[(groups_assets[\"Asset_Name\"].isin(lowprice_assets)) & (groups_assets[\"Asset_Name\"]!=\"Bitcoin\")]   # Others\nfig, ax = plt.subplots(nrows=1, ncols=1, figsize=(25, 10))\nax2 = ax.twinx()\npalette ={\"Bitcoin\": \"#000000\"}\ng=sns.lineplot(data=btc, x=\"date\", y=\"Close\", hue=\"Asset_Name\",err_style=\"bars\", ci=68,ax=ax, palette=palette)\nsns.move_legend(g, \"upper left\")\ng=sns.lineplot(data=others, x=\"date\", y=\"Close\", hue=\"Asset_Name\",err_style=\"bars\", ci=68,ax=ax2)","metadata":{"execution":{"iopub.status.busy":"2021-11-21T17:35:06.837517Z","iopub.execute_input":"2021-11-21T17:35:06.837829Z","iopub.status.idle":"2021-11-21T17:35:07.369482Z","shell.execute_reply.started":"2021-11-21T17:35:06.837789Z","shell.execute_reply":"2021-11-21T17:35:07.368606Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"lowprice_assets = ['Stellar','TRON','Dogecoin']\nothers =  groups_assets[(groups_assets[\"Asset_Name\"].isin(lowprice_assets)) & (groups_assets[\"Asset_Name\"]!=\"Bitcoin\")]   # Others\nfig, ax = plt.subplots(nrows=1, ncols=1, figsize=(25, 10))\nax2 = ax.twinx()\npalette ={\"Bitcoin\": \"#000000\"}\ng=sns.lineplot(data=btc, x=\"date\", y=\"Close\", hue=\"Asset_Name\",err_style=\"bars\", ci=68,ax=ax, palette=palette)\nsns.move_legend(g, \"upper left\")\ng=sns.lineplot(data=others, x=\"date\", y=\"Close\", hue=\"Asset_Name\",err_style=\"bars\", ci=68,ax=ax2)","metadata":{"execution":{"iopub.status.busy":"2021-11-21T17:35:07.371474Z","iopub.execute_input":"2021-11-21T17:35:07.371673Z","iopub.status.idle":"2021-11-21T17:35:07.880999Z","shell.execute_reply.started":"2021-11-21T17:35:07.371643Z","shell.execute_reply":"2021-11-21T17:35:07.880219Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Volatility","metadata":{}},{"cell_type":"markdown","source":"Volatility often refers to the amount of uncertainty or risk related to the size of changes in a security's value. A higher volatility means that a security's value can potentially be spread out over a larger range of values. This means that the price of the security can change dramatically over a short time period in either direction. A lower volatility means that a security's value does not fluctuate dramatically, and tends to be more steady.\n\n<div class=\"alert alert-block alert-warning\">\n<b>References:</b>\n<ul>\n    <li><a href = \"https://www.investopedia.com/terms/v/volatility.asp\">Volatility</a></li>\n</ul>\n</div>","metadata":{}},{"cell_type":"code","source":"btc = crypto_df[crypto_df[\"Asset_ID\"]==1]\nbtc_grouped_1d = group_trading_timeseries(btc, time_step_size='1d')  \nbtc_grouped_1d = btc_grouped_1d.loc[pd.to_datetime('01/01/2021', format=\"%d/%m/%Y\"):\n                        pd.to_datetime('22/10/2021', format=\"%d/%m/%Y\")]\n\n\nmpf.plot(btc_grouped_1d, type='candle', figratio=(3,1), style='nightclouds', title=\"BTC Daily Price\", volume=True)","metadata":{"execution":{"iopub.status.busy":"2021-11-21T17:35:07.882216Z","iopub.execute_input":"2021-11-21T17:35:07.882379Z","iopub.status.idle":"2021-11-21T17:35:10.061573Z","shell.execute_reply.started":"2021-11-21T17:35:07.882358Z","shell.execute_reply":"2021-11-21T17:35:10.060523Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Since the data is at one minute its a good idea to resample it in order to view in others timeframes, functions <b>group_trading_timeseries</b> and <b>group_trading_timeseries_all</b> are created for this purpose","metadata":{}},{"cell_type":"markdown","source":"## Technical Analysis","metadata":{}},{"cell_type":"markdown","source":" <center><img src=\"https://errante.com/wp-content/uploads/2020/07/Errante-Trading-Tools-Understanding-Technical-Indicators.jpg\" style = \"max-height:300px;\"></center> \n \nTechnical analysis is a trading discipline employed to evaluate investments and identify trading opportunities by analyzing statistical trends gathered from trading activity, such as price movement and volume.\n\n<div class=\"alert alert-block alert-warning\">\n<b>Key Takeaways:</b>\n<ul>\n    <li>Technical analysis is a trading discipline employed to evaluate investments and identify trading opportunities in price trends and patterns seen on charts.</li>\n    <li>Technical analysts believe past trading activity and price changes of a security can be valuable indicators of the security's future price movements.</li>\n    <li>Technical analysis is a trading discipline employed to evaluate investments and identify trading opportunities in price trends and patterns seen on charts.</li>\n</ul>\n<br/>\n\n","metadata":{}},{"cell_type":"markdown","source":"## Technical Analysis charts\nAcross the industry, there are hundreds of patterns and signals that have been developed by researchers to support technical analysis trading, it would be a bit tedious to code them. \nFortunately there is a technical analysis library in python available(created by <a href=\"https://github.com/bukosabino\" >bukosabino</a>), the library has implemented 42 indicators:\n\n\n<b>Volume:</b>\n<ul>\n<li>Money Flow Index (MFI)</li>\n<li>Accumulation/Distribution Index (ADI)</li>\n<li>On-Balance Volume (OBV)</li>\n<li>Chaikin Money Flow (CMF)</li>\n<li>Force Index (FI)</li>\n<li>Ease of Movement (EoM, EMV)</li>\n<li>Volume-price Trend (VPT)</li>\n<li>Negative Volume Index (NVI)</li>\n<li>Volume Weighted Average Price (VWAP)</li>\n</ul>\n<b>Volatility:</b>\n<ul>\n<li>Average True Range (ATR)</li>\n<li>Bollinger Bands (BB)</li>\n<li>Keltner Channel (KC)</li>\n<li>Donchian Channel (DC)</li>\n<li>Ulcer Index (UI)</li>\n</ul>\n\n<b>Trend:</b>\n<ul>\n<li>Simple Moving Average (SMA)</li>\n<li>Exponential Moving Average (EMA)</li>\n<li>Weighted Moving Average (WMA)</li>\n<li>Moving Average Convergence Divergence (MACD)</li>\n<li>Average Directional Movement Index (ADX)</li>\n<li>Vortex Indicator (VI)</li>\n<li>Trix (TRIX)</li>\n<li>Mass Index (MI)</li>\n<li>Commodity Channel Index (CCI)</li>\n<li>Detrended Price Oscillator (DPO)</li>\n<li>KST Oscillator (KST)</li>\n<li>Ichimoku Kinkō Hyō (Ichimoku)</li>\n<li>Parabolic Stop And Reverse (Parabolic SAR)</li>\n<li>Schaff Trend Cycle (STC)</li>\n</ul>\n\n<b>Momentum:</b>\n<ul>\n<li>Relative Strength Index (RSI)</li>\n<li>Stochastic RSI (SRSI)</li>\n<li>True strength index (TSI)</li>\n<li>Ultimate Oscillator (UO)</li>\n<li>Stochastic Oscillator (SR)</li>\n<li>Williams %R (WR)</li>\n<li>Awesome Oscillator (AO)</li>\n<li>Kaufman's Adaptive Moving Average (KAMA)</li>\n<li>Rate of Change (ROC)</li>\n<li>Percentage Price Oscillator (PPO)</li>\n<li>Percentage Volume Oscillator (PVO)</li>\n</ul>\n<b>Others:</b>\n<ul>\n<li>Daily Return (DR)</li>\n<li>Daily Log Return (DLR)</li>\n<li>Cumulative Return (CR)</li>\n</ul>\n\n\n\n<b>Documentation:</b>\n<ul>\n    <li><a href = \"https://technical-analysis-library-in-python.readthedocs.io/en/latest/\">Technical Analysis library documentation</a></li>\n</ul>\n</div>\n","metadata":{}},{"cell_type":"code","source":"crypto_df_filtered = crypto_df[pd.to_datetime('01/01/2018', format=\"%d/%m/%Y\"):\n                        pd.to_datetime('02/01/2018', format=\"%d/%m/%Y\")]\nasset_list = [0,6] #Binance Coin, Ethereum\ncrypto_assets = crypto_df_filtered[crypto_df_filtered[\"Asset_ID\"].isin(asset_list)]\ncrypto_assets= group_trading_timeseries_all(crypto_assets, time_step_size='5min')  \ncrypto_assets = add_all_ta_features(crypto_assets, open=\"Open\", high=\"High\", low=\"Low\", close=\"Close\", volume=\"Volume\", fillna=True)\ncrypto_assets = crypto_assets.reset_index()\ncrypto_assets.set_index(\"date\", inplace=True)","metadata":{"execution":{"iopub.status.busy":"2021-11-21T17:35:10.063486Z","iopub.execute_input":"2021-11-21T17:35:10.063711Z","iopub.status.idle":"2021-11-21T17:35:11.520023Z","shell.execute_reply.started":"2021-11-21T17:35:10.063687Z","shell.execute_reply":"2021-11-21T17:35:11.519266Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class TAIndicator():\n    def __init__(self,  name=\"\", type=\"\", lower_limit=np.nan, upper_limit=np.nan, color='#00FF00', chart=\"line\", support_indicators=[], is_support_indicator=False,secondary_y=False):\n        self.name = name\n        self.type = type\n        self.lower_limit = lower_limit\n        self.upper_limit = upper_limit\n        self.color =  color\n        self.color_function =  None\n\n        self.chart = chart\n        self.support_indicators = support_indicators\n        self.is_support_indicator = is_support_indicator\n        self.secondary_y = secondary_y\n      \n      \n\ncolumns= crypto_assets.columns.values\nindicators = []\n\nfor column in columns:\n    if column.startswith(\"momentum\"):\n        indicators.append(TAIndicator(name=column, type=\"momentum\"))\n    elif column.startswith(\"volume\") and column != \"volume\":\n        indicators.append(TAIndicator(name=column, type=\"volume\"))\n    elif column.startswith(\"volatility\"):\n        indicators.append(TAIndicator(name=column, type=\"volatility\"))\n    elif column.startswith(\"trend\"):\n        indicators.append(TAIndicator(name=column, type=\"trend\"))\n    elif column.startswith(\"others\"):\n        indicators.append(TAIndicator(name=column, type=\"others\"))\n\nupdate_indicator_property(indicators, \"momentum_rsi\", \"lower_limit\", 30)\nupdate_indicator_property(indicators, \"momentum_rsi\", \"upper_limit\", 70)\nupdate_indicator_property(indicators, \"momentum_stoch_rsi\", \"lower_limit\", 0.3)\nupdate_indicator_property(indicators, \"momentum_stoch_rsi\", \"upper_limit\", 0.7)\n\n#support_indicators\n\n#trend_macd', 'trend_macd_signal',     'trend_macd_diff'\n#MACD\nupdate_indicator_property(indicators, \"trend_macd_diff\", \"chart\", \"bar\")\n\n\n#update_indicator_property(indicators, \"trend_macd_diff\", \"color\", macd_hist_color)\n\n\nupdate_indicator_property(indicators, \"trend_macd_signal\", \"is_support_indicator\", True)#color\nupdate_indicator_property(indicators, \"trend_macd_signal\", \"color\", \"#FF0000\")\n\nupdate_indicator_property(indicators, \"trend_macd_diff\", \"is_support_indicator\", True)\n\n#Bollinger bands\nupdate_indicator_property(indicators, \"volatility_bbl\", \"is_support_indicator\", True)\nupdate_indicator_property(indicators, \"volatility_bbl\", \"secondary_y\", False)\nupdate_indicator_property(indicators, \"volatility_bbw\", \"is_support_indicator\", True)\nupdate_indicator_property(indicators, \"volatility_bbw\", \"secondary_y\", False)\nbb_support_ind= filter_indicators(indicators,['volatility_bbl'])\nupdate_indicator_property(indicators, \"volatility_bbh\", \"support_indicators\", bb_support_ind)\n\n\nmacd_support_ind= filter_indicators(indicators,['trend_macd_signal', 'trend_macd_diff'])\nupdate_indicator_property(indicators, \"trend_macd\", \"support_indicators\", macd_support_ind)\n\n\n","metadata":{"execution":{"iopub.status.busy":"2021-11-21T17:35:11.521263Z","iopub.execute_input":"2021-11-21T17:35:11.521486Z","iopub.status.idle":"2021-11-21T17:35:11.536146Z","shell.execute_reply.started":"2021-11-21T17:35:11.521456Z","shell.execute_reply":"2021-11-21T17:35:11.534941Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n\nindicators_plotted= [\"momentum_rsi\",\"momentum_stoch_rsi\"]\nindicators_plotted= []\nindicators_plotted=['trend_macd',\"momentum_stoch_rsi\",\"momentum_rsi\",\"volatility_bbh\"]\nindicators_plotted= [] #all\n\ntype_indicators=[\"momentum\",\"volume\",\"volatility\",\"trend\",\"others\"]\n#type_indicators=[\"momentum\"]\n\n#type_indicators=[\"volatility\"]\n\nfor type in type_indicators:\n    for moneda in asset_list:\n        asset = crypto_assets[crypto_assets[\"Asset_ID\"]==moneda]\n        plot_candle_indicators(asset,filter_indicators(indicators,indicators_plotted,type),asset_names_dict[moneda]+\"-\"+type)\n","metadata":{"execution":{"iopub.status.busy":"2021-11-21T18:05:16.787117Z","iopub.execute_input":"2021-11-21T18:05:16.787419Z","iopub.status.idle":"2021-11-21T18:05:28.161316Z","shell.execute_reply.started":"2021-11-21T18:05:16.787387Z","shell.execute_reply":"2021-11-21T18:05:28.160164Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<h1>Continue....</h1>","metadata":{}}]}