<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Alex K on Medium]]></title>
        <description><![CDATA[Stories by Alex K on Medium]]></description>
        <link>https://medium.com/@sane.ai?source=rss-88ed5cd82154------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*nHAWLRF2iV6JminbCF-g7Q.jpeg</url>
            <title>Stories by Alex K on Medium</title>
            <link>https://medium.com/@sane.ai?source=rss-88ed5cd82154------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 09:35:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sane.ai/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Deep Reinforcement Learning for Crypto Trading]]></title>
            <link>https://medium.com/coinmonks/deep-reinforcement-learning-for-crypto-trading-ed385e87ab0e?source=rss-88ed5cd82154------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed385e87ab0e</guid>
            <category><![CDATA[crypto]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[bots]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Alex K]]></dc:creator>
            <pubDate>Fri, 17 May 2024 18:25:50 GMT</pubDate>
            <atom:updated>2024-07-01T10:37:57.051Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 5: Live Trading</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-qaJRlOZmk4uZtnRN86tgA.png" /><figcaption>photo by <a href="https://unsplash.com/@traxer">Traxer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>Disclaimer: The information provided herein does not constitute financial advice. All content is presented solely for educational purposes.</em></p><h3>Introduction</h3><p>This is the fifth and the last part of my blog series on reinforcement learning for crypto trading.</p><ul><li><a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-72c06bb9b04c">Part 0: Introduction</a></li><li><a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-part-1-data-preparation-682173ef3000">Part 1: Data preparation</a></li><li><a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-261f8820f129">Part 2: Trading strategy</a></li><li><a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-6b5705128732">Part 3: Training</a></li><li><a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-2d2a8204bf79">Part 4: Backtesting</a></li><li><a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-ed385e87ab0e">Part 5: Live trading</a></li></ul><p>This blog post explains my approach to live trading on Bybit testnet.</p><p>As I mentioned in <a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-72c06bb9b04c">Part 0: Introduction</a>, my main goal is to connect with potential employers or investors and ultimately become a professional quant.</p><h3>Prerequisites</h3><ul><li><a href="https://www.bybit.com/invite?ref=GLW3W6">Bybit</a> testnet account</li></ul><h3>Choosing a cryptocurrency exchange</h3><p>Once we are satisfied with the backtesting results on the validation dataset, the next step is to move to a real exchange. Crypto exchanges provide a great option if you want to test your strategy but don’t want to lose real money, so-called Testnets. The network trading real money is called Mainnet. I conducted thorough research to identify which exchange would best suit my needs. The winner is <a href="https://www.bybit.com/invite?ref=GLW3W6">Bybit</a> because its testnet UI, API and Last price are almost identical to the Bybit mainnet exchange. It also offers lower fees for perpetual futures trading than most crypto exchanges.</p><p>The Last price is used for exchange settlements, not the Market or Index price. This is a problem with the <a href="https://www.binance.com/en/activity/referral-entry/CPA?ref=CPA_00B4B2T411">Binance</a> testnet. The last price on the Binance testnet is a mess, so <em>realized_pnl</em> and other account parameters calculated during trading are unreliable if fetched via Binance API and not calculated explicitly in the environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7nrEkG0sAInkRgAgH7SVIA.png" /><figcaption>FTM last price on Binance testnet; image by author</figcaption></figure><p>On the other hand, the Bybit testnet has large, unrealistic spikes in BTC and ETH last prices, which can skew trading results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z8Nih97JM5NeR11IdoX4lA.png" /><figcaption>BTC last price on Bybit testnet; image by author</figcaption></figure><p>However, there is no such problem with altcoins. For altcoins such as FTM, the Bybit mainnet and testnet price charts are almost identical (except for <em>volume</em>).<em> </em>For the live trading environment, we only need the Last price so the exchange calculates all account parameters correctly; candlesticks and volume are scrapped from Bybit mainnet even though trades are executed on the testnet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C4AnkZGg22fbZjcYYKGhfg.png" /><figcaption>FTM price on Bybit mainnet (left) and testnet (right); image by author</figcaption></figure><p>Another good feature of the Bybit testnet is that you can change the <em>api_key</em>, <em>api_secret</em>, and <em>testnet</em> flag without any other code changes and start trading immediately on the mainnet:</p><pre>from pybit.unified_trading import HTTP<br><br>session = HTTP(testnet=False, api_key=&quot;...&quot;, api_secret=&quot;...&quot;)</pre><p>If I were trading BTC or ETH, I would change my stack: <a href="https://glassnode.com/">Glassnode</a> as the on-chain data provider instead of <a href="https://santiment.net/">Santiment</a> and the <a href="https://www.deribit.com/dashboard">Deribit</a> exchange instead of <a href="https://www.bybit.com/invite?ref=GLW3W6">Bybit</a> because the Deribit testnet does not have the aforementioned problems and Glassnode has a more comprehensive set of metrics for BTC and ETH.</p><p>Since the Last price slightly deviates on mainnet and testnet, the trading results on both networks would be slightly different. The skew is negligible and up to 0.1% per episode (2 weeks) because my strategy is not high-frequency.</p><p>The environment I coded used for training and backtesting is also not one-to-one identical to the real exchange. I compared agent returns from online data (real-time trading on the Bybit testnet) and offline data sets (collected over the same time period) evaluated using my backtesting framework discussed in <a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-2d2a8204bf79">Part 4: Backtesting</a>. Returns may deviate by up to 0.5% per episode in both directions up and down since the learning environment does not capture all the processes occurring on the exchange under the hood.</p><p>No universal strategy fits all market regimes, so I typically deploy multiple bots (with different policies). Each policy is represented by a checkpoint saved during different training runs and after a different number of training epochs. This diversifies sources of profit in different market conditions and reduces risks. Even if one bot fails, the average return will still be positive.</p><p>Bybit allows you to have up to 20 sub-accounts under your main account. You can deploy one bot per subaccount; each bot can read the metrics_outfile.npy file stored on disk every 1 hour and call the API corresponding to its own subaccount. I deploy my bots on the Google Cloud Platform.</p><p>List of commands to start collecting live data (last 1 week of data from the current timestamp) and store them on disk every hour:</p><pre>python scraper_binance.py --coins &quot;BTC,ETH,FTM&quot; --resolutions &quot;1h,1d&quot; --endpoint_file_paths &quot;./data/endpoints_file_path_binance.json&quot; --save_folder &quot;./data/test/binance/live&quot; --mode &quot;live&quot;<br>python scraper_bybit.py --coins &quot;BTC,ETH,FTM&quot; --resolutions &quot;1h,1d&quot; --endpoint_file_paths &quot;./data/endpoints_file_path_bybit.json&quot; --save_folder &quot;./data/test/bybit/live&quot; --mode &quot;live&quot;<br>python scraper_santiment.py --coins &quot;BTC,ETH,FTM&quot; --resolutions &quot;1h,24h&quot; --endpoint_file_paths &quot;./data/endpoints_file_path_santiment.json&quot; --save_folder &quot;./data/test/santiment/live&quot; --mode &quot;live&quot;</pre><h3>Results</h3><p>I do not publish code for live trading. If you are interested in it or would like to see more trading results, please contact me directly. In short, <a href="https://github.com/xkaple00/deep-reinforcement-learning-for-crypto-trading/blob/master/envs/training_env.py">training_env.py</a> should be modified to interact with Bybit API, and the data preprocessing pipeline should be changed to work with live online data rather than offline historical datasets.</p><p>A screen recording during bot live trading on the Bybit exchange:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FelY9TdrdpgI%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DelY9TdrdpgI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FelY9TdrdpgI%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a373e687ce8ca4ffb30d7d549205222/href">https://medium.com/media/2a373e687ce8ca4ffb30d7d549205222/href</a></iframe><p>I’m also posting <em>reaslized_pnl</em> reports exported from the Bybit of 3 different bots.</p><p>Bot 1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WaQh3s59pnizua5KVPHYig.png" /><figcaption>bot 1 realized_pnl; image by author</figcaption></figure><p><a href="https://docs.google.com/spreadsheets/d/1lxF0WQTYjiQ5V7MXUrSLjeXKUQzEEwoO7DtLtvyM83Y/edit?usp=sharing">Link</a> to Google sheet.</p><p>Bot 2:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AO3a3sIT__IiaSpqJ7Irww.png" /><figcaption>bot 2 realized_pnl; image by author</figcaption></figure><p><a href="https://docs.google.com/spreadsheets/d/1F_3BHa55tO8_udskmSDqxP0-XvnaYlOdZyxue5CNJaE/edit?usp=sharing">Link</a> to Google sheet.</p><p>Bot 3:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NT7wES8f4nOnH8iDLXWCpg.png" /><figcaption>bot 3 realized_pnl; image by author</figcaption></figure><p><a href="https://docs.google.com/spreadsheets/d/13vwNGRLrG5f9KLc-xWJ2tKWAkGR2LXbMr5ItMdINXwo/edit?usp=sharing">Link</a> to Google sheet.</p><h3>Conclusion</h3><p>This blog series provided a comprehensive overview of Deep Reinforcement Learning for Crypto Trading, culminating in live trading on the Bybit testnet. Published results demonstrate the potential of this approach.</p><p>Here are the key takeaways:</p><ul><li>Bybit testnet offers a realistic environment for testing crypto trading strategies due to its close resemblance to the mainnet.</li><li>The slight deviations between Bybit’s mainnet and testnet, along with limitations of the training environment, necessitate adjustments for real-world trading.</li><li>Diversifying trading bots with different policies helps mitigate risk and capture profits in various market conditions.</li></ul><p>The published strategy has known problems, which I partially resolved during further development. Feel free to point out any potential problems with this approach. I have created more complex trading strategies with more advanced neural network architectures which are more profitable and reliable than the version posted here. Published code is a good starting point for further development.</p><p>I’m investing small amounts of my money into bots, but more testing and development are needed before increasing the assets under management.</p><p>If you see potential and want to invest in further development or want to offer me a job as a Quant/ML Engineer, I’d be happy to answer your questions. I have more ideas to implement but also need more computing resources and larger data sets. I trained all models on my PC with two Nvidia RTX 2080 Ti GPUs. I also can’t afford datasets from data providers targeting institutional clients.</p><p>This ends Part 5: Live trading and the whole blog series about Deep Reinforcement Learning for Crypto Trading. I hope you enjoyed reading as much as I enjoyed writing and coding. I believe all the information provided will be helpful for your crypto journey.</p><p>Please contact me if you want to see more results or explore collaboration opportunities.</p><h3>Contacts</h3><p>My email: <a href="/service/mailto:alex.kaplenko@sane-ai.dev">alex.kaplenko@sane-ai.dev</a></p><p>My LinkedIn: <a href="https://www.linkedin.com/in/alex-sane-ai/">https://www.linkedin.com/in/alex-sane-ai/</a></p><p>GitHub: <a href="https://github.com/xkaple00/deep-reinforcement-learning-for-crypto-trading">https://github.com/xkaple00/deep-reinforcement-learning-for-crypto-trading</a></p><p>Link to support Ukraine: <a href="https://war.ukraine.ua/donate/">https://war.ukraine.ua/donate/</a></p><p>Visit us at <a href="https://www.datadriveninvestor.com/"><em>DataDrivenInvestor.com</em></a></p><p>Subscribe to DDIntel <a href="https://www.ddintel.com/"><em>here</em></a>.</p><p>Join our creator ecosystem <a href="https://join.datadriveninvestor.com/"><em>here</em></a>.</p><p>DDI Official Telegram Channel: <a href="https://t.me/+tafUp6ecEys4YjQ1">https://t.me/+tafUp6ecEys4YjQ1</a></p><p>Follow us on <a href="https://www.linkedin.com/company/data-driven-investor"><em>LinkedIn</em></a>, <a href="https://twitter.com/@DDInvestorHQ"><em>Twitter</em></a>, <a href="https://www.youtube.com/c/datadriveninvestor"><em>YouTube</em></a>, and <a href="https://www.facebook.com/datadriveninvestor"><em>Facebook</em></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed385e87ab0e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/deep-reinforcement-learning-for-crypto-trading-ed385e87ab0e">Deep Reinforcement Learning for Crypto Trading</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Reinforcement Learning for Crypto Trading]]></title>
            <link>https://medium.com/coinmonks/deep-reinforcement-learning-for-crypto-trading-2d2a8204bf79?source=rss-88ed5cd82154------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d2a8204bf79</guid>
            <category><![CDATA[crypto]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[bots]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Alex K]]></dc:creator>
            <pubDate>Fri, 17 May 2024 18:25:03 GMT</pubDate>
            <atom:updated>2024-07-01T10:37:59.390Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 4: Backtesting</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bXTYpMe9hv0ttmT6-_LOGw.png" /><figcaption>photo by <a href="https://unsplash.com/@dylancalluy">Dylan Calluy</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>Disclaimer: The information provided herein does not constitute financial advice. All content is presented solely for educational purposes.</em></p><h3>Introduction</h3><p>This is the fourth part of my blog post series on reinforcement learning for crypto trading.</p><ul><li><a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-72c06bb9b04c">Part 0: Introduction</a></li><li><a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-part-1-data-preparation-682173ef3000">Part 1: Data preparation</a></li><li><a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-261f8820f129">Part 2: Trading strategy</a></li><li><a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-6b5705128732">Part 3: Training</a></li><li><a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-2d2a8204bf79">Part 4: Backtesting</a></li><li><a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-ed385e87ab0e">Part 5: Live trading</a></li></ul><p>This article explains the backtesting framework I created.</p><p>The results presented in this blog post are obtained using different PPO hyperparameters, policy network, and dataset than described in the previous blog posts. The dataset has a 5-minute resolution instead of 1 hour. The reward function used is a weighted sum of <em>realized_pnl </em>and <em>unrealized_pnl</em>.</p><p>As I mentioned in <a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-72c06bb9b04c">Part 0: Introduction</a>, my main goal is to connect with potential employers or investors and ultimately become a professional quant.</p><h3>Resources</h3><ul><li><a href="https://github.com/xkaple00/deep-reinforcement-learning-for-crypto-trading/blob/master/backtest.ipynb">backtest.ipynb</a></li><li><a href="https://github.com/xkaple00/deep-reinforcement-learning-for-crypto-trading/blob/master/envs/statistics_recorder.py">statistics_recorder.py</a></li></ul><h3>Multi-model analysis</h3><p>After training is completed, we must evaluate our algorithm on historical data (backtesting).</p><p>During training, checkpoints are saved every <em>checkpoint_freq</em> epoch in the ./results/PPO folder:</p><pre>tune.run(<br>    &quot;PPO&quot;,<br>    stop={&quot;timesteps_total&quot;: int(1e10)},<br>    config=ppo_config,<br>    local_dir=&quot;./results&quot;, # default folder &quot;~ray_results&quot; <br>    checkpoint_freq=12,<br>    checkpoint_at_end=False,<br>    keep_checkpoints_num=None,<br>    verbose=2,<br>    reuse_actors=False,<br>    # resume=True,<br>    # restore=&quot;./results/PPO/PPO_CryptoEnv_1a171_00000_0_2024-05-02_11-51-01/checkpoint_000012&quot;<br>)</pre><p>You can end up with a couple hundred saved checkpoints after a few days of training. The question is which checkpoint to choose for real trading on the crypto exchange. The last saved checkpoint does not necessarily have the best risk/reward ratio on the validation dataset since the policy network tries different strategies to maximize cumulative reward on the training dataset. I developed a logic under MULTI MODEL TEST section of the <a href="https://github.com/xkaple00/deep-reinforcement-learning-for-crypto-trading/blob/master/backtest.ipynb">backtest.ipynb</a> to calculate a set of metrics for each checkpoint on the validation dataset using the <a href="https://github.com/xkaple00/deep-reinforcement-learning-for-crypto-trading/blob/master/envs/statistics_recorder.py"><em>StatisticsRecorder</em></a> class:</p><ul><li><em>annual_volatility</em></li><li><em>sharpe_ratio</em></li><li><em>calmar_ratio</em></li><li><em>stability</em></li><li><em>max_drawdown</em></li><li><em>omega_ratio</em></li><li><em>sortino_ratio</em></li><li><em>tail_ratio</em></li><li><em>daily_value_at_risk</em></li><li><em>final_return (total)</em></li><li><em>final_return_long</em></li><li><em>final_return_short</em></li></ul><p><a href="https://github.com/quantopian/pyfolio">Pyfolio</a> library is used. JSON file with all calculated metrics is saved on disk for further analysis.</p><p>To activate recording statistics set <em>record_stats</em> flag to True in <a href="https://github.com/xkaple00/deep-reinforcement-learning-for-crypto-trading/blob/master/config.py">config.py</a>:</p><pre>env_config={<br>    &quot;dataset_name&quot;: &quot;dataset&quot;,  # .npy files should be in ./data/dataset/<br>    &quot;leverage&quot;: 2, # leverage for perpetual futures<br>    &quot;episode_max_len&quot;: 168 * 2, # train episode length, 2 weeks<br>    &quot;lookback_window_len&quot;: 168, <br>    &quot;train_start&quot;: [2000, 7000, 12000, 17000, 22000],<br>    &quot;train_end&quot;: [6000, 11000, 16000, 21000, 26000], <br>    &quot;test_start&quot;: [6000, 11000, 16000, 21000, 26000],<br>    &quot;test_end&quot;: [7000, 12000, 17000, 22000, 29377-1], <br>    &quot;order_size&quot;: 50, # dollars<br>    &quot;initial_capital&quot;: 1000, # dollars<br>    &quot;open_fee&quot;: 0.12e-2, # taker_fee<br>    &quot;close_fee&quot;: 0.12e-2, # taker_fee<br>    &quot;maintenance_margin_percentage&quot;: 0.012, # 1.2 percent<br>    &quot;initial_random_allocated&quot;: 0, # opened initial random long/short position up to initial_random_allocated $<br>    &quot;regime&quot;: &quot;training&quot;,<br>    &quot;record_stats&quot;: True, # True for backtesting<br>}</pre><p>The metrics I pay close attention to are:</p><ul><li><em>final_return </em>(should be as high as possible)</li><li><em>max_drawdown </em>(should be as low as possible)</li><li>ratio between <em>final_return_long </em>and <em>final_return_short</em></li></ul><p>Ideally, I want the bot to be profitable on shorts and not lose money on longs during a downtrend, and vice versa during an uptrend.</p><p>The for loop to evaluate each saved checkpoint:</p><pre>for i, checkpoint_path in enumerate(checkpoints_paths): <br>    print(&quot;index:&quot;, i, &quot;/&quot;, len(checkpoints_paths))<br>    print(&quot;checkpoint_path:&quot;, checkpoint_path)<br><br>    agent.load_checkpoint(checkpoint_path)<br><br>    done = False<br>    account_equity = []<br>    account_balance = ppo_config[&quot;env_config&quot;][&quot;initial_capital&quot;]<br>    total_reward = 0<br>    obs = env.reset()[0]<br><br>    while not done:<br>        action = agent.compute_single_action(observation=obs, prev_action=None, prev_reward=None)<br>        <br>        obs, reward, done, _, info = env.step(action)<br>        account_balance = info[&quot;equity&quot;][-1]<br>        account_equity.append(account_balance)<br><br>        total_reward += reward<br><br>    final_return.append(account_equity[-1])<br>    final_return_long.append(np.sum(info[&quot;reward_realized_pnl_long&quot;]) + info[&#39;unrealized_pnl_long&#39;][-1])<br>    final_return_short.append(np.sum(info[&quot;reward_realized_pnl_short&quot;]) + info[&#39;unrealized_pnl_short&#39;][-1])<br><br>    perf_stats_all = backtest_stats(account_equity)</pre><h4>Results</h4><p>I publish the results of one of my experiments (different PPO hyperparameters, policy network, and dataset than described in the previous blog posts). Dataset resolution is 5 min, <em>initial_balance</em> is 5000$ and <em>order_size</em> is 50$. The bot can invest 1% of its <em>initial_balance </em>per timestep.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*CgjIDCCnJxylm39_X6h9cA.png" /><figcaption>evaluation dataset FTM price (strong downtrend for 55 days); image by author</figcaption></figure><p>There are 188 checkpoints saved during training.</p><p><em>equity</em> at the end of the episode for each of the 188 saved checkpoints:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*JhjjbbhudgSiPeLKEBWL_w.png" /><figcaption>final equity per checkpoint; image by author</figcaption></figure><p><em>max_drawdown</em> for each of the 188 saved checkpoints:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*PpyGUbX22lYVgg6O-ORzZA.png" /><figcaption>max_drawdown per checkpoint; image by author</figcaption></figure><p>It is clear that as the training progresses, the policy network explores different trading strategies. The strategies learned by the first 50 checkpoints were almost liquidated (90% drawdown) in such a strong downtrend and their final equity was about 2000$ (loss of 3000$). The policy for checkpoints in the range [115:160] looks much better since <em>max_drawdown</em> is only around 20% and the <em>equity </em>at the end of the episode is about 12000$ (7000$ profit).</p><h3>Single-model analysis</h3><p>After choosing a few checkpoints with the best risk/reward ratio and metrics such as Sharpe and Sortino ratio on the validation dataset, we can perform a more in-depth analysis on them under the SINGLE MODEL BACKTEST section of the <a href="https://github.com/xkaple00/deep-reinforcement-learning-for-crypto-trading/blob/master/backtest.ipynb">backtest.ipynb</a>. Let’s try checkpoint number 158. From calculated statistics, I see that its <em>max_drawdown</em> is -0.182 (18.2%), profit on long positions is 1213.91$, and profit on short positions is 6459.7$. Despite the strong downtrend, the agent appears profitable, opening long positions at the local bottoms.</p><p>We can visualize the equity on the validation dataset. Equity takes into account realized and unrealized profits.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*iA30O7MCF_uGFWTiIRj7tA.png" /><figcaption>account equity; image by author</figcaption></figure><p>Wallet balance (takes into account only realized profits).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*efVt6fz8bbNxEfJ4IDVmgw.png" /><figcaption>wallet_balance; image by author</figcaption></figure><p>We can also visualize profits realized for long and short positions separately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*DTOH1lwVyBpjZi_-YYMocw.png" /><figcaption>realised_pnl_long; image by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*xPuwgrV-tgtYeqhDyFiUyw.png" /><figcaption>realised_pnl_short; image by author</figcaption></figure><p>It’s also possible to visualize the cumulative rewards the agent receives. The reward function is a combination of <em>realized_pnl </em>and <em>unrealized_pnl</em>. The highlighted areas correspond to periods of time when the agent holds a position at a loss and receives small negative rewards each time step that accumulate over time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*bArPFYZ24pJ9XVusui2Clg.png" /><figcaption>agent cumulative reward; image by author</figcaption></figure><p>In the notebook, a few more metrics can be visualized: <em>reward_realised_pnl_short</em> and <em>reward_realised_pnl_long</em> (per timestep, not cumulative), <em>unrealised_pnl_short</em> and <em>unrealised_pnl_long</em> to see periods of drawdown. I also calculate how many times the agent took each action. During a downtrend, it should open short positions more frequently than long positions and vice versa.</p><h4>Cross-validation</h4><p>The SINGLE MODEL SLIDING WINDOW BACKTEST section offers an option to do a backtest using <a href="https://nixtlaverse.nixtla.io/neuralforecast/examples/cross_validation_tutorial.html">cross-validation</a>. That is, evaluate not over the whole validation dataset but rather shift the sliding window (of length <em>episode_length</em>) in each iteration of the for loop by <em>episode_start_shift</em> timesteps.</p><p><em>ppo_config[“env_config”]</em> values are overridden for each sliding window interval:</p><pre>episode_start_shift = 168<br>episode_length = 168 * 2<br>start_index = 26000<br>end_index = 29377<br><br>account_equity = []<br><br>for test_start in range(start_index, end_index - 1, episode_start_shift):<br>    ppo_config[&quot;env_config&quot;][&quot;test_start&quot;] = [test_start]<br>    ppo_config[&quot;env_config&quot;][&quot;test_end&quot;] =  [min(test_start + episode_length, end_index) - 1]<br>    ppo_config[&quot;env_config&quot;][&quot;episode_max_len&quot;] = ppo_config[&quot;env_config&quot;][&quot;test_end&quot;][0] - ppo_config[&quot;env_config&quot;][&quot;test_start&quot;][0]</pre><p>This approach is more informative because we can test how well the agent performs under different starting conditions.</p><p>There is a result of cross-validation with the parameters: <em>episode_start_shift</em> is 512, <em>episode_length</em> is 4096 (approx. 2 weeks considering 5 min timesteps), <em>initial_balance</em> is 5000$. The chart shows <em>equity</em> at the end of each cross-validation interval.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/0*dZ_Qfvow8FbBkT91" /><figcaption>equity per sliding window interval; image by author</figcaption></figure><p>As we can see, the agent completed only 1 episode out of 32 with significant losses. This is episode number 15. An <em>equity</em> of 6500$ means a profit of 1500$ or 1500/5000*100 = 30% return in two weeks.</p><h3>Plot trades</h3><p>I’ve also created a framework to visualize individual trades during backtesting, which helps me better understand the learned policy from the human perspective and build trust in AI decisions.</p><p>The orange line is a relative FTM price; blue line is cumulative <em>realized_pnl</em>; <em>average_price</em> for position<em> </em>is visualized in purple. Vertical red/green lines correspond to closing the entire position (action number 4), no matter how large it is. Green/red tickers correspond to adding to or subtracting from a position. Zoomed-in charts are viewed better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dkWpHaKmdUe-DziKt_K72g.png" /><figcaption>long trades; image by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_yM2lPYAyQKd1Q3qI2mz-g.png" /><figcaption>short trades; image by author</figcaption></figure><p>Since different learned strategies can be better suited for different market conditions and there is no one-to-rule-them-all strategy, I usually choose a few different checkpoints to deploy and diversify risks.</p><h3>Conclusion</h3><p>This article presented a framework for backtesting a deep reinforcement learning agent trained for crypto trading. The backtesting process allows us to evaluate the performance of the trained agent on historical data and select the best performing models for potential live trading.</p><p>We explored different metrics to assess the agent’s performance, including final return and maximum drawdown. We also visualized the agent’s equity, wallet balance, and realized/unrealized profits to gain a deeper understanding of its trading behavior.</p><p>The backtesting framework also incorporates cross-validation techniques to assess the agent’s performance under various market conditions. Finally, we discussed the importance of visualizing individual trades to gain insights into the learned policy and build trust in the agent’s decision-making capabilities.</p><p>By employing this backtesting framework, we can effectively identify promising trading strategies and refine the agent’s behavior before deploying it in a live trading environment.</p><p>This ends Part 4: Backtesting, see you in the next <a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-ed385e87ab0e">Part 5: Live trading</a>.</p><p>If you are interested in cooperation, feel free to contact me.</p><h3>Contacts</h3><p>My email: <a href="/service/mailto:alex.kaplenko@sane-ai.dev">alex.kaplenko@sane-ai.dev</a></p><p>My LinkedIn: <a href="https://www.linkedin.com/in/alex-sane-ai/">https://www.linkedin.com/in/alex-sane-ai/</a></p><p>GitHub: <a href="https://github.com/xkaple00/deep-reinforcement-learning-for-crypto-trading">https://github.com/xkaple00/deep-reinforcement-learning-for-crypto-trading</a></p><p>Link to support Ukraine: <a href="https://war.ukraine.ua/donate/">https://war.ukraine.ua/donate/</a></p><p>Visit us at <a href="https://www.datadriveninvestor.com/"><em>DataDrivenInvestor.com</em></a></p><p>Subscribe to DDIntel <a href="https://www.ddintel.com/"><em>here</em></a>.</p><p>Join our creator ecosystem <a href="https://join.datadriveninvestor.com/"><em>here</em></a>.</p><p>DDI Official Telegram Channel: <a href="https://t.me/+tafUp6ecEys4YjQ1">https://t.me/+tafUp6ecEys4YjQ1</a></p><p>Follow us on <a href="https://www.linkedin.com/company/data-driven-investor"><em>LinkedIn</em></a>, <a href="https://twitter.com/@DDInvestorHQ"><em>Twitter</em></a>, <a href="https://www.youtube.com/c/datadriveninvestor"><em>YouTube</em></a>, and <a href="https://www.facebook.com/datadriveninvestor"><em>Facebook</em></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d2a8204bf79" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/deep-reinforcement-learning-for-crypto-trading-2d2a8204bf79">Deep Reinforcement Learning for Crypto Trading</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Reinforcement Learning for Crypto Trading]]></title>
            <link>https://medium.com/coinmonks/deep-reinforcement-learning-for-crypto-trading-6b5705128732?source=rss-88ed5cd82154------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b5705128732</guid>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[crypto]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[bots]]></category>
            <dc:creator><![CDATA[Alex K]]></dc:creator>
            <pubDate>Fri, 17 May 2024 18:24:05 GMT</pubDate>
            <atom:updated>2024-07-01T10:38:01.942Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 3: Training</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A2dNVi-IdIZYdHDqT8hYKA.png" /><figcaption>photo by <a href="https://unsplash.com/@agk42">Alex Knigh</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>Disclaimer: The information provided herein does not constitute financial advice. All content is presented solely for educational purposes.</em></p><h3>Introduction</h3><p>This is the third part of my blog post series on reinforcement learning for crypto trading:</p><ul><li><a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-72c06bb9b04c">Part 0: Introduction</a></li><li><a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-part-1-data-preparation-682173ef3000">Part 1: Data preparation</a></li><li><a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-261f8820f129">Part 2: Trading strategy</a></li><li><a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-6b5705128732">Part 3: Training</a></li><li><a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-2d2a8204bf79">Part 4: Backtesting</a></li><li><a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-ed385e87ab0e">Part 5: Live trading</a></li></ul><p>This article explains the reinforcement learning algorithm, neural network architecture and the training process.</p><p>As I mentioned in <a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-72c06bb9b04c">Part 0: Introduction</a>, my main goal is to connect with potential employers or investors and ultimately become a professional quant.</p><h3>Resources</h3><ul><li><a href="https://github.com/xkaple00/deep-reinforcement-learning-for-crypto-trading/blob/master/train.py">train.py</a></li><li><a href="https://github.com/xkaple00/deep-reinforcement-learning-for-crypto-trading/blob/master/config.py">config.py</a></li><li><a href="https://github.com/xkaple00/deep-reinforcement-learning-for-crypto-trading/blob/master/models/transformer.py">transformer.py</a></li><li><a href="https://drive.google.com/file/d/12IyS3PKTx0KQr-J28vYOYJon5qpIRhsB/view?usp=sharing">tensorboard_logs</a></li></ul><h3>Reinforcement learning library</h3><p>The essential question is which library to use for reinforcement learning (RL). I decided to choose <a href="https://docs.ray.io/en/latest/rllib/index.html">RLlib</a> from <a href="https://www.ray.io/">Ray</a>. RLlib is an open-source library that supports production-level, highly distributed RL workloads while maintaining unified and simple APIs. It has wider functionality, more implemented RL algorithms, and is better supported than other RL libraries, in my opinion. RLlib supports both the most popular deep-learning frameworks: <a href="https://github.com/ray-project/ray/blob/master/rllib/examples/custom_torch_policy.py">PyTorch</a> and <a href="https://github.com/ray-project/ray/blob/master/rllib/examples/custom_tf_policy.py">TensorFlow</a>. RLlib algorithms (such as “PPO” or “IMPALA”) allow you to set the <em>num_workers</em> config parameter, such that your workloads can run on hundreds of CPUs thus parallelizing and speeding up learning. RLlib auto-vectorizes <em>gymnasium.Envs</em> via the <em>num_envs_per_worker</em> config parameter. Environment workers can then batch and thus significantly speedup the action computing forward pass. RLlib’s API stack built on top of Ray offers off-the-shelf, highly distributed algorithms, policies, loss functions, and default models (including the option to auto-wrap a neural network with LSTM or attention net).</p><h3>RL algorithm</h3><p>Due to the ability of RL agents to outperform their human competitors in many challenging tasks, the development of new RL algorithms has gained substantial attention in recent years. Nowadays, many RL algorithms are available, to name a few — DDQN, VPG, A3C, SAC, TRPO, DDPG, TD3, ACTR, MPO, PPO. A full list of RL algorithms supported by RLlib can be found <a href="https://docs.ray.io/en/latest/rllib/rllib-algorithms.html">here</a>. No universal RL algorithm can outperform all other algorithms in every possible RL environment. Instead, some algorithms are designed for fast learning in fully observable environments with dense rewards. In contrast, other algorithms are designed to focus on slower but consistent learning in partially observable environments with sparse rewards which is our case.</p><h4>Algorithms classification</h4><p>After we decided which library to use, the next question was what type of algorithms best suited our needs. RL algorithms can be divided into model-free vs model-based and on-policy vs off-policy categories. Crypto markets are not similar to board games like chess, where we can hard-code all the rules and their known outcome. We don’t have a model for them. This way, we can filter out all model-based algorithms, such as: Dyna-Q, Monte Carlo Tree Search (MCTS), Prioritized Sweeping, Adaptive Dynamic Programming (ADP), Model Predictive Control (MPC), etc.</p><p>On-policy and off-policy refer to two broad categories of reinforcement learning algorithms. The key difference between them lies in how they generate and learn from the data:</p><ol><li>On-Policy Reinforcement Learning Algorithms: On-policy algorithms learn from the current policy. In other words, these algorithms learn the value function according to the current policy and improve the policy based on the learned value function (relatively smaller replay buffer). For instance, SARSA (State-Action-Reward-State-Action) or <a href="https://openai.com/index/openai-baselines-ppo/">PPO</a> (Proximal Policy Optimization) are on-policy algorithms. They use the current policy to decide their future actions and then update it based on the learned values.</li><li>Off-Policy Reinforcement Learning Algorithms: Off-policy algorithms, on the other hand, can learn from a different policy from the one they are currently executing. This means they can learn from experiences collected from past policies (relatively larger replay buffer). This allows the agent to learn from a wide range of experiences, not just the current ones. An example of an off-policy algorithm is <a href="https://towardsdatascience.com/reinforcement-learning-explained-visually-part-5-deep-q-networks-step-by-step-5a5317197f4b">Deep Q-Learning</a>, where the learning process involves looking at the maximum reward possible for the next state, irrespective of the action taken under the current policy.</li></ol><p>In summary, on-policy algorithms are algorithms where the agent learns the value function according to the current action derived from the policy currently in use. In contrast, off-policy learns from actions taken outside of the current policy.</p><p>However, off-policy algorithms might be less effective in non-stationary environments (i.e., the underlying dynamics change over time), like the cryptocurrency market. Off-policy algorithms are a good choice if you have a lot of historical data and the market dynamics don’t change too rapidly. On the other hand, if the market is highly volatile and changes rapidly, on-policy could be more effective due to its ability to learn and adapt continuously.</p><p>Examples of on-policy model-free algorithms:</p><ol><li><a href="https://medium.com/sciforce/reinforcement-learning-and-asynchronous-actor-critic-agent-a3c-algorithm-explained-f0f3146a14ab">A3C (Asynchronous Advantage Actor-Critic)</a> uses two neural networks: an actor that decides which action to take and a critic that determines how good the action was. The actor updates the policy based on the advantage (the difference between the actual return and the estimated return), and the critic estimates the return.</li><li><a href="https://towardsdatascience.com/trust-region-policy-optimization-trpo-explained-4b56bd206fc2">TRPO (Trust Region Policy Optimization)</a> modifies the policy by setting a specific region in which the policy can be updated. The policy update is ensured not to be too big to prevent instability.</li><li><a href="https://openai.com/index/openai-baselines-ppo">PPO (Proximal Policy Optimization)</a> combines the best of both worlds from A3C and TRPO. It tries to limit the policy change at each update to avoid harmful large updates.</li></ol><h4>Proximal Policy Optimization (PPO)</h4><p>We will be using PPO throughout this blog series, its design ensures a stable and consistent improvement of the policy and value networks over the course of the entire training procedure. When PPO is provided with sufficient training time, it eventually converges to a better final policy than other RL algorithms. PPO also supports discrete action space, which aligns with our trading strategy.</p><p>In the Proximal Policy Optimization algorithm, two neural networks are typically involved:</p><ol><li>Policy network (Actor): the Policy network is responsible for generating the actions for the agent. Given the state of the environment, the Policy network outputs a probability distribution over the available actions. The agent then selects the action based on this distribution. The training aims to adjust the Policy network parameters to produce actions that lead to higher rewards. Policy network solves a classification problem. When the observation state (flattened 1D feature vector) is received as input, the Policy network predicts one of four possible classes (actions).</li><li>Value network (Critic): the Value network is used to estimate the expected return (future rewards) of being in a given state or taking an action in a given state. This is used to compute the Advantage function, which measures how much better an action is compared to the average action in that state. The Advantage function is used to update the Policy network in a direction that improves the expected return. Value network solves a regression problem. It receives a feature vector and outputs a single number (Advantage).</li></ol><p>The Policy network and Value network work together to allow the agent to learn an optimal policy that maximizes the expected return. The Policy network proposes actions, and the Value network critiques these actions, providing a signal that is used to improve the policy. We need only a Policy network (Actor) for inference.</p><p>In some implementations of PPO, a single network with two sets of output layers (one for the policy and one for the value function) is used instead of two separate networks. This can be adjusted using the parameter <em>training.model.vf_share_layers</em> in <a href="https://github.com/xkaple00/deep-reinforcement-learning-for-crypto-trading/blob/master/config.py">config.py</a>.</p><p>The PPO algorithm uses two main mechanisms to ensure that the updated policy is not far away from the current policy to avoid instability:</p><ol><li>Clipped Probability Ratio: PPO proposes an objective function that limits the new policy from deviating too much from the old policy. It does this by clipping the policy ratio (the ratio between new and old policy probabilities). The clipping ensures that the ratio stays close to 1, and the new policy remains ‘proximal’ to the old policy. This reduces the risk of harmful updates.</li><li>Adaptive KL Penalty: PPO also uses a mechanism called Adaptive KL Penalty, which constrains the step size of the policy update. It checks the Kullback-Leibler (KL) divergence between the new and old policy. If the KL divergence is above a certain threshold, the new policy tries to deviate too much from the old policy, and the update is penalized.</li></ol><h4>PPO config</h4><p>My PPO config is defined in <a href="https://github.com/xkaple00/deep-reinforcement-learning-for-crypto-trading/blob/master/config.py">config.py</a> file.</p><p>This set of parameters is a good starting point for seeing that training goes as expected:</p><pre>ppo_config = (<br>    PPOConfig()<br>    # .rl_module(_enable_rl_module_api=False)<br>    .framework(&#39;tf&#39;)<br>    .environment(<br>        env=&#39;CryptoEnv&#39;,<br>        env_config={<br>            &quot;dataset_name&quot;: &quot;dataset&quot;,  # .npy files should be in ./data/dataset/<br>            &quot;leverage&quot;: 2, # leverage for perpetual futures<br>            &quot;episode_max_len&quot;: 168 * 2, # train episode length, 2 weeks<br>            &quot;lookback_window_len&quot;: 168, # 1 week<br>            &quot;train_start&quot;: [2000, 7000, 12000, 17000, 22000],<br>            &quot;train_end&quot;: [6000, 11000, 16000, 21000, 26000], <br>            &quot;test_start&quot;: [6000, 11000, 16000, 21000, 26000],<br>            &quot;test_end&quot;: [7000, 12000, 17000, 22000, 29377-1], <br>            &quot;order_size&quot;: 50, # dollars<br>            &quot;initial_capital&quot;: 1000, # dollars<br>            &quot;open_fee&quot;: 0.12e-2, # taker_fee<br>            &quot;close_fee&quot;: 0.12e-2, # taker_fee<br>            &quot;maintenance_margin_percentage&quot;: 0.012, # 1.2 percent<br>            &quot;initial_random_allocated&quot;: 0, # opened initial random long/short position up to initial_random_allocated $<br>            &quot;regime&quot;: &quot;training&quot;,<br>            &quot;record_stats&quot;: False, # True for backtesting<br>        },<br>        observation_space=gym.spaces.Box(<br>            low=-np.inf,<br>            high=np.inf,<br>            shape=(183 * 168,),<br>            dtype=np.float32<br>        ),<br>        action_space=gym.spaces.Discrete(4),<br>    )<br>    .training(<br>        lr=5e-5,<br>        gamma=0.995, # 1.<br>        grad_clip=30.,<br>        entropy_coeff=0.03,<br>        kl_coeff=0.05,<br>        kl_target=0.01, # not used if kl_coeff == 0.<br>        num_sgd_iter=10,<br>        use_gae=True,<br>        clip_param=0.3, # larger values for more policy change<br>        vf_clip_param=10,<br>        train_batch_size=15 * 8 * 168, # num_rollout_workers * num_envs_per_worker * rollout_fragment_length<br>        shuffle_sequences=True,<br>        model={<br>            &quot;vf_share_layers&quot;: False,<br>            &quot;custom_model&quot;: &quot;TransformerModelAdapter&quot;,<br>            &quot;custom_model_config&quot;: {<br>                &quot;d_history_flat&quot;: 168 * 183,<br>                &quot;num_obs_in_history&quot;: 168,<br>                &quot;d_obs&quot;: 183,<br>                &quot;d_time&quot;: 2, # hour, day<br>                &quot;d_account&quot;: 2, # unrealized_pnl, available_balance<br>                &quot;d_candlesticks_btc&quot;: 34, # TA indicators<br>                &quot;d_candlesticks_ftm&quot;: 34, # TA indicators<br>                &quot;d_santiment_btc_1h&quot;: 30,<br>                &quot;d_santiment_btc_1d&quot;: 26,<br>                &quot;d_santiment_ftm_1h&quot;: 27, <br>                &quot;d_santiment_ftm_1d&quot;: 28, <br>                &quot;d_obs_enc&quot;: 256,<br>                &quot;num_attn_blocks&quot;: 3,<br>                &quot;num_heads&quot;: 4,<br>                &quot;dropout_rate&quot;: 0.1<br>            }<br>        }<br>    )<br>    .evaluation(<br>        evaluation_interval=1,<br>        evaluation_duration=8,<br>        evaluation_duration_unit=&#39;episodes&#39;,<br>        evaluation_parallel_to_training=False,<br>        evaluation_config={<br>            &quot;explore&quot;: False,<br>            &quot;env_config&quot;: {<br>                &quot;regime&quot;: &quot;evaluation&quot;,<br>                &quot;record_stats&quot;: False, # True for backtesting<br>                &quot;episode_max_len&quot;: 168 * 2, # validation episode length<br>                &quot;lookback_window_len&quot;: 168, <br>            }<br>        },<br>        evaluation_num_workers=4<br>    )<br>    .rollouts(<br>        num_rollout_workers=15,<br>        num_envs_per_worker=8,<br>        rollout_fragment_length=168,<br>        batch_mode=&#39;complete_episodes&#39;,<br>        preprocessor_pref=None<br>    )<br>    .resources(<br>        num_gpus=1<br>    )<br>    .debugging(<br>        log_level=&#39;WARN&#39;<br>    )<br>)</pre><p>There are several hyperparameters in the configuration that are particularly important:</p><ul><li><em>lr</em> (learning rate): the step size at each iteration while moving toward a minimum of a loss function.</li><li><em>grad_clip</em>: the hyperparameter epsilon in the PPO paper, which is used to clip the policy update to prevent too drastic updates. If this value is too high, the policy may update too much, which can destabilize learning; if it’s too low, the policy may not learn effectively.</li><li><em>num_sgd_iter</em>: equivalent to the number of epochs, defining the number of times to iterate through collected batches of data during the SGD (Stochastic Gradient Descent) process. If this value is too low, it may lead to underfitting; if it’s too high, it may lead to overfitting.</li><li><em>train_batch_size</em>: batch size for all learner workers. A smaller batch size may lead to a noisier gradient estimation, while a larger one may provide a more accurate estimation but at the cost of computational resources.</li><li><em>gamma</em> (discount factor): determines the importance of future rewards. A high gamma makes the agent consider future rewards more heavily, promoting long-term strategies, while a low gamma makes the agent prioritize immediate rewards.</li><li><em>entropy_coeff</em> (entropy coefficient): This provides a bonus reward for more random actions, encouraging exploration. If you’re finding that your agent isn’t exploring the environment enough, you might need to increase this coefficient.</li></ul><p>These hyperparameters can significantly affect the performance and stability of the PPO algorithm. You can learn more about PPO-specific config parameters <a href="https://docs.ray.io/en/latest/rllib/rllib-algorithms.html#ray.rllib.algorithms.ppo.ppo.PPOConfig.training">here</a>. The common config for all Ray algorithms is <a href="https://docs.ray.io/en/latest/rllib/rllib-training.html#common-parameters">here</a>.</p><h3>Neural Network Architecture</h3><p>RLlib supports the use of recurrent/attention models for all its policy-gradient algorithms (A3C, PPO, PG, IMPALA), and the necessary sequence processing support is built into its policy evaluation utilities.</p><p>You can start using RLLib models out of the box by setting <em>use_lstm </em>or <em>use_attention </em>parameters to True in your model config. The observation state will be processed by an LSTM layer or an attention (GTrXL) network respectively.</p><p>The usage of LSTM is obvious since we work with time series data. Transformer architectures are very promising for our use case, but training a transformer takes much more time and computational resources. Nvidia RTX 2080 Ti with 11 GB memory is enough for training with the published config. <a href="https://nixtlaverse.nixtla.io/neuralforecast/index.html">NeuralForecast</a> library offers a comprehensive list of architectures you can experiment with.</p><p>If you want to create a custom policy and value models, follow this <a href="https://docs.ray.io/en/latest/rllib/rllib-models.html#custom-models-implementing-your-own-forward-logic">guide</a>.</p><h4>Custom policy and value models</h4><p>I’ve implemented more advanced models with superior performance, one of which is open-sourced in a <a href="https://github.com/xkaple00/deep-reinforcement-learning-for-crypto-trading/blob/master/models/transformer.py">transformer.py</a> file. If you are interested in my research, feel free to contact me.</p><p>My neural network architecture represents a sophisticated model designed for processing various types of time-series data. This architecture comprises multiple custom layers and follows a Transformer-based pattern to encode and process sequential data efficiently. It covers pre-processing, encoding transformational data, and producing actionable outputs.</p><p>Firstly, let’s outline the significant components and their role in the architecture:</p><ol><li><em>InputSplit</em> layer takes a flat tensor of observation history and splits it into logically separate segments such as time, account information, TA indicators for BTC and FTM, and Santiment data for BTC and FTM over 1-hour and 1-day intervals.</li><li><em>TimeEncoding </em>and <em>AccountEncoding</em> layers encode time and account information into denser representations.</li><li><em>CandlesticksEncoding</em> and <em>SantimentEncoding</em> handle the encoding of TA data and Santiment data for BTC and FTM.</li><li><em>ObsEncodingInternal </em>and <em>ObsEncodingExternal</em> layers combine the internal (time and account) and external (TA and Santiment data) encodings to produce representations that account for internal state and market conditions.</li><li><em>Stem </em>and <em>StemOutputConcatenation</em> serve as the entry point for feeding the encoded data into the transformer model. It processes and combines both internal and external encodings before passing them down the pipeline.</li><li><em>AttentionBlock </em>and <em>TransformerOutputTimePooling </em>make the core of the transformer architecture, applying self-attention mechanisms to capture dependencies across different points in time and different features within the data. The <em>TransformerOutputTimePooling </em>layer aggregates the transformer’s encoded information to focus on the most recent state for decision-making.</li><li><em>ActionBranch </em>and <em>ValueBranch </em>Layers represent the heads of the network responsible for producing actionable outputs. The <em>ActionBranch </em>predicts the next action based on the encoded input sequence, while the <em>ValueBranch </em>estimates the expected returns or value from taking such actions.</li></ol><p><em>TransformerModel </em>is a top-level layer that combines all the components mentioned above into a coherent model architecture, feeding forward through processing units, attention blocks, and finally to output layers for actions and value estimation.</p><p>This architecture is designed with flexibility in mind, allowing for adjustment of dimensions, encoding depths, and the number of attention blocks to adapt to different datasets and problem settings. It is particularly suited for RL environments where the model needs to make sequential decisions based on historical data and the most recent internal and external states. The use of attention mechanisms ensures that the network can focus on the most relevant information over the input sequence, improving its capacity to predict complex time-series patterns effectively.</p><h3>Training</h3><p>In RLlib there are 2 ways to interact with the algorithm. You can use the basic Python API or Ray Tune to tune hyperparameters of your reinforcement learning algorithm. I prefer the latter option.</p><p>Command to start training:</p><pre>python train.py</pre><p>Ray Tune API example:</p><pre>tune.run(<br>    &quot;PPO&quot;,<br>    stop={&quot;timesteps_total&quot;: int(1e10)},<br>    config=ppo_config,<br>    local_dir=&quot;./results&quot;, # default folder &quot;~ray_results&quot; <br>    checkpoint_freq=12,<br>    checkpoint_at_end=False,<br>    keep_checkpoints_num=None,<br>    verbose=2,<br>    reuse_actors=False,<br>    # resume=True,<br>    # restore=&quot;./results/PPO/PPO_CryptoEnv_1a171_00000_0_2024-05-02_11-51-01/checkpoint_000012&quot;<br>)</pre><p>The RL feedback loop repeatedly collects data for agent policies, trains the policies on these collected data, and makes sure the policies’ weights are kept in sync. The environment data contains observations, taken actions, received rewards and so-called <em>done</em> flags, indicating the boundaries of different episodes the agents play through. The training iterates over a loop of action -&gt; reward -&gt; next state -&gt; train -&gt; repeat, until the <em>stop</em> condition is hit.</p><h4>Tensorboard logs</h4><p>I usually monitor tensorboard metrics until they start to saturate, and then I stop the training. I do not apply early stopping because monitored metrics are noisier than those in the supervised learning setting, and they can start to improve after a considerable amount of training time. Trained models and tensorboard logs are saved under <em>local_dir</em> every <em>checkpoint_freq</em> epochs. There is a <a href="https://drive.google.com/file/d/12IyS3PKTx0KQr-J28vYOYJon5qpIRhsB/view?usp=sharing">tensorboard</a> file with one of my experiments.</p><p>Notes on the most important tensorboard metrics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oIbNmAs6gItS_2Bq6oa4DA.png" /><figcaption>average rewards per training epoch; image by author</figcaption></figure><p>The average positive reward during training indicates that the agent is profiting from the training dataset since the agent reward is proportional to <em>realized_pnl</em> when closing a position or when the episode end condition is met.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2l_PZHdAgAv_XTrkZc1S2w.png" /><figcaption>average rewards per validation epoch; image by author</figcaption></figure><p>The average validation rewards are not as smooth as training rewards, but you can notice that most of the episode rewards are above zero. This means the agent makes a profit on the validation dataset despite high fees (twice the actual taker fees). Again, the rewards are proportional to the agent’s realized profit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GQtH1ruh1D1uILdN9t3fBQ.png" /><figcaption>entropy per training epoch; image by author</figcaption></figure><p>Entropy decline proves that the agent becomes more confident in taking specific actions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RIb_iF4aENhbN3tf6FA6yA.png" /><figcaption>policy loss per training epoch; image by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hDCizOSAJjRzpKNwF8WcdQ.png" /><figcaption>value function loss per training epoch; image by author</figcaption></figure><p>Policy loss and Value function loss are decreasing as expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YT--V79IwwNZOyJaH-10kw.png" /><figcaption>value function explained variance per training epoch; image by author</figcaption></figure><p>Value function explained variance increases gradually and then saturates near 0.99 as expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hqWUb4qYS6355GdRTuRkBg.png" /><figcaption>average episode length per training epoch; image by author</figcaption></figure><p>Sometimes, the length of a training episode is shorter than <em>episode_max_len</em>, which means liquidation occurred. The agent encounters liquidations during training and experience that this hurts.</p><p>In <a href="https://github.com/xkaple00/deep-reinforcement-learning-for-crypto-trading/blob/master/train.py">train.py</a> you can <em>resume </em>training from the last RLlib run or <em>restore </em>the checkpoint path from which you would like to continue training.</p><h3><strong>Conclusion</strong></h3><p>This article provided a comprehensive overview of the training process involved in deep reinforcement learning for crypto trading. We explored the reasoning behind choosing RLlib from Ray as the reinforcement learning library, along with the selection of the Proximal Policy Optimization (PPO) algorithm. The PPO configuration parameters were explained in detail, highlighting their impact on the algorithm’s performance.</p><p>We discussed the implementation of a custom neural network architecture designed for processing time-series data effectively. This architecture utilizes a transformer-based approach to capture dependencies within the data and make informed decisions.</p><p>Finally, the training process itself was explored, including the feedback loop and key metrics monitored through TensorBoard logs. Understanding these metrics is crucial for evaluating the agent’s performance and determining the optimal stopping point for training</p><p>This ends Part 3: Training, see you in the next <a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-2d2a8204bf79">Part 4: Backtesting</a>.</p><p>If you are interested in cooperation, feel free to contact me.</p><h3>Contacts</h3><p>My email: <a href="/service/mailto:alex.kaplenko@sane-ai.dev">alex.kaplenko@sane-ai.dev</a></p><p>My LinkedIn: <a href="https://www.linkedin.com/in/alex-sane-ai/">https://www.linkedin.com/in/alex-sane-ai/</a></p><p>GitHub: <a href="https://github.com/xkaple00/deep-reinforcement-learning-for-crypto-trading">https://github.com/xkaple00/deep-reinforcement-learning-for-crypto-trading</a></p><p>Link to support Ukraine: <a href="https://war.ukraine.ua/donate/">https://war.ukraine.ua/donate/</a></p><p>Visit us at <a href="https://www.datadriveninvestor.com/"><em>DataDrivenInvestor.com</em></a></p><p>Subscribe to DDIntel <a href="https://www.ddintel.com/"><em>here</em></a>.</p><p>Join our creator ecosystem <a href="https://join.datadriveninvestor.com/"><em>here</em></a>.</p><p>DDI Official Telegram Channel: <a href="https://t.me/+tafUp6ecEys4YjQ1">https://t.me/+tafUp6ecEys4YjQ1</a></p><p>Follow us on <a href="https://www.linkedin.com/company/data-driven-investor"><em>LinkedIn</em></a>, <a href="https://twitter.com/@DDInvestorHQ"><em>Twitter</em></a>, <a href="https://www.youtube.com/c/datadriveninvestor"><em>YouTube</em></a>, and <a href="https://www.facebook.com/datadriveninvestor"><em>Facebook</em></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b5705128732" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/deep-reinforcement-learning-for-crypto-trading-6b5705128732">Deep Reinforcement Learning for Crypto Trading</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Reinforcement Learning for Crypto Trading]]></title>
            <link>https://medium.com/coinmonks/deep-reinforcement-learning-for-crypto-trading-261f8820f129?source=rss-88ed5cd82154------2</link>
            <guid isPermaLink="false">https://medium.com/p/261f8820f129</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[crypto]]></category>
            <category><![CDATA[bots]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Alex K]]></dc:creator>
            <pubDate>Fri, 17 May 2024 18:15:07 GMT</pubDate>
            <atom:updated>2024-07-01T10:38:04.202Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 2: Trading Strategy</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gW_py8A-nVLUuMX4BQ3J8Q.jpeg" /><figcaption>photo by <a href="https://unsplash.com/@artrachen">Art Rachen</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>Disclaimer: The information provided herein does not constitute financial advice. All content is presented solely for educational purposes.</em></p><h3>Introduction</h3><p>This is the second part of my blog post series on reinforcement learning for crypto trading:</p><ul><li><a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-72c06bb9b04c">Part 0: Introduction</a></li><li><a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-part-1-data-preparation-682173ef3000">Part 1: Data preparation</a></li><li><a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-261f8820f129">Part 2: Trading strategy</a></li><li><a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-6b5705128732">Part 3: Training</a></li><li><a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-2d2a8204bf79">Part 4: Backtesting</a></li><li><a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-ed385e87ab0e">Part 5: Live trading</a></li></ul><p>This article explains the trading strategy and the reinforcement learning environment.</p><p>As I mentioned in <a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-72c06bb9b04c">Part 0: Introduction</a>, my main goal is to connect with potential employers or investors and ultimately become a professional quant.</p><h3>Resources</h3><ul><li><a href="https://github.com/xkaple00/deep-reinforcement-learning-for-crypto-trading/blob/master/envs/training_env.py">training_env.py</a></li><li><a href="https://github.com/xkaple00/deep-reinforcement-learning-for-crypto-trading/blob/master/envs/gym_space_builder.py">gym_space_builder.py</a></li><li><a href="https://github.com/xkaple00/deep-reinforcement-learning-for-crypto-trading/blob/master/config.py">config.py</a></li></ul><h3>Trading Strategy</h3><p>Bots trade perpetual futures contracts with <a href="https://academy.binance.com/en/articles/what-is-leverage-in-crypto-trading">leverage</a> 2 (I experimented with different leverages, but we will stick to leverage 2 throughout the entire blog series; this value provides a meaningful risk-reward ratio for volatile altcoins trading).</p><p>The published strategy operates in <a href="https://www.binance.com/en/blog/futures/managing-risks-with-hedge-mode-in-crypto-futures-trading-3345275339961971082">One-Way mode</a>; the bot can hold only a long or a short position at any given point. I also created bots trading only longs, only shorts, and bots operating in a <a href="https://www.binance.com/en/blog/futures/managing-risks-with-hedge-mode-in-crypto-futures-trading-3345275339961971082">Hedge mode</a>, which is not included in the published version.</p><p>According to my experiments, “long” bots are very profitable in a bull market (even a poorly trained agent can be profitable if allowed to open only long positions during an uptrend), well-trained agents rarely open long positions during a bear market. Bots operating in Hedge mode often learn a hedging strategy and simultaneously hold a long and a short position of equal sizes.</p><p><a href="https://www.coinbase.com/learn/tips-and-tutorials/dollar-cost-averaging">Dollar-cost averaging (DCA)</a> is another concept I’ve used. The idea is not to let bots invest all their available capital at once but rather in small portions per timestep. Bots operate on a 1-hour timeframe, so they can open/close long/short positions or choose to do nothing every 1 hour.</p><p>I use the concept of position <a href="https://www.bybit.com/en/help-center/article/How-to-calculate-average-entry-price"><em>average_price</em></a>. The average price is recalculated when we add to the position (sell action for short position or buy action for long position). The average price is not recalculated if the position size is reduced (buy action for shorts or sell for longs).</p><p>You can freely play with different <em>available_balance</em>, <em>order_size</em> and <em>leverage</em> ratios. Just be careful, there is a minimum position size in coins or USDT equivalent that cryptocurrency exchanges allow to open. For example, on Bybit you cannot open a position smaller than 1 FTM. At the time of writing FTM all-time-high is around 3.5$ and I believe it will rise further after the Bitcoin halving in 2024, so adjust your order size to be equal to or greater than the FTM price.</p><p>There are two options for how to close a position:</p><ol><li>Reduce by <em>order_size</em>, that is reduce <em>position_value</em> by 100$. Position reduction can take place in multiple time steps.</li><li>Close the entire position at once, no matter how large it is. This option is useful in case of black-swan events or rapid market swings, similar to the “Panick Sell” button.</li></ol><p>I’ve developed more advanced strategies but the strategy explained in this guide is a good starting point. Market orders are used to open or close positions. I just want to keep it simple for blog purposes, limit orders however have smaller fees and it’s possible to create more advanced strategies using even more <a href="https://www.bybit.com/en-US/help-center/s/article/What-is-a-limit-market-conditional-order">complex order types</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4BLh0PZV-OBYbUwPBas4og.png" /><figcaption>hedging mode on Bybit, long and short positions are opened simultaneously; image by author</figcaption></figure><p>In the hedging mode both long and short positions are open. If the agent “predicts” the price will rise, <em>position_value_long </em>is greater than <em>position_value_short</em>, and vice versa. If the price starts rising, the agent will close the short position at a small loss, and after a further price increase, the long position will be closed with a larger profit. The long/short <em>position_value</em> ratio itself can serve as an indicator of the agent’s “forecast” regarding the future market trend. Often the values of both positions are equal (hedging) in the case of a neutral market. This strategy works better in trending markets.</p><h3>Gym environment</h3><p>A reinforcement learning agent needs an environment — a set of rules it can follow. Using the <a href="https://gymnasium.farama.org/index.html">Gymnasium</a> library, I coded an appropriate environment for my strategy.</p><p>Config for the environment:</p><pre>  env_config={<br>      &quot;dataset_name&quot;: &quot;dataset&quot;,  # .npy files should be in ./data/dataset/<br>      &quot;leverage&quot;: 2, # leverage for perpetual futures<br>      &quot;episode_max_len&quot;: 168 * 2, # train episode length, 2 weeks<br>      &quot;lookback_window_len&quot;: 168, # 1week<br>      &quot;train_start&quot;: [2000, 7000, 12000, 17000, 22000],<br>      &quot;train_end&quot;: [6000, 11000, 16000, 21000, 26000], <br>      &quot;test_start&quot;: [6000, 11000, 16000, 21000, 26000],<br>      &quot;test_end&quot;: [7000, 12000, 17000, 22000, 29377-1], <br>      &quot;order_size&quot;: 50, # dollars<br>      &quot;initial_capital&quot;: 1000, # dollars<br>      &quot;open_fee&quot;: 0.12e-2, # taker_fee<br>      &quot;close_fee&quot;: 0.12e-2, # taker_fee<br>      &quot;maintenance_margin_percentage&quot;: 0.012, # 1.2 percent<br>      &quot;initial_random_allocated&quot;: 0, # opened initial random long/short position up to initial_random_allocated $<br>      &quot;regime&quot;: &quot;training&quot;,<br>      &quot;record_stats&quot;: False, # True for backtesting<br>  },</pre><p>The environment simulates interactions on the exchange. It has three main attributes: <em>observation_space</em>, <em>action_space</em>, and <em>reward</em>.</p><h4>Action space</h4><p>I already explained an <em>action_space </em>in the previous section. Let’s now formalize it:</p><pre>action_space = gymnasium.spaces.Discrete(4)</pre><p>There are 4 discrete actions:</p><ol><li>Do nothing</li><li>Add to the long/short position an <em>order_size</em> amount of USDT</li><li>Reduce a long/short position by <em>order_size</em> amount of USDT</li><li>Close entire position</li></ol><p>In Hedge mode, the action space has 4 * 4 = 16 options, making exploration quadratically more complex.</p><p>I’ve also experimented with training agents with continuous action spaces but discrete action spaces have worked better so far. A continuous action space increases the complexity of the problem and makes the learning process longer. For instance, deciding how much of a particular coin to buy or sell at any given time involves infinite choices, making it harder for the agent to learn optimal policies. Discrete action spaces generally lead to faster convergence during training.</p><h4>Observation space</h4><p>Throughout this blog series, we use a custom Transformer architecture, which is discussed in detail in <a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-6b5705128732">Part 3: Training</a>. Transformers store previous timesteps using a window approach. Neural network input is a 3D tensor of dimensions (batch_size, sequence_length, num_features).</p><p>sequence_length corresponds to <em>lookback_window_len</em> parameter in <a href="https://github.com/xkaple00/deep-reinforcement-learning-for-crypto-trading/blob/master/config.py">config.py</a> and is equal to 168, which is 168 hours or 1 week. Agent receives 1 last week of data as an observation state to make a decision every timestep.</p><p>num_features consists of two parts:</p><ol><li>The static (internal state) part is stored on disk in a metrics_outfile.npy, as discussed in <a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-part-1-data-preparation-682173ef3000">Part 1: Data preparation</a>. There are 181 static features: day, hour, TA indicators, on-chain and sentiment metrics for FTM and BTC.</li><li>The dynamic (external state) part consists of 2 exchange account parameters: <em>available_balance </em>and <em>unrealised_pnl.</em> These two features are dynamic because they change depending on the agent’s previous actions. <em>available_balance </em>gives an agent information on whether it can add to the existing position; <em>unrealised_pnl</em> signals the number of rewards the agent receives if it closes the position at the current timestep.</li></ol><p><em>Scaler</em> class scales and preprocesses data to a valid observation format:</p><pre>class Scaler:<br>    def __init__(self, min_quantile: int = 1, max_quantile: int = 99, scale_coef: float = 1e3) -&gt; None:<br>        self.transformer = None # &lt;class &#39;sklearn.preprocessing._data.RobustScaler&#39;&gt;<br>        self.min_quantile = min_quantile<br>        self.max_quantile = max_quantile<br>        self.scale_coef = scale_coef<br><br>    def reset(self, state_array, reset_array):<br>        # don&#39;t apply scaler to day, hour, unrealized_pnl and available_balance columns<br>        self.transformer = RobustScaler(quantile_range=(self.min_quantile, self.max_quantile)).fit(reset_array[:, 4:]) <br>        scaled_np_array = self.step(state_array)<br><br>        return scaled_np_array<br><br>    def step(self, state_array):<br>        day_column = state_array[:, [0]] <br>        hour_column = state_array[:, [1]]<br>        available_balance = state_array[:, [2]] / self.scale_coef<br>        unrealized_pnl = state_array[:, [3]] / self.scale_coef<br>        transformed_indicators = np.clip(self.transformer.transform(state_array[:, 4:]), a_min=-10., a_max=10.)<br>        scaled_np_array = np.hstack((day_column, hour_column, available_balance, unrealized_pnl, transformed_indicators)).astype(np.float32)<br>        return scaled_np_array</pre><p>The <em>scaled_np_array</em> is the 2D array with columns:</p><ul><li><em>day_column</em></li><li><em>hour_column</em></li><li><em>available_balance</em></li><li><em>unrealized_pnl</em></li><li><em>transformed_indicators</em> (includes TA indicators, on-chain and sentiment metrics)</li></ul><p><em>observation_space</em> is a flattened 1D vector with shape (183 * 168, ):</p><pre>observation_space=gymnasium.spaces.Box(<br>  low=-np.inf,<br>  high=np.inf,<br>  shape=(183 * 168,),<br>  dtype=np.float32<br>)</pre><h4>Reward function</h4><p>The agent learns from the rewards it receives, positive rewards for doing “right” actions and negative rewards for doing “wrong” actions. The simplest possible reward function returns a normalized profit and loss when a position is closed. The reward is proportional to <em>realized_pnl</em> in this case. For example, if an agent closes a position in 50$ profit, we can divide it by <em>initial_balance </em>of 1000$ so the reward equals 0.05 to ensure rewards are always in a meaningful range of [-1:1]</p><p>Realized reward function:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FbEn4a5L5mLebjQwXzrWp1t&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2FbEn4a5L5mLebjQwXzrWp1t&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="200" height="96" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa0caffeeba1c8faa8d396030d60bd2b/href">https://medium.com/media/fa0caffeeba1c8faa8d396030d60bd2b/href</a></iframe><p>In code:</p><pre>reward = (self.reward_realized_pnl_short + self.reward_realized_pnl_long) / self.initial_balance</pre><p>The problem of sparse rewards can arise if the agent doesn’t close positions for a long period of time. It becomes more difficult for the agent to capture the correlation between actions in the past and recent rewards received for closing a position.</p><p>Another reward function can give rewards each timestep depending on how account <em>equity</em> has changed compared to the previous timestep.</p><p>Equity reward function:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FepjVev6kfBHksQn7Jbp6BV&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2FepjVev6kfBHksQn7Jbp6BV&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="200" height="96" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4c0f09b7f419e29ed20ed450699ab46/href">https://medium.com/media/e4c0f09b7f419e29ed20ed450699ab46/href</a></iframe><p>In this case, rewards can become very noisy and harder to learn from.</p><p>I’ve also tested a combined reward: the agent receives a reward for closing a position (<em>realized_pnl</em>) and also a small reward equal to the fraction of <em>unrealized_pnl</em> during each timestep.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FeaZkzWHrrMfzrixQRP64iZ&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2FeaZkzWHrrMfzrixQRP64iZ&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="1164" height="159" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac7f431f28607c2331790c9d8042087c/href">https://medium.com/media/ac7f431f28607c2331790c9d8042087c/href</a></iframe><p>In simpler terms, the <em>coef</em> is like a slider that adjusts how much weight we give to unrealized profits and losses compared to realized ones. For example, if the <em>coef</em> is set at 0.01, it means that holding a position at a loss for 100 time steps is as bad as just closing it out right away. In both cases, the cumulative negative rewards would be the same.</p><p>It’s also possible to punish an agent for holding a position in loss and not giving it any positive rewards for holding a position in profit. Many papers use the <a href="https://www.investopedia.com/terms/s/sharperatio.asp">Sharpe</a> or <a href="https://www.investopedia.com/terms/s/sortinoratio.asp">Sortino</a> ratio as a reward function; you can also try it. The choice of reward function dramatically affects training dynamics.</p><p>When the episode ends after <em>episode_max_len</em> timesteps have been played, the agent closes all open positions and receives an appropriate reward.</p><h4>Step &amp; Reset methods in the training environment</h4><p>I did my best to capture all the intricacies to simulate processes under the hood on the exchange during opening/closing positions and the liquidation process. The training environment is not one-to-one similar to real exchanges, but I believe it catches all main concepts such as:</p><ul><li>bid/ask spread</li><li>opening/closing fees</li><li>all calculations between exchange account parameters such as: <em>equity, wallet_balance, available_balance, margin, position_value, unrealized_pnl, </em>etc</li><li>liquidation process</li><li>logical things, such as: the agent cannot open a new position if <em>available_balance</em> is lower than <em>order_size</em>, etc</li></ul><p>Environment doesn’t take into account funding fees and slippage. This is compensated by a fee twice as large as the real one, which the agent pays for opening/closing positions. At the time of writing, the non-Vip <em>taker_fee</em> on Bybit is 0.06%. I use 0.12% during training.</p><p>As stated:</p><blockquote>“The more you sweat in training, the less you bleed in combat.”</blockquote><p>The bid/ask spread is constant rather than the exchange’s real bid/ask price. In my environment, the bid/ask price deviates from the middle price by the <em>taker_fee</em> * 2.</p><p>During training, the algorithm randomly samples a timestep for the episode beginning from the training dataset and then plays for <em>episode_max_len </em>timesteps calling <em>step</em> method every timestep. Episode length (336 timesteps) corresponds to 2 weeks. After that, the <em>reset </em>method returns the agent to the initial state and the process repeats. If the liquidation happens in the middle of the episode, the agent receives a negative reward and the episode ends (episode length in this case is shorter than 336).</p><p>Code for the <em>step</em> method of <a href="https://github.com/xkaple00/deep-reinforcement-learning-for-crypto-trading/blob/master/envs/training_env.py"><em>LearningCryptoEnv</em></a> class:</p><pre>  def step(self, action: int):<br>      assert action in [0, 1, 2, 3], action<br><br>      self.price_bid = self.price_array[self.time_absolute, 0] * (1 - self.open_fee)<br>      self.price_ask = self.price_array[self.time_absolute, 0] * (1 + self.open_fee)<br><br>      margin_short_start = self.margin_short<br>      margin_long_start = self.margin_long<br><br>      self.reward_realized_pnl_short = 0.<br>      self.reward_realized_pnl_long = 0.<br><br>      # Oneway actions<br>      if action == 0:  # do nothing<br>          self.reward_realized_pnl_long = 0.<br>          self.reward_realized_pnl_short = 0.<br><br>      # similar to &quot;BUY&quot; button<br>      if action == 1: # open/increace long position by self.order_size<br>          if self.coins_long &gt;= 0:<br>              if self.available_balance &gt; self.order_size:<br>                  buy_num_coins = self.order_size / self.price_ask<br>                  self.average_price_long = (self.position_value_long + buy_num_coins * self.price_ask) / (self.coins_long + buy_num_coins)<br>                  self.initial_margin_long += buy_num_coins * self.price_ask / self.leverage<br>                  self.coins_long += buy_num_coins<br><br>          if -self.coins_short &gt; 0: # close/decreace short position by self.order_size<br>              buy_num_coins = min(-self.coins_short, self.order_size / self.price_ask)<br>              self.initial_margin_short *= min((-self.coins_short - buy_num_coins), 0.) / -self.coins_short<br>              self.coins_short = min(self.coins_short + buy_num_coins, 0) # cannot be positive<br>              realized_pnl = buy_num_coins * (self.average_price_short - self.price_ask)  # buy_num_coins is positive<br>              self.wallet_balance += realized_pnl<br>              self.reward_realized_pnl_short = realized_pnl<br><br>      # similar to &quot;SELL&quot; button<br>      if action == 2: # close/reduce long position by self.order_size<br>          if self.coins_long &gt; 0:<br>              sell_num_coins = min(self.coins_long, self.order_size / self.price_ask)<br>              self.initial_margin_long *= (max((self.coins_long - sell_num_coins), 0.) / self.coins_long)<br>              self.coins_long = max(self.coins_long - sell_num_coins, 0) # cannot be negative<br>              realized_pnl = sell_num_coins * (self.price_bid - self.average_price_long)<br>              self.wallet_balance += realized_pnl<br>              self.reward_realized_pnl_long = realized_pnl<br><br>          if -self.coins_short &gt;= 0: # open/increase short position by self.order_size<br>              if (self.available_balance &gt; self.order_size):<br>                  sell_num_coins = self.order_size / self.price_ask<br>                  self.average_price_short = (self.position_value_short + sell_num_coins * self.price_bid) / (-self.coins_short + sell_num_coins)<br>                  self.initial_margin_short += sell_num_coins * self.price_ask / self.leverage<br>                  self.coins_short -= sell_num_coins<br><br>      self.liquidation = -self.unrealized_pnl_long - self.unrealized_pnl_short &gt; self.margin_long + self.margin_short<br>      self.episode_maxstep_achieved = self.time_relative == self.max_step<br><br>      # CLOSE entire position or LIQUIDATION<br>      if action == 3 or self.liquidation or self.episode_maxstep_achieved:<br>          # close LONG position<br>          if self.coins_long &gt; 0:<br>              sell_num_coins = self.coins_long   <br>              # becomes zero<br>              self.initial_margin_long *= max((self.coins_long - sell_num_coins), 0.) / self.coins_long <br>              # becomes zero<br>              self.coins_long = max(self.coins_long - sell_num_coins, 0)<br>              realized_pnl = sell_num_coins * (self.price_bid - self.average_price_long)<br>              self.wallet_balance += realized_pnl<br>              self.reward_realized_pnl_long = realized_pnl<br><br>          # close SHORT position<br>          if -self.coins_short &gt; 0:<br>              buy_num_coins = -self.coins_short<br>              # becomes zero<br>              self.initial_margin_short *= min((self.coins_short + buy_num_coins), 0.) / self.coins_short<br>              # becomes zero<br>              self.coins_short += buy_num_coins<br>              realized_pnl = buy_num_coins * (self.average_price_short - self.price_ask) # buy_num_coins is positive<br>              self.wallet_balance += realized_pnl<br>              self.reward_realized_pnl_short = realized_pnl<br><br>      self.margin_short, self.margin_long = self._calculate_margin_isolated()<br>      self.available_balance = max(self.wallet_balance - self.margin_short - self.margin_long, 0)<br>      self.unrealized_pnl_short = (-self.coins_short * (self.average_price_short - self.price_ask))  # self.coins_short is negatve<br>      self.unrealized_pnl_long = (self.coins_long * (self.price_bid - self.average_price_long)) # - self.fee_to_close_long<br>      next_equity = (self.wallet_balance + self.unrealized_pnl_short + self.unrealized_pnl_long)<br><br>      done = self.episode_maxstep_achieved or self.liquidation # end of episode or liquidation event<br><br>      # reward function<br>      # normalize rewards to fit [-10:10] range<br>      reward = (self.reward_realized_pnl_short + self.reward_realized_pnl_long) / self.initial_balance<br>      # reward = (next_equity - self.equity) / self.initial_balance # reward function for equity changes<br><br>      self.equity = next_equity<br><br>      margin_short_end = self.margin_short<br>      margin_long_end = self.margin_long<br>      <br>      obs_step = self._get_observation_step(self.time_absolute)<br>      obs = self.scaler.step(obs_step).flatten()<br><br>      self.statistics_recorder.update(<br>          action=action,<br>          reward=reward,<br>          reward_realized_pnl_short=self.reward_realized_pnl_short,<br>          reward_realized_pnl_long=self.reward_realized_pnl_long,<br>          unrealized_pnl_short = self.unrealized_pnl_short,<br>          unrealized_pnl_long = self.unrealized_pnl_long,<br>          margin_short_start=margin_short_start,<br>          margin_long_start=margin_long_start,<br>          margin_short_end=margin_short_end,<br>          margin_long_end=margin_long_end,<br>          num_steps=self.time_relative,<br>          coins_short=self.coins_short,<br>          coins_long=self.coins_long,<br>          equity=self.equity,<br>          wallet_balance=self.wallet_balance,<br>          average_price_short = self.average_price_short,<br>          average_price_long = self.average_price_long,<br>      )<br><br>      info = self.statistics_recorder.get()            <br><br>      self.time_absolute += 1<br>      self.time_relative += 1<br><br>      return obs, reward, done, False, info</pre><p>I usually invest 1000$ per bot. With <em>leverage </em>2, the maximum <em>position_value </em>is<em> </em>2000$. If <em>order_size </em>is 50$ and <em>leverage</em> is 2, the open <em>position_value</em> is 100$ reduced by <em>open_fee</em>. The <em>available_balance </em>after opening a position with <em>order_size </em>50$ is reduced by 50$. The strategy opens orders in amounts 5% of the <em>initial_balance</em>.</p><p>Each timestep bot can increase or decrease <em>position_value </em>by 100$. Assuming the maximum <em>position_value </em>2000$, the minimum time to allocate the whole <em>available_balance </em>is 2000 / 100 * 1 hour = 20 hours, in case of adding to a position for 20 hours in a row. That is, the agent must be very confident that the price will rise to open multiple long positions in a row for a few hours.</p><p><em>reset</em> method:</p><pre>  def reset(self, seed=7, options={}):<br>      self._reset_env_state()<br>      state_array, reset_array = self._get_observation_reset()<br>      scaled_obs_reset = self.scaler.reset(state_array, reset_array).flatten()<br><br>      # return scaled_obs_reset<br>      return scaled_obs_reset, {}</pre><p>I’ve implemented a few more ideas:</p><ul><li>more recent timesteps are more important and should be sampled more frequently during training than older ones.</li><li>The initial state is not constant every time after <em>reset</em> method is called, I simulated that with a certain probability at the beginning of the episode, the agent already has open long or short positions at the particular price levels; so it should learn the best policy even at the unfavorable starting conditions. I implemented a logic that as the training progresses (more training epochs pass) the starting conditions become more and more challenging. Hence, it becomes harder for the agent to get positive rewards.</li><li>Users can define several training and validation intervals inside the dataset at different timesteps, rather than validating on the last few months of data; <a href="https://nixtlaverse.nixtla.io/neuralforecast/examples/cross_validation_tutorial.html">cross-validation</a> provides more meaningful validation results obtained from different market regimes.</li></ul><h3>Conclusion</h3><p>This article described the core components of a deep reinforcement learning environment for cryptocurrency trading with a focus on perpetual futures contracts. I introduced a trading strategy that utilizes concept of dollar-cost averaging. The environment uses the Gymnasium library and provides observations, actions, and rewards tailored to the cryptocurrency trading domain.</p><p>We explored different aspects including:</p><ul><li>Trading strategy with long/short order types and position management.</li><li>Gymnasium environment with its key attributes: action space, observation space, and reward function.</li></ul><p>This ends Part 2: Trading strategy, see you in the next <a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-6b5705128732">Part 3: Training</a>.</p><p>If you are interested in cooperation, feel free to contact me.</p><h3>Contacts</h3><p>My email: <a href="/service/mailto:alex.kaplenko@sane-ai.dev">alex.kaplenko@sane-ai.dev</a></p><p>My LinkedIn: <a href="https://www.linkedin.com/in/alex-sane-ai/">https://www.linkedin.com/in/alex-sane-ai/</a></p><p>GitHub: <a href="https://github.com/xkaple00/deep-reinforcement-learning-for-crypto-trading">https://github.com/xkaple00/deep-reinforcement-learning-for-crypto-trading</a></p><p>Link to support Ukraine: <a href="https://war.ukraine.ua/donate/">https://war.ukraine.ua/donate/</a></p><p>Visit us at <a href="https://www.datadriveninvestor.com/"><em>DataDrivenInvestor.com</em></a></p><p>Subscribe to DDIntel <a href="https://www.ddintel.com/"><em>here</em></a>.</p><p>Join our creator ecosystem <a href="https://join.datadriveninvestor.com/"><em>here</em></a>.</p><p>DDI Official Telegram Channel: <a href="https://t.me/+tafUp6ecEys4YjQ1">https://t.me/+tafUp6ecEys4YjQ1</a></p><p>Follow us on <a href="https://www.linkedin.com/company/data-driven-investor"><em>LinkedIn</em></a>, <a href="https://twitter.com/@DDInvestorHQ"><em>Twitter</em></a>, <a href="https://www.youtube.com/c/datadriveninvestor"><em>YouTube</em></a>, and <a href="https://www.facebook.com/datadriveninvestor"><em>Facebook</em></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=261f8820f129" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/deep-reinforcement-learning-for-crypto-trading-261f8820f129">Deep Reinforcement Learning for Crypto Trading</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Reinforcement Learning for Crypto Trading]]></title>
            <link>https://medium.com/coinmonks/deep-reinforcement-learning-for-crypto-trading-part-1-data-preparation-682173ef3000?source=rss-88ed5cd82154------2</link>
            <guid isPermaLink="false">https://medium.com/p/682173ef3000</guid>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[crypto]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[bots]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Alex K]]></dc:creator>
            <pubDate>Fri, 17 May 2024 18:12:59 GMT</pubDate>
            <atom:updated>2024-07-01T10:38:08.057Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 3: Data preparation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JtZeLofb-jLR2SN6tY37mQ.png" /><figcaption>photo by <a href="https://unsplash.com/@michael_f">Michael Förtsch</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>Disclaimer The information provided herein does not constitute financial advice. All content is presented solely for educational purposes.</em></p><h3>Introduction</h3><p>This is the first part of my blog post series on reinforcement learning for crypto trading:</p><ul><li><a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-72c06bb9b04c">Part 0: Introduction</a></li><li><a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-part-1-data-preparation-682173ef3000">Part 1: Data preparation</a></li><li><a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-261f8820f129">Part 2: Trading strategy</a></li><li><a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-6b5705128732">Part 3: Training</a></li><li><a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-2d2a8204bf79">Part 4: Backtesting</a></li><li><a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-ed385e87ab0e">Part 5: Live trading</a></li></ul><p>This article explains the data collection and data normalization process.</p><p>As I mentioned in <a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-72c06bb9b04c">Part 0: Introduction</a>, my main goal is to connect with potential employers or investors and ultimately become a professional quant.</p><h3>Prerequisites</h3><ul><li><a href="https://santiment.net/">Santiment</a> API PRO subscription</li></ul><h3>Resources</h3><p>I do not publish datasets due to privacy concerns; however, I opensource code to collect them via Santiment and Binance/Bybit APIs.</p><p><a href="https://github.com/xkaple00/deep-reinforcement-learning-for-crypto-trading/blob/master/dataset.ipynb">dataset.ipynb</a></p><p>To scrape the dataset, you should create an account on the Santiment platform and <a href="https://academy.santiment.net/products-and-plans/create-an-api-key/#creating-an-api-key">acquire the API key</a>. Binance and Bybit APIs market data are accessible without account registration.</p><h3>Data used</h3><p>Data is the fuel for machine learning algorithms. Therefore, obtaining historical and real-time high-quality data is a top priority. The vast majority of blog posts and research papers on this topic make use of only a few technical indicators. I believe this is enough for a publication but certainly not enough for real trading. My strategy uses four main sources for data:</p><ol><li>Candlesticks (OHLCV) and technical indicators derived from them using <a href="https://github.com/twopirllc/pandas-ta">Pandas TA</a> library.</li><li>On-chain data from providers such as <a href="https://santiment.net/">Santiment</a> or <a href="https://glassnode.com/">Glassnode</a>. In this blog series, we will focus on Santiment. Santiment offers a free trial of the two-week PRO plan and the most comprehensive suite of metrics for ERC-20 tokens. Glassnode, on the other hand, offers the best suite of on-chain metrics for BTC and ETH on the market; however, it targets institutional clients.</li><li>Data from crypto exchanges, such as Funding rate, Open interest, Open value, etc. You can fetch it directly from the exchange APIs but Santiment also does it for a few centralized exchanges.</li><li>Social sentiment metrics from social networks are also offered by the <a href="https://santiment.net/">Santiment</a> data provider.</li></ol><p>Other types of data I’ve experimented with, but they are not included in the public part of my project:</p><ul><li>limited order book data</li><li>proprietary price prediction indicators using deep learning</li></ul><p>Traders use indicators from different time frames to make more informed decisions, and so does my strategy, which uses various metrics at 1-hour and 1-day timeframes. Bots operate in 1-hour discrete time steps, which means a reinforcement learning agent decides to open/close a long/short position or do nothing every 1 hour.</p><p>This blog series focuses on trading Fantom (FTMUSDT trading pair). I’ve chosen this coin because it has strong fundamentals and is one of the most volatile coins among the Top 100 by market cap; I need volatility for my strategy. Santiment provides a wide range of metrics for Fantom (more than 600 since FTM is an ERC-20 token).</p><p>Altcoins usually follow BTC and ETH prices. That’s why I decided to include exchange, on-chain, and sentiment data for the two largest coins by market cap in my dataset. Some on-chain data for Tether (USDT) can also be included in the dataset because Tether is used as collateral. Stablecoins are essential to the crypto space; their flows can provide some insight.</p><h3>Dataset structure</h3><p>Datasets used for training and validation have more than 30000 timesteps on average.</p><p>The final dataset consists of 2 files:</p><ul><li>a traded coin price is in price_outfile.npy file</li><li>metrics_outfile.npy is a 2D array, rows correspond to timesteps, and columns to features</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4AALFGnunNmAu_zhIOoiWA.png" /><figcaption>a chunk of the dataset; image by author</figcaption></figure><p>The Jupyter notebook used to generate the dataset is <a href="https://github.com/xkaple00/deep-reinforcement-learning-for-crypto-trading/blob/master/dataset.ipynb">dataset.ipynb</a>. The Jupyter notebook used to generate the dataset is<a href="https://github.com/xkaple00/deep-reinforcement-learning-for-crypto-trading/blob/master/dataset.ipynb"> dataset.ipynb</a>. This notebook uses Python files to scrape data from corresponding platforms:</p><ul><li><a href="https://github.com/xkaple00/deep-reinforcement-learning-for-crypto-trading/blob/master/scraper_binance.py">scraper_binance.py</a></li><li><a href="https://github.com/xkaple00/deep-reinforcement-learning-for-crypto-trading/blob/master/scraper_bybit.py">scraper_bybit.py</a></li><li><a href="https://github.com/xkaple00/deep-reinforcement-learning-for-crypto-trading/blob/master/scraper_santiment.py">scraper_santiment.py</a></li></ul><p>All files have command-line arguments to define start and end dates, timeframes, and coins to scrape. “historical” mode creates a dataset for training and “live” mode scrapes the last 1 week of data (168 hours, which is an observation state for the agent) every 1 hour and stores files to disk.</p><pre>if __name__ == &quot;__main__&quot;:<br>    parser = argparse.ArgumentParser(description=&#39;Run the Santiment data scraper with specified parameters.&#39;)<br>    parser.add_argument(&#39;--coins&#39;, required=True, help=&#39;Comma-separated list of coin names, e.g.,&quot;BTC,ETH,USDT,FTM,BAT&quot;&#39;)<br>    parser.add_argument(&#39;--resolutions&#39;, required=True, help=&#39;Comma-separated list of resolutions, e.g.,&quot;1h,24h&quot;&#39;)<br>    parser.add_argument(&#39;--start_time&#39;, required=False, help=&#39;Start datetime in ISO format, e.g., &quot;2020-07-01T00:00:00&quot;, not used for live data&#39;)<br>    parser.add_argument(&#39;--end_time&#39;, required=False, help=&#39;End datetime in ISO format, e.g., &quot;2024-04-11T00:00:00&quot;, not used for live data&#39;)<br>    parser.add_argument(&#39;--endpoint_file_paths&#39;, required=True, help=&#39;path of endpoints_file_path_santiment.json&#39;)<br>    parser.add_argument(&#39;--save_folder&#39;, required=True, help=&#39;Folder path to save the scraped data, e.g., &quot;./data/test/santiment/historical&quot;&#39;)<br>    parser.add_argument(&#39;--mode&#39;, required=True, help=&#39;mode to scrape data&#39;, choices=[&quot;historical&quot;, &quot;live&quot;])<br><br>    args = parser.parse_args()<br>    main(args)</pre><p>You can select TA indicators to be calculated by rewriting .csv files under <a href="https://github.com/xkaple00/deep-reinforcement-learning-for-crypto-trading/tree/master/data/endpoints/binance">./data/endpoints/binance</a>; and Santiment metrics to be collected under <a href="https://github.com/xkaple00/deep-reinforcement-learning-for-crypto-trading/tree/master/data/endpoints/santiment">./data/endpoints/santiment</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/112/1*KxpNXmmhQXA4ANUYHGKkeQ.png" /><figcaption>list of TA indicators for FTM at 1 hour and 1 day timeframes; image by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*iQY4RY2d05rkEobsKJiBLA.png" /><figcaption>list of Santiment metrics for FTM at 1 hour timeframe; image by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*MBvP1yzEMeA7gDhbbvFDBg.png" /><figcaption>list of Santiment metrics for FTM at 24 hours timeframe; image by author</figcaption></figure><p>Scrapers use <em>open_time</em> as the Pandas dataframe index during data collection for all .csv files. The final dataset timesteps in <em>metrics_outfile.npy</em>, however, are <em>close_time </em>to align the latest available values for all metrics at every timestep. Timestamps use the UTC+0 time zone.</p><h3>Technical analysis data preparation</h3><p>I collected this set of data from <a href="https://binance-docs.github.io/apidocs/spot/en/#change-log">Binance API</a> or <a href="https://bybit-exchange.github.io/docs/v5/intro">Bybit AP</a>I: ‘open’, ‘high’, ‘low’, ‘close’, ‘volume’, ‘open_time’’ at ‘1h’ and ‘1d’ time intervals.</p><p>Candlesticks are further used to calculate technical indicators using <a href="https://github.com/twopirllc/pandas-ta">Pandas TA</a> library. The Pandas TA <em>strategy</em> method utilizes multiprocessing for bulk indicator processing. Visualized indicators are similar to <a href="https://www.tradingview.com/symbols/BTCUSD/">TradingView</a> charts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NHqACxPFWHdy3wBuL-xyNg.png" /><figcaption>Average True Range TradingView chart; image by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*wnlRZx7bQw2pw8liN3z2ng.png" /><figcaption>Average True Range PandasTA indicator; image by author</figcaption></figure><h3>On-chain and sentiment data preparation</h3><p>It is more complicated with on-chain data. I collect <a href="https://santiment.net/">Santiment</a> data for FTM as well as BTC. BTC serves as an index for the whole crypto market, and a negative BTC sentiment spike on Twitter (such as China bans crypto) could significantly impact the FTM price. This approach would also work for ETH or another top 100 coin for which Santiment provides all the necessary data.</p><p><a href="https://santiment.net/">Santiment</a> data has two main minimum time intervals: “5m” and “24h” a user can aggregate upon. I aggregate “5m” metrics into “1h” time frame to match the Trading strategy time step. The only exception is the metric <em>funding_rate </em>calculated every “8h” on some exchanges. I use raw “24h” metrics without further aggregations.</p><p>There is a problem with some <a href="https://santiment.net/">Santiment</a> on-chain and sentiment metrics — a time lag between data appearing on the blockchain or social network and the time it is stored in a database, which is not the case with almost real-time price data from centralized crypto exchanges. Moreover, on-chain data can mutate over time and some on-chain metrics suffer from look-ahead bias. Detailed explanation <a href="https://insights.glassnode.com/introducing-point-in-time-data/">here</a>.</p><p><a href="https://santiment.net/">Santiment</a> doesn’t have point-in-time data, so my solution is to introduce a latency shift. That is to shift data in the training dataset by 1 hour later to match the latency of data used for live trading. For example, a datapoint is stored in Santiment database under timestamp 2022–03–27 <strong>10</strong>:00:00, in my dataset this datapoint is under timestamp 2022–03–27 <strong>11</strong>:00:00 to make sure this stored value is immutable and doesn’t have look-ahead bias. This is not the perfect solution, but it seems to work for my strategy because it is not high-frequency.</p><p><a href="https://glassnode.com/">Glassnode</a> provides a more comprehensive set of metrics for BTC and ETH analysis. Still, since the published strategy focuses on altcoins, I decided to stick to Santiment, at least for the public part of my project. You also need to become a Glassnode institutional client to get access to their API.</p><h3>More thoughts on my dataset</h3><p>Why did I use a few TA indicators and did not use over 600 metrics aggregated at different time intervals <a href="https://santiment.net/">Santiment</a> PRO subscription provides for FTM? The final dataset presented in this blog already contains 181 features, so one reason is to avoid the <a href="https://www.datacamp.com/blog/curse-of-dimensionality-machine-learning">curse of dimensionality</a>. It also takes considerably longer to train a neural network in a reinforcement learning setting than in classical supervised learning. With an increased number of features, it can take days to train an agent on 1 GPU.</p><p>I learned a lot about all kinds of metrics and chose the most informative ones. I also trained agents on larger datasets and then applied techniques such as <em>IntegratedGradients</em> from <a href="https://captum.ai/">Captum</a> library to see how each feature contributed to the trained neural network output. I filtered out features that had less impact.</p><p>Interestingly, metrics such as MVRV at different timeframes or funding rates were the most significant on the agent decisions, social metrics however were almost ignored by the trained agents. Agents trading BTC or ETH could learn profitable policies just by using Technical indicators, which is not the case for agents trading altcoins such as FTM. I was able to achieve the best results with datasets of mixed technical and on-chain metrics.</p><p>The final dataset still has 181 features, which is a lot, so feel free to reduce its number, for example, by removing some BTC metrics. An extreme is to train an agent using just FTM price. I also added columns for weekdays and hours of the day to create time encodings for the <a href="https://github.com/xkaple00/deep-reinforcement-learning-for-crypto-trading/blob/master/models/transformer.py">transformer</a> neural network, which is used as an agent backbone.</p><p>The dataset starts at the end of 2020 to capture the bull market in 2021, the bear market in 2022, sideways moves in 2023, and the new bull cycle in 2024. Ideally, training and validation datasets contain periods with uptrends and downtrends to evaluate how well the bot performs in each market regime. I implemented a feature to define a few training and validation intervals, rather than validating on the last few months of data. For example, here we have 5 train intervals each 4000 timesteps (hours) long, and each followed by a validation interval, 1000 timesteps long.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DLMNN-c7PnUioJLNt3D9iA.png" /><figcaption>Training and validation subsets, FTM price</figcaption></figure><p>Test dataset is de-facto paper trading on <a href="https://testnet.bybit.com/trade/usdt/FTMUSDT">Bybit testnet</a>. Since the neural net tries to approximate the training dataset, it is not true that a larger dataset is ultimately better. The crypto market can change significantly for a “short” time and policy learned from the old data may not be valid for the latest data.</p><p>I use a <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.RobustScaler.html">Robust scaler</a> from Sklearn to normalize the data. As stated in the docs, it scales features using statistics robust to outliers. Our dataset has many outliers, especially for on-chain and social data. This scaler removes the median and scales the data according to the quantile range. According to my experiments, training was more stable and converged to better results if the scaler was fit <strong>not </strong>on the whole training dataset globally but rather locally on the lookback window preceding the current timestep. The fitted on the lookback window scaler is then applied to the current observation state during training and live trading on the exchange. <a href="https://github.com/xkaple00/deep-reinforcement-learning-for-crypto-trading/blob/master/envs/scaler.py">Link</a> to the <em>Scaler</em> class.</p><h3>Conclusion</h3><p>In this first part of the blog series, we explored the data preparation process. We discussed the various data sources, including exchange data, on-chain and social sentiment data. We learned how to collect and pre-process this data to create a suitable dataset.</p><p>The key takeaways from this part are:</p><ul><li>It’s essential to use a variety of data sources beyond just technical indicators for effective trading. BTC metrics can serve as leading indicators for FTM.</li><li>On-chain and social sentiment data introduce complexities due to time lags and look-ahead bias. We addressed this by introducing a latency shift in the training data.</li><li>The curse of dimensionality can negatively impact the training process. We carefully selected informative features and used techniques to reduce the final number of features in the dataset.</li></ul><p>We also explored the structure of the final dataset for the deep learning model training and inference.</p><p>This ends Part 1: Data preparation. See you in the next part, <a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-261f8820f129">Part 2: Trading strategy</a>.</p><p>If you are interested in cooperation, feel free to contact me.</p><h3>Contacts</h3><p>My email: <a href="/service/mailto:alex.kaplenko@sane-ai.dev">alex.kaplenko@sane-ai.dev</a></p><p>My LinkedIn: <a href="https://www.linkedin.com/in/alex-sane-ai/">https://www.linkedin.com/in/alex-sane-ai/</a></p><p>GitHub: <a href="https://github.com/xkaple00/deep-reinforcement-learning-for-crypto-trading">https://github.com/xkaple00/deep-reinforcement-learning-for-crypto-trading</a></p><p>Link to support Ukraine: <a href="https://war.ukraine.ua/donate/">https://war.ukraine.ua/donate/</a></p><p>Visit us at <a href="https://www.datadriveninvestor.com/"><em>DataDrivenInvestor.com</em></a></p><p>Subscribe to DDIntel <a href="https://www.ddintel.com/"><em>here</em></a>.</p><p>Join our creator ecosystem <a href="https://join.datadriveninvestor.com/"><em>here</em></a>.</p><p>DDI Official Telegram Channel: <a href="https://t.me/+tafUp6ecEys4YjQ1">https://t.me/+tafUp6ecEys4YjQ1</a></p><p>Follow us on <a href="https://www.linkedin.com/company/data-driven-investor"><em>LinkedIn</em></a>, <a href="https://twitter.com/@DDInvestorHQ"><em>Twitter</em></a>, <a href="https://www.youtube.com/c/datadriveninvestor"><em>YouTube</em></a>, and <a href="https://www.facebook.com/datadriveninvestor"><em>Facebook</em></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=682173ef3000" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/deep-reinforcement-learning-for-crypto-trading-part-1-data-preparation-682173ef3000">Deep Reinforcement Learning for Crypto Trading</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Reinforcement Learning for Crypto Trading]]></title>
            <link>https://medium.com/coinmonks/deep-reinforcement-learning-for-crypto-trading-72c06bb9b04c?source=rss-88ed5cd82154------2</link>
            <guid isPermaLink="false">https://medium.com/p/72c06bb9b04c</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[crypto]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[bots]]></category>
            <dc:creator><![CDATA[Alex K]]></dc:creator>
            <pubDate>Fri, 17 May 2024 18:11:46 GMT</pubDate>
            <atom:updated>2024-07-01T10:38:11.817Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 0: Introduction</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*64rSRFbmcNOQz2vf-b_ptQ.png" /><figcaption>photo by <a href="https://unsplash.com/@frankiefoto">frank mckenna</a> on<a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral"> Unsplash</a></figcaption></figure><p><em>Disclaimer: The information provided herein does not constitute financial advice. All content is presented solely for educational purposes.</em></p><h3>Introduction</h3><p>This is the introduction of a blog series about my reinforcement learning journey in crypto. The current chapter provides a high-level overview of the building blocks of my working solution. A detailed description of each block is provided in separate chapters:</p><ul><li><a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-72c06bb9b04c">Part 0: Introduction</a></li><li><a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-part-1-data-preparation-682173ef3000">Part 1: Data preparation</a></li><li><a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-261f8820f129">Part 2: Trading strategy</a></li><li><a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-6b5705128732">Part 3: Training</a></li><li><a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-2d2a8204bf79">Part 4: Backtesting</a></li><li><a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-ed385e87ab0e">Part 5: Live trading</a></li></ul><h3>Resources</h3><p><a href="https://github.com/xkaple00/deep-reinforcement-learning-for-crypto-trading">https://github.com/xkaple00/deep-reinforcement-learning-for-crypto-trading</a></p><h3>About myself</h3><p>I’m a senior machine learning engineer who started my career in 2016. I have an inventor mindset. During my career, I’ve become the author of four US Patents in the fields of computer vision and signal processing using deep learning and reinforcement learning.</p><p>Here is a list of my patents:</p><ol><li><a href="https://patents.google.com/patent/US11901155B2/en?oq=11901155">https://patents.google.com/patent/US11901155B2/en?oq=11901155</a></li><li><a href="https://patents.google.com/patent/US11815479B2/en?oq=11815479">https://patents.google.com/patent/US11815479B2/en?oq=11815479</a></li><li><a href="https://patents.google.com/patent/US11703468B2/en?oq=11703468">https://patents.google.com/patent/US11703468B2/en?oq=11703468</a></li><li><a href="https://patents.google.com/patent/EP4024039B1/en?oq=20220208508">https://patents.google.com/patent/EP4024039B1/en?oq=20220208508</a></li></ol><p>I became fascinated with the crypto space in 2021 and started trading crypto manually. After a few months, my gains were equal to my losses (not a bad start for a newbie in crypto). Manual trading, however, was very time-consuming and emotionally exhaustive, as you might imagine. Then, I realized that I could automate trading, considering my professional background.</p><h3>Motivation</h3><p>I <a href="https://github.com/xkaple00/deep-reinforcement-learning-for-crypto-trading">opensource</a> a big chunk of my code and share some impactful ideas on my project. I publish the basic version of my solution — the runnable code that can be adapted by other quant traders. The advanced version of my solution includes several additional essential aspects that allow the AI bots to provide a substantially better risk-reward ratio than the basic version. I will include links to the accompanying files at the beginning of each chapter. It’s better to review the code while reading to follow my ideas. <em>Variables</em> from the code are shown in <em>italics</em> in the blog articles.</p><p>There are several sources of motivation to open source something that most crypto trading companies try to hide and protect in every possible way:</p><ol><li>Accelerate research in the reinforcement learning field for trading. Provide a community and individuals just like me with tools that they can use to build new exciting projects. I’ve used a lot of open-source projects in my career, and now I want to give something back to the community to maintain a balance of giving and receiving.</li><li>Crypto trading has become my true passion, and I would like to switch my career entirely and become a Professional Quant. I’m looking for collaboration opportunities with companies and professional teams. It’s always better to work with similar-minded people to share ideas and learn from each other.</li><li>My algorithm and trading strategy are imperfect, and I would like constructive feedback from more experienced quant traders.</li></ol><h3>Problem statement</h3><p>Market-neutral strategies seem to be the most lucrative, as is HFT (high-frequency trading) or Arbitrage because if done correctly, it can be a stable source of income despite the up-and-down market swings. However, I was aware of the enormous competition in the HFT space. As an individual, I had zero chances to succeed considering my available hardware and resources. So I decided to focus on mid-term trading and create bots that mimic human traders and trade perpetual futures contracts to go long during uptrends and short during downtrends.</p><p>As you might have guessed, the most logical thing to do is predict future market trends first. Knowing what the price of a coin will be in 1 hour or 1 day is a crucial prerequisite for success. I spent time predicting trends using libraries such as <a href="https://nixtlaverse.nixtla.io/neuralforecast/index.html">Neuralforecast</a>, <a href="https://pytorch-forecasting.readthedocs.io/en/stable/">Pytorch forecasting</a> and proprietary AI models. But as it turned out, no future trend indicator is 100% precise and it’s very challenging to predict the future in such a complex and volatile environment as the crypto space. Moreover, a lot of other questions arise:</p><ol><li>When to close a position at a loss to prevent even more significant losses if the trend forecast turns out to be wrong.</li><li>When to close a position at a profit if the trend forecast is correct, but the price may go even higher.</li><li>Most importantly, which part of the funds to allocate into long and short positions, how to decide on position sizes, and how to do account management.</li></ol><p>Even if you have a reliable forecasting indicator, an entire trading strategy must be created around it. This is where reinforcement learning comes to the rescue. Deep reinforcement learning algorithms recently beat professional Go and <a href="https://openai.com/index/openai-five-defeats-dota-2-world-champions/">Dota 2</a> players. So why can’t it beat professional traders?</p><h3>Reinforcement learning</h3><p>Since crypto markets are highly manipulated and I can access only a few metrics that do not catch all the intricacies happening in the market to predict future price moves, reinforcement learning is a natural choice. Even with limited prediction abilities, reinforcement learning agents can react accordingly to market changes rather than trying to predict the exact future prices. This concept works similarly to the <a href="https://www.investopedia.com/terms/r/rsi.asp">Relative Strength Index (RSI)</a>. RSI values below 30 don’t precisely predict future prices in a time horizon of 1 hour, 1 day, etc. Still, they signal that from a statistical point of view, there is a high probability of opening a profitable long position so the agent can act accordingly and then wait to obtain new observation states. Agent’s learned strategy can close a position at a profit when the RSI spikes above 70 or a loss if the RSI goes below 20.</p><p>Trading fits perfectly into the reinforcement learning paradigm with a partially observable environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PN0r6bbZt8iQOEs6hyRGig.png" /><figcaption>agent takes actions in an environment, which is interpreted into a reward and a representation of the state, which are fed back into the agent; source Wikipedia</figcaption></figure><p>The environment is the crypto market itself. There are two types of environments:</p><ol><li><a href="https://github.com/xkaple00/deep-reinforcement-learning-for-crypto-trading/blob/master/envs/training_env.py">Training environment</a> (also used for backtesting).</li><li>Live trading environment.</li></ol><p>In the training environment, the agent explores the outcomes of opening and closing positions in a sequence. After training is done, the bot is deployed to a live trading environment.</p><p>The agent is a trading bot that sends API requests in the correct order to maximize rewards. The agent’s actions in the environment are orders to open or close positions.</p><p>A crypto exchange is an interpreter that provides an agent with a positive reward for performing profitable actions and a negative reward for performing actions leading to losses. State or observation space is actually the state of your exchange account, which contains: unrealized profit and loss, available cash, etc, as well as a bunch of technical, on-chain, and social indicators (a detailed overview is in <a href="https://medium.com/@xkaple00/deep-reinforcement-learning-for-crypto-trading-part-1-data-preparation-682173ef3000">Part 1: Data preparation</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hY4xa3IYSYAtS3NSLPkSow.png" /><figcaption>observation and action space inside exchange UI; image by author</figcaption></figure><p>The simplest possible reward equals the normalized amount of money the bot gains or loses while closing a position (realized profit and loss).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GrQHwk15VScO6dIf1XgMgg.png" /><figcaption>realized PnL; image by author</figcaption></figure><h3>Results</h3><p>To make further reading more exciting, I’m sharing the trading results of two bots among the entire fleet of my bots on <a href="https://www.bybit.com/invite?ref=GLW3W6">Bybit</a>.</p><p><strong>Bot 1:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mn3sQQBtQ6LGT1U35PZFHg.png" /><figcaption>bot 1 realized PnL; image by author</figcaption></figure><p><a href="https://docs.google.com/spreadsheets/d/1yKoFLzDj8RUReZ9Asb61eNlt6lee_ZgAGtrjTFN0twA/edit?usp=sharing">Link</a> to Google sheet with trading data exported from Bybit.</p><p><strong>Bot 2:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5B_hsBLoxNe6lgGDaBWZzA.png" /><figcaption>bot 2 realized PnL; image by author</figcaption></figure><p><a href="https://docs.google.com/spreadsheets/d/1c0uLVGZD2qV3311E76m08mO9tvIo6rggfvjG0xutxbc/edit?usp=sharing">Link</a> to Google sheet with trading data exported from Bybit.</p><h3>Conclusion</h3><p>This blog post introduced the concept of using deep reinforcement learning for crypto trading. We explored the challenges of traditional forecasting methods and how reinforcement learning can address them. The environment, agent, and reward system were explained, laying the groundwork for future parts of the series where we’ll dive into data preparation, training, and live trading</p><p>This ends Part 0: Introduction, see you in the next <a href="https://medium.com/@sane.ai/deep-reinforcement-learning-for-crypto-trading-part-1-data-preparation-682173ef3000">Part 1: Data preparation</a>.</p><p>If you are interested in cooperation, feel free to contact me.</p><h3>Contacts</h3><p>My email: <a href="/service/mailto:alex.kaplenko@sane-ai.dev">alex.kaplenko@sane-ai.dev</a></p><p>My LinkedIn: <a href="https://www.linkedin.com/in/alex-sane-ai/">https://www.linkedin.com/in/alex-sane-ai/</a></p><p>GitHub: <a href="https://github.com/xkaple00/deep-reinforcement-learning-for-crypto-trading">https://github.com/xkaple00/deep-reinforcement-learning-for-crypto-trading</a></p><p>Link to support Ukraine: <a href="https://war.ukraine.ua/donate/">https://war.ukraine.ua/donate/</a></p><p>Visit us at <a href="https://www.datadriveninvestor.com/"><em>DataDrivenInvestor.com</em></a></p><p>Subscribe to DDIntel <a href="https://www.ddintel.com/"><em>here</em></a>.</p><p>Join our creator ecosystem <a href="https://join.datadriveninvestor.com/"><em>here</em></a>.</p><p>DDI Official Telegram Channel: <a href="https://t.me/+tafUp6ecEys4YjQ1">https://t.me/+tafUp6ecEys4YjQ1</a></p><p>Follow us on <a href="https://www.linkedin.com/company/data-driven-investor"><em>LinkedIn</em></a>, <a href="https://twitter.com/@DDInvestorHQ"><em>Twitter</em></a>, <a href="https://www.youtube.com/c/datadriveninvestor"><em>YouTube</em></a>, and <a href="https://www.facebook.com/datadriveninvestor"><em>Facebook</em></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72c06bb9b04c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/deep-reinforcement-learning-for-crypto-trading-72c06bb9b04c">Deep Reinforcement Learning for Crypto Trading</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>