<?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 Fabian Ridder on Medium]]></title>
        <description><![CDATA[Stories by Fabian Ridder on Medium]]></description>
        <link>https://medium.com/@fabian_r?source=rss-107d29e0e405------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*pJJx1ULdK4svtdHq1wLEZw.jpeg</url>
            <title>Stories by Fabian Ridder on Medium</title>
            <link>https://medium.com/@fabian_r?source=rss-107d29e0e405------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 08:06:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fabian_r/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[I Automated a Trading YouTube Channel]]></title>
            <link>https://medium.com/coinmonks/my-project-an-automated-trading-youtube-channel-d79493223760?source=rss-107d29e0e405------2</link>
            <guid isPermaLink="false">https://medium.com/p/d79493223760</guid>
            <category><![CDATA[business]]></category>
            <category><![CDATA[side-hustle]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[youtube]]></category>
            <category><![CDATA[trading]]></category>
            <dc:creator><![CDATA[Fabian Ridder]]></dc:creator>
            <pubDate>Wed, 20 Nov 2024 14:57:58 GMT</pubDate>
            <atom:updated>2025-01-12T15:21:04.004Z</atom:updated>
            <content:encoded><![CDATA[<h4>Automatically generating a script, AI voice, animations, backtesting, …</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o7-qWiGCt9--ps9BrJG6IQ.jpeg" /><figcaption>Thumbnail. Image by author.</figcaption></figure><p>Hey, fellow traders!</p><p>Today, I want to present to you one project I worked on here and then over the past months: <strong>automatically creating YouTube videos from a given trading strategy.</strong></p><h3>The Beginning 🚀</h3><p>Everything started when I was recommended these YouTube videos demonstrating their Python scripts for creating basic YouTube shorts or TikToks. However, most of these videos are just a <strong>waste of time</strong>: listening to an AI voice talk some sh** about quotes by famous people or “fun” facts while watching meaningless stock footage or stolen gameplay.</p><p>I don’t use TikTok or YouTube Shorts, but I heard it’s already flooded with such a waste of disk space and internet bandwidth. Thus, still hooked by that idea, I wondered if there weren’t better content ideas.</p><h3>The “Idea” 💡</h3><p>Well, <em>“the idea”</em> sounds a bit exaggerated, but <strong>backtesting trading strategies</strong> is almost always the same procedure, which is why it definitely fits this case. Not to mention that this Medium channel is mostly about trading.</p><p>Thus, I wanted to build something that takes backtesting results and creates a basic analysis video. So, <a href="https://www.youtube.com/@the-gen-trader"><strong>The Genuine Trader</strong></a><strong> was born</strong>. <em>Why “genuine,”</em> you might ask? Well, it’s because of all those terrible YouTubers clickbaiting the hell out of any bogus trading strategy, and I wanted to make YouTube videos that stand out from that sh**. Backtesting results that aren’t fake and pure numbers, so people see that trading isn’t a magical get-rich-quick scheme.</p><h4>A Self-Content-Feeding YouTube Channel</h4><p>Initially, I aimed to create a <strong>full-automated Python script running 24/7</strong> and creating insightful YouTube videos daily by taking trading strategy suggestions from the previous YouTube video’s comments. By doing so, we’d make a <strong>self-sustaining cycle</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q70Ul9NeRT7VAR3SMW7Xuw.png" /><figcaption>Self-sustaining cycle of creating backtest videos on YouTube. Image by author.</figcaption></figure><h3>A View from Above 🪂</h3><p>A rough overview of the entire procedure, from comments to YouTube video, looks this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dABVKDOwd8Suwk3UDeK-2w.png" /><figcaption>How to create a video from a previous video’s comment. Image by author.</figcaption></figure><p>Unfortunately, I haven’t finished coding the entire procedure. You’ll see why in a minute. But the whole process is quite simple:</p><ol><li><strong>Fetching</strong> the <strong>comments</strong> from a previous YouTube video and extracting comments starting with <em>#backtest</em>.</li><li>ChatGPT is then prompted to validate each idea and <strong>choose</strong> the <strong>most</strong> promising or <strong>appropriate</strong> <strong>one</strong>.</li><li>Now, given the comment and the docs of my backtesting engine, <strong>ChatGPT</strong> <strong>writes</strong> the code necessary to <strong>backtest</strong> the explained strategy.</li><li>We then <strong>run</strong> that <strong>backtest</strong>, which returns the results.</li><li>These results are used to <strong>create</strong> a YouTube <strong>video</strong>.</li><li><strong>Upload</strong> the video to YouTube.</li></ol><blockquote>For the sake of simplicity, I omitted some intermediate steps, e.g., checking if the strategy can be tested with the available data, if the backtest doesn’t take too long, if the strategy or a similar one has already been tested, if the comment is some attack, …</blockquote><p>But what does a video look like?! Let’s see.</p><h3>A YouTube Video’s Structure ▶️</h3><p>The <strong>structure</strong> is very basic and <strong>depends</strong> on whether it is a YouTube video or a YouTube Short. The following structure is the full one for YouTube videos. YouTube Shorts are missing some of these steps in order to be shorter, as the name already suggests ;)</p><h4>1) Greeting the Viewer (~7 secs)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y6LvTR2N_jD-G8Iz3gNrQg.png" /><figcaption>Step 1: Greet viewer. Image by author.</figcaption></figure><h4>2) Explaining the Strategy (~25 secs)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hR7E0sc6_DKH-RRNVxeU1Q.png" /><figcaption>Step 2: Explain strategy with rendered markdown. Image by author.</figcaption></figure><h4>3) Demonstrating the Backtest Environment (~10 secs)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nrUI2KWi-hBIPnjK8l7Vbw.png" /><figcaption>Step 3: Show assumptions for backtesting. Image by author</figcaption></figure><h4>4) A Short Disclaimer (2 secs)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7tnFNND054LhfZKuhExDLw.png" /><figcaption>Step 4: Show short disclaimer. Image by author</figcaption></figure><h4>5) Demonstrating Examplary Trades (~1 min)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*As30nr0ERvaaDDaEikHaUA.png" /><figcaption>Step 5: Demonstrating the median winning, median losing, random winning, and random losing trade. Image by author</figcaption></figure><h4>6) Animating the Portfolio’s Development over Time (~20 secs)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lCcip_pkjT5KJcKwu_xDyw.png" /><figcaption>Step 6: Watching a growing/developing equity curve over time. Image by author</figcaption></figure><h4>7) Discussing the Strategy’s Results (~40 secs)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NJ_NkINjP-WfcwbQ29KJyw.png" /><figcaption>Step 7: Talking numbers. Image by author</figcaption></figure><h4>8) Strategy-Benchmark Comparison (~15 secs)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e0U3pmPgJJ440WhdNWHCwQ.png" /><figcaption>Step 8: Animating now both equity curves for strategy and benchmark. Image by author</figcaption></figure><h4>9) Comparing the Strategy’s Results to the Benchmark’s Results (~45 secs)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5StKkoFS9k-3_ueIgxKs_A.png" /><figcaption>Step 9: Talking numbers again, but comparing them to benchmark. Image by author</figcaption></figure><h4>10) Outro (~20 secs)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k5SdzAg0lFwBgSKpRKOWBA.png" /><figcaption>Step 10: Ending the video. Image by author</figcaption></figure><p>If you want to see it in action, have a look yourself:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FC-U6PGvZ18o%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DC-U6PGvZ18o&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FC-U6PGvZ18o%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/9211a6e4664f88b0acfeda3f2f0182b6/href">https://medium.com/media/9211a6e4664f88b0acfeda3f2f0182b6/href</a></iframe><h3>A Sad Ending ❌</h3><p>However, I discontinued this project because of the following reasons:</p><ol><li>👎🏻 The videos aren’t that interesting. That’s at least what I think.</li><li>👎🏻 Since most strategies will perform awfully, it’d be hard to start growing an audience.</li><li>👎🏻 The backtesting engine isn’t programmed correctly for some cases, and I didn’t have the time and motivation to fix it yet.</li><li>👎🏻 Full automation will probably reduce the quality of strategies and thumbnails.</li><li>👎🏻 Uploading YouTube videos cannot be 100%-automated using Python, at least from what I know.</li></ol><p>If you’re still interested in the YouTube channel I created for this project, here it is:</p><p><a href="https://www.youtube.com/@the-gen-trader">The Genuine Trader</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*p6rtAAxFk1Pt-LBu.png" /><figcaption><a href="https://www.buymeacoffee.com/fabianr">If you’d like to support me, I’d really appreciate it 🫶🏻</a></figcaption></figure><h3>Interested in Other Trading Stuff?</h3><ul><li><a href="https://medium.com/coinmonks/how-i-evaluate-a-trading-indicator-without-a-convential-backtest-0840aa8493c6">How I Evaluate a Trading Strategy Without Conventionally Backtesting It</a></li><li><a href="https://medium.com/coinmonks/i-backtested-tradinglabs-indicator-that-you-ll-ever-need-f66d0b312e0b">TradingLab’s “Insane“ Indicator Ensemble</a></li><li><a href="https://medium.com/coinmonks/i-made-codetradings-scalping-strategy-profitable-for-crypto-5916c9b81e6a">Scalping but Profitable (incl. Fees)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d79493223760" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/my-project-an-automated-trading-youtube-channel-d79493223760">I Automated a Trading YouTube Channel</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[How I Evaluate a Trading Strategy Without Conventionally Backtesting It]]></title>
            <link>https://medium.com/coinmonks/how-i-evaluate-a-trading-indicator-without-a-convential-backtest-0840aa8493c6?source=rss-107d29e0e405------2</link>
            <guid isPermaLink="false">https://medium.com/p/0840aa8493c6</guid>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[investing]]></category>
            <category><![CDATA[stocks]]></category>
            <dc:creator><![CDATA[Fabian Ridder]]></dc:creator>
            <pubDate>Tue, 27 Aug 2024 13:21:42 GMT</pubDate>
            <atom:updated>2024-08-29T18:14:36.103Z</atom:updated>
            <content:encoded><![CDATA[<h4>Let’s keep significance as high as possible!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d93B4Pl8-GrOzF1ZeCqfkw.jpeg" /><figcaption>Thumbnail. Image by author.</figcaption></figure><p>Hey, fellow traders! Today, we’ll explore a way to evaluate and visualize the potential effectiveness of trading signals without conventionally backtesting them. But first, let’s understand the problem we face when backtesting!</p><blockquote>The code is at the end of this article as a jupyter notebook in Google Colab. Price data also gets automatically downloaded ;)</blockquote><h3>A Dangerous Backtesting Problem</h3><p>Usually, when I stumble across a strategy, I implement it as a whole: entries, exits, risk management, fees, slippage, spread, and so on. So, we try to simulate how we would’ve potentially traded with the money we would’ve had. But often, besides all those other backtest assumptions, there is a substantial problem when doing this:</p><p><strong><em>There are trades we couldn’t enter, but we would’ve entered.</em></strong></p><p>This can be due to several reasons. For example,</p><ol><li>there is not enough cash left to enter the position,</li><li>or we already have bought the symbol and don’t want to buy more, as our portfolio would be exposed to a higher risk regarding that one symbol.</li></ol><p>By restricting us this way, we lose valuable trades that would’ve helped us evaluate the strategy. However, it highly depends on the strategy and the amount of signals it produces.</p><p>It cannot only affect the <strong>significance</strong> of the strategy’s performance, but it can also impact the <strong>entire backtest results</strong>. Here’s an example of a (very bad) long-only Bollinger Bands® mean reversion strategy on AAPL with 1,975 signals starting on</p><p>A) March 16, 2001</p><p>B) and one business day later on March 19, 2001:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uvs7Wiz9oQ_a5J73z_XHmQ.png" /><figcaption><strong>A)</strong> Strategy starting on March 16, 2001. Annualized return of <strong>35.66%</strong>. <strong>105</strong> trades. Image by author.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kxSnV81S3xt8ua_yw-LLUQ.png" /><figcaption><strong>B)</strong> Strategy starting on March 19, 2001. Annualized return of <strong>38.72%</strong>. <strong>108</strong> trades. Image by author.</figcaption></figure><p>This is not the perfect example, but I hope you get the gist: We just started the backtest one business day later, and the overall annualized return has decreased by 3%. Some trades also differ from strategy A to B. We even had 1,975 signals, but only ~100 (~5%) have been used to enter trades. That’s the problem we’re dealing with.</p><h3>Dealing With the Problem</h3><p>Instead of simulating an entire market and the associated trading behavior, we take a look at the <strong>price development relative to the entry signal, </strong>which looks like this for the strategy above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f8w04vUCZ-E5XguZKExcbA.png" /><figcaption>Mean and median price development of all signals of the Bollinger Bands strategy on AAPL. 10 days before and 20 days after signal. 1984 entry signals. Image by author.</figcaption></figure><p>The deep blue line represents the mean price development, the dashed line the median price development, and the filled area displays the standard deviation.</p><p>After the signal, the price slightly increases on average, suggesting that it is a good indicator, right? We can’t really say yet because AAPL had been quite a flying rocket during the past decades. Thus, any long-only strategy on AAPL would have been profitable anyhow. This is why we also need to compare this to a benchmark signal, meaning that every single day is a signal. I’ve added its mean price development as a red line to the plot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*75AlG1GmhMOrSnoorUGWxg.png" /><figcaption>Same plot as above, but including the benchmark. Image by author.</figcaption></figure><p>As you can see, our signal isn’t better than buying AAPL every single day.</p><p>I also added the ability to pass commissions to the function, which lowers the overall price development (and entry price) by a given amount. For the following plot, I’ve set the overall commissions to 0.005 (0.5%), but for the rest of this article, I’ll set them to 0 so that we can focus solely on the signal without having to care about more assumptions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RO5sP2M2GXZz-QGCyj5yIw.png" /><figcaption>Same plot as above, but including the commisions. Image by author.</figcaption></figure><p>As you can see, all the blue stuff moved down by 0.5%. I know this is kept a bit too easy but you can change it on your own if you want to. As already said, we’ll focus on the pure signal without commissions from now on.</p><h3>Example Time!</h3><p>Let’s have a look at some examplary signals:</p><h4><strong>1) RSI(10) Crossing Below 40 (NVDA)</strong></h4><pre>signal = (talib.RSI(adj_close, timeperiod=10) &lt;= 40) \<br>         &amp; (talib.RSI(shift_nb(adj_close, 1), timeperiod=10) &gt; 40)</pre><p>This strategy on the daily timeframe produced 26 signals, which is a rather small number to conclude that it really is significantly ““better”” than the benchmark, as the following plot might suggest:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x3DMKnM4WQcvQ-ZwH20nWA.png" /><figcaption>Price development of 26 signals of a RSI crossover strategy on NVDA. 50 days before and 100 days after signal. Image by author.</figcaption></figure><h4>2) Close Price Increases 3 Times in a Row (<strong>MSFT</strong>)</h4><pre>signal = (adj_close &gt; shift_nb(adj_close, 1)) \<br>         &amp; (shift_nb(adj_close, 1) &gt; (shift_nb(adj_close, 2)))</pre><p>You can clearly see the 3-day increase before the signal, which — expectedly — has no effect on a better future performance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*beR6wZxvuWjxcJDhFiZEsw.png" /><figcaption>Price development of 1,501 signals of a strategy looking if MSFT increases 3 days in a row. 50 days before and 100 days after signal. Image by author.</figcaption></figure><p>It’s fun to make these plots. However, there’s a new problem. Maybe, you’ve already spotted it.</p><h3>The New Problem</h3><p>It’s our x-axis: We plot the price development over constant time. It’d be helpful if we had a strategy that just closes each position after <em>x</em> days, but that’s rarely the case. Many strategies utilize take profits, stop losses, trailing stops, or other techniques to close a trade.</p><p>So, instead of assuming a fixed timeout, we now need to extend our strategy by adding exit signals. For this article, we stick to a simple ATR-based take profit and stop loss. I used it in a lot of other previous stories, but to those of you who don’t know it, it’s pretty simple:</p><pre>stop_loss = close[i] - atr14[i] * sl_atr_factor<br>take_profit = close[i] + atr14[i] * sl_atr_factor * rrr</pre><p>The factor <em>sl_atr_factor</em> just scales the range between stop loss and take profit, whilse the <em>rrr</em> (<strong>R</strong>isk <strong>R</strong>eward <strong>R</strong>atio) determines how much we are willing to risk, i.e., it scales up/down the take profit in proportion to the risk.</p><h4>How Do We Plot the Price Development Now?</h4><p>Well, we just take the average trade duration and adjust every trade’s price development to this average trade duration by using linear interpolation if needed. That’s already the entire magic.</p><p>Given the previous strategy (price increasing 3 days in a row) with a <em>sl_atr_factor</em> of 2 and an <em>rrr</em> of 1.5 and extended with an RSI below 30, the plot looks like this:</p><pre>signal = (adj_close &gt; shift_nb(adj_close, 1)) \<br>         &amp; (shift_nb(adj_close, 1) &gt; (shift_nb(adj_close, 2))) \<br>         &amp; (talib.RSI(shift_nb(adj_close, 1), timeperiod=10) &lt; 30)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZlEbjBkJnlbvrnczN8CymQ.png" /><figcaption>Price development of 24 trades on the strategy on MSFT. All trades have been interpolated to 22 days (average trade duration). <em>sl_atr_factor=2, rrr=1.5. </em>Image by author.</figcaption></figure><p>You can read the plot as follows: Every trade has been created at 0 and closed at 22 no matter the real trade duration. This is what the linear interpolation was for. I removed the price development before the signal since this isn’t relevant. Apparently, we should’ve closed each trade a bit earlier because of the small valley around 18. We can easily control this by decreasing the <em>sl_atr_factor</em>. Let’s try a <em>sl_atr_factor </em>of 1.8:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xHuo_SqcmVDvlHZKJB_WIQ.png" /><figcaption>Price development of 24 trades on the strategy on MSFT. All trades have been interpolated to 22 days (average trade duration). <em>sl_atr_factor=1.8, rrr=1.5. </em>Image by author.</figcaption></figure><p>Nice! Looks even better now with the maximum at the end (at 14) for both median and mean! So, the plot demonstrates that the strategy <strong>supposedly</strong> outperforms the benchmark, but again, be careful; we’ve only 24 trades! So, this needs to be tested further.</p><p>I leave this and playing with the code up to you. Code is below.</p><blockquote>Happy trading, everyone :)</blockquote><h3>“Mandatory” Self-Promotion Part</h3><p>Here’s other stuff I’ve made:</p><ul><li><a href="https://medium.com/coinmonks/detecting-price-channels-in-python-c53fdae46fe3">How I Detect Price Channels Robustly in Python</a></li><li><a href="https://medium.com/coinmonks/i-backtested-tradinglabs-indicator-that-you-ll-ever-need-f66d0b312e0b">TradingLab’s “Insane“ Indicator Ensemble</a></li><li><a href="https://medium.com/coinmonks/i-made-codetradings-scalping-strategy-profitable-for-crypto-5916c9b81e6a">Scalping but Profitable (incl. Fees)</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mCC3KGm27sDmGUfT.png" /><figcaption><a href="https://www.buymeacoffee.com/fabianr">If you’d like to support me, I’d really appreciate it 🫶🏻</a></figcaption></figure><h3>The Code is Coming Now</h3><p>Here’s the code. Have fun!</p><p><a href="https://colab.research.google.com/drive/1SlzjFrFU1mPXdSlbCFiuvJrrWm3IPu_N?usp=sharing">Google Colab</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0840aa8493c6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/how-i-evaluate-a-trading-indicator-without-a-convential-backtest-0840aa8493c6">How I Evaluate a Trading Strategy Without Conventionally Backtesting It</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[TradingLab’s “Insane“ Indicator Ensemble]]></title>
            <link>https://medium.com/coinmonks/i-backtested-tradinglabs-indicator-that-you-ll-ever-need-f66d0b312e0b?source=rss-107d29e0e405------2</link>
            <guid isPermaLink="false">https://medium.com/p/f66d0b312e0b</guid>
            <category><![CDATA[investing]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[stocks]]></category>
            <dc:creator><![CDATA[Fabian Ridder]]></dc:creator>
            <pubDate>Mon, 01 Jul 2024 10:36:41 GMT</pubDate>
            <atom:updated>2024-08-22T22:20:23.931Z</atom:updated>
            <content:encoded><![CDATA[<h4>“The Only Indicator You’ll Ever Need”? Let’s check!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u76N7OVPGPQH4UU77FJ_Jw.jpeg" /><figcaption>Thumbnail. Image by author.</figcaption></figure><p>Hey everyone! I’m back with another backtest I definitely wanted to do, as TradingLab posted a video with a supposedly insane indicator ensemble that “we need to try.” You can find the video right here:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FHFKRgIRzeQ8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DHFKRgIRzeQ8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FHFKRgIRzeQ8%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/71f6a0b5a64edf4c563baf328f769b1b/href">https://medium.com/media/71f6a0b5a64edf4c563baf328f769b1b/href</a></iframe><p>However, I wondered if his strategy is really that good. So let’s put it to a test. Let’s go!</p><h3>Which Indicators?</h3><p>TradingLab focussed on two indicators available on TradingView:</p><h4>1) EMA Trend Meter by colinmck</h4><p>This indicator (or at least the part that will be used) just utilizes four EMAs based on the close price and checks if all three EMAs are above the baseline EMA. The Python code looks like this:</p><pre>import talib<br><br>def ema_trend_meter(close, len0=13, len1=21, len2=34, len3=55):<br>    ema0 = talib.EMA(close, timeperiod=len0)<br>    ema1 = talib.EMA(close, timeperiod=len1)<br>    ema2 = talib.EMA(close, timeperiod=len2)<br>    ema3 = talib.EMA(close, timeperiod=len3)<br>    return ema1 &lt; ema0, ema2 &lt; ema0, ema3 &lt; ema0</pre><p>In TradingView, these EMA comparisons are illustrated with three colored lines that are either red or green:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n4ObUtvdCJRajrHesKGrog.png" /><figcaption>The EMA Trend Meter in the lower part of the image (Stock: NVDA)</figcaption></figure><h4>2) Stochastic Momentum Indicator (SMI) by surjithctly</h4><p>This indicator (or at least the part that we will use) employs the difference between a rolling maximum and rolling minimum combined with some EMAs. It ranges between -100 and 100, with high values indicating being overbought and low values indicating the opposite. Given three pandas.Series, the python function looks like this:</p><pre>import talib<br>import numpy as np<br><br>def stochastic_momentum_index(low, high, close, a=10, b=3):<br>    ll = low.rolling(window=a).min()<br>    hh = high.rolling(window=a).max()<br>    diff = hh - ll<br>    rdiff = close - (hh + ll) / 2<br><br>    avgrel = talib.EMA(talib.EMA(rdiff, timeperiod=b), timeperiod=b)<br>    avgdiff = talib.EMA(talib.EMA(diff, timeperiod=b), timeperiod=b)<br><br>    SMI = np.where(avgdiff != 0, (avgrel / (avgdiff / 2) * 100), 0)<br>    SMIsignal = talib.EMA(SMI, timeperiod=b)<br>    emasignal = talib.EMA(SMI, timeperiod=10)<br><br>    return SMIsignal, emasignal</pre><p>On TradingView, you might see something like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KMxirjEDTiKoBC0tkHGZmQ.png" /><figcaption>The SMI in the lower part of the image (Stock: NVDA)</figcaption></figure><h3>The Strategy</h3><p>TradingLab suggests to trade on higher timeframes like 4H or 1D <em>(we will do this in a minute)</em> and came up with these parameters:</p><h4>1) EMA Trend Meter:</h4><ul><li>Baseline EMA: 13</li><li>Fast EMA: 21</li><li>Medium EMA: 34</li><li>Slow EMA: 55</li></ul><h4>2) SMI</h4><ul><li>A: 10</li><li>B: 3</li></ul><h4>When to Enter?</h4><p><strong>Long</strong>: All lines of the EMA Trend Meter are green, the SMI has been below -40 and crossed above its EMA.</p><p><strong>Short</strong>: Well, just the exact opposite: All lines of the EMA Trend Meter are red, the SMI has been above 40 and crossed below its EMA.</p><h4>When to Exit?</h4><p>We set the stop loss at the recent swing low/high <em>(I hate people saying this. It’s so imprecise…)</em> and our take profit using a risk reward ratio of 2.</p><h4>Example Trade</h4><p>I’ve looked at NVDA and found this trade, for example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ApLyAUEpu0lKw8vn2Nml3A.png" /><figcaption>Cherry-picked trade using the logic as explained (Stock: NVDA). Image by author.</figcaption></figure><p>The SMI has been below -40 and crossed above its EMA, and the EMA Trend Meter has three green lines. That is the trading logic we aim for. Then, the stop loss was set at the previous swing low, and the take profit was calculated using a risk reward ratio of 2:1.</p><h3>The Backtest</h3><p>But what is the big picture? One trade alone has no significance. We’ll backtest it on the daily timeframe between January 2011 and May 2024 on stocks that were added to the S&amp;P 500 in 2009 and 2010 in order to avoid survivor bias. The more or less “randomly” chosen stocks are shown below.</p><pre># 21 stocks<br>stocks = [&quot;KMX&quot;, &quot;CB&quot;, &quot;FFIV&quot;, &quot;JCI&quot;, &quot;NFLX&quot;, &quot;NRG&quot;, &quot;OKE&quot;, &quot;TT&quot;, &quot;BKNG&quot;, &quot;ES&quot;, &quot;FMC&quot;, &quot;HRL&quot;, &quot;IRM&quot;, &quot;ORLY&quot;, &quot;PWR&quot;, &quot;ROP&quot;, &quot;ROST&quot;, &quot;VTR&quot;, &quot;V&quot;, &quot;WELL&quot;, &quot;WDC&quot;]</pre><p>The recent swing low or recent swing high is simply examined by looking at the previous 25 lows and taking the minimum or vice versa for the most recent swing high. Additionally, the SMI needs to exceed the -40 to 40 band in the last ten days. I know both approaches are a bit naïve, but let’s keep it simple! Just for prevention, we’ll not enter a trade if the stop loss percentage exceeds -20%.</p><p>Since we’ll trade multiple stocks at once, I also added some logic to handle this with a few more parameters:</p><ul><li>Maximum risk per trade: 8%</li><li>Risk per trade: 2%</li></ul><p>Now, let’s run a backtest with $10,000, 0.1% fees, 0.1% slippage, 0.1% spread, and 10% annual borrowing fees!</p><h4>Results</h4><p>This run gave us not so pretty results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZL9aNOCl0trcpTmWRPhTRg.png" /><figcaption>Equity curve of the strategy. Image by author.</figcaption></figure><p>Whoops! A <strong>sortino ratio of 0.0038</strong> and a <strong>total return of -0.06%</strong>. Doesn’t look that promising to me. Maybe we can tweak it a bit by checking if the stock is consolidating or not. At least, this is how TradingLab tries to improve the strategy: Don’t enter a trade when the stock is moving sideways. He has his own indicator, which I don’t know, and will not fall for buying. So alternatively, we measure consolidation with a regression on the last 80 closes with this function:</p><pre>import numpy as np<br><br>def regression_analysis(arr):<br>    x = np.arange(len(arr))<br>    <br>    A = np.vstack([x, np.ones(len(x))]).T<br>    slope, intercept = np.linalg.lstsq(A, arr, rcond=None)[0]<br>    <br>    regression_line = slope * x + intercept<br>    <br>    mean_absolute_error = np.mean(np.abs(arr - regression_line))<br>    <br>    mean_value = np.mean(arr)<br>    <br>    percentage_mean_error = (mean_absolute_error / mean_value) * 100<br>    <br>    return slope, percentage_mean_error</pre><p>Thus, we update our entry conditions:</p><blockquote><strong>Long</strong>: Previous conditions + positive slope + percentage_mean_error &lt; 3%</blockquote><blockquote><strong>Short</strong>: Previous conditions + negative slope + percentage_mean_error &lt; 3%</blockquote><p>By doing so, it gets slightly better:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GW6vQfw9brTjV3Dn1sPimg.png" /><figcaption>Equity curve after trying to remove signals during consolidation periods. Image by author.</figcaption></figure><p>Still, just a <strong>sortino ratio of 0.2830</strong> and a <strong>total return of 2%</strong> in more than 13 years? Come on…</p><h3>Making the Exit Logic My Way</h3><p>If we analyze the equity curve, we clearly see, that each trade does not last long, which is probably due to the way how TradingLab calculates the stop loss. So, let’s try to increase the average duration of a trade, hoping to get better results. For that, I’d use a 32-day ATR with a factor of 5 in order to calculate the current stop loss and take profit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TJ5xN2ooX_hTtQr52vDhtA.png" /><figcaption>Equity curve after exchanging the stop loss calculation. Image by author.</figcaption></figure><p>A <strong>sortino ratio of 0.8005</strong> and a <strong>total return of 16.94%</strong>. That’s better! However, the annual return <strong>(CAGR) is at 1.17%</strong>. This might be due to the fact that we are only risking 8% of our equity at maximum, and we don’t have a lot of trades at once, so most of the time, we have cash in our account that isn’t made use of. For instance, we can increase the maximum risk per trade to 35% and risk per trade to 15% and add more stocks to our universe to tackle this. I just chose the stocks that were added to the S&amp;P 500 in 2007 and 2008:</p><pre># Now: 51 stocks<br>stocks = [&quot;KMX&quot;, &quot;CB&quot;, &quot;FFIV&quot;, &quot;JCI&quot;, &quot;NFLX&quot;, &quot;NRG&quot;, &quot;OKE&quot;, &quot;TT&quot;, &quot;BKNG&quot;, &quot;ES&quot;, &quot;FMC&quot;, &quot;HRL&quot;, &quot;IRM&quot;, &quot;ORLY&quot;, &quot;PWR&quot;, &quot;ROP&quot;, &quot;ROST&quot;, &quot;VTR&quot;, &quot;V&quot;, &quot;WELL&quot;, &quot;WDC&quot;, &quot;APH&quot;, &quot;CF&quot;, &quot;CTRA&quot;, &quot;DVA&quot;, &quot;FAST&quot;, &quot;DOC&quot;, &quot;ISRG&quot;, &quot;IVZ&quot;, &quot;LHX&quot;, &quot;MA&quot;, &quot;NDAQ&quot;, &quot;PM&quot;, &quot;RSG&quot;, &quot;CRM&quot;, &quot;SJM&quot;, &quot;WEC&quot;, &quot;WYNN&quot;, &quot;AVB&quot;, &quot;RL&quot;, &quot;CHRW&quot;, &quot;HST&quot;, &quot;AIZ&quot;, &quot;DFS&quot;, &quot;AKAM&quot;, &quot;MHCP&quot;, &quot;ICE&quot;, &quot;EXPE&quot;, &quot;EXPD&quot;, &quot;J&quot;, &quot;AMT&quot;]</pre><blockquote>Please keep in mind that this strategy would do both longing and shorting equally, which means — more or less — that no benchmark is necessary. More or less!</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NMHoIpzsAtIbclwIYtomsQ.png" /><figcaption>Equity curve after extending the stock universe, but also increasing the risk. Image by author.</figcaption></figure><p>Look at that! A <strong>CAGR of 9.1%</strong>, <strong>max drawdown of -24.2%</strong>, and <strong>sortino ratio of 1.13</strong> with <strong>95 trades </strong>for a ““market neutral”” strategy. Not bad, but also not tremendously overwhelming. If you’re still interested in a buy-and-hold benchmark, I’ve got you covered ;) This is how your portfolio might have looked like if you’d spread a total of $100,000 across the stock universe equally in 2011:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V5iEkGKLB3lNgJnm7Amhkg.png" /><figcaption>Equity curve of buy-and-holding the stock universe. Image by author.</figcaption></figure><p>Well, a CAGR of 14.78%, max drawdown of -36.07%, and a sortino ratio of 1.22. That’s definitely better than our strategy, but how would the buy-and-hold strategy have performed, if the market has not been that bullish? Probably worse.</p><blockquote>I’ll not share my code this time. Sorry, guys!</blockquote><p>Nonetheless, I hope you liked it! Happy trading, everyone! :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mCC3KGm27sDmGUfT.png" /><figcaption><a href="https://www.buymeacoffee.com/fabianr">If you’d like to support me, I’d really appreciate it 🫶🏻</a></figcaption></figure><h3>Other Trading Stuff</h3><ul><li><a href="https://medium.com/coinmonks/i-made-codetradings-scalping-strategy-profitable-for-crypto-5916c9b81e6a">Scalping but Profitable (incl. Fees)</a></li><li><a href="https://medium.com/coinmonks/backtesting-s-r-breakouts-in-python-8c77ca3f62fb">I Backtested S&amp;R Breakouts in Python</a></li><li><a href="https://medium.datadriveninvestor.com/backtesting-channel-breakouts-using-my-own-price-channel-algorithm-450ee48ce871">Backtesting Channel Breakouts Using My Own Price Channel Algorithm</a></li><li><a href="https://medium.com/coinmonks/detecting-price-channels-in-python-c53fdae46fe3">How I Detect Price Channels Robustly in Python</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f66d0b312e0b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/i-backtested-tradinglabs-indicator-that-you-ll-ever-need-f66d0b312e0b">TradingLab’s “Insane“ Indicator Ensemble</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[Scalping but Profitable (incl. Fees)]]></title>
            <link>https://medium.com/coinmonks/i-made-codetradings-scalping-strategy-profitable-for-crypto-5916c9b81e6a?source=rss-107d29e0e405------2</link>
            <guid isPermaLink="false">https://medium.com/p/5916c9b81e6a</guid>
            <category><![CDATA[investing]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[trading]]></category>
            <dc:creator><![CDATA[Fabian Ridder]]></dc:creator>
            <pubDate>Wed, 28 Feb 2024 16:23:45 GMT</pubDate>
            <atom:updated>2024-03-01T20:38:57.118Z</atom:updated>
            <content:encoded><![CDATA[<h3>Scalping but Profitable and Including Fees</h3><h4>220% in 3.5 months on EUR/USD? Sounds a bit suspicious to me. Let’s validate it and see if we can apply it to crypto as well!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2t81G6WH4KZshiy_c9WSrA.jpeg" /><figcaption>Thumbnail. Image by author.</figcaption></figure><p>Hey there! I’m back now! Let’s dive straight into trading!</p><blockquote>The code and the parameters I used are at the end ;)</blockquote><h3>Today‘s Topic</h3><p>As you already know, I’m a subscriber of the YouTube channel CodeTrading. He has uploaded a new video presenting a simple scalping strategy:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FC3bh6Y4LpGs%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DC3bh6Y4LpGs&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FC3bh6Y4LpGs%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/066f8cb79d7b81e1e0f9141def05f618/href">https://medium.com/media/066f8cb79d7b81e1e0f9141def05f618/href</a></iframe><p>Somehow, he achieved 220% in 3.5 months on EUR/USD. However, two things bother me regarding his backtest:</p><ul><li>a leverage ratio that’s way too high (30:1) and</li><li>no transaction costs.</li></ul><p>So, this isn’t really realistic, especially the assumption that there are no transaction costs. I have some strategies that would achieve quite high returns when testing without fees, but that’s not how the world works. So, let’s take a look at the strategy ourselves! Let’s get started!</p><h3>The Strategy in The Video</h3><ul><li>5-minute timeframe on EUR/USD</li><li><strong>Uptrend</strong>: EMA(30) &gt; EMA(50) for the latest 7 candles</li><li><strong>Downtrend</strong>: EMA(30) &lt; EMA(50) for the latest 7 candles</li><li><strong>Buy</strong>: Uptrend &amp; Close &lt; lower Bollinger Band(15, std=1.5)</li><li><strong>Sell</strong>: Downtrend &amp; Close &gt; upper Bollinger Band(15, std=1.5)</li><li><strong>Close position</strong> using stop loss and take profit (using 1.1*ATR(7) and RRR=1.5)</li></ul><p>Didn’t understand every detail? No worries! You can still look it up in the code :)</p><h3>So, what are we doing now? We are doing the following:</h3><ul><li>Instead of EUR/USD, we’re using cryptocurrencies.</li><li>No leverage.</li><li>Transaction costs of 0.1% per trade.</li></ul><blockquote>I’ll include the code at the end of the story so you don’t have to scroll that much ;)</blockquote><p>Here are the results for ETH/USD using the same parameters that were shown in the video:</p><pre>params = {<br>    &#39;fast_ema_period&#39;: 30,<br>    &#39;slow_ema_period&#39;: 50,<br>    &#39;bb_period&#39;: 14,<br>    &#39;bb_std&#39;: 1.5,<br>    &#39;atr_period&#39;: 7,<br>    &#39;atr_factor&#39;: 1.1,<br>    &#39;rrr&#39;: 1.5,<br>    &#39;trend_ma_period&#39;: 7,<br>    &#39;trend_threshold&#39;: 1<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zqan70O7FY5i_wf3QDRkXA.png" /><figcaption>Backtest on ETH/USD 5min timeframe, no fees and no leverage. Grey: ETH, Purple: Portfolio. Plot by author.</figcaption></figure><p>We see that the strategy itself might not be bad, because the equity curve has been fighting its way up since hitting its low point at 50k.</p><p>It is probably not applicable to cryptocurrencies in the same way. However, we want to stick with cryptocurrencies. Let’s see how it looks like when adding fees:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UyefmZSlJvdUF4p3Dln2KA.png" /><figcaption>Backtest on ETH/USD 5min timeframe, 0.1% fees and no leverage. Grey: ETH, Purple: Portfolio. Plot by author.</figcaption></figure><p>Ouch! Added fees and we’re immediately burning money. That’s very common in algorithmic trading.</p><p>Let’s adjust the parameters a bit so that we don’t open and close thousands of positions. Maybe this one right here:</p><pre>params = {<br>    &#39;fast_ema_period&#39;: 40,<br>    &#39;slow_ema_period&#39;: 100,<br>    &#39;bb_period&#39;: 50,<br>    &#39;bb_std&#39;: 4,<br>    &#39;atr_period&#39;: 5,<br>    &#39;atr_factor&#39;: 4,<br>    &#39;rrr&#39;: 1,<br>    &#39;trend_ma_period&#39;: 1,<br>    &#39;trend_threshold&#39;: 1<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mUwx_Katqx9WIfupW1AtRA.png" /><figcaption>A better backtest on ETH/USD 5min timeframe, 0.1% fees and no leverage. Grey: ETH, Purple: Portfolio. Plot by author.</figcaption></figure><p>Looks better, right? Here are some stats:</p><ul><li><strong>Win Rate</strong>: 62%</li><li><strong>Max. Drawdown</strong>: 18%</li><li><strong>Total Trades</strong>: 175 in 1112 Days</li><li><strong>Sortino Ratio</strong>: 2.28</li><li><strong>Total Return</strong>: 166.5%</li></ul><h3>Improving Our Approach for Optimization</h3><p>Tbh, that is probably overfit, because I made a grid search on 100% of the data without a train/test split. So, let’s see if we can approach it in a better way.</p><p>We’ll extend the strategy with the RSI indicator:</p><ul><li><strong>Buy</strong>: Uptrend &amp; Close &lt; lower Bollinger Band(15, std=1.5) &amp; RSI &lt; Certain Threshold</li><li><strong>Sell</strong>: Downtrend &amp; Close &gt; upper Bollinger Band(15, std=1.5) &amp; RSI &gt; Certain Threshold</li></ul><p>Next, we are checking 138,240 different parameter combinations on the first 60% of the data. However, we are not using the total return or Sortino ratio to evaluate a combination. Instead, we are using the following score:</p><h4>Evaluating The Performance of an Equity Curve/Combination</h4><p>For each equity curve, we take 20 windows with a 20% overlap. Then, we check if there was a loss or profit in this window. Afterwards, we calculate the average and thus obtain a score between 0 and 1. This means that if we had 8 “positive” windows out of the 20 windows, then we have a score of 8/20 = 0.4.</p><p>Here is an example with 6 windows and an overlap of 25%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5LfbfDkUOHnaRwHRXMM_aw.jpeg" /><figcaption>Example of overlapping windows for calculating the score. (windows=6, overlap=25%, score=0.5). Image by author.</figcaption></figure><p>Why this? To ensure a relatively steady upward trend, we need to consider more than just the Sortino Ratio. For instance, if there’s a +200% trade at the start of the equity curve but the curve goes downhill afterward, it means the strategy isn’t reliable. Even with a good Sortino ratio, this lucky trade doesn’t make the strategy sound. This new score isn’t perfect, but it’s a useful starting point for analysis.</p><p>Now, here are the results for the training phase (first 60%) and the testing phase (other 40%). I took the top 50 combinations and then sorted them by descending <em>test_sortino:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*STr5YTMeN4uYssgUcWZbkg.png" /><figcaption>Backtest results for train (60%) and test (40%) based on our simple score. Image by author.</figcaption></figure><p>Based on these figures, I’d go with one of the combinations between 30708 and 30713. Although the Sortino ratio isn’t the highest among the combinations, the higher return in both the training and test phases makes it a justified choice. Here’s how the plots look for 30708:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qqc1WJhJPZ4dwPYfxFvRYw.png" /><figcaption>Combination 30708 on ETH/USD 5min timeframe (training), 0.1% fees and no leverage. Grey: ETH, Purple: Portfolio. Plot by author.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VLikdXwPdrg76-ficpA7sA.png" /><figcaption>Combination 30708 on ETH/USD 5min timeframe (test), 0.1% fees and no leverage. Grey: ETH, Purple: Portfolio. Plot by author.</figcaption></figure><p>So, we’ve got this strategy that’s actually doing better on the test data than it did in training. That’s not a bad thing, I’d say. Here are the parameters for it:</p><pre>{<br>    &quot;fast_ema_period&quot;: 20,<br>    &quot;slow_ema_period&quot;: 100,<br>    &quot;bb_period&quot;: 50,<br>    &quot;bb_std&quot;: 3,<br>    &quot;atr_period&quot;: 5,<br>    &quot;atr_factor&quot;: 3,<br>    &quot;rrr&quot;: 4,<br>    &quot;rsi_period&quot;: 14,<br>    &quot;rsi_dist&quot;: 0,<br>    &quot;trend_ma_period&quot;: 1,<br>    &quot;trend_threshold&quot;: 1<br>}</pre><h3>Also Taking a Look at The Sortino Ratio</h3><p>Let’s take a look at some other combinations. Actually, I’ve been tracking not just the total return for each window in our score, but also the Sortino ratio. So, we can make use of this or combine it with the total return.</p><p>Let’s say, instead of calculating…</p><pre>(df_returns &gt; 0.0).mean(axis=1).sort_values(ascending=False).head(50)</pre><p>…we’ll calculate…</p><pre>(df_sortinos &gt; 2.0).mean(axis=1).sort_values(ascending=False).head(50)</pre><p>So basically, a window is now considered “green” if the Sortino ratio is above 2; otherwise, it’s red. Here’s how the table of the top 50 sorted by <em>test_sortino</em> looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c9uYeACIjwv5JE0frjjY9A.png" /><figcaption>Backtest results for train (60%) and test (40%) based on our score for sortino ratios. Image by author.</figcaption></figure><p>A series of combinations has really caught my attention: 22116 to 22121. They’ve got solid Sortino ratios during both training and testing, as well as strong returns in either case.Let’s dive deeper into this!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kFlreayyqg4mC4e_Gx1Wfg.png" /><figcaption>Combination 22116 on ETH/USD 5min timeframe (training), 0.1% fees and no leverage. Grey: ETH, Purple: Portfolio. Plot by author.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z2Dz0zCOgEkP5TSOZ0Uusw.png" /><figcaption>Combination 22116 on ETH/USD 5min timeframe (test), 0.1% fees and no leverage. Grey: ETH, Purple: Portfolio. Plot by author.</figcaption></figure><p>The new results look pretty much like the previous ones. Nothing stunning, except that we’ve spruced up the portfolio numbers a bit. Here are the parameters for that:</p><pre>{<br>    &quot;fast_ema_period&quot;: 20,<br>    &quot;slow_ema_period&quot;: 100,<br>    &quot;bb_period&quot;: 50,<br>    &quot;bb_std&quot;: 3,<br>    &quot;atr_period&quot;: 5,<br>    &quot;atr_factor&quot;: 3,<br>    &quot;rrr&quot;: 4,<br>    &quot;rsi_period&quot;: 14,<br>    &quot;rsi_dist&quot;: 0,<br>    &quot;trend_ma_period&quot;: 1,<br>    &quot;trend_threshold&quot;: 1<br>}</pre><h3>Be Careful</h3><p>Sure, I must admit, we have to be a little careful here. Even though it might not seem like overfitting at first glance, given that the overall test results are quite good, we should also consider the selected parameters. It seems that the risk-reward ratio is at 4, which is already on the higher side — especially considering that we still have an <em>atr_factor</em> of 3. So please be cautious!</p><p>I hope you enjoyed it. I’ll leave further investigations up to you again! Until next time :-)</p><p>Here‘s another strategy from the same YouTuber which I tested:</p><p><a href="https://medium.com/coinmonks/backtesting-s-r-breakouts-in-python-8c77ca3f62fb">I Backtested S&amp;R Breakouts in Python</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OydDj-BZ7VAiY0IC.png" /><figcaption><a href="https://www.buymeacoffee.com/fabianr">If you’d like to support me, I’d really appreciate it 🫶🏻</a></figcaption></figure><h3>The Code</h3><p>Here’s the code I used for backtesting. The only thing that is missing is the price data. That is up to you!</p><pre>import numpy as np<br>import numba<br>import talib<br>import vectorbt as vbt<br>import pandas as pd<br><br><br>@numba.njit<br>def get_enex(closes, rsi, rsi_dist, is_uptrend, is_downtrend, above_bb, beneath_bb, atr_perc, rrr, max_position_age):<br>    entries = np.zeros(closes.shape[0])<br>    exits = np.zeros(closes.shape[0])<br>    short_entries = np.zeros(closes.shape[0])<br>    short_exits = np.zeros(closes.shape[0])<br><br>    pos = 0<br>    entry_i = 0<br>    lower_limit = 0<br>    upper_limit = 0<br><br>    for i in range(closes.shape[0]):<br>        if pos == 0:<br>            if beneath_bb[i] and is_uptrend[i] and rsi[i] &lt;= 50-rsi_dist:<br>                pos = 1<br>                entries[i] = True<br>                entry_i = i<br>                lower_limit = (1 - atr_perc[i]) * closes[i]<br>                upper_limit = (1 + atr_perc[i] * rrr) * closes[i]<br><br>            elif above_bb[i] and is_downtrend[i] and rsi[i] &gt;= 50+rsi_dist:<br>                pos = -1<br>                short_entries[i] = True<br>                entry_i = i<br>                lower_limit = (1 - atr_perc[i] * rrr) * closes[i]<br>                upper_limit = (1 + atr_perc[i]) * closes[i]<br>        else:<br>            if closes[i] &gt; upper_limit or closes[i] &lt; lower_limit or i - entry_i &gt; max_position_age:<br>                if pos == 1:<br>                    exits[i] = True<br>                else:<br>                    short_exits[i] = True<br>                pos = 0<br><br>    return entries, exits, short_entries, short_exits<br><br><br>def get_enex_easily(o, h, l, c, v, fast_ema_period, slow_ema_period, trend_ma_period, trend_threshold, bb_period, bb_std, atr_period, atr_factor, rrr, rsi_period, rsi_dist, max_position_age):<br>    atr_perc = (talib.ATR(h, l, c, timeperiod=atr_period) / c) * atr_factor<br><br>    rsi = talib.RSI(c, timeperiod=rsi_period)<br><br>    fast_ema = talib.EMA(c, timeperiod=fast_ema_period)<br>    slow_ema = talib.EMA(c, timeperiod=slow_ema_period)<br>    if trend_ma_period &lt;= 1:<br>        is_uptrend   = fast_ema &gt; slow_ema<br>        is_downtrend = fast_ema &lt; slow_ema<br>    else:<br>        is_uptrend   = talib.SMA(np.array(fast_ema &gt; slow_ema, dtype=np.float64), timeperiod=trend_ma_period) &gt;= trend_threshold<br>        is_downtrend = talib.SMA(np.array(fast_ema &lt; slow_ema, dtype=np.float64), timeperiod=trend_ma_period) &gt;= trend_threshold<br><br>    upper_bb, _, lower_bb = talib.BBANDS(c, bb_period, bb_std, bb_std)<br>    above_bb = c &gt; upper_bb<br>    beneath_bb = c &lt; lower_bb<br><br>    return get_enex(c, rsi, rsi_dist, is_uptrend, is_downtrend, above_bb, beneath_bb, atr_perc, rrr, max_position_age)<br><br><br># Candle data of crypto currency in variables o, h, l, c, v<br><br>params = {<br>    &quot;fast_ema_period&quot;: 20,<br>    &quot;slow_ema_period&quot;: 100,<br>    &quot;bb_period&quot;: 50,<br>    &quot;bb_std&quot;: 3,<br>    &quot;atr_period&quot;: 5,<br>    &quot;atr_factor&quot;: 3,<br>    &quot;rrr&quot;: 4,<br>    &quot;rsi_period&quot;: 14,<br>    &quot;rsi_dist&quot;: 0,<br>    &quot;trend_ma_period&quot;: 1,<br>    &quot;trend_threshold&quot;: 1<br>}<br><br>entries, exits, short_entries, short_exits = get_enex_easily(o, h, l, c, v,<br>                                                                **params,<br>                                                                max_position_age=12*24*5)<br><br>pf = vbt.Portfolio.from_signals(c, entries, exits, short_entries, short_exits, fees=0.001, freq=&quot;5m&quot;)<br><br>print(pf.stats())<br>pf.plot().show()</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5916c9b81e6a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/i-made-codetradings-scalping-strategy-profitable-for-crypto-5916c9b81e6a">Scalping but Profitable (incl. Fees)</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[I Put 11 Years of Medium into Numbers]]></title>
            <link>https://levelup.gitconnected.com/11-years-of-medium-in-numbers-e387eebf0c6f?source=rss-107d29e0e405------2</link>
            <guid isPermaLink="false">https://medium.com/p/e387eebf0c6f</guid>
            <category><![CDATA[writing]]></category>
            <category><![CDATA[analysis]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[medium]]></category>
            <dc:creator><![CDATA[Fabian Ridder]]></dc:creator>
            <pubDate>Tue, 23 Jan 2024 04:00:50 GMT</pubDate>
            <atom:updated>2024-03-18T00:39:28.679Z</atom:updated>
            <content:encoded><![CDATA[<h3>11 Years</h3><h4>&gt;50 Million Stories Ever Published, Priorities and What Happened at the End of 2021?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s2e3R9167nTo5p-VRUaYWw.jpeg" /><figcaption>Thumbnail. Image by author.</figcaption></figure><p>Medium already exists for more than 11 years — since August 2012 to be exact. So I scraped the <a href="https://medium.com/sitemap/posts/2023/posts-2023-12-06.xml">sitemap</a> of Medium in order to investigate how it developed since it was founded.</p><blockquote>I scraped the data on January 10, 2024. That’s the reason why there’s a lack of data for January 2024. So don’t be surprised ;)</blockquote><p>Sit back and have a look at some numbers. Let’s go! 🙌🏻</p><h3>The Development of Posts 📈</h3><p>First, we’re going to start at how much stories were published each year. Medium is getting flooded with stories since 2022 as you can see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FxGH030jkDmx1HxRrjDTiA.png" /><figcaption>Stories published in each year. Plot by author.</figcaption></figure><p>That are <strong>52.207.852 stories ever published</strong> to Medium <em>(January 10, 2024)</em>! Let’s look at them in more detail:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wtKcHpparPGLsc6uFNtZnA.png" /><figcaption>Stories published in each month. Plot by author.</figcaption></figure><p>I’m wondering why there’s a <strong>huge increase at the end of 2021 🧐 </strong>COVID-19 was at the beginning of 2020 and ChatGPT was made publicly available at the end of 2022. I can’t think of any other reason. Please, let me know what you think! 💬</p><p>The next plot visualizes the last modifications of each story. <strong>Only 10.73% of stories were changed after publishing</strong>. This means that 89.27% of stories were never touched again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bKi_HafS5j5Kwc0ZJ1SPMQ.png" /><figcaption>Last story modifications per month. Plot by author.</figcaption></figure><p>Now, some of you already saw it: The increase of stories published at the end of 2021 is much stronger than its increase of modifications. Let’s divide them and see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-BEm8x6ja-hPZvkQBjC_4A.png" /><figcaption>Number of last modifications divided by number of stories published. Plot by author.</figcaption></figure><p>And again! There’s a significant change at the end of 2021: <strong>Stories are changed less than before.</strong> It seems like that people tend to care less about their posts 🤔</p><h3>The Development of “Priority” 📉</h3><p>Next, we’re going to investigate the “priority” of single stories. I don’t know exactly what it is, but every story is assigned a priority (0.2, 0.5, 0.7 or 1.0). This is how a story looks like:</p><pre>...<br>&lt;url&gt;<br>  &lt;loc&gt;https://medium.com/@gingerbangshotline/tips-for-writing-super-short-fiction-the-fine-art-of-whittling-2fde3578e654&lt;/loc&gt;<br>  &lt;lastmod&gt;2023-09-24&lt;/lastmod&gt;<br>  &lt;changefreq&gt;monthly&lt;/changefreq&gt;<br>  &lt;priority&gt;0.5&lt;/priority&gt;<br>&lt;/url&gt;<br>...</pre><p>I assume it has something to do with the recommendation algorithm. The higher your priority, the more you’re recommened. Idk, this is just a guess. 🤷‍♂️</p><p>Right here, you see the average priority of all stories published per month:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x8kH3-MYMhM1lSc86Xl8Lg.png" /><figcaption>Average priority of all stories published in a month. Plot by author.</figcaption></figure><p>The <strong>average priority is slightly decreasing</strong>, possibly due to the significant increase in stories published daily on Medium. I suggest two theories:</p><ol><li>The relationship between writers and readers is changing because more people want to become writers.</li><li>There is a higher number of unread stories on Medium, resulting in lower priority for those stories.</li></ol><p>I believe both theories are valid, noting that the increase may be caused by bots posting numerous stories. It’s important to remember that these are all theories!</p><p><strong>The correlation between the number of published stories and the mean priority is -85.72%</strong>. So the more stories are published, the lower the overall priority.<strong> </strong>This also clearly illustrates the next plot when you compare it to the amount of stories published each month.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4dqtGVyOR73p3KzsgIQorA.png" /><figcaption>Percentage of stories published per month grouped by their priority. Plot by author.</figcaption></figure><p>So currently <em>(January 2024) …</em></p><ul><li>… <strong>84.46%</strong> of stories have a priority of 0.2,</li><li><strong>12.88%</strong> a priority of 0.5,</li><li><strong>2.14%</strong> a priority of 0.7 and</li><li><strong>0.52%</strong> a priority of 1.0.</li></ul><p>As you can see, there’s a greater number of low-priority stories right now because their priority and popularity still need to be assessed in the next few weeks. However, you can still observe a higher plateau since the end of 2021. This is probably due to the significant increase in new stories being published. I am inclined to suggest that Medium is being flooded with a ton of low-quality stories, but we can’t draw this conclusion as we don’t precisely know what priority means. Even if it is related to recommendations, we still can’t conclude that definitively because we don’t understand what the algorithm deems recommendable and what it does not. It might be about quality, or it might be something else. 🤷‍♂️</p><p>However, the next plot suggests that people are writing much more:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mTXbwBFh5jxBvkaE-c6OtA.png" /><figcaption>Average amount of stories published per writer per month. Plot by author.</figcaption></figure><p>In December 2023 every writer who published that month <strong>wrote 7 stories on average</strong>! That’s a lot. Maybe, there are just a few bots publishing hundreds of stories a day so the average increases. So let’s double check it and plot the median:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YaqGBqRRejgRG61lDcMsWA.png" /><figcaption>Median amount of stories published per writer per month. Plot by author.</figcaption></figure><p>Alright! It looks like the last hypothesis is true. There are probably just a few accounts spamming. However, we can still see that the median is jumping up from 1 to 2 stories per month for the very first time. So I still think, people are publishing more stories per month than before.</p><h3>Conclusion 🏁</h3><p>Well, there are some things we can <strong>cautiously</strong> conclude:</p><ul><li>Much more stories are published to Medium every day.</li><li>People tend more to leave their story untouched after posting it.</li><li>Medium is getting filled with low priority stories preempting high priority stories — especially during the last months.</li><li>Writers seem to publish more often.</li></ul><blockquote>Please, be cautious when using these conclusions! My assumption is that there are just some bots uploading a lot of stories or even the same story to Medium several times which might explain all of the observations above.</blockquote><p><strong>Please, let me know what happened at the end of 2021! Did Medium announce or change anything at that time?</strong> Or is this just the start of people starting to spam stories? I really don’t know. 🤷‍♂️</p><p>I hope you enjoyed this little analysis. There’s still some other data I scraped which might be part of another story. Let’s see! 😁</p><p>Here are some other analyses I did:</p><ul><li><a href="https://levelup.gitconnected.com/clickbait-classification-of-5-million-medium-stories-0fc3c0b2d4f4">Using ChatGPT to Classify Medium Stories as Clickbait or Not</a></li><li><a href="https://levelup.gitconnected.com/analysis-of-4-030-501-stories-is-there-an-optimal-time-to-post-medium-stories-e743721721f2">I Analyzed 4 Million Medium Stories for the Best Time To Publish</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*54DaJo3SgBthR3AF.png" /><figcaption><a href="https://www.buymeacoffee.com/fabianr">If you’d like to support me, I’d really appreciate it 🫶🏻</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e387eebf0c6f" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/11-years-of-medium-in-numbers-e387eebf0c6f">I Put 11 Years of Medium into Numbers</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Backtested S&R Breakouts in Python]]></title>
            <link>https://medium.com/coinmonks/backtesting-s-r-breakouts-in-python-8c77ca3f62fb?source=rss-107d29e0e405------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c77ca3f62fb</guid>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[investing]]></category>
            <dc:creator><![CDATA[Fabian Ridder]]></dc:creator>
            <pubDate>Sat, 25 Nov 2023 06:19:04 GMT</pubDate>
            <atom:updated>2023-11-30T21:45:30.312Z</atom:updated>
            <content:encoded><![CDATA[<h4>Do we manage to trade support &amp; resistance algorithmically?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dzgxk2Hd2DoUuNg6PKXCdg.jpeg" /><figcaption>Thumbnail. Image by author.</figcaption></figure><p>I’ve subscripted to the YouTube channel “CodeTrading” which I highly recommend. Recently, he uploaded a video <em>“Maximizing Profits with Python Backtesting: Price Breakout Strategy &amp; Dynamic Trade Management” </em>and also does some streams about this trading approach. These are definitely worth watching. The video can be found here:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FHClxCVvfXDM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DHClxCVvfXDM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FHClxCVvfXDM%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/b6091e78bae2b503f44f56e99bc4ab59/href">https://medium.com/media/b6091e78bae2b503f44f56e99bc4ab59/href</a></iframe><p>I find this simple idea quite interesting and want to test if we can reproduce these results or get even better results. I haven’t written a single line of code yet, but let’s see what we‘re going to come up with. Let’s get started!</p><h3>The Strategy 📖</h3><p>If you haven’t watched his video, don’t worry. I explain what he did:</p><ol><li>Detect pivot points</li><li>Check if the last 3 pivot points are in a certain range (e.g. 0.1%)</li><li><strong>Long</strong>: Price closes above the band of upper pivot points</li><li><strong>Short</strong>: Price closes below the band of lower pivot points</li><li><strong>Closing position</strong>: Stop loss of 3% and take profit of 6%. If the position reaches 3% in profit, we close half the position and adjust the stop loss to the price we entered (-&gt; break even).</li></ol><p>Here’s an example for entering a long position:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tZ4y7o88dtHog1PY-8WEIw.png" /><figcaption>Price breaking through the resistance band — ETH/USD, 5min. Image by author.</figcaption></figure><h3>Let’s Code 👨‍💻</h3><p>No much <em>bla bla</em>. Here it is:</p><pre>import numba<br>import vectorbt as vbt<br>import numpy as np<br><br>@numba.njit<br>def shift_nb(arr, num, fill_value=np.nan):<br>    if num &gt;= 0:<br>        return np.concatenate((np.full(num, fill_value), arr[:-num]))<br>    else:<br>        return np.concatenate((arr[-num:], np.full(-num, fill_value)))<br><br>@numba.njit<br>def get_extrema(h, l, neighbours=3):<br>    maxima = np.full((h.shape[0]), True)<br>    minima = np.full((h.shape[0]), True)<br><br>    for n in range(1, neighbours+1):<br>        maxima &amp;= (h &gt; shift_nb(h, n)) &amp; (h &gt; shift_nb(h, -n))<br>        minima &amp;= (l &lt; shift_nb(l, n)) &amp; (l &lt; shift_nb(l, -n))<br><br>    return maxima, minima<br><br>@numba.njit<br>def get_sizes(c, window_size=80, min_rank=3, pivot_points=3, band_perc=0.002, stop_loss=0.03, rrr=2, take_profit_steps=2, dynamic_stop_loss=True):<br>    sizes = np.zeros(shape=(c.shape[0]))<br><br>    entry_i = -1<br>    pos = 0<br>    # Array of all positions (&lt;size&gt;, &lt;stop_loss&gt;, &lt;take_profit&gt;, &lt;take_profit_step_below&gt;)<br>    positions = np.zeros(shape=(take_profit_steps, 4))<br><br>    for i in range(window_size, c.shape[0]):<br>        # Current window of closes<br>        local_c = c[i-window_size+1:i+1]<br><br>        # If in no position...<br>        if pos == 0:<br>            # Get minima and maxima as an array of booleans<br>            maxima, minima = get_extrema(local_c, local_c, min_rank)<br><br>            # Get only the prices from the latest upper pivot points<br>            maxima_prices = local_c[maxima]<br>            # If there at least &lt;pivot_points&gt; pivot points...<br>            if maxima_prices.shape[0] &gt;= pivot_points:<br>                # ...then get the latest &lt;pivot_points&gt; ones<br>                latest_maxima_prices = maxima_prices[-pivot_points:]<br>                highest_price = np.max(latest_maxima_prices)<br>                lowest_price = np.min(latest_maxima_prices)<br>                # ...and check if they are all in a certain range.<br>                if highest_price / lowest_price - 1 &lt;= band_perc:<br>                    # If they are, then check if the price has been closed above this range.<br>                    if local_c[-1] &gt;= np.mean(latest_maxima_prices) * (1 + band_perc/2):<br>                        # This means: Long!<br>                        sizes[i] += 1<br>                        entry_i = i<br>                        pos = 1<br><br>                        # Buy 100% with different take profits<br>                        for take_profit_step in range(take_profit_steps):<br>                            positions[take_profit_step, 0] = 1 / take_profit_steps<br>                            positions[take_profit_step, 1] = local_c[-1] * (1 - stop_loss)<br>                            positions[take_profit_step, 2] = local_c[-1] * (1 + (stop_loss * rrr / take_profit_steps) * (take_profit_step+1))<br>                            positions[take_profit_step, 3] = local_c[-1] * (1 + (stop_loss * rrr / take_profit_steps) * (take_profit_step))<br><br>            # Get only the prices from the latest lower pivot points<br>            minima_prices = local_c[minima]<br>            # If there at least &lt;pivot_points&gt; pivot points...<br>            if minima_prices.shape[0] &gt;= pivot_points:<br>                # ...then get the latest &lt;pivot_points&gt; ones<br>                latest_minima_prices = minima_prices[-pivot_points:]<br>                highest_price = np.max(latest_minima_prices)<br>                lowest_price = np.min(latest_minima_prices)<br>                # ...and check if they are all in a certain range.<br>                if highest_price / lowest_price - 1 &lt;= band_perc:<br>                    # If they are, then check if the price has been closed below this range.<br>                    if local_c[-1] &lt;= np.mean(latest_minima_prices) * (1 - band_perc/2):<br>                        # This means: Short!<br>                        sizes[i] -= 1<br>                        entry_i = i<br>                        pos = -1<br><br>                        # Sell 100% with different take profits<br>                        for take_profit_step in range(take_profit_steps):<br>                            positions[take_profit_step, 0] = 1 / take_profit_steps<br>                            positions[take_profit_step, 1] = local_c[-1] * (1 + stop_loss)<br>                            positions[take_profit_step, 2] = local_c[-1] * (1 - (stop_loss * rrr / take_profit_steps) * (take_profit_step+1))<br>                            positions[take_profit_step, 3] = local_c[-1] * (1 - (stop_loss * rrr / take_profit_steps) * (take_profit_step))<br><br>        else:<br>            # If we&#39;re in a long position...<br>            if pos == 1:<br>                for position_i in range(positions.shape[0]):<br>                    # If this position has not been closed yet...<br>                    if positions[position_i, 0] &gt;= 1e-8:<br>                        # ...sell if price reached take profit.<br>                        if local_c[-1] &gt;= positions[position_i, 2]:<br>                            sizes[i] -= positions[position_i, 0]<br>                            positions[position_i, 0] = 0<br><br>                            if dynamic_stop_loss:<br>                                # And increase stop loss of the other positions<br>                                positions[position_i:, 1] = positions[position_i, 3]<br><br>                        # ...sell if price reached stop loss.<br>                        if local_c[-1] &lt;= positions[position_i, 1]:<br>                            sizes[i] -= positions[position_i, 0]<br>                            positions[position_i, 0] = 0<br><br>                # If all positions closed...<br>                if positions[:, 0].sum() &lt;= 1e-8:<br>                    # ...reset and store.<br>                    pos = 0<br><br>            # If we&#39;re in a short position...<br>            elif pos == -1:<br>                for position_i in range(positions.shape[0]):<br>                    # If this position has not been closed yet...<br>                    if positions[position_i, 0] &gt;= 1e-8:<br>                        # ...buy back if price reached take profit.<br>                        if local_c[-1] &lt;= positions[position_i, 2]:<br>                            sizes[i] += positions[position_i, 0]<br>                            positions[position_i, 0] = 0<br><br>                            if dynamic_stop_loss:<br>                                # And decrease stop loss of the other positions<br>                                positions[position_i:, 1] = positions[position_i, 3]<br><br>                        # ...buy back if price reached stop loss.<br>                        if local_c[-1] &gt;= positions[position_i, 1]:<br>                            sizes[i] += positions[position_i, 0]<br>                            positions[position_i, 0] = 0<br><br>                # If all positions closed...<br>                if positions[:, 0].sum() &lt;= 1e-8:<br>                    # ...reset and store.<br>                    pos = 0<br><br>    return sizes<br><br><br>sizes = get_sizes(<br>    c=closes,<br>    window_size=100,<br>    min_rank=3,<br>    pivot_points=3,<br>    band_perc=0.002,<br>    stop_loss=0.03,<br>    rrr=2,<br>    take_profit_steps=2,<br>    dynamic_stop_loss=True<br>)<br><br>pf = vbt.Portfolio.from_orders(ohlcv[:, 3], sizes, init_cash=1, freq=&quot;5m&quot;, fees=0.000875)<br>print(pf.stats())<br>pf.plot().show()</pre><p><strong>Why 0.0875% fees?</strong> I’ve explained that in my past story:</p><p><a href="https://medium.datadriveninvestor.com/backtesting-channel-breakouts-using-my-own-price-channel-algorithm-450ee48ce871">Backtesting Channel Breakouts Using My Own Price Channel Algorithm</a></p><p>The code above gives us the following result on <em>ETH/USD</em> (5min):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*riFfTqChvp7Fvckl_Yb3zA.png" /><figcaption>Backtest stats of the strategy provided in the video. Image by author.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7zKvAfCA5vf6skSBefSgvA.png" /><figcaption>Backtest plot of the strategy provided in the video. Image by author.</figcaption></figure><p>Again, pretty disappointing (like my last story). But this time it’s what we should’ve expected. Why? In the video, the daily timeframe has been used. Currently, we’re trading on the 5min timeframe and detecting pivot points by incorporating just 3 neighbouring candles. Of course, we get false signals. However, we’ll stick to the 5min timeframe because we don’t want to lose valuable candle information due to data compression. So here’s a list about what to change:</p><h4>What To Change</h4><ul><li><strong>📅 “Virtually increasing the timeframe”</strong> by using a higher <em>window_size</em> and a higher <em>min_rank</em>.</li><li>♾️ Adding a parameter <strong><em>max_position_age</em></strong>, so a trade cannot be open forever.</li><li>📉 Calculating the <strong>stop loss with the ATR</strong> instead of a fixed stop loss of 3%.</li></ul><p>I also made it much more efficient by removing the call of <em>get_extrema</em> out of the for loop and added some other logic instead in order to avoid the look-ahead bias. By doing so, we <strong>achieve 12 it/sec</strong> <strong>rather than 1 min/it</strong> (when having a high <em>min_rank</em> and <em>window_size</em>).</p><blockquote>I’ll append that final function at the end of this article. Otherwise, you need to scroll a lot again ;)</blockquote><p>In order to get “good” parameters, I’ve made my computer try 432,000 different combinations during a night. Afterwards, I noticed that <em>vectorbt</em> made very weird and wrong calculations. For instance, there was a max drawdown of 4238% and -100% total return with a positive sortino ratio?!? I’ve probably used it in a wrong way.</p><p>As a consequence, I’ve made the <strong>calculations on my own</strong>. For example, this is the code for calculating an approximate sortino ratio of an already existing equity curve:</p><pre>ANN_FACTOR = 365 * 24 * 12 # 5 min timeframe and market is open 24/7<br>ANN_FACTOR_SQRT = np.sqrt(ANN_FACTOR)<br>def calc_sortino_ratio(equity):<br>    returns = np.diff(equity) / equity[:-1]<br>    average_annualized_return = np.nanmean(returns) * ANN_FACTOR<br>    neg_only_returns = np.where(returns &lt;= 0.0, returns, 0.0)<br>    downside_risk = np.sqrt(np.nanmean(neg_only_returns ** 2)) * ANN_FACTOR_SQRT<br>    sortino_ratio = average_annualized_return / downside_risk<br>    return sortino_ratio</pre><p>To be honest, <em>calc_sortino_ratio</em> isn’t perfect either. But by doing all the math manually, we at least don’t get equity curves below -100%. I’ve looked at some of the best results of the previously incorrectly calculated combinations and still got these <strong>pretty results</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*9g5ZCry6gCVFllAP5Oib6w.png" /><figcaption>“Train” period of trading ETH/USD on 5min timeframe. Image by author.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*hpxbELHgq22wDBoZsj-tJw.png" /><figcaption>Test period of trading ETH/USD on 5min timeframe. Image by author.</figcaption></figure><p><strong>Looks like we’re on to something</strong>, as the test period doesn’t have a bad performance either. With some further manual fine-tuning in a few minutes I achieved this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*HkGh0QLy42q8sUgSeNnBig.png" /><figcaption>Test period of trading ETH/USD on 5min timeframe, manually fine-tuned. Image by author.</figcaption></figure><p>This is how I called it:</p><pre>pf_close, trades = sim(<br>    c=closes,<br>    atr_perc=atr_perc,<br>    window_size=600,<br>    min_rank=120,<br>    pivot_points=2,<br>    band_perc=0.003,<br>    atr_factor=5,<br>    rrr=2,<br>    take_profit_steps=1,<br>    dynamic_stop_loss=False,<br>    max_position_age=500<br>)<br><br>plt.plot(pf_close)<br>print(trades)<br>print(calc_sortino_ratio(pf_close))</pre><p>Hope this was a bit more satisfying than the last story. I’ll leave the rest to you:</p><ul><li>Looking if it can also be applied on <strong>other cryptocurrencies</strong> <em>(started it already and seems to be promising as well)</em> or</li><li>if it’s <strong>overfit</strong> or</li><li>if it’s really a <strong>money-making machine</strong>.</li></ul><p>Would love to receive some feedback on this. Until next time! :)</p><h3>The Final Simulation Function</h3><pre>@numba.njit<br>def sim(c, atr_perc, window_size=80, min_rank=3, pivot_points=3, band_perc=0.002, atr_factor=1.5, rrr=2, take_profit_steps=2, dynamic_stop_loss=True, max_position_age=200, fees=0.000875):<br>    entry_i = -1<br>    pos = 0<br>    # Array of all positions (&lt;size&gt;, &lt;stop_loss&gt;, &lt;take_profit&gt;, &lt;take_profit_step_below&gt;)<br>    positions = np.zeros(shape=(take_profit_steps, 4))<br><br>    pf_close = np.ones(shape=c.shape[0])<br>    cash = 1<br>    invested = 0<br>    trades = 0<br><br>    maxima, minima = get_extrema(c, c, min_rank)<br><br>    for i in range(window_size, c.shape[0]):<br>        # Current window of closes<br>        local_c = c[i-window_size+1:i+1]<br><br>        # If in no position...<br>        if pos == 0:<br>            pf_close[i] = cash<br><br>            # Get minima and maxima as an array of booleans<br>            window_maxima = maxima[i-window_size+1:i+1].copy()<br>            window_maxima[-min_rank:] = False<br>            window_minima = minima[i-window_size+1:i+1].copy()<br>            window_minima[-min_rank:] = False<br><br>            # Get only the prices from the latest upper pivot points<br>            maxima_prices = local_c[window_maxima]<br>            # If there at least &lt;pivot_points&gt; pivot points...<br>            if maxima_prices.shape[0] &gt;= pivot_points:<br>                # ...then get the latest &lt;pivot_points&gt; ones<br>                latest_maxima_prices = maxima_prices[-pivot_points:]<br>                highest_price = np.max(latest_maxima_prices)<br>                lowest_price = np.min(latest_maxima_prices)<br>                # ...and check if they are all in a certain range.<br>                if highest_price / lowest_price - 1 &lt;= band_perc:<br>                    # If they are, then check if the price has been closed above this range.<br>                    if local_c[-1] &gt;= np.mean(latest_maxima_prices) * (1 + band_perc/2):<br>                        # This means: Long!<br>                        entry_i = i<br>                        pos = 1<br>                        trades += 1<br><br>                        invested = cash * (1 - fees)<br>                        cash = 0<br><br>                        stop_loss = atr_perc[i] * atr_factor<br><br>                        # Buy 100% with different take profits<br>                        for take_profit_step in range(take_profit_steps):<br>                            positions[take_profit_step, 0] = invested / take_profit_steps<br>                            positions[take_profit_step, 1] = local_c[-1] * (1 - stop_loss)<br>                            positions[take_profit_step, 2] = local_c[-1] * (1 + (stop_loss * rrr / take_profit_steps) * (take_profit_step+1))<br>                            positions[take_profit_step, 3] = local_c[-1] * (1 + (stop_loss * rrr / take_profit_steps) * (take_profit_step))<br><br>            # Get only the prices from the latest lower pivot points<br>            minima_prices = local_c[window_minima]<br>            # If there at least &lt;pivot_points&gt; pivot points...<br>            if minima_prices.shape[0] &gt;= pivot_points:<br>                # ...then get the latest &lt;pivot_points&gt; ones<br>                latest_minima_prices = minima_prices[-pivot_points:]<br>                highest_price = np.max(latest_minima_prices)<br>                lowest_price = np.min(latest_minima_prices)<br>                # ...and check if they are all in a certain range.<br>                if highest_price / lowest_price - 1 &lt;= band_perc:<br>                    # If they are, then check if the price has been closed below this range.<br>                    if local_c[-1] &lt;= np.mean(latest_minima_prices) * (1 - band_perc/2):<br>                        # This means: Short!<br>                        entry_i = i<br>                        pos = -1<br>                        trades += 1<br><br>                        invested = cash * (1 - fees)<br>                        cash = 0<br><br>                        stop_loss = atr_perc[i] * atr_factor<br>                        <br>                        # Sell 100% with different take profits<br>                        for take_profit_step in range(take_profit_steps):<br>                            positions[take_profit_step, 0] = invested / take_profit_steps<br>                            positions[take_profit_step, 1] = local_c[-1] * (1 + stop_loss)<br>                            positions[take_profit_step, 2] = local_c[-1] * (1 - (stop_loss * rrr / take_profit_steps) * (take_profit_step+1))<br>                            positions[take_profit_step, 3] = local_c[-1] * (1 - (stop_loss * rrr / take_profit_steps) * (take_profit_step))<br><br>        else:<br>            # If we&#39;re in a long position...<br>            if pos == 1:<br>                for position_i in range(positions.shape[0]):<br>                    # If this position has not been closed yet...<br>                    if positions[position_i, 0] &gt;= 1e-8:<br>                        # ...sell if price reached take profit.<br>                        if local_c[-1] &gt;= positions[position_i, 2]:<br>                            pos_inv = positions[position_i, 0]<br><br>                            invested -= pos_inv<br>                            cash += pos_inv * (c[i] / c[entry_i]) * (1 - fees)<br><br>                            positions[position_i, 0] = 0<br><br>                            if dynamic_stop_loss:<br>                                # And increase stop loss of the other positions<br>                                positions[position_i:, 1] = positions[position_i, 3]<br><br>                        # ...sell if price reached stop loss or trade is too old.<br>                        if local_c[-1] &lt;= positions[position_i, 1] or i - entry_i &gt;= max_position_age:<br>                            pos_inv = positions[position_i, 0]<br><br>                            invested -= pos_inv<br>                            cash += pos_inv * (c[i] / c[entry_i]) * (1 - fees)<br><br>                            positions[position_i, 0] = 0<br><br>                # If all positions closed...<br>                if positions[:, 0].sum() &lt;= 1e-8:<br>                    # ...reset and store.<br>                    pos = 0<br><br>                pf_close[i] = cash + invested * c[i] / c[entry_i]<br><br>            # If we&#39;re in a short position...<br>            elif pos == -1:<br>                for position_i in range(positions.shape[0]):<br>                    # If this position has not been closed yet...<br>                    if positions[position_i, 0] &gt;= 1e-8:<br>                        # ...buy back if price reached take profit.<br>                        if local_c[-1] &lt;= positions[position_i, 2]:<br>                            pos_inv = positions[position_i, 0]<br><br>                            invested -= pos_inv<br>                            cash += pos_inv * (2 - c[i] / c[entry_i]) * (1 - fees)<br><br>                            positions[position_i, 0] = 0<br><br>                            if dynamic_stop_loss:<br>                                # And decrease stop loss of the other positions<br>                                positions[position_i:, 1] = positions[position_i, 3]<br><br>                        # ...buy back if price reached stop loss or trade is too old.<br>                        if local_c[-1] &gt;= positions[position_i, 1] or i - entry_i &gt;= max_position_age:<br>                            pos_inv = positions[position_i, 0]<br><br>                            invested -= pos_inv<br>                            cash += pos_inv * (2 - c[i] / c[entry_i]) * (1 - fees)<br><br>                            positions[position_i, 0] = 0<br><br>                # If all positions closed...<br>                if positions[:, 0].sum() &lt;= 1e-8:<br>                    # ...reset and store.<br>                    pos = 0<br><br>                pf_close[i] = cash + invested * (2 - c[i] / c[entry_i])<br><br>    return pf_close, trades<br><br># atr_perc calculation using talib (pip3 install ta-lib):<br>import talib<br>atr_perc = talib.ATR(highs, lows, closes, &lt;period&gt;) / closes<br><br>pf_close, trades = sim(<br>    c=closes,<br>    atr_perc=atr_perc,<br>    window_size=400,<br>    min_rank=80,<br>    pivot_points=2,<br>    band_perc=0.005,<br>    atr_factor=5,<br>    rrr=3,<br>    take_profit_steps=4,<br>    dynamic_stop_loss=False,<br>    max_position_age=500<br>)<br><br>plt.plot(pf_close)<br>print(trades)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Uy953IMblfu3HSJ1.png" /><figcaption><a href="https://www.buymeacoffee.com/fabianr">If you’d like to support me, I’d really appreciate it 🫶🏻</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c77ca3f62fb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/backtesting-s-r-breakouts-in-python-8c77ca3f62fb">I Backtested S&amp;R Breakouts in Python</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[Backtesting Channel Breakouts Using My Own Price Channel Algorithm]]></title>
            <link>https://medium.datadriveninvestor.com/backtesting-channel-breakouts-using-my-own-price-channel-algorithm-450ee48ce871?source=rss-107d29e0e405------2</link>
            <guid isPermaLink="false">https://medium.com/p/450ee48ce871</guid>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[investing]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Fabian Ridder]]></dc:creator>
            <pubDate>Fri, 17 Nov 2023 02:02:16 GMT</pubDate>
            <atom:updated>2023-11-17T02:16:06.036Z</atom:updated>
            <content:encoded><![CDATA[<h4>Let’s put the algorithm to the test and see if it’s a money-making machine or probably not.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ai7ozkt1EpVXkTgMLeyoJQ.jpeg" /><figcaption>Thumbnail. Image by author.</figcaption></figure><p>In one of my last stories I’ve proposed an algorithm for detecting price channels “more reliably and robustly” — at least in my opinion. If you missed it, it’s here:</p><p><a href="https://medium.com/coinmonks/detecting-price-channels-in-python-c53fdae46fe3">How I Detect Price Channels Robustly in Python</a></p><p>Because the <em>p-value</em> wasn’t that helpful I removed it and I rewrote the algorithm using <em>numba</em>. By doing so I again achieved a <strong>speedup of roughly 50x</strong>!</p><p>Now, we’ve got a pretty handy tool which we can use for trading price channels. But what exactly are we going to trade? Well, we’ll keep it quite simple and just consider breakouts.</p><h4>Assumptions</h4><p>In this article, I’ll use <strong>cryptocurrencies</strong> for backtesting. “<em>Why cryptocurrencies?</em>”, you might think. The reason why I prefer cryptocurrencies is that I believe that the price is more likely to be driven by historical price data than the price of stocks, for instance. There are much more people trading cryptocurrencies based on historical patterns than people trading stocks based on patterns. That’s at least my opinion. And because many people might trade based on patterns, I guess these patterns really appear in the price chart.</p><p>Apart from that, it’s <em>more or less secure</em> to trade on a DEX and transaction fees are quite low as well, e.g. DYDX with a <strong>worst case fee of 0.05%:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t68fW1cAtuV9lYUiReJBWA.png" /><figcaption>Fees structure of DYDX in November 2023. Image by author. (<a href="https://trade.dydx.exchange/portfolio/fees">Link here</a>)</figcaption></figure><p><em>Tier I</em> even used to have zero fees! However, DYDX increased it to 0.05% which is good nonetheless. Furthermore, most spreads of the 37 coins on DYDX are not that big and it also has a lot of volume:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P-96iFgQHp7j302gEkpnFA.png" /><figcaption>Market overview DYDX in November 2023. Image by author.</figcaption></figure><p>From a past trading project with real trades for all trading pairs on DYDX, I got an average <strong>deviation of 0.175%</strong> from the theoretical profit (or loss). That’s why we’ll use <strong>0.0875% for fees</strong> in our backtests. Enough theory! Let’s get started with backtesting!</p><h3>The Strategy</h3><ul><li>We <strong>enter long</strong> when the current close crosses above the upper trend line of the detected price channel.</li><li>We <strong>enter short</strong> when the current close is below the lower trend line.</li><li><strong>Stop loss</strong> is the highest/lowest pivot point used in the detection.</li><li><strong>Take profit</strong> is calculated with the stop loss and the <strong>risk reward ratio of 2.0</strong>.</li><li>We <strong>close the position</strong> if the stop loss or the take profit is hit or the position is still open after 96 periods (8 hours on 5min timeframe).</li></ul><p>There is no money management or whatsoever. We just invest 100% of our money and that’s it — a bit too naive, but we don’t want to overcomplicate the strategy either.</p><p>These are the parameters for the backtesting function I wrote. If you still remember how the algorithm of the last article works, most of the parameters will probably look familiar to you (<em>Remember: I removed the p-value!</em>):</p><pre>showcase_params = {<br>  # PRICE CHANNEL DETECTION:<br>    &quot;window_size&quot;: 60,<br>    &quot;max_rank_possible&quot;: 20,<br>    &quot;min_rank_for_detection&quot;: 3,<br>    &quot;min_pivot_point_count&quot;: 3,<br>    &quot;max_age_latest_pivot_point&quot;: 10,<br>    &quot;min_r_squared&quot;: 0.98,<br>    &quot;max_crossing_perc&quot;: 0.3,<br>    &quot;min_pivot_points_inbetween&quot;: 2,<br>  # NEW:<br>    &quot;min_channel_score&quot;: 1000,<br>    &quot;tp_perc&quot;: 1,<br>    &quot;rrr&quot;: 2.0,<br>    &quot;max_position_age&quot;: 96,<br>    &quot;min_tp&quot;: 0.003,<br>    &quot;exit_freedom_perc&quot;: 0.000<br>}</pre><h4>The New 6 Parameters</h4><ul><li><strong>“min_channel_score”</strong>: The minimum score of a detected price channel.</li><li><strong>“tp_perc”</strong>: This is a number usually between 1 and 0 (but can also be bigger than 1). It’s multiplied with the take profit and stop loss.</li><li><strong>“rrr”</strong>: This is just the risk reward ratio.</li><li><strong>“max_position_age”</strong>: If the price doesn’t hit the stop loss or the take profit after this amount of periods, the trade will be closed.</li><li><strong>“min_tp”</strong>: This is the minimum take profit. It’s to avoid a take profit of e.g. 0.001% which will become unprofitable after fees and slippage.</li><li><strong>“exit_freedom_perc”</strong>: This is the percentage added upon the trend line. If <em>exit_freedom_perc = 1%</em>, then we enter a position once the price has increased to at least 1% above the trend line or decreased to at least 1% below the trend line.</li></ul><p>Here is an example of trading ETH/USDT between <em>2020–12–25 </em>and<em> 2022–05–01</em> on a 5 min timeframe. I used the price data of Binance because the price data of DYDX seems to be chunky sometimes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TWM2J1KNx2i0XRaRT4qS5w.png" /><figcaption>Plot of cumulative returns of the strategy. Image by author.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lEu_gXupHvP9dsbJAUDfqA.png" /><figcaption>Stats of the strategy. Image by author.</figcaption></figure><p>Well,… isn’t really stunning, right? Let’s see if we can fine-tune our parameters a bit in order to get better results. I’ve changed them to the following:</p><pre>showcase_params = {<br>  # PRICE CHANNEL DETECTION:<br>    &quot;window_size&quot;: 100,<br>    &quot;max_rank_possible&quot;: 20,<br>    &quot;min_rank_for_detection&quot;: 3,<br>    &quot;min_pivot_point_count&quot;: 3,<br>    &quot;max_age_latest_pivot_point&quot;: 15,<br>    &quot;min_r_squared&quot;: 0.95,<br>    &quot;max_crossing_perc&quot;: 0.05,<br>    &quot;min_pivot_points_inbetween&quot;: 1,<br>  # NEW:<br>    &quot;min_channel_score&quot;: 1300,<br>    &quot;tp_perc&quot;: 1,<br>    &quot;rrr&quot;: 1,<br>    &quot;max_position_age&quot;: 192,<br>    &quot;min_tp&quot;: 0.003,<br>    &quot;exit_freedom_perc&quot;: 0.000<br>}</pre><p>These parameters lead to the following plot and metrics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zL-hIOhGZqwgcku158V_wQ.png" /><figcaption>Plot of Cumulative Returns of the fine-tuned Strategy. Image by author.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KuCcJUPbLPh0UYIOIy6W-Q.png" /><figcaption>Stats of the fine-tuned strategy. Image by author.</figcaption></figure><p>Definitely a bit better, but still it doesn’t meet my expectations. Here are the cumulative returns for the (test) period <em>2022–05–01 to 2023–02–28</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qS_cwloksd4l983CsbeaIg.png" /><figcaption>Plot of cumulative returns of the fine-tuned strategy (test period). Image by author.</figcaption></figure><h4>Let’s Have a Look at Some Trades</h4><p>There are entries I would have classified as a good entry point as well, but the stop loss is hit nonetheless. <strong>Return: -1.9907%</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3k2TwUoW8JlnRD0-29Guiw.png" /><figcaption>Example 1) A trade I would’ve made too. Image by author.</figcaption></figure><p>However, you can’t really forecast the price with 100% certainty. Trading is “just” a game of probabilities, so it’s already sufficient to be right in 60% of the cases, for example (assuming a risk reward ratio ≥ 1). But that’s not easy to achieve.</p><p>Here’s another one which I also would’ve done, but was profitable this time.<strong> Return: +0.8260%</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_U38vcPH5i-s8QXoPI01fw.png" /><figcaption>Example 2) A trade I would’ve made too. Image by author.</figcaption></figure><p>Nonetheless, there are also trades which are questionable. For instance, I would’ve not used the pivot point in the lower left corner, but the “smaller” pivot points that follow after it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qp-idh3JPv9wk_pqWJU1pQ.png" /><figcaption>Example 3) A trade I would’ve not made. Image by author.</figcaption></figure><p>I think you get the gist. The <strong>algorithm isn’t perfect</strong>. That means we’re trading price channels that our algorithm classifies as good, although some of them aren’t.</p><blockquote>That’s it?</blockquote><blockquote>Yes, almost :/</blockquote><p>That was the machine on its own. Let’s try to <strong>change the task</strong> to the following: The algorithm detects potential candidates to trade and a human approves/disapproves the entry and sets the stop loss/take profit.</p><h3>Using Human Approval</h3><p>I adapted the code and looked at a lot of candidates for two hours. Here are the <strong>disappointing results</strong> on the test period:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AdnCoWv7Q1MFg0pqton5RQ.png" /><figcaption>Plot of cumulative returns of the strategy with human approval (test period). Image by author.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wRqqbfANr97dj2BYMeekUA.png" /><figcaption>Stats of the strategy with human approval. Image by author.</figcaption></figure><p>What’s the conclusion? Well, I probably shouldn’t trade manually and stay with programming.</p><h3>Key Takeaways</h3><ul><li>The detection algorithm might be <strong>a bit too “complex”</strong>. It’s probably easier and better to consider a very specific pattern, e.g. 3 alternating ups and downs which all have a rank above 10.</li><li>I also noticed that sometimes a channel was detected that looked worse than a channel I detected on my own using the same candlesticks. The algorithm preferred that one because of the high rank of a pivot point used in that channel. The <strong>other channel I saw has never been evaluated</strong>. <em>(The reason: The algorithm doesn’t evaluate every single combination of pivot points. It sorts them and before evaluation it repeatedly removes the one with the smallest rank.)</em></li><li>Trying to <strong>approve trades by humans</strong> might be a good idea. But you need to be quite experienced in my opinion.</li><li>The entire time we assumed that trading “good” price channels is profitable. However, this is <strong>just a hypothesis</strong> (we couldn’t verify nor falsify).</li></ul><p>Hope this wasn’t too disappointing for you. And if this really was a money-making machine, I probably wouldn&#39;t share it online ;)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZAGhI1M29EpgUV_G.png" /><figcaption><a href="https://www.buymeacoffee.com/fabianr">If you’d like to support me, I’d really appreciate it 🫶🏻</a></figcaption></figure><p>Subscribe to DDIntel <a href="https://www.ddintel.com/">Here</a>.</p><p>Have a unique story to share? Submit to DDIntel <a href="https://datadriveninvestor.com/ddintelsubmission">here</a>.</p><p>Join our creator ecosystem <a href="https://join.datadriveninvestor.com/">here</a>.</p><p><a href="https://ddintel.datadriveninvestor.com/"><em>DDIntel</em> </a>captures the more notable pieces from our <a href="https://www.datadriveninvestor.com/"><em>main site</em></a> and our popular <a href="https://medium.datadriveninvestor.com/"><em>DDI Medium publication</em></a>. Check us out for more insightful work from our community.</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=450ee48ce871" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/backtesting-channel-breakouts-using-my-own-price-channel-algorithm-450ee48ce871">Backtesting Channel Breakouts Using My Own Price Channel Algorithm</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using ChatGPT to Classify Medium Stories as Clickbait or Not]]></title>
            <link>https://levelup.gitconnected.com/clickbait-classification-of-5-million-medium-stories-0fc3c0b2d4f4?source=rss-107d29e0e405------2</link>
            <guid isPermaLink="false">https://medium.com/p/0fc3c0b2d4f4</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Fabian Ridder]]></dc:creator>
            <pubDate>Wed, 25 Oct 2023 04:37:57 GMT</pubDate>
            <atom:updated>2023-12-17T22:22:31.806Z</atom:updated>
            <content:encoded><![CDATA[<h3>Let‘s Classify Millions of Medium Stories as Clickbait or Not</h3><h4>I’ve scraped 5 million Medium stories. Let’s train classifiers and create a custom data set.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yhnm0ZrBK3yiLWmcCJhT4Q.jpeg" /><figcaption>Thumbnail (also a bit clickbait-ish). Image by author.</figcaption></figure><h3>Problem</h3><p>We have a data set of 5 million Medium stories and want to classify each title as<strong> <em>clickbait</em> </strong>or<strong> <em>non-clickbait</em></strong> in order to conduct further analysis. This is how the data looks like:</p><pre>import pandas as pd<br>stories_df = pd.read_csv(&quot;data/stories_df.csv&quot;)<br><br>stories_df.shape<br># (4986410, 33)<br><br># little preview for you<br>stories_df[[&quot;title&quot;, &quot;clapCount&quot;, &quot;wordCount&quot;, &quot;voterCount&quot;, &quot;postResponsesCount&quot;, &quot;tag0&quot;, &quot;tag1&quot;]]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KRDLf2EzMWGrMdkc_SidGA.png" /><figcaption>Preview: A portion of all columns of the data frame. Image by author.</figcaption></figure><pre>stories_df.columns<br># Index([&#39;id&#39;, &#39;title&#39;, &#39;isPublished&#39;, &#39;mediumUrl&#39;, &#39;collection&#39;,<br>#        &#39;isLimitedState&#39;, &#39;allowResponses&#39;, &#39;visibility&#39;, &#39;clapCount&#39;,<br>#        &#39;wordCount&#39;, &#39;voterCount&#39;, &#39;statusForCollection&#39;, &#39;pinnedAt&#39;,<br>#        &#39;latestPublishedAt&#39;, &#39;firstPublishedAt&#39;, &#39;readingTime&#39;, &#39;isLocked&#39;,<br>#        &#39;sequence&#39;, &#39;isSeries&#39;, &#39;uniqueSlug&#39;, &#39;creator_id&#39;,<br>#        &#39;pendingCollectionId&#39;, &#39;subtitle&#39;, &#39;subtitleIsFullContent&#39;,<br>#        &#39;postResponsesCount&#39;, &#39;previewImageAlt&#39;, &#39;previewImageId&#39;, &#39;tag0&#39;,<br>#        &#39;tag1&#39;, &#39;tag2&#39;, &#39;tag3&#39;, &#39;tag4&#39;, &#39;tag5&#39;],<br>#       dtype=&#39;object&#39;)</pre><p>In a previous article we’ve already familiarized ourselves a little with the data:</p><p><a href="https://levelup.gitconnected.com/analysis-of-4-030-501-stories-is-there-an-optimal-time-to-post-medium-stories-e743721721f2">I Analyzed 4 Million Medium Stories for the Best Time To Publish</a></p><h3>Two Solutions</h3><ol><li>Training a model based on an <strong>already existing data set</strong></li><li>Creating <strong>our own data set with an LLM </strong>and training a model afterwards</li></ol><p>In the following, we’ll regard “<em>clickbait</em>” as</p><blockquote>exaggerating, sensational sounding and enticing titles.</blockquote><p>Actually, clickbait is a bit more than that because it not only tempts you to click, but also usually doesn’t really describe what you expect from the content of an article. Unfortunately, we cannot check this as the data only includes the title and not the content, which is why we stick with this definition. That being said, let’s get started!</p><h3>1) Existing Data Sets</h3><p>I’ve searched for some time and found only one more or less useful source:</p><ul><li>Kaggle data set by Aman Anand (<a href="https://www.kaggle.com/datasets/amananandrai/clickbait-dataset">here</a>)</li></ul><p>Here are 10 samples from this data set:</p><pre>| clickbait | headline                                                          |<br>|----------:|:------------------------------------------------------------------|<br>|         1 | We Taught These Grandmas How To Do The Nae Nae And It Was Cute AF |<br>|         1 | 17 Perfect Products For Embracing Your Inner Kanye                |<br>|         1 | Here&#39;s How To Draw A Hand, Maybe                                  |<br>|         1 | Can You Identify These Movies Based On The Main Character&#39;s BFF   |<br>|         1 | 21 Tweets That Prove Your Brain Can Be A Real Dick Sometimes      |<br>|         0 | Senate rejects short-term extension of the USA PATRIOT Act        |<br>|         0 | Wal-Mart to Rebuild Health Clinic Business                        |<br>|         0 | Research shows that bats cry to detect prey                       |<br>|         0 | Galatasaray clinch 17th Turkish title                             |<br>|         0 | 2008 Leisure Taiwan launched in Taipei World Trade Center         |<br>32000 rows × 2 columns</pre><p>Unfortunately, all data sets that I found contain the same data as the data set above. Let me know if you find something better! However, this one seems to be “widely” used, probably because its concept of labelling has been inspired by the following paper:</p><blockquote>Abhĳnan Chakraborty, Bhargavi Paranjape, Sourya Kakarla, &amp; Niloy Ganguly. (2016). Stop Clickbait: Detecting and Preventing Clickbaits in Online News Media. <a href="https://arxiv.org/pdf/1610.09786.pdf">https://arxiv.org/pdf/1610.09786.pdf</a></blockquote><p>They definitely found some interesting results. For instance, the distribution of the title length differs from clickbait to non-clickbait:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*S3gZwEAP403f9BDn4rNBxg.png" /><figcaption>Distribution of title length. Abhĳnan Chakraborty, Bhargavi Paranjape, Sourya Kakarla, &amp; Niloy Ganguly. (2016). Stop Clickbait: Detecting and Preventing Clickbaits in Online News Media. <a href="https://arxiv.org/pdf/1610.09786.pdf">https://arxiv.org/pdf/1610.09786.pdf</a></figcaption></figure><p>Furthermore, clickbait consists of more…</p><ul><li>word contractions <em>(e.g. does not -&gt; doesn’t)</em></li><li>stopwords <em>(e.g. in, a, for, to, …)</em></li><li>exaggerations <em>(e.g. awe-inspiring, breathtakingly, gut-wrenching, soul-stirring)</em></li><li>determiners <em>(e.g. the, this, my, your, many, two, …):</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*2PUeNprDBNMiRFZEi3V7aQ.png" /><figcaption>Percentage of word types in clickbait and non-clickbait titles. Abhĳnan Chakraborty, Bhargavi Paranjape, Sourya Kakarla, &amp; Niloy Ganguly. (2016). Stop Clickbait: Detecting and Preventing Clickbaits in Online News Media. <a href="https://arxiv.org/pdf/1610.09786.pdf">https://arxiv.org/pdf/1610.09786.pdf</a></figcaption></figure><p>The paper also presents other results. So if you’re interested, the link is above. But that was enough theory! Let’s go to the more fun part!</p><h4>1.1) Training A Model</h4><p>We’ll use <em>fasttext</em> because it’s extremely <strong>easy to use</strong>, extremely <strong>fast</strong> (as the name might suggest) and often comes up with <strong>very good results</strong>. We don’t need more Python code than that:</p><pre>import pandas as pd<br>import fasttext<br>from sklearn.model_selection import train_test_split<br><br>clickbait_df = pd.read_csv(&quot;clickbait.csv&quot;)<br>clickbait_df[&quot;label&quot;] = clickbait_df[&quot;clickbait&quot;].replace({0: &quot;__label__no&quot;, 1: &quot;__label__yes&quot;})<br>clickbait_df[&quot;fasttext&quot;] = clickbait_df[&quot;label&quot;] + &quot; &quot; + clickbait_df[&quot;headline&quot;]<br><br>train, test = train_test_split(clickbait_df, test_size=0.2)<br><br>print(train[&quot;clickbait&quot;].mean())<br># 0.5017578125 (-&gt; almost no imbalance)<br>print(test[&quot;clickbait&quot;].mean())<br># 0.4928125 (-&gt; almost no imbalance)<br><br>with open(&quot;clickbait.train&quot;, &quot;w&quot;) as file:<br>    file.write(&quot;\n&quot;.join(train[&quot;fasttext&quot;]))<br>with open(&quot;clickbait.test&quot;, &quot;w&quot;) as file:<br>    file.write(&quot;\n&quot;.join(test[&quot;fasttext&quot;]))<br><br>model = fasttext.train_supervised(input=&quot;clickbait.train&quot;)<br>model.test(&quot;clickbait.test&quot;)<br># (6400, 0.99015625, 0.99015625)</pre><p>That’s it! Training and testing was done in less than a second and we already achieved an <strong>accuracy of 99.02%</strong> on test data! I love this tool so much!</p><h4>1.2) Testing The Model</h4><p>Let’s see if this works well for Medium stories too. For that, I let the model predict the class for the first 10 stories of the data frame:</p><pre>| clickbait | confidence | title                                                                                |<br>| --------: | :--------- | :----------------------------------------------------------------------------------- |<br>|         0 | 0.9721     | Generative Video Music : AI Innovation Challenge                                     |<br>|         0 | 1.0        | Transitioning to Tech: Travel Writer to Machine Learning and Data Science Enthusiast |<br>|         0 | 0.9999     | Navigating the MLOps Tool Landscape: A Practical Guide 🌟🛠️                          |<br>|         1 | 0.9994     | 29 Must-Have Python Libraries For Data Science And Machine Learning                  |<br>|         0 | 1.0        | Understanding Confusion Matrix for Model Evaluation in Machine Learning              |<br>|         0 | 0.9993     | STRIKING A BALANCE. The Positive and Negative Impacts of AI                          |<br>|         0 | 1.0        | Navigating the AI Landscape: Choosing the Right Model for Your Problem               |<br>|         0 | 0.9025     | Master Python Inheritance with These Tricks                                          |<br>|         0 | 1.0        | Understanding the Key Differences: Supervised vs. Unsupervised Learning              |<br>|         0 | 1.0        | Generative AI for Interior Design: benefits, challenges and opportunities            |</pre><p>It looks like it already does a good job, although I consider the title <em>“STRIKING A BALANCE…”</em> and “<em>Master Python Inheritance with These Tricks</em>” clickbait-ish. In order to evaluate how good this model performs on Medium stories, we need a test data set which doesn’t exist yet.</p><h3>2) Creating a Data Set on Our Own</h3><p>First, I spent 2 hours manually labeling 770 titles, which was a waste of time as it is extremely subjective and difficult to determine which title is clickbait and which is not.</p><p>But there are LLMs out there which have a deep understanding of language and — at least — pretend to be objective. So, I chose <em>ChatGPT-Instruct</em> as a model and used OpenAI’s API in order to make this process a bit faster and not that painful as before. Why <em>ChatGPT-Instruct</em>? Well, it’s good enough and <strong>cheap</strong>. The entire process of labelling <strong>16,000 titles </strong>(that had more than 11 clappers)<strong> cost me $1.24</strong> thanks to the option “<em>max_tokens=6</em>”. This is the prompt and the function I wrote:</p><blockquote><em>Is this headline </em>CLICKBAIT<em>, </em>CLICKBAIT-ISH<em>, </em>FACTUAL<em> or </em>UNKNOWN<em> if it cannot be assessed. Explain it briefly! <br>Title: {</em>title<em>}<br>Class:</em></blockquote><pre>def classify_gpt(title):<br>    prompt = f&quot;&quot;&quot;Is this headline CLICKBAIT, CLICKBAIT-ISH, FACTUAL or UNKNOWN if it cannot be assessed. Explain it briefly!    <br>Title: {title}<br>Class:&quot;&quot;&quot;<br><br>    response = openai.Completion.create( <br>        model=&quot;gpt-3.5-turbo-instruct&quot;, prompt=prompt, max_tokens=6, temperature=0<br>    )<br>    responses.append(response)<br><br>    input_tokens += response.usage[&quot;prompt_tokens&quot;]<br>    output_tokens += response.usage[&quot;completion_tokens&quot;]<br><br>    answer = response.choices[0].text<br><br>    if &quot;FACTUAL&quot;.lower() in answer.lower()[:min(30, len(answer))]:<br>        return &quot;FACTUAL&quot;, answer<br>    elif &quot;CLICKBAIT-ISH&quot;.lower() in answer.lower()[:min(30, len(answer))]:<br>        return &quot;CLICKBAIT-ISH&quot;, answer<br>    elif &quot;CLICKBAIT&quot;.lower() in answer.lower()[:min(30, len(answer))]:<br>        return &quot;CLICKBAIT&quot;, answer<br>    elif &quot;UNKNOWN&quot;.lower() in answer.lower()[:min(30, len(answer))]:<br>        return &quot;UNKNOWN&quot;, answer<br><br>    return &quot;ERROR&quot;, answer</pre><p>As you can see, there are more than two labels. During prompting the model sometimes identified a title as “FACTUAL”, although it appeared to be “CLICKBAIT-ISH”. I gave ChatGPT the option “UNKNOWN” as well in order to prevent potential hallucinations. Here are some examples:</p><pre>classify_gpt(&quot;The Essence of AI Death Technology&quot;)<br># (&#39;CLICKBAIT&#39;, &#39; CLICKBAIT\n\nExplanation:&#39;)<br><br>classify_gpt(&quot;I Made A Lot Money Fast. Every 4-year-old Can Do It Too.&quot;)<br># (&#39;CLICKBAIT&#39;, &#39; CLICKBAIT\n\nExplanation:&#39;)<br><br>classify_gpt(&quot;I Tried Selling ChatGPT Digital Products For 30 Days&quot;)<br># (&#39;FACTUAL&#39;, &#39; FACTUAL\n\nExplanation: This&#39;)<br><br>classify_gpt(&quot;Top 20 mobile apps which nobody knows about…&quot;)<br>#(&#39;CLICKBAIT&#39;, &#39; CLICKBAIT\n\nExplanation:&#39;)<br><br>classify_gpt(&quot;Forecasting Tomorrow’s Stock Price with Today’s News&quot;)<br># (&#39;FACTUAL&#39;, &#39; FACTUAL\n\nThis headline is&#39;)</pre><p>Of course, the model isn’t perfect but definitely better and faster than me. Here are the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZRm0JaN8Zt4SZu9YEZ8A8Q.png" /><figcaption>Our new data set labelled by ChatGPT-Instruct. Image by author.</figcaption></figure><pre>own_test_set[&quot;llm_class&quot;].value_counts()<br># CLICKBAIT        7257<br># FACTUAL          4651<br># UNKNOWN          3286<br># CLICKBAIT-ISH     806<br># Name: llm_class, dtype: int64</pre><p>Since our model is a binary classifier, we’ll regard “CLICKBAIT-ISH” as clickbait too. Titles labelled as “UNKNOWN” are removed. By doing so and after getting rid of the class imbalance with oversampling, we achieve an <strong>accuracy of 60.20%</strong>. How can we do better?</p><p>Let’s train a new <em>fasttext</em> model directly on our new data set! In the following we want it to predict one of four classes:</p><pre>own_test_set = pd.read_csv(&quot;own_test_set.csv&quot;)<br><br>own_test_set = own_test_set[(own_test_set[&quot;llm_class&quot;] != &quot;ERROR&quot;)]<br>own_test_set[&quot;label&quot;] = own_test_set[&quot;llm_class&quot;].replace({&quot;FACTUAL&quot;: &quot;__label__factual&quot;, &quot;CLICKBAIT&quot;: &quot;__label__clickbait&quot;, &quot;CLICKBAIT-ISH&quot;: &quot;__label__clickbaitish&quot;, &quot;UNKNOWN&quot;: &quot;__label__unknown&quot;})<br>own_test_set[&quot;fasttext&quot;] = own_test_set[&quot;label&quot;] + &quot; &quot; + own_test_set[&quot;title&quot;]<br><br>own_train, own_test = train_test_split(own_test_set, test_size=0.2)<br><br># Get rid of class imbalance<br>own_train = oversample_one_hot_encoded(own_train, np.array([<br>    own_train[&quot;label&quot;] == &quot;__label__clickbait&quot;,<br>    own_train[&quot;label&quot;] == &quot;__label__factual&quot;,<br>    own_train[&quot;label&quot;] == &quot;__label__unknown&quot;,<br>    own_train[&quot;label&quot;] == &quot;__label__clickbaitish&quot;,<br>]))<br>own_test = oversample_one_hot_encoded(own_test, np.array([<br>    own_test[&quot;label&quot;] == &quot;__label__clickbait&quot;,<br>    own_test[&quot;label&quot;] == &quot;__label__factual&quot;,<br>    own_test[&quot;label&quot;] == &quot;__label__unknown&quot;,<br>    own_test[&quot;label&quot;] == &quot;__label__clickbaitish&quot;,<br>]))<br><br>with open(&quot;own_test_set.train&quot;, &quot;w&quot;) as file:<br>    file.write(&quot;\n&quot;.join(own_train[&quot;fasttext&quot;]))<br>with open(&quot;own_test_set.test&quot;, &quot;w&quot;) as file:<br>    file.write(&quot;\n&quot;.join(own_test[&quot;fasttext&quot;]))<br><br>own_train[&quot;llm_class&quot;].value_counts() / own_train.shape[0]<br># CLICKBAIT        0.25<br># FACTUAL          0.25<br># UNKNOWN          0.25<br># CLICKBAIT-ISH    0.25<br># Name: llm_class, dtype: float64<br><br>own_test[&quot;llm_class&quot;].value_counts() / own_test.shape[0]<br># CLICKBAIT        0.25<br># FACTUAL          0.25<br># UNKNOWN          0.25<br># CLICKBAIT-ISH    0.25<br># Name: llm_class, dtype: float64<br><br>own_model = fasttext.train_supervised(input=&quot;own_test_set.train&quot;)<br>own_model.test(&quot;own_test_set.test&quot;)<br># (5816, 0.46011004126547456, 0.46011004126547456)</pre><p>Well, an accuracy of <strong>46.01% </strong>for 4 classes is not that bad. Let’s try to turn this into a binary classification again:</p><pre>own_test_set = pd.read_csv(&quot;own_test_set.csv&quot;)<br><br>own_test_set = own_test_set[(own_test_set[&quot;llm_class&quot;] != &quot;ERROR&quot;)]<br>own_test_set[&quot;label&quot;] = own_test_set[&quot;llm_class&quot;].replace({&quot;FACTUAL&quot;: &quot;__label__no&quot;, &quot;CLICKBAIT&quot;: &quot;__label__yes&quot;, &quot;CLICKBAIT-ISH&quot;: &quot;__label__yes&quot;, &quot;UNKNOWN&quot;: &quot;__label__no&quot;})<br>own_test_set[&quot;fasttext&quot;] = own_test_set[&quot;label&quot;] + &quot; &quot; + own_test_set[&quot;title&quot;]<br><br>own_train, own_test = train_test_split(own_test_set, test_size=0.2)<br><br># Get rid of class imbalance<br>own_train = oversample_binary(own_train, own_train[&quot;label&quot;] == &quot;__label__yes&quot;)<br>own_test = oversample_binary(own_test, own_test[&quot;label&quot;] == &quot;__label__yes&quot;)<br><br>with open(&quot;own_test_set.train&quot;, &quot;w&quot;) as file:<br>    file.write(&quot;\n&quot;.join(own_train[&quot;fasttext&quot;]))<br>with open(&quot;own_test_set.test&quot;, &quot;w&quot;) as file:<br>    file.write(&quot;\n&quot;.join(own_test[&quot;fasttext&quot;]))<br><br>own_train[&quot;llm_class&quot;].value_counts() / own_train.shape[0]<br># CLICKBAIT        0.25<br># FACTUAL          0.25<br># UNKNOWN          0.25<br># CLICKBAIT-ISH    0.25<br># Name: llm_class, dtype: float64<br><br>own_test[&quot;llm_class&quot;].value_counts() / own_test.shape[0]<br># CLICKBAIT        0.25<br># FACTUAL          0.25<br># UNKNOWN          0.25<br># CLICKBAIT-ISH    0.25<br># Name: llm_class, dtype: float64<br><br>own_model = fasttext.train_supervised(input=&quot;own_test_set.train&quot;)<br>own_model.test(&quot;own_test_set.test&quot;)<br># (3250, 0.7283076923076923, 0.7283076923076923)</pre><p>I’ve treated “UNKNOWN” the same as “FACTUAL” because then we achieved an accuracy of <strong>72.83% </strong>instead of 66.02%. Of course, an entire LLM would be the best classifier, but we have millions of stories. Thus, it might get a bit expensive when sending millions of requests to OpenAI. And we’re also assuming that ChatGPT identifies each title correctly, which might be questionable as well. This could probably be improved by sending each prompt several times with a slightly greater temperature and using majority voting afterwards, by employing few-shot prompting and by spending more time on prompt engineering.</p><p>I tried other approaches like preprocessing the titles (stop words, punctuation, lemmatization or TF-IDF vectorization) and giving this to different classifiers. But they <strong>never got more than 70%</strong>. There’s one other approach that was more promising: Turning every title into an embedding (of size 1536) with the OpenAI API using <em>text-embedding-ada-002</em>. After spending some time and $0.02 on making 16,000 requests for 16,000 titles and training a normal fully connected neural network, I accomplished more than <strong>81% accuracy</strong>. This is the simple neural network I built:</p><pre>model = Sequential()<br>model.add(layers.Dense(2048, input_shape=(X_train.shape[1:])))<br>model.add(layers.Dropout(0.2))<br>model.add(layers.Dense(1024))<br>model.add(layers.Dropout(0.1))<br>model.add(layers.Dense(512))<br>model.add(layers.Dropout(0.1))<br>model.add(layers.Dense(128))<br>model.add(layers.Dense(64))<br>model.add(layers.Dense(1, activation=&quot;sigmoid&quot;))</pre><p>I know, there’s a significant difference between 73% and 81% accuracy, but I wouldn’t like to send millions of requests to OpenAI just for getting embeddings and +8% more accuracy. The test dataset together with the embeddings have already a substantial size— more than half a gigabyte to be more precise. If I continued to gather these embeddings my hard drive would explode. And I’m a bit tired of this project as well.</p><p>It’s just easier and faster to use the already trained <em>fasttext</em> model in order to classify the rest of the data. Certainly, even better approaches exist, but this is what we currently need to work with. Please, let me know if you have other or better ideas!</p><h3>3) Plotting Our Work</h3><p>We need to keep in mind that we’re working with a classifier which “only” achieved 73%, so we have to be <strong>careful with drawing conclusions</strong> from the following plots.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M_qBdbCxUgCCFRjgHCItxQ.png" /><figcaption>Percentage of stories identified as ‘clickbait’ by our trained model. Image by author.</figcaption></figure><p>It looks like nothing has really changed in this year (2023) when it comes to clickbait. If we only consider those stories that are classified with a confidence above 95%, we’ll get the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PbX1lMFqLL1y7_z0aPJbsA.png" /><figcaption>Percentage of stories identified as ‘clickbait’ with a confidence &gt; 0.95. Image by author.</figcaption></figure><p>There doesn’t seem to be a difference. Maybe, does reading time relate to clickbait in any way?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D2ov0gw_xr4XirVRn2uxKg.png" /><figcaption>Percentage of stories identified as ‘clickbait’ — reading time (min). Image by author. 🟥 paywall &amp; publication, 🟩 no paywall &amp; publication, 🟦 paywall &amp; no publication, 🟨 no paywall &amp; no publication</figcaption></figure><p>Apparently, very short stories tend to have less clickbait than longer stories. Furthermore, clickbait appears to peak at around 4 minutes of reading time, which applies at least to all groups except for the green one.</p><p>That’s it! Hope you liked it and stay tuned for the “real” analysis!</p><p>If you missed <strong>my previous analysis</strong>:</p><p><a href="https://levelup.gitconnected.com/analysis-of-4-030-501-stories-is-there-an-optimal-time-to-post-medium-stories-e743721721f2">I Analyzed 4 Million Medium Stories for the Best Time To Publish</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NTYhTc3qimwRLpjiU1Ihpw.png" /><figcaption><a href="https://www.buymeacoffee.com/fabianr">If you’d like to support me, I’d really appreciate it 🫶🏻</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0fc3c0b2d4f4" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/clickbait-classification-of-5-million-medium-stories-0fc3c0b2d4f4">Using ChatGPT to Classify Medium Stories as Clickbait or Not</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Detect Price Channels Robustly in Python]]></title>
            <link>https://medium.com/coinmonks/detecting-price-channels-in-python-c53fdae46fe3?source=rss-107d29e0e405------2</link>
            <guid isPermaLink="false">https://medium.com/p/c53fdae46fe3</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[investing]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[trading]]></category>
            <dc:creator><![CDATA[Fabian Ridder]]></dc:creator>
            <pubDate>Tue, 17 Oct 2023 14:31:25 GMT</pubDate>
            <atom:updated>2023-10-26T22:18:45.390Z</atom:updated>
            <content:encoded><![CDATA[<h4>Let’s automate what a lot traders do manually!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-XqEEp0Rhrf3KNEztPlIdg.jpeg" /><figcaption>Thumbnail. Image by author.</figcaption></figure><h3>Problem</h3><p>Creating a <strong>more robust</strong> and <strong>reliable</strong> price channel detection algorithm.</p><p><em>(The </em><strong><em>final algorithm</em></strong><em> and a notebook are </em><strong><em>at the end</em></strong><em> of this article.)</em></p><h3>Conventional Solution</h3><ol><li><strong>Detecting pivot points</strong> by comparing highs/lows to their 2 or 3 neighbours each and check if it’s the highest/lowest of them.</li><li><strong>Doing linear regression</strong> for all pivot points in order to get the upper and lower trend line.</li><li><strong>Entering a position</strong> once the price has left the channel.</li></ol><p>By doing so, we get price channels that look like the following. I think we can achieve better results with the given data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lrm0NpiNdZEfl1qbpj8vBg.png" /><figcaption>“Naive” linear regression for all previous maxima and minima. Image by author.</figcaption></figure><h3>My Solution</h3><p>First, I want to show you what my algorithm leads to. In my opinion, it’s definitely better than the above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RXI0JjtBbAP3qP9NcCn_dg.png" /><figcaption>My results for the same price data. Image by author.</figcaption></figure><h3>1. Pivot Point Detection</h3><p>For pivot point detection I already proposed an approach in this story:</p><p><a href="https://medium.com/coinmonks/smoothing-price-data-for-pivot-points-7e4e14e4e1e7">How I Smooth Price Data Much More Efficiently for Pivot Point Detection</a></p><p>However, during my tests it turned out that the pivot points created by this method are reasonably good, but it’s better to have too much pivot points instead of losing an important one. “Bad” ones can be filtered out later.</p><h4>“So what’s your new approach then?”, you might ask.</h4><p>Well, I copied the way people detect maxima and minima but adapted it by adding a “rank” to each pivot point. This “rank” represents the confidence or strength of a pivot point, so we don’t just get an array of 0’s and 1’s. The rank tells us how many adjacent highs/lows are lower/higher than the current high/low.</p><p>Here’s the “conventional” function:</p><pre>def get_extrema(h, l, neighbours=3):<br>    maxima = np.ones(shape=(h.shape[0]), dtype=bool)<br>    minima = np.ones(shape=(h.shape[0]), dtype=bool)<br><br>    for n in range(1, neighbours+1):<br>        maxima &amp;= (h &gt; shift_nb(h, n)) &amp; (h &gt; shift_nb(h, -n))<br>        minima &amp;= (l &lt; shift_nb(l, n)) &amp; (l &lt; shift_nb(l, -n))<br><br>    return maxima, minima</pre><p>And this is the function that assigns a rank to all highs and lows:</p><pre>def get_ranked_extrema(h, l, max_neighbours=10):<br>    maxima = np.zeros(shape=(h.shape[0]), dtype=int)<br>    minima = np.zeros(shape=(h.shape[0]), dtype=int)<br><br>    for n in range(1, max_neighbours+1):<br>        maxima_filter = np.where(maxima == n-1)[0]<br>        maxima[maxima_filter] += ((h &gt;= shift_nb(h, n)) &amp; (h &gt; shift_nb(h, -n)))[maxima_filter]<br><br>        minima_filter = np.where(minima == n-1)[0]<br>        minima[minima_filter] += ((l &lt;= shift_nb(l, n)) &amp; (l &lt; shift_nb(l, -n)))[minima_filter]<br><br>    return maxima, minima</pre><p>It takes twice as long as the upper function, but we’re talking about milliseconds and we want rather good results slowly than moderate results fast. An average iteration over 54,416 rows took the first function <strong>2.945 ms</strong> and the second function <strong>5.775 ms</strong>. If you’re wondering what <em>shift_nb</em> is: It’s a “numbafied” function that just shifts a numpy array by n indices. This is how it looks like (thanks to <a href="https://stackoverflow.com/a/62841583">this answer on StackOverflow</a>):</p><pre>@numba.njit<br>def shift_nb(arr, num, fill_value=np.nan):<br>    if num &gt;= 0:<br>        return np.concatenate((np.full(num, fill_value), arr[:-num]))<br>    else:<br>        return np.concatenate((arr[-num:], np.full(-num, fill_value)))</pre><p>Now, we can plot our ranked pivot points:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lcz69sz_DIoNPUHMYe29pA.png" /><figcaption>Rank of highs and lows is indicated by the size of the corresponding blob. Image by author.</figcaption></figure><p>I used the setting <em>max_neighbours=20</em> for the upper plot, so the maximum rank which highs or lows can have is 20. For instance, the big purple circle at the top has a rank of 20, so it must be a very important one. Now, when we remove those with a rank lower than 3, the plot becomes a bit clearer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0AV4VTD6Xgv9a7b-WJ7m8A.png" /><figcaption>Only highs and lows with a rank ≥ 3. Image by author.</figcaption></figure><p>Doesn’t look that bad already, right? But we didn’t really achieved anything new apart from these ranks. These come in handy when we want to assess the quality of a price channel.</p><h3>2. Finding The Best Fitting Price Channel</h3><p>This is a task where we can’t really determine if price channel A or B is really better than the other because price channels are more subjective than looking at a plot of RSI values, for example. However, we need metrics that help us determine the quality of a price channel numerically. I’ve come up with the following:</p><h4><strong>a) Pearson correlation coefficient </strong>(used as ‘r’)</h4><p>This tells us how strong the relationship between two variables is — in our case <em>time</em> and <em>price</em>. If we square this number, we get the coefficient of determination which is a value between 0 and 1. You can say: <strong>the higher, the better</strong> the regression. We aim for a minimum value of 0.9 in this analysis. It is automatically calculated by scipy:</p><pre>from scipy.stats import linregress<br><br>slope, intercept, r, p, err = linregress(x, y)</pre><h4><strong>b) The p-value (used as ‘p’)</strong></h4><p>The p-value is a measure that indicates the strength of evidence against a null-hypothesis in a statistical hypothesis test. I don’t want to go too deep, just keep in mind: <strong>“The lower, the better!”</strong> Imagine that it becomes lower as the first and last pivot points of the regression are further apart, so that the regression is “more meaningful” — to put it simply.</p><h4><strong>c) The rank of a pivot point</strong></h4><p>We discussed this already.</p><h4><strong>d) Crossing price percentage</strong></h4><p>If we already calculated the upper trend line, the <em>crossing price percentage</em> is just the number of periods above the trend line divided by the number of all periods. This is the formula for the upper trend line. The formula for the lower trend line is analogous.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3PkEgWJks97meHculR6xIw.png" /></figure><p>Maybe a bit too simple. You can definitely adapt it by including how strong the price exceeds the trend line or anything else that you think is important. This value <strong>should be low</strong>. We’ll use a maximum of 0.05 in the coding part.</p><h4>e) Max age of the latest pivot point</h4><p>We don’t want price channels to be too old. For instance, when we conduct a detection in the last 200 periods, we want to avoid detecting a price channel in the first 40 periods.</p><h4><strong>f) Number of pivot points on the trend line between the first and last pivot point on the other trend line</strong></h4><p>I asked ChatGPT for a better name, but it didn’t understand it at all. This is just the count of pivot points on the lower/upper trend line whose x values are between the x values of the first and last pivot point on the upper/lower trend line. It’s to avoid the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5x8Z0IYMOijO0HLkXOMA2Q.png" /><figcaption>Maxima and minima don’t really form a price channel. Image by author.</figcaption></figure><p>I know, these pivot points aren’t correct, but I hope you get the point. We don’t want all minima to be followed by all maxima or vice versa.</p><h3>“Where’s the code?!”</h3><p>It’s coming! The first version computes every single combination of minima and maxima with at least 3 pivot points and evaluates the “score” of the resulting price channel. In order to quantize the quality of a price channel, I suggest the following formula:</p><pre>channel_score = min_r*min_r * max_r*max_r * (1-min_p)*(1-max_p)</pre><p>And this is the first version that tries to maximize this score when a price channel meets our criteria:</p><pre>def get_best_channel(<br>        h, l, c, max_rank_possible=20, min_rank_for_detection=3,<br>        min_pivot_point_count=3, max_age_latest_pivot_point=20,<br>        min_r_squared=0.9, max_p_value=0.5, max_crossing_perc=0.05,<br>        min_pivot_points_inbetween=1):<br>    # Calculate the rank of each high and low<br>    all_maxima, all_minima = get_ranked_extrema(h, l, max_rank_possible)<br><br>    # Filter out minima whose rank is too low<br>    all_minima_x = np.where(all_minima &gt;= min_rank_for_detection)[0]<br>    all_minima_y = l[all_minima_x]<br>    all_minima_weights = all_minima[all_minima_x]<br><br>    # Filter out maxima whose rank is too low<br>    all_maxima_x = np.where(all_maxima &gt;= min_rank_for_detection)[0]<br>    all_maxima_y = h[all_maxima_x]<br>    all_maxima_weights = all_maxima[all_maxima_x]<br>    <br>    best_lower_trend_line = None<br>    best_lower_trend_stats = None<br>    best_upper_trend_line = None<br>    best_upper_trend_stats = None<br>    best_channel_score = -1<br><br>    # Iterate over all combinations of minima and maxima with a min. count of &lt;min_pivot_point_count&gt;<br>    for minima_count in range(min_pivot_point_count, all_minima_x.shape[0]+1):<br>        combs_minima = itertools.combinations(np.arange(all_minima_x.shape[0]), minima_count)<br>        for maxima_count in range(min_pivot_point_count, all_maxima_x.shape[0]+1):<br>            combs_maxima = itertools.combinations(np.arange(all_maxima_x.shape[0]), maxima_count)<br>            <br>            # Iterate over each combination of minima...<br>            for minima_comb in combs_minima:<br>                # Convert tuple to array<br>                minima_comb = np.array(minima_comb)<br><br>                # Get combination of minima<br>                minima_x = all_minima_x[minima_comb] <br>                minima_y = all_minima_y[minima_comb] <br>                minima_weights = all_minima_weights[minima_comb]<br><br>                # Do linear regression for these minima<br>                min_slope, min_intercept, min_r, min_p, min_err = linregress(minima_x, minima_y)<br>                # The coefficient of determination needs to be high enough<br>                if min_r*min_r &lt;= min_r_squared or min_p &gt;= max_p_value:<br>                    continue<br>            <br>                # Calculate the regression line<br>                min_line_x = np.arange(np.min(minima_x), c.shape[0])<br>                min_line_y = min_intercept + min_slope * min_line_x<br>                # Calculate the crossing price percentage<br>                min_crossing_price_perc = np.mean(c[min_line_x] &lt; min_line_y)<br>                # This needs to be sufficiently small<br>                if min_crossing_price_perc &gt;= max_crossing_perc:<br>                    continue<br><br>                # For this combination of minima go through all combinations of maxima...<br>                for maxima_comb in combs_maxima:<br>                    # Convert tuple to array<br>                    maxima_comb = np.array(maxima_comb)<br>                    <br>                    # Get combination of maxima<br>                    maxima_x = all_maxima_x[maxima_comb] <br>                    maxima_y = all_maxima_y[maxima_comb] <br>                    maxima_weights = all_maxima_weights[maxima_comb]<br><br>                    # At least &lt;min_pivot_points_inbetween&gt; minima need to be between the first and the last maxima<br>                    if np.sum((np.min(maxima_x) &lt;= minima_x) &amp; (minima_x &lt;= np.max(maxima_x))) &lt; min_pivot_points_inbetween:<br>                        continue<br>                    # At least &lt;min_pivot_points_inbetween&gt; maxima need to be between the first and the last minima<br>                    if np.sum((np.min(minima_x) &lt;= maxima_x) &amp; (maxima_x &lt;= np.max(minima_x))) &lt; min_pivot_points_inbetween:<br>                        continue<br><br>                    # Do linear regression for these maxima<br>                    max_slope, max_intercept, max_r, max_p, max_err = linregress(maxima_x, maxima_y)<br>                    # The coefficient of determination needs to be high enough<br>                    if max_r*max_r &lt;= min_r_squared or max_p &gt;= max_p_value:<br>                        continue<br><br>                    # Calculate the regression line<br>                    max_line_x = np.arange(np.min(maxima_x), c.shape[0])<br>                    max_line_y = max_intercept + max_slope * max_line_x<br>                    # Calculate the crossing price percentage<br>                    max_crossing_price_perc = np.mean(c[max_line_x] &gt; max_line_y)<br>                    # This needs to be sufficiently small<br>                    if max_crossing_price_perc &gt;= max_crossing_perc:<br>                        continue<br><br>                    # The latest pivot point should not be too old<br>                    if c.shape[0] - max(np.max(minima_x), np.max(maxima_x)) &gt; max_age_latest_pivot_point:<br>                        continue<br><br>                    # Calculate a score that makes channel A better than channel B (difficult and can be definitely changed)<br>                    channel_score = min_r*min_r * max_r*max_r * (1-min_p)*(1-max_p)<br><br>                    if best_channel_score &lt; channel_score:<br>                        best_channel_score = channel_score<br>                        best_lower_trend_line = {<br>                            &quot;line_x&quot;: min_line_x,<br>                            &quot;line_y&quot;: min_line_y,<br>                            &quot;points_x&quot;: minima_x,<br>                            &quot;points_y&quot;: minima_y,<br>                            &quot;points_weights&quot;: minima_weights<br>                        }<br>                        best_lower_trend_stats = {<br>                            &quot;slope&quot;: min_slope,<br>                            &quot;intercept&quot;: min_intercept,<br>                            &quot;r&quot;: min_r,<br>                            &quot;p&quot;: min_p,<br>                            &quot;err&quot;: min_err,<br>                            &quot;crossing_price_perc&quot;: min_crossing_price_perc<br>                        }<br>                        best_upper_trend_line = {<br>                            &quot;line_x&quot;: max_line_x,<br>                            &quot;line_y&quot;: max_line_y,<br>                            &quot;points_x&quot;: maxima_x,<br>                            &quot;points_y&quot;: maxima_y,<br>                            &quot;points_weights&quot;: maxima_weights<br>                        }<br>                        best_upper_trend_stats = {<br>                            &quot;slope&quot;: max_slope,<br>                            &quot;intercept&quot;: max_intercept,<br>                            &quot;r&quot;: max_r,<br>                            &quot;p&quot;: max_p,<br>                            &quot;err&quot;: max_err,<br>                            &quot;crossing_price_perc&quot;: max_crossing_price_perc<br>                        }<br>                    <br>    return best_lower_trend_line, best_lower_trend_stats, best_upper_trend_line, best_upper_trend_stats, best_channel_score</pre><p>Here’s an example of the “best” price channel in the very first 80 periods of my price data. You can clearly see that it misses the most important pivot point with a rank of 20. Apart from that it doesn’t look too bad:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*66eF8K2jc8xxS-t6_8WFFQ.png" /><figcaption>Price channel calculated with the first version. Image by author.</figcaption></figure><p>This is how I called the function:</p><pre>best_lower_trend_line, best_lower_trend_stats, best_upper_trend_line, best_upper_trend_stats, best_channel_score = get_best_channel(<br>      h=h, l=l, c=c,<br>      max_rank_possible=20,<br>      min_rank_for_detection=3,<br>      min_pivot_point_count=3,<br>      max_age_latest_pivot_point=20,<br>      min_r_squared=0.9,<br>      max_p_value=0.5,<br>      max_crossing_perc=0.05,<br>      min_pivot_points_inbetween=1<br>  )</pre><h4>Optimizing The Code</h4><p>I don’t expect you to fully understand the function, but you’ve probably spotted <strong>two downsides</strong>:</p><ul><li>👎🏻 <strong>We assess almost every possible combination</strong> of pivot points which can become computationally expensive on a large amount of data.</li><li>👎🏻 We <strong>don’t utilize the rank</strong> of pivot points.</li></ul><p>So let’s include the rank in our score, so our algorithm focusses more on more important pivot points! I just multiplied the old score with the sum of ranks of all pivot points that were used for both regressions.</p><pre>channel_score = (np.sum(minima_weights) * np.sum(maxima_weights)) * min_r*min_r * max_r*max_r * (1-min_p)*(1-max_p)</pre><p>This score leads to a better result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bgh4XGfoZnWOeOoEU71W9g.png" /><figcaption>Price channel calculated with the new formula of the channel score. Image by author.</figcaption></figure><p>However, we still face the problem that the algorithm is quite slow:</p><ul><li>Iterations: 1000</li><li>Rolling Window Size: 80</li><li>Settings: The same as above</li><li>Time needed: <strong>40.81 secs </strong>(=&gt; <strong>40.81 ms per iteration</strong>)</li></ul><p>Let’s make this a bit better by not checking every combination. Instead, we can sort all pivot points by their rank, get rid of the one with the lowest rank, evaluate the price channel, and do this again with fewer pivot points. As a consequence, we achieve a <strong>speedup of 16x</strong> as it only took<strong> 2.4974 secs </strong>(=&gt; <strong>2.5 ms per iteration</strong>). Furthermore, the price channel didn’t change:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fAnORiIGYVhg9JSWAyAiUg.png" /><figcaption>The same result as before. Image by author.</figcaption></figure><p>If you don’t need to be quick, I recommend going through all the combinations as then you won’t run the risk of skipping a “better” pricing channel.</p><p>I changed the window size to 50 and looked for a price channel with a minimum score of 1000. This kind of price channels seems to be rare in my data, but this is what I got after the algorithm has seen the first 15% of data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gXOrkKau3rlJ71wvMHUfKQ.png" /><figcaption>A beautiful price channel detected by the algorithm. Image by author.</figcaption></figure><p>Nice, that’s it! The final version of my algorithm is appended at the end of this story. Hope you liked it and <strong>happy trading </strong>:)</p><h4>Because I was asked, here’s a notebook for testing the algorithm:</h4><p><a href="https://colab.research.google.com/drive/1IWKI9C2KL9XUuYDB5FtE5urx1oQKHlLE?usp=sharing">Google Colaboratory</a></p><h4>The Second And Final Version</h4><pre>def get_best_channel(<br>        h, l, c, max_rank_possible=20, min_rank_for_detection=3,<br>        min_pivot_point_count=3, max_age_latest_pivot_point=20,<br>        min_r_squared=0.9, max_p_value=0.5, max_crossing_perc=0.05,<br>        min_pivot_points_inbetween=1):<br>    # Calculate the rank of each high and low<br>    all_maxima, all_minima = get_ranked_extrema(h, l, max_rank_possible)<br><br>    # Filter out minima whose rank is too low<br>    all_minima_x = np.where(all_minima &gt;= min_rank_for_detection)[0]<br>    all_minima_y = l[all_minima_x]<br>    all_minima_weights = all_minima[all_minima_x]<br><br>    # Filter out maxima whose rank is too low<br>    all_maxima_x = np.where(all_maxima &gt;= min_rank_for_detection)[0]<br>    all_maxima_y = h[all_maxima_x]<br>    all_maxima_weights = all_maxima[all_maxima_x]<br>    <br>    best_lower_trend_line = None<br>    best_lower_trend_stats = None<br>    best_upper_trend_line = None<br>    best_upper_trend_stats = None<br>    best_channel_score = -1<br><br>    # &quot;Sort minima by their rank and after each iteration remove the minimum with the lowest rank&quot;<br>    for minima_count in range(min_pivot_point_count, all_minima_x.shape[0]+1):<br>        minima_comb = np.argpartition(all_minima_weights, -minima_count)[-minima_count:]<br><br>        # Get combination of minima<br>        minima_x = all_minima_x[minima_comb] <br>        minima_y = all_minima_y[minima_comb] <br>        minima_weights = all_minima_weights[minima_comb]<br><br>        # Do linear regression for these minima<br>        min_slope, min_intercept, min_r, min_p, min_err = linregress(minima_x, minima_y)<br>        # The coefficient of determination needs to be high enough<br>        if min_r*min_r &lt;= min_r_squared or min_p &gt;= max_p_value:<br>            continue<br>    <br>        # Calculate the regression line<br>        min_line_x = np.arange(np.min(minima_x), c.shape[0])<br>        min_line_y = min_intercept + min_slope * min_line_x<br>        # Calculate the crossing price percentage<br>        min_crossing_price_perc = np.mean(c[min_line_x] &lt; min_line_y)<br>        # This needs to be sufficiently small<br>        if min_crossing_price_perc &gt;= max_crossing_perc:<br>            continue<br><br>        # &quot;Sort maxima by their rank and after each iteration remove the maximum with the lowest rank&quot;<br>        for maxima_count in range(min_pivot_point_count, all_maxima_x.shape[0]+1):<br>            maxima_comb = np.argpartition(all_maxima_weights, -maxima_count)[-maxima_count:]<br>            <br>            # Get combination of maxima<br>            maxima_x = all_maxima_x[maxima_comb] <br>            maxima_y = all_maxima_y[maxima_comb] <br>            maxima_weights = all_maxima_weights[maxima_comb]<br><br>            # At least &lt;min_pivot_points_inbetween&gt; minima need to be between the first and the last maxima<br>            if np.sum((np.min(maxima_x) &lt;= minima_x) &amp; (minima_x &lt;= np.max(maxima_x))) &lt; min_pivot_points_inbetween:<br>                continue<br>            # At least &lt;min_pivot_points_inbetween&gt; maxima need to be between the first and the last minima<br>            if np.sum((np.min(minima_x) &lt;= maxima_x) &amp; (maxima_x &lt;= np.max(minima_x))) &lt; min_pivot_points_inbetween:<br>                continue<br><br>            # Do linear regression for these maxima<br>            max_slope, max_intercept, max_r, max_p, max_err = linregress(maxima_x, maxima_y)<br>            # The coefficient of determination needs to be high enough<br>            if max_r*max_r &lt;= min_r_squared or max_p &gt;= max_p_value:<br>                continue<br><br>            # Calculate the regression line<br>            max_line_x = np.arange(np.min(maxima_x), c.shape[0])<br>            max_line_y = max_intercept + max_slope * max_line_x<br>            # Calculate the crossing price percentage<br>            max_crossing_price_perc = np.mean(c[max_line_x] &gt; max_line_y)<br>            # This needs to be sufficiently small<br>            if max_crossing_price_perc &gt;= max_crossing_perc:<br>                continue<br><br>            # The latest pivot point should not be too old<br>            if c.shape[0] - max(np.max(minima_x), np.max(maxima_x)) &gt; max_age_latest_pivot_point:<br>                continue<br><br>            # Calculate a score that makes channel A better than channel B (difficult and can be definitely changed)<br>            channel_score = (np.sum(minima_weights) * np.sum(maxima_weights)) * min_r*min_r * max_r*max_r * (1-min_p)*(1-max_p)<br><br>            if best_channel_score &lt; channel_score:<br>                best_channel_score = channel_score<br>                best_lower_trend_line = {<br>                    &quot;line_x&quot;: min_line_x,<br>                    &quot;line_y&quot;: min_line_y,<br>                    &quot;points_x&quot;: minima_x,<br>                    &quot;points_y&quot;: minima_y,<br>                    &quot;points_weights&quot;: minima_weights<br>                }<br>                best_lower_trend_stats = {<br>                    &quot;slope&quot;: min_slope,<br>                    &quot;intercept&quot;: min_intercept,<br>                    &quot;r&quot;: min_r,<br>                    &quot;p&quot;: min_p,<br>                    &quot;err&quot;: min_err,<br>                    &quot;crossing_price_perc&quot;: min_crossing_price_perc<br>                }<br>                best_upper_trend_line = {<br>                    &quot;line_x&quot;: max_line_x,<br>                    &quot;line_y&quot;: max_line_y,<br>                    &quot;points_x&quot;: maxima_x,<br>                    &quot;points_y&quot;: maxima_y,<br>                    &quot;points_weights&quot;: maxima_weights<br>                }<br>                best_upper_trend_stats = {<br>                    &quot;slope&quot;: max_slope,<br>                    &quot;intercept&quot;: max_intercept,<br>                    &quot;r&quot;: max_r,<br>                    &quot;p&quot;: max_p,<br>                    &quot;err&quot;: max_err,<br>                    &quot;crossing_price_perc&quot;: max_crossing_price_perc<br>                }<br>                        <br>    return best_lower_trend_line, best_lower_trend_stats, best_upper_trend_line, best_upper_trend_stats, best_channel_score</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NTYhTc3qimwRLpjiU1Ihpw.png" /><figcaption><a href="https://www.buymeacoffee.com/fabianr">If you’d like to support me, I’d really appreciate it 🫶🏻</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c53fdae46fe3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/detecting-price-channels-in-python-c53fdae46fe3">How I Detect Price Channels Robustly in Python</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[I Analyzed 4 Million Medium Stories for the Best Time To Publish]]></title>
            <link>https://levelup.gitconnected.com/analysis-of-4-030-501-stories-is-there-an-optimal-time-to-post-medium-stories-e743721721f2?source=rss-107d29e0e405------2</link>
            <guid isPermaLink="false">https://medium.com/p/e743721721f2</guid>
            <category><![CDATA[medium]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[publishing]]></category>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Fabian Ridder]]></dc:creator>
            <pubDate>Sat, 07 Oct 2023 13:04:36 GMT</pubDate>
            <atom:updated>2023-10-26T22:29:29.232Z</atom:updated>
            <content:encoded><![CDATA[<h4>Yes, there is a best time, and you’ll find out in the next few minutes.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HVyxs7nrkOur1mUhRrxXxw.jpeg" /><figcaption>When should you hit this button? Image by author.</figcaption></figure><h3>1) What Did I Do? 🧐</h3><p>I read some articles where people analyzed their own or others’ stories on Medium. I thought, <em>“I could do this better”</em>, so I created a web scraper to gather a large number of stories from Medium using the GraphQL endpoint for analysis.</p><h3>2) What Data Did I Scrape? 📄</h3><p>Well, take a look for yourself:</p><pre>import pandas as pd<br>stories_df = pd.read_csv(&quot;data/stories_df.csv&quot;)<br><br>stories_df.shape<br># (4986410, 33)</pre><p>After some initial cleaning and removal of stories published before January 2023 and after September 2023, we already lost 1 million stories:</p><pre>stories_df.shape<br># (4030501, 33)<br><br><br>stories_df.info()<br><br>Int64Index: 4030501 entries, 182 to 4986305<br>Data columns (total 33 columns):<br> #   Column                 Dtype         <br>---  ------                 -----         <br> 0   id                     object        <br> 1   title                  object        <br> 2   isPublished            float64       <br> 3   mediumUrl              object        <br> 4   collection             object        <br> 5   isLimitedState         float64       <br> 6   allowResponses         float64       <br> 7   visibility             object        <br> 8   clapCount              float64       <br> 9   wordCount              float64       <br> 10  voterCount             float64       <br> 11  statusForCollection    object        <br> 12  pinnedAt               float64       <br> 13  latestPublishedAt      datetime64[ns]<br> 14  firstPublishedAt       datetime64[ns]<br> 15  readingTime            float64       <br> 16  isLocked               float64       <br> 17  sequence               object        <br> 18  isSeries               float64       <br> 19  uniqueSlug             object        <br> 20  creator_id             object        <br> 21  pendingCollectionId    object        <br> 22  subtitle               object        <br> 23  subtitleIsFullContent  float64       <br> 24  postResponsesCount     float64       <br> 25  previewImageAlt        object        <br> 26  previewImageId         object        <br> 27  tag0                   object        <br> 28  tag1                   object        <br> 29  tag2                   object        <br> 30  tag3                   object        <br> 31  tag4                   object        <br> 32  tag5                   object        <br>dtypes: datetime64[ns](2), float64(12), object(19)<br>memory usage: 1.0+ GB</pre><p>Yeah. That’s still a lot. And there are numerous questions we can explore further. <strong>Feel free to share your ideas</strong>, and I might investigate some of them in future stories ;)</p><h3>3) Today’s Question 💭</h3><blockquote>What’s the optimal time to publish a Medium story?</blockquote><p>To answer that, let’s first become a little familiar with our treasure trove of data. Let’s jump in and have some fun!</p><h4>Playing a Bit With The Data 🧸</h4><p>Now, let’s create some basic plots to visualize the number of stories already published in this year (2023):</p><pre>stories_df[&quot;publish_calendar_week&quot;] = stories_df[&quot;firstPublishedAt&quot;].dt.to_period(&quot;W&quot;).dt.start_time<br>amount_by_week = stories_df[&quot;publish_calendar_week&quot;].value_counts()<br>plt.bar(amount_by_week.index, amount_by_week.values, width=5)<br>plt.xlabel(&quot;calendar week&quot;)<br>plt.ylabel(&quot;# stories&quot;)<br>plt.title(&quot;Amount of Stories Published Between 2023-01-01 and 2023-09-30&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*39to_BK1RMaNVdfEPSOOIA.png" /><figcaption>Number of stories — calendar week. Image by author.</figcaption></figure><p>This looks good! At first glance, there don’t seem to be any errors in our data, except for the first bar. But that’s because 2023 started on a Sunday. So, the number of stories published in that week is the same as the number of stories published on that single day. Apart from that, you’ve probably noticed a slight uptrend: In the recent weeks and months, more stories were posted on Medium. Let’s take a closer look at each day:</p><pre>amount_by_date = stories_df[&quot;firstPublishedAt&quot;].dt.floor(freq=&quot;d&quot;).value_counts()<br>plt.bar(amount_by_date.index, amount_by_date.values)<br>plt.title(&quot;Amount of Stories Published Between 2023-01-01 and 2023-09-30&quot;)<br>plt.xlabel(&quot;date&quot;)<br>plt.ylabel(&quot;# stories&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HXVACDxEmEMeR8a91nsZxQ.png" /><figcaption>Number of stories — date. Image by author.</figcaption></figure><p>Ok, I see some seasonality in the data. This happens because of the weeks, which will become clearer when we plot the median number of stories by each weekday:</p><pre>amount_by_weekday = stories_df[&quot;firstPublishedAt&quot;].dt.floor(freq=&quot;d&quot;).value_counts()<br>amount_by_weekday_df = pd.DataFrame(amount_by_weekday).reset_index().rename({&quot;index&quot;: &quot;day&quot;, &quot;firstPublishedAt&quot;: &quot;count&quot;}, axis=1)<br>amount_by_weekday_df[&quot;weekday&quot;] = amount_by_weekday_df[&quot;day&quot;].dt.weekday<br><br>amount_by_weekday = amount_by_weekday_df.groupby(&quot;weekday&quot;)[&quot;count&quot;].aggregate(np.median)<br>plt.bar(amount_by_weekday.index, amount_by_weekday.values)<br>plt.xlabel(&quot;weekday&quot;)<br>plt.ylabel(&quot;# stories&quot;)<br>plt.title(&quot;Amount of Stories by Weekday (Median)&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kPJEr3Dhk4aVo09Wu62cbA.png" /><figcaption>Number of stories — weekday. Image by author.</figcaption></figure><p>Most stories are published on Mondays, and then the number decreases day by day. On weekends, even fewer stories are posted. What about the time of day? When do people click the green “Publish” button?</p><pre>amount_by_hour = stories_df[&quot;firstPublishedAt&quot;].dt.floor(freq=&quot;h&quot;).value_counts()<br>amount_by_hour_df = pd.DataFrame(amount_by_hour).reset_index().rename({&quot;index&quot;: &quot;hour&quot;, &quot;firstPublishedAt&quot;: &quot;count&quot;}, axis=1)<br>amount_by_hour_df[&quot;hour&quot;] = amount_by_hour_df[&quot;hour&quot;].dt.hour<br><br>amount_by_hour = amount_by_hour_df.groupby(&quot;hour&quot;)[&quot;count&quot;].aggregate(np.median)<br>plt.bar(amount_by_hour.index, amount_by_hour.values)<br>plt.xlabel(&quot;time of day&quot;)<br>plt.ylabel(&quot;# stories&quot;)<br>plt.title(&quot;Amount of Stories by Time of Day (Median)&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y6nC1Qr6MkM9__QcSgb4sQ.png" /><figcaption>Number of stories — time of day. Image by author.</figcaption></figure><p>Initially, I thought it’s reasonable to assume that most stories are published around noon. However, I hadn’t considered that the datetime the scraper retrieves is in UTC, and storytellers, of course, live in different time zones. A quick google search “<em>At what time is the world’s population awake?” </em>gave me this <a href="https://www.quora.com/At-what-time-of-day-are-the-most-people-simultaneously-awake-worldwide">post on Quora</a>. It’s just a “guess” by the author, but he said around 12:40 UTC which also matches our plot above. Nevertheless, I dug a bit deeper and discovered the awesome article <em>“</em><a href="https://observablehq.com/@mattdzugan/population-by-time-zone-creating-a-dataset"><em>Population by Time Zone — Creating a Dataset</em></a><em>”</em> by Matt Dzugan on observablehq. It took the website some time to generate the following plot, but here it is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Rqb6wPXb5D8YaClbdh3vw.png" /><figcaption>Population — timezone. Plot and data by Matt Dzugan on observablehq (<a href="https://observablehq.com/@mattdzugan/population-by-time-zone-creating-a-dataset">here</a>)</figcaption></figure><p>Now, I can use this data to plot the number of people awake by the hour of the day (UTC). To do this, I estimated the percentage of people awake in a timezone, rather than assuming that most people are awake between 6 am and 10 pm and using this as a rolling window. I hope you can agree with the weights I came up with:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ysw0XI8ek6GiqoxWPoKA7w.png" /><figcaption>Estimated percentage of people awake — time of day. Image by author.</figcaption></figure><p>By applying this to Matt Dzugan’s data, we obtain the following result, which finally provides an answer to our question <em>“When is the world’s population awake?”:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vq7bwGxpO0zImV69PxJZ7Q.png" /><figcaption>People awake — time of day (UTC). Image by author.</figcaption></figure><p>Great! It looks quite similar to our plot and it peaks around noon as well. And again, we can be a little more certain that the data might be correct.</p><p>When we combine the hourly and weekly plots, we get this beautiful result:</p><pre>amount_by_hour = stories_df[&quot;firstPublishedAt&quot;].dt.floor(freq=&quot;h&quot;).value_counts()<br>amount_by_hour_df = pd.DataFrame(amount_by_hour).reset_index().rename({&quot;index&quot;: &quot;hour&quot;, &quot;firstPublishedAt&quot;: &quot;count&quot;}, axis=1)<br>amount_by_hour_df[&quot;weekhour&quot;] = amount_by_hour_df[&quot;hour&quot;].dt.hour + 24*amount_by_hour_df[&quot;hour&quot;].dt.weekday<br><br>amount_by_weekhour = amount_by_hour_df.groupby(&quot;weekhour&quot;)[&quot;count&quot;].aggregate(np.median)<br>plt.bar(amount_by_weekhour.index, amount_by_weekhour.values)<br>plt.xlabel(&quot;hour of the week&quot;)<br>plt.ylabel(&quot;# stories&quot;)<br>plt.title(&quot;Amount of Stories by Hour of Week (Median)&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HpRIeRolOjxfMryblsY6DA.png" /><figcaption>Number of stories — time of the week. Image by author.</figcaption></figure><p>You can clearly see every single day of the week and again that fewer stories are published on the weekend. But that’s enough with getting familiar with our data! You’re probably already yelling:</p><h3>4) “Please, Just Answer The Question!” 😫</h3><p>Alright, alright. For that, we need a metric which helps us identify how many views/reads a story has. (Un)fortunately, this isn’t publicly available. However, thanks to <a href="https://medium.com/@microbioscopicdata?source=post_page-----129760d46249--------------------------------">MicroBioscopicData</a>, who analyzed his story stats and shared them with us, we can assume an approximate correlation of 0.77 between claps and views/reads. Well, one shouldn’t really project these stats of 25 stories onto all stories published on Medium, but I haven’t found anything better to go with. If you want to see what he did, his story can be found here:</p><p><a href="https://levelup.gitconnected.com/analyzing-my-medium-statistics-with-python-a-data-science-journey-for-beginners-129760d46249">Analyzing My Medium Statistics with Python: A Data Science Journey for Beginners</a></p><p>Since claps often tend to have outliers, it’s better to stick to the median/percentiles. I’ve prepared some animations of percentiles ranging from 50% to 95%. (Values below 50% are consistently 0, and values above 95% approach extreme outliers, which isn’t very interesting.). These GIFs might take a bit of time to load. <em>(If not, you can simply scroll to the results at the end.)</em></p><p><strong>Amount of claps by weekday:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*blgXBGzTQh7DGR1u7Kansg.gif" /><figcaption>Growing percentiles: Number of claps — weekday. GIF by author.</figcaption></figure><p>We observe that Sunday is always number one in the race. This is probably because most people don’t work on Sundays. But this can’t really be the reason, as we are currently examining when a story is posted, not when people read or clap for it. I suggest two theories:</p><ol><li>Medium’s algorithm promotes stories the most, immediately after they have been made available online. This may then be the time when most people see the story and clap for it.</li><li>Medium’s algorithm is more likely to recommend stories to people at the same time as the stories are published.</li></ol><p>However, I think it’s highly unlikely that these theories are true.</p><p><strong>Amount of claps by hour of the day:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*o2vx7FIwg6JXqdT1xwP8dA.gif" /><figcaption>Growing percentiles: Number of claps — time of day. GIF by author.</figcaption></figure><p>Interesting! It seems there’s a significant difference between publishing in the morning and publishing in the evening. We’ll focus on that in a minute.</p><p><strong>Amount of claps by week hour:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*_ztUMy8C0AnKTdhL379hVQ.gif" /><figcaption>Growing percentiles: Number of claps — time of the week. GIF by author.</figcaption></figure><p>Now, we figured out why Sunday performed so well in the first race: There aren’t really more claps during the day, but in the night/morning. I guess that people stay up later on Saturdays and/or get up a bit later on Sundays, stay in bed and clap for stories — assuming one of the above theories is true.</p><h3>So The Answer Is “Publishing in The Evening”? 👀</h3><p><strong>Well, it’s not that simple 😬.</strong> We’ll analyze this in more detail below.</p><h4>Segmenting Stories into Four Groups</h4><p>Up until now, we’ve been looking at all stories. However, during my analysis, it turned out that it’s important to categorize these stories into four groups:</p><pre>| group  | paywalled | in_publication | percentage_of_stories | median_claps | median_clap_ratio |<br>|:-------|:----------|:---------------|----------------------:|-------------:|------------------:|<br>| 0 (🟥) | False     | False          |              0.774690 |            0 |           3.88965 |<br>| 1 (🟩) | False     | True           |              0.075166 |            4 |           8.72727 |<br>| 2 (🟦) | True      | False          |              0.074865 |           19 |          14.0     |<br>| 3 (🟨) | True      | True           |              0.075278 |          136 |          25.0     |</pre><p>If you’re wondering what the clap ratio is: It just represents the <em>number of claps per clapper</em>. You can clearly see that the majority of stories (77%) are published without a paywall and without being submitted to a publication. The rest makes up 7.5% each. When we look at the median claps and median clap ratio, it suggests that you <strong>definitely should turn the paywall on and submit to a publication</strong>! Take a look at the growing percentiles plots, which provide an even clearer visualization:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*GGSc7a17eDDtnoD_JGgqlQ.gif" /><figcaption>Growing percentiles: Number of claps — time of the week. GIF by author. 🟥 paywall &amp; publication, 🟩 no paywall &amp; publication, 🟦 paywall &amp; no publication, 🟨 no paywall &amp; no publication</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*7te3KQuSwlm0YgtUPs6tAw.gif" /><figcaption>Growing percentiles: Number of claps — time of day. GIF by author. 🟥 paywall &amp; publication, 🟩 no paywall &amp; publication, 🟦 paywall &amp; no publication, 🟨 no paywall &amp; no publication</figcaption></figure><p>As the animation can be quite annoying, we’ll do the following before interpreting these plots:</p><h4>Removing The Time Dimension</h4><p>To make it easier to analyze without remembering each frame, I tried to remove the time dimension. I took each frame’s plot, multiplied it by a weight calculated as <em>min(1-percentile, percentile)</em> divided by <em>max(blue, green, red, yellow)</em>, and added them up. I know, not really scientific, but here’s what we got:</p><p><strong>“Weighted percentile average of claps” by hour of the day:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ulM9QbqDii1geysVtWrSPw.png" /><figcaption>“Weighted percentile average of claps” — time of day. Image by author. 🟥 paywall &amp; publication, 🟩 no paywall &amp; publication, 🟦 paywall &amp; no publication, 🟨 no paywall &amp; no publication</figcaption></figure><p>I would’ve never thought that time would matter that much, especially for the yellow group with values around 0.0015 and red stories moving around 0.8. That’s roughly<strong> 500 times</strong> better! The best value is 1.0, which, of course, the red group approaches the most.</p><p>Let’s take a final look at the weekdays, and then we’ll definitely draw a conclusion! I promise!</p><p><strong>“Weighted percentile average of claps” by week hour:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kcxcs1ZQ1qC8xCuvcFbRYw.png" /><figcaption>“Weighted percentile average of claps” — time of the week. Image by author. 🟥 paywall &amp; publication, 🟩 no paywall &amp; publication, 🟦 paywall &amp; no publication, 🟨 no paywall &amp; no publication</figcaption></figure><p>It seems we shouldn’t really care that much about the weekday, except for the green group, which has better values on the weekend. So, let’s have a closer look at it:</p><p><strong>“Weighted percentile average of claps” by week hour on Saturdays and Sundays:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yD9Ms5WNd9FK_qup-qC16g.png" /><figcaption>“Weighted percentile average of claps” — time of the week (weekend). Image by author. 🟥 paywall &amp; publication, 🟩 no paywall &amp; publication, 🟦 paywall &amp; no publication, 🟨 no paywall &amp; no publication</figcaption></figure><h3>Results 📌</h3><ol><li>If we rank the groups from best to worst, it’s 🟥 &gt; 🟦 &gt; 🟩 &gt; 🟨. Apparently, it’s better to publish a paywalled story not in a publication (🟦) than posting a non-paywalled story in a publication (🟩).</li><li>Red, green and blue are bit noisy, so 7.5% of the data each still seems to be insufficient. Nonetheless, I’d recommend publishing…</li><li>🟥 around 4 pm on a Saturday (UTC)</li><li>🟦 around 11 am on a Saturday (UTC) or around 12 pm on a Sunday (UTC)</li><li>🟩 around 1 pm on a Saturday (UTC) or around 12 pm on a Sunday (UTC)</li><li>🟨 around 9 pm on a Saturday (UTC) or around 9 pm on a Sunday (UTC)</li></ol><p>It’s still a mystery to me why Medium’s recommendation algorithm really cares about time. Maybe, there’s something wrong with my interpretation, but I find these results somehow trustworthy — especially when looking at the yellow plot, which isn’t noisy at all. Of course, we could’ve divided the stories into even more groups, but then these plots might become even noisier, and I want to focus on other questions as well.</p><p>I’ll post this story around 1 pm on a Saturday because I’m not sure if this story will be successfully published in a publication. It’s a compromise between group blue and red and probably just a matter of belief.</p><p>Thank you for reading! Hope you liked it! <strong>Do you have any questions? Found Mistakes? Ideas for further analysis? Please, let me know :)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NTYhTc3qimwRLpjiU1Ihpw.png" /><figcaption><a href="https://www.buymeacoffee.com/fabianr">If you’d like to support me, I’d really appreciate it 🫶🏻</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e743721721f2" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/analysis-of-4-030-501-stories-is-there-an-optimal-time-to-post-medium-stories-e743721721f2">I Analyzed 4 Million Medium Stories for the Best Time To Publish</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>