<?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 Stefano Antinori on Medium]]></title>
        <description><![CDATA[Stories by Stefano Antinori on Medium]]></description>
        <link>https://medium.com/@stefano.antinori?source=rss-758a98e01e69------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*skGKL1uPFvDgkEGpLYXb1g.png</url>
            <title>Stories by Stefano Antinori on Medium</title>
            <link>https://medium.com/@stefano.antinori?source=rss-758a98e01e69------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 04:43:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@stefano.antinori/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[Backtesting Knock-Out For Fun and Profit]]></title>
            <link>https://medium.com/@stefano.antinori/backtesting-knock-out-for-fun-and-profit-3e1ae589254e?source=rss-758a98e01e69------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e1ae589254e</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[backtesting-strategy]]></category>
            <dc:creator><![CDATA[Stefano Antinori]]></dc:creator>
            <pubDate>Sun, 18 Jun 2023 21:40:49 GMT</pubDate>
            <atom:updated>2023-06-18T21:50:45.016Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article I’ll go through the ideation and implementation of a simple Python engine to execute backtesting strategies over a specific financial tool called <em>Knock-Out option.</em></p><p><em>Please note before going on: the goal of this article is not by any mean to suggest or promote trading. Please always consider the risks and the suitability of your investment. Invest at your on risk :)</em></p><p>There are different types of Knock-out options used in different ways and targeting different kinds of investors. The one we’ll focus on for our lab is simple: once selected the market and the type of our bet (UP if expecting bullish market, DOWN if expecting bearish market) we are presented with two relevant quantities:</p><ul><li><strong>Strike Price:</strong> the price at which the position will be closed automatically with a gain equal to the invested money</li><li><strong>Barrier: </strong>the price at which<strong> </strong>the<strong> </strong>position will be closed automatically with a loss equal to invested money</li></ul><p>During the course of investment, that is generally intraday, you can hold or close the position as long as the price remains within the two thresholds. You’ll get +1 value if the price goes up 1 or -1 if the price goes down 1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*z18-b9B7yDas44xA9L59yw.png" /><figcaption>Knock out selection example</figcaption></figure><p>As a simple example (see picture above), I buy a UP position for $150 when the underlying stock is 10.000, so the <strong>barrier</strong> will be at 9.850 and the <strong>strike price</strong> will be 10.150. Suppose that along the day the stock price reaches 10.056, then you can close the position with a gain of $56. The same if the price falls down to 9.890, if you decide to not take further risks, you can close the position with a loss of $110.</p><p>While knock-out options can limit downside risk, they also come with a higher degree of risk than traditional options. Investors should carefully consider their investment objectives and risk tolerance before investing in knock-out options.</p><p>Once identified risks and opportunities of this kind of investments, let’s try to build an investment strategy (indeed very simple) and check what are the outcomes.</p><h3>Prep the Ingredients</h3><p>As pretty much everything out there, we need data to work on.</p><p><a href="https://github.com/ranaroussi/yfinance">yfinance</a> is a good candidate since it offers a set of simple API which provide an abstraction layer on top of Yahoo finance API. For our purposes we’ll not need too much from it, but you are encouraged to explore other features.</p><p>After installing yfinance and other modules like pandas through <em>pip </em>we start initializing some parameters and structures</p><pre>import yfinance as yf<br>from datetime import datetime, timedelta<br>import matplotlib.pyplot as plt<br>import pandas as pd<br><br># Parameters&#39; initialization<br># Initial investment<br>inistake = 150<br># Amount deducted from investment by the operator<br>spread = 3<br># List of acceptable values for Stop Loss and Take Profit %<br>astoploss = atakeprofit = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]<br># Dictionary of relevant data for the analysis<br>payouts = {&#39;tp&#39;:[],&#39;sl&#39;:[],&#39;tpsl&#39;:[],&#39;payout&#39;:[], &#39;stake&#39;:[], &#39;gain&#39;:[], &#39;payout-max&#39;:[], &#39;payout-min&#39;:[]}</pre><p><em>inistake </em>is initial amount invested, <em>spread </em>is what the bank or trading platform takes for the service, <em>astoploss</em> and <em>atekeprofit </em>are the % we’ll use to protect our orders. You’ll see that there is something interesting in them and we’ll go deeper in the analysis of what happens.</p><h3><strong>Assemble the Engine</strong></h3><p>We define now a function which will coordinate the execution of the backtesting flow:</p><pre>def execute_strategy(to, depth, strategy, dump, plot):<br>    &quot;&quot;&quot;<br>    The engine of the backtesting analysis. Executes the logic of calling a strategy passed as input.<br><br>    Args:<br>        to (str): the most recent date of the analysis<br>        depth (str): how many days back in the past<br>        strategy (str): a strategy index corresponding to existing strategies<br>        dump (bool): dump relevant data to filesystem<br>        plot (bool): plot payout graph vs tp and sl %<br>    &quot;&quot;&quot;<br>    since, dmins,dmaxs = dateranges(to, depth)<br>    interval = &#39;5m&#39;<br>    masterdata = yf.Ticker(&#39;^NDX&#39;).history(start=since, end=to, interval=interval)[[&#39;Open&#39;, &#39;High&#39;, &#39;Low&#39;, &#39;Close&#39;, &#39;Volume&#39;]]<br>    <br>    print(masterdata.head())<br>    print(masterdata.tail())</pre><p>There is some boilerplate code to derive dates and hours compatible with the market open and close. That part is managed by some functions outside the scope of this article. If you are interested please reach me out to receive the complete source code of this lab.</p><p>Basically <em>to</em> and <em>depth</em> parameters are used to retrieve the relevant data for the analysis, that is the classic OHLC + Volume:</p><pre>masterdata = yf.Ticker(&#39;^NDX&#39;).history(start=since, end=to, interval=interval)[[&#39;Open&#39;, &#39;High&#39;, &#39;Low&#39;, &#39;Close&#39;, &#39;Volume&#39;]]</pre><p>Here we have used a hardcoded symbol ^NDX which represent Nasdaq 100 index, but that is obviously generalizable.</p><p>Let’s have a look to how it looks like: for timeframe more recent than 7 days we can benefit from more precise sampling at 1 minute resolution, otherwise the minimum resolution will be 5 minutes.</p><pre>                                  Open          High           Low         Close   Volume<br>Datetime                                                                                  <br>2023-06-12 09:30:00-04:00  14623.055664  14623.055664  14608.099609  14608.099609        0<br>2023-06-12 09:31:00-04:00  14611.684570  14611.684570  14597.003906  14597.003906  4665054<br>2023-06-12 09:32:00-04:00  14593.116211  14596.743164  14588.535156  14595.415039  4199708<br>2023-06-12 09:33:00-04:00  14592.864258  14607.425781  14592.864258  14606.227539  5340467<br>2023-06-12 09:34:00-04:00  14610.247070  14617.978516  14604.415039  14604.415039  4478279<br>                                   Open          High           Low         Close    Volume<br>Datetime                                                                                   <br>2023-06-16 15:55:00-04:00  15085.503906  15088.166016  15082.853516  15085.259766  10200000<br>2023-06-16 15:56:00-04:00  15083.385742  15087.080078  15080.779297  15085.276367  12695000<br>2023-06-16 15:57:00-04:00  15085.799805  15089.511719  15083.244141  15089.511719  14876000<br>2023-06-16 15:58:00-04:00  15089.540039  15089.585938  15086.267578  15087.040039   4927000<br>2023-06-16 15:59:00-04:00  15085.985352  15086.097656  15074.532227  15084.999023   9588000</pre><p>The core part of the engine is where we cycle through all possible take profit and stop loss percentages, following our intuition that for this kind of investment the combination of both thresholds can be crucial.</p><p>The engine is strategy-agnostic, so that we can plug a given strategy preserving the backtesting execution scheleton.</p><pre>for tp,sl in ((tp, sl) for tp in atakeprofit for sl in astoploss):<br>    payout = 0<br>    stake = 0<br>    phist = []<br>    for dmin, dmax in zip(dmins, dmaxs):<br>        data = masterdata.loc[(masterdata.index &gt;= dmin) &amp; (masterdata.index &lt;= dmax)]<br>        if len(data) &gt; 0:<br>            payout = payout + globals()[f&#39;strategy_{strategy}&#39;](data, tp, sl, False)<br>            phist.append(payout)<br>            stake = stake + inistake<br><br>    gain = payout/stake * 100<br>    pmin = min(phist)<br>    pmax = max(phist)<br>    payouts[&#39;tp&#39;].append(tp)<br>    payouts[&#39;sl&#39;].append(sl)<br>    payouts[&#39;tpsl&#39;].append(f&#39;{tp}-{sl}&#39;)<br>    payouts[&#39;payout&#39;].append(payout)<br>    payouts[&#39;stake&#39;].append(stake)<br>    payouts[&#39;gain&#39;].append(gain)<br>    payouts[&#39;payout-max&#39;].append(pmax)<br>    payouts[&#39;payout-min&#39;].append(pmin)</pre><p>What we want to do is to cycle over all possible combination of take profit and stop loss % (e.g. 5–5, 5–10, etc.) and for each combination simulate the investment strategy for the selected time frame. During the execution we collect some metrics that we’ll analyze later.</p><h3>Add The Sauce</h3><p>Ok it’s time to add the strategy, the ingredient without which our pasta is tasteless.</p><p>Here</p><pre>payout = payout + globals()[f&#39;strategy_{strategy}&#39;](data, tp, sl, False)</pre><p>we call a strategy algo by its index, to have back a payout at each cycle, which means for every day of execution.</p><p>Now, we just implemented a couple of strategies, not very sophisticated: <em>strategy_1</em> simulates a BUY order at the beginning of the day, while <em>strategy_2</em> simulates a SELL order at the beginning of the day. Basically, the first one forecasts a bullish market over the day, the second forecasts a bearish market over the day. For sake of time let’s see how the first one is implemented:</p><pre>def strategy_1(data, tp, sl, dump):<br>    &quot;&quot;&quot;<br>    This strategy is based on opening BUY positions and maintaining them until:<br>    - The takeprofit threshold is reached<br>    - The stoploss threshold is reached<br>    - The End Of Day is reached<br>    Args:<br>        data (DataFrame): Data to be analysed<br>        tp (int): take profit %<br>        sl (int): stop loss %<br>        dump (bool): if to persist data or not<br><br>    Returns:<br>        int: payout computed within a cycle<br>    &quot;&quot;&quot;<br>    stoploss = sl<br>    takeprofit = tp<br>    payout = 0<br>    <br>    iniprice = data.iloc[0][&#39;Open&#39;]<br>    for index, row in data.iterrows():  <br>        high = float(row[&#39;High&#39;])<br>        low = float(row[&#39;Low&#39;])<br>        close = float(row[&#39;Close&#39;])<br>            <br>        hstake = high - iniprice<br>        lstake = low - iniprice<br>        if dump: print(f&#39;{index},{hstake},{lstake},{high},{low},{close},{iniprice}&#39;)<br>        # high price check<br>        if hstake &gt;= inistake*takeprofit/100:<br>            payout = inistake*takeprofit/100<br>            if dump: print(f&#39;{index},SELL,{payout}&#39;)<br>            return payout<br>        <br>        # low price check<br>        if lstake &lt;= -inistake*stoploss/100:<br>            payout = -inistake*stoploss/100<br>            if dump: print(f&#39;{index},DEFAULT,{payout}&#39;)<br>            return payout<br>        <br>    # if there is no stop loss AND no take profit<br>    payout = data.iloc[-1][&#39;Close&#39;] - iniprice<br>    if dump: print(f&#39;{index},EOD,{payout}&#39;)<br>    return payout</pre><p>In a nutshell, the strategy scans every datapoint of the DataFrame passed in input and looks for three possible outcomes:</p><ul><li>Exit by hitting the Take Profit price</li><li>Exit by hitting a Stop Loss price</li><li>Exit by reaching the End of Day price</li></ul><p>Note that since you are kicked out of the game whenever the price reaches a threshold, not only in “Close” price, we evaluate those conditions over the “High” and “Low” prices to be more precise.</p><p>At the end of the execution of the entire cycle we’ll have a structure payouts filled with the results sampled for every combination of take-profit and stop-loss. We want to see which combination generates the maximum payoff:</p><pre>print(f&quot;MAX:\n{pdf.loc[pdf[&#39;payout&#39;].idxmax()]}&quot;)</pre><p>Let’s take for example the following execution spanning 14 days</p><pre>&gt;python3 yfin.py --mode execute --end_date &#39;2023-06-17&#39; --depth 14 --strategy 1 --dump False --plot False</pre><pre>MAX:<br>tp                   65<br>sl                   35<br>tpsl              65-35<br>payout        461.31543<br>stake              1500<br>gain          30.754362<br>payout-max    513.81543<br>payout-min     78.81543<br>Name: 246, dtype: object</pre><p>We see that overall, this simple strategy has been profitable over the 14 days, with a return of investment of about 30%, with a highest return of 513,81 and final return of 461,31. The lowest payout has been of 78,81 which means a loss of around 50% of our initial investment.</p><p>But how the distribution of payouts looks like in function of the thresholds we have set? Here comes the interesting part, because we see that very different % of tp and sl produce similar payouts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0fEDyorlvsXyyqI5EFKVPQ.png" /></figure><p>For example 65–65 and 40–100 are very close in payout generation, but differs a lot in terms of percentages. That is surprising, because one would expect to have similar combinations of thresholds generating similar payouts. This phenomenon suggest to go further in the analysis, maybe in a future article</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GWMixPzsDpSQBWaOL8-cgA.png" /></figure><p>Even more evident is this behavior in the right part of the plot, where for example 20–80 generates almost the same payout as 80–20!</p><p>Wrapping up: we have seen how to implement a simple backtesting engine and a strategy. We evaluated some results even though partial. In the next articles we’ll go through more extensive analysis to assess robustness of our assumptions.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e1ae589254e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>