<?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 Guilherme Ziegler on Medium]]></title>
        <description><![CDATA[Stories by Guilherme Ziegler on Medium]]></description>
        <link>https://medium.com/@guilherme.ziegler?source=rss-59d66406fdbf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_jkXlLU_-Z_wKIbGVp6Jbg.jpeg</url>
            <title>Stories by Guilherme Ziegler on Medium</title>
            <link>https://medium.com/@guilherme.ziegler?source=rss-59d66406fdbf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 04:53:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@guilherme.ziegler/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[How Banks Should Lend Your Money]]></title>
            <link>https://levelup.gitconnected.com/how-banks-should-lend-your-money-819226ff3749?source=rss-59d66406fdbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/819226ff3749</guid>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Guilherme Ziegler]]></dc:creator>
            <pubDate>Mon, 06 Jul 2026 14:36:45 GMT</pubDate>
            <atom:updated>2026-07-06T14:36:45.201Z</atom:updated>
            <content:encoded><![CDATA[<h4>Pricing credit under time, risk, and survival dynamics</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qc7hcxouc1Hi2snTq5pbvg.png" /><figcaption>Figure 1. A Traveler Who Paid Death’s Interest. Source: Gemini</figcaption></figure><p>After some time working with the lending cycle in Brazilian banks, one key question came to mind:</p><p>How can we introduce microeconomic principles to properly price the interest rate that should be offered to a potential borrower, given their risk profile?</p><p>This article aims to address this question by discussing fundamental concepts in financial mathematics, including compound interest, amortization (Price system), funding cost, spread, breakeven, default risk, expected profit and loss, and the survival of the contract.</p><p>For those familiar with my work, I will also incorporate Python to build a simulator capable of optimizing how much banks should charge as a risk premium for their lending activity.</p><p>I divide this article into two parts. The first one explains everything the reader needs to know regarding how banks should lend their money. The second one builds a Python class to work on a synthetic database and generate the pricing for new customers.</p><blockquote>But first things first.</blockquote><p>We will approach this by:</p><ul><li>Explaining key mathematical and financial concepts such as the interest rate, Price (French amortization) system, spread and cost of funding, breakeven, risk, expected losses and recovery, contract survival and more.</li><li>Providing basic Python code to explain and illustrate the concepts.</li><li>Building a simulator that works on synthetic data to estimate the probability of default and how much we should price the loan (Part 2).</li><li>Applying the simulator to predict the revenue from new customers (Part 2).</li></ul><h4><a href="https://levelup.gitconnected.com/how-to-build-a-table-of-contents-for-your-article-in-medium-0747ad771087?postPublishedType=repub">Table of Contents</a></h4><p><strong>Topics<br></strong><a href="#1036">Compound Interest</a><br><a href="#50d8">Spread and Cost of Funding</a> <br><a href="#e29f">Price (French Amortization) System</a><br><a href="#c9b5">Breakeven</a><br><a href="#36a9">Risk</a> <br><a href="#b889">Expected Loss and Recovery</a> <br><a href="#6bdc">Survival of the Contract</a> <br><a href="#fba4">Expected Loss Spread</a> <br><a href="#8eae">Funding Cost and Target Profitability Calibration</a><br><a href="#cc69">How Much Should the Bank Charge</a><br><a href="#4457">Model Limitations</a><br><a href="#8a80">Predictable Revenue</a><br><a href="#2212">Final Thoughts</a><br><a href="#a761">References</a></p><p><strong>Equations<br></strong><a href="#91d6">Equation 1. Compound Interest </a><br><a href="#a704">Equation 2. Future Value (PV)</a><br><a href="#a4b6">Equation 3. Net Return</a><br><a href="#b8bc">Equation 4. Interest Component</a><br><a href="#fbcc">Equation 5. Principal Amortization (Aₜ)</a><br><a href="#2926">Equation 6. Outstanding Balance (Bₜ)</a><br><a href="#8474">Equation 7 Price Constant Installment</a><br><a href="#b0bc">Equation 8. Installment (P) Calculation</a><br><a href="#3c2f">Equation 9. First Installment Interest (I₁)</a><br><a href="#3697">Equation 10. First Installment Amortization (A₁)</a> <br><a href="#5b9a">Equation 11. First Installment Balance (B₁)</a> <br><a href="#f9d2">Equation 12. Interest Rate Decomposition</a><br><a href="#7c14">Equation 13. Breakeven of the Contract</a><br><a href="#bfa3">Equation 14. Expected Loss Model </a><br><a href="http://(/#aa30)">Equation 15. Expected Loss Calculation (EL)</a><br><a href="#2258">Equation 16. Period Survival Probability</a><br><a href="#afda">Equation 17. Cumulative Survival</a><br><a href="#7d00">Equation 18. Hazard Rate</a><br><a href="#16fa">Equation 19. Weibull Hazard Rate </a><br><a href="#6985">Equation 20. Expected Loss Spread (ELS)</a><br><a href="#1b35">Equation 21. Interest Rate with Profitability</a><br><a href="#1891">Equation 22. Required Profitability</a><br><a href="#d818">Equation 23. Cost of Funding Decomposition</a><br>E<a href="#7913">quation 24. Final Risk-Adjusted Lending Rate</a><br><a href="#27c6">Equation 25. Expected Net Profit</a></p><p><strong>Tables <br></strong><a href="#50c0">Table 1. Price System Cash Flow Decomposition</a> <br><a href="#24e4">Table 2. Breakeven Analysis</a> <br><a href="#3cd7">Table 3. Hypothetical Credit Portfolio</a> <br><a href="#bc4e">Table 4. Hypothetical Credit Portfolio with Default Probabilities</a> <br><a href="#0d47">Table 5. Ratings Expected Loss (EL)</a><br><a href="#a884">Table 6. Survival Curve — Rating E (Constant Hazard)</a><br><a href="#04a9">Table 7. Survival Curve — Rating E (Weibull)</a> <br><a href="#19c3">Table 8. Annualized ELS by Rating and Installments (% p.a.) </a><br><a href="#c991">Table 9. ROE × Leverage Matrix</a><br><a href="#f6aa">Table 10. Risk-Adjusted Loan Pricing by Credit Rating</a></p><p><strong>Figures<br></strong><a href="#86e9">Figure 1. A Traveler Who Paid Death’s Interest. Source: Gemini</a><br><a href="#24ce">Figure 2. Survival Curves by Credit Rating (A–E)</a><br><a href="#04a9">Figure 3. Survival Curves by Credit Rating (A–E) — Weibull</a></p><h3>Compound Interest</h3><p>A bank lends money today and expects to receive more in the future. The mechanism that governs this exchange is compound interest, defined by Equation 1:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2FxAy3sZwQdZ86eTZeD1RDRP&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FxAy3sZwQdZ86eTZeD1RDRP" width="200" height="137" frameborder="0" scrolling="no"><a href="https://medium.com/media/e62a91014df59a96e612d4e3988dcad4/href">https://medium.com/media/e62a91014df59a96e612d4e3988dcad4/href</a></iframe><p>Where:</p><ul><li>PV is the present value (amount lent).</li><li>FV is the future value (amount received).</li><li>i is the interest rate.</li><li>n is the number of periods.</li></ul><p>This equation encodes a simple idea:</p><blockquote><em>Money today is worth more than money tomorrow.</em></blockquote><p>In a frictionless world, this would be enough. A bank could simply lend at a rate (i), wait (n) periods, and receive (FV) considering the borrower will pay with certainty.</p><p>Putting Equation 1 into numbers, lets assume:</p><ul><li>The reader is borrowing $1,000 from the bank (PV).</li><li>The reader will pay back in twelve months (n).</li><li>The bank will charge 2% interest per month.</li></ul><p>The future value (FV) is given by the capitalization of that borrowed money, Equation 2:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2F5ubcnzdNwW8d7wzXdSJEQL&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2F5ubcnzdNwW8d7wzXdSJEQL" width="564" height="137" frameborder="0" scrolling="no"><a href="https://medium.com/media/09decb951d4908038614897e6863397e/href">https://medium.com/media/09decb951d4908038614897e6863397e/href</a></iframe><p>Thus, the total amount the bank receives once the contract is fully settled is $1,268.24.</p><p>We can slightly rearrange Equation 1. By dividing FV by PV, we isolate the compound growth factor driven by the interest rate of 2% per month.</p><p>In other words, the ratio 1.268241 is generated by compounding a 2% monthly interest rate over 12 periods.</p><p>If we subtract the principal, we obtain the net return, which represents the investment’s profitability, 26.82% over the period, Equation 3<strong>.</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2FrDN7GP3oRYTDvaBoggn2xb&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FrDN7GP3oRYTDvaBoggn2xb" width="296" height="152" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5cfa4a9d3ea8d22daae94a48941d131/href">https://medium.com/media/c5cfa4a9d3ea8d22daae94a48941d131/href</a></iframe><p>All this material is mainly covered in financial mathematics textbooks, so I’m not making it more complicated than it needs to be.</p><p>We see that from the initial operation, the bank made a 26.82% out of it, that is how profitable the operation was.</p><blockquote>In fact, in the real world, things go slightly south.</blockquote><blockquote>We’ll get to that later.</blockquote><p>So far, banks treat the interest rate as compensation for the risk of lending money. In this view, the higher the rate (i), the higher the profitability.</p><h4>Price (French Amortization) System</h4><p>Now let’s move on to how banks offer money to customers. This operation is formalized through a contract, commonly referred to as <em>consumer credit</em>, in which the bank grants a loan and the customer repays it over time in installments.</p><p>All contracts are defined by a set of core elements:</p><ul><li>The number of installments (n).</li><li>A loan principal (PV).</li><li>The interest component (i) embedded in each installment.</li></ul><blockquote>In most cases, borrowers have little clarity about the total amount they are actually paying over the life of the contract.</blockquote><p>There are several amortization systems used to structure these loans (e.g., Price system, SAC, and mixed schemes), but here we focus on the Price (French amortization) system, as it is the most widely used in retail credit.</p><p>In the Price system, the value of each installment (Pₜ<strong>)</strong> is composed of two parts:</p><ul><li>Interest component (Iₜ).</li><li>Principal amortization (Aₜ).</li></ul><p>Their summation gives us the amount of each installment (Pₜ), constant over time, meaning the customer always pays back the same amount of money in each period until the contract is liquidated.</p><p>Now the interest component always incides on the previous total balance (Bₜ₋₁), Equation 4:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2FvbEPpg4EeiPWsYojLDDdxq&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FvbEPpg4EeiPWsYojLDDdxq" width="200" height="96" frameborder="0" scrolling="no"><a href="https://medium.com/media/0264164c5ff2a6085063956f814b007d/href">https://medium.com/media/0264164c5ff2a6085063956f814b007d/href</a></iframe><p>So that, as the outstanding balance decreases over time, the interest component also decreases, and the borrower gradually pays less interest in each installment.</p><p>The principal amortization (Aₜ)​ is obtained by subtracting the interest component (Iₜ)​ from the fixed installment (Pₜ)​, Equation 5:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2Faf5T9NhCLNmcHsg77xKXPK&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2Faf5T9NhCLNmcHsg77xKXPK" width="200" height="96" frameborder="0" scrolling="no"><a href="https://medium.com/media/d985499b4267d409590ece4a0bd441ae/href">https://medium.com/media/d985499b4267d409590ece4a0bd441ae/href</a></iframe><p>The balance (Bₜ) is given by subtracting from the previous balance (Bₜ₋₁) the principal amortization (Aₜ)​, Equation 6. below:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2FukDWiZEaLAopz3VisHbKNp&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FukDWiZEaLAopz3VisHbKNp" width="200" height="96" frameborder="0" scrolling="no"><a href="https://medium.com/media/fef4816a72232d2d7e1dd3f6f34c3a08/href">https://medium.com/media/fef4816a72232d2d7e1dd3f6f34c3a08/href</a></iframe><p>We need to determine how much the customer is paying in each installment. We derive the fixed installment P by imposing that the present value of all future payments must equal the principal PV.</p><p>In other words, the loan is priced such that the value of the incoming cash flows, when discounted at the interest rate i, exactly matches the amount lent today.</p><p>This leads to Equation 7, below:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2FxeSeJnPE6vbCyB5ig18fdm&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FxeSeJnPE6vbCyB5ig18fdm" width="200" height="96" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c9f18ad105b6c6c6ad0b5e5e9a4de4a/href">https://medium.com/media/0c9f18ad105b6c6c6ad0b5e5e9a4de4a/href</a></iframe><blockquote>All hands on Math!</blockquote><p>Following up, we now have all we need to calculate the price system for any given operation.</p><p>Let’s assume we are the bank and we lend under the same conditions mentioned above: $1,000 (PV), 12 installments, and 2% interest per month.</p><p>First, we compute the fixed installment (P):</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2Fah8HXDzazdyU4wmffY4yDH&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2Fah8HXDzazdyU4wmffY4yDH" width="200" height="96" frameborder="0" scrolling="no"><a href="https://medium.com/media/612d1d6ba6762c800fe26b70fa138f6b/href">https://medium.com/media/612d1d6ba6762c800fe26b70fa138f6b/href</a></iframe><p>Then we compute interest from the previous balance (Bₜ₋₁), which is exactly the money lent (PV), Equation 9:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2FoMNWMexudg3m1nph369zsi&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FoMNWMexudg3m1nph369zsi" width="200" height="96" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba40ac085c4e66ccc75b35fd9ae58e9d/href">https://medium.com/media/ba40ac085c4e66ccc75b35fd9ae58e9d/href</a></iframe><p>Next, we subtract the interest from the fixed installment P to obtain the amortization A₁, Equation 10.</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2Fw7jgmWLnnbw5AhMgaRV3A6&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2Fw7jgmWLnnbw5AhMgaRV3A6" width="200" height="96" frameborder="0" scrolling="no"><a href="https://medium.com/media/74d247fc33c785e49ec642aa5f7b8276/href">https://medium.com/media/74d247fc33c785e49ec642aa5f7b8276/href</a></iframe><p>Finally, from the original PV, which corresponds to Bₜ₋₁ in the first period, we compute the remaining balance after amortization, which defines the principal to be carried into the next period, as shown in Equation 11:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2F521rDvQ4jUQHqyF1bdFJQC&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2F521rDvQ4jUQHqyF1bdFJQC" width="200" height="96" frameborder="0" scrolling="no"><a href="https://medium.com/media/035f0c10681d66db03563cc96e010b2d/href">https://medium.com/media/035f0c10681d66db03563cc96e010b2d/href</a></iframe><p>Then we repeat the process until the 12th installment, and if we do the computations correctly, the remaining balance (B₁₂) at the end is zero.</p><p>We have now covered the initial concepts of financial mathematics. Next, let’s put everything together in Python to compute and generate the cash flow of any given price system.</p><pre>import pandas as pd<br><br>def price_schedule(pv, rate, n_periods):<br>    installment = pv * rate / (1 - (1 + rate) ** (-n_periods))<br>    <br>    schedule = []<br>    balance = pv<br><br>    schedule.append({<br>        &quot;period&quot;: 0,<br>        &quot;installment&quot;: 0.0,<br>        &quot;interest&quot;: 0.0,<br>        &quot;amortization&quot;: 0.0,<br>        &quot;balance&quot;: balance<br>    })<br><br>    for t in range(1, n_periods + 1):<br>        interest = rate * balance<br>        amortization = installment - interest<br>        balance = balance - amortization<br><br>        schedule.append({<br>            &quot;period&quot;: t,<br>            &quot;installment&quot;: installment,<br>            &quot;interest&quot;: interest,<br>            &quot;amortization&quot;: amortization,<br>            &quot;balance&quot;: balance<br>        })<br><br>    return pd.DataFrame(schedule).round(2)<br><br>df = price_schedule(pv=1000, rate=0.02, n_periods=12)<br>df.set_index(&#39;period&#39;, inplace=True)<br><br>df.head(12)</pre><p>That’s fairly elementary code and should generate a Table 1 with all cashflows over time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*M4n8jYp5vgrhPgleTEEyQw.png" /><figcaption>Table 1. Price System Cash Flow Decomposition</figcaption></figure><p>Note that, in Table 1, the final balance converges to zero, and the interest paid decreases over time as amortization increases.</p><h4>Spread and Cost of Funding</h4><p>In credit pricing, the interest rate charged to the borrower is not arbitrary. It is built on top of the bank’s own cost of capital, which reflects how much the institution pays to fund its operations, and an additional spread, which represents compensation for risk, liquidity, and profit margin.</p><blockquote>Intuitively, the bank borrows money from investors (most commonly through instruments such as securities and debentures) and lends this capital to customers, who are the actual end users of the funds.</blockquote><blockquote>The difference between the cost of obtaining this money and the rate at which it is lent defines is the spread.</blockquote><p>Formally, the interest rate can be decomposed as:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2FoYzcGpWPHYPRxJ1FSisiEu&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FoYzcGpWPHYPRxJ1FSisiEu" width="200" height="96" frameborder="0" scrolling="no"><a href="https://medium.com/media/fae2ed0be059a659a612efcac4690532/href">https://medium.com/media/fae2ed0be059a659a612efcac4690532/href</a></iframe><p>Where:</p><ul><li>i is the loan interest rate,</li><li>c is the cost of funding (cost of capital),</li><li>s is the credit spread.</li></ul><p>From a cash flow perspective, each installment in the Price system embeds this rate into the valuation of the contract.</p><blockquote>In other words, the each installment (Pₜ) carries a part of the cost structure of the bank and its remunaration.</blockquote><p>Let’s assume the bank funds itself by paying investors a base interest rate plus an annual premium. The lending rate, when converted to a monthly rate i, must exceed the cost of capital c by a spread s.</p><h4>Breakeven</h4><p>In credit operations, the breakeven point represents the condition under which the present value of expected cash inflows exactly equals the cost of funding the loan.</p><p>At this point, the operation generates zero economic profit, meaning the spread is fully offset by expected losses and funding costs.</p><p>By looking at Table 1, we can intuitively identify the breakeven point as the moment when the sum of all paid installments exceeds the principal.</p><p>More formally, breakeven occurs when the cumulative cash inflow equals the initial disbursed amount, Equation 13:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2Fj8LzvWz1sdbtYsxQXq5zZk&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2Fj8LzvWz1sdbtYsxQXq5zZk" width="200" height="96" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6537562ffc0c953ee65ce3ed212a0bd/href">https://medium.com/media/b6537562ffc0c953ee65ce3ed212a0bd/href</a></iframe><p>It can be obtained in python by summing installments overtime and checking when the cumulative cashflows exceed the principal (PV).</p><p>Let’s add the previous code a few lines:</p><pre>def price_schedule(pv, rate, n_periods):<br>    installment = pv * rate / (1 - (1 + rate) ** (-n_periods))<br>    <br>    schedule = []<br>    balance = pv<br>    cumulative_cf = 0.0 # cumulative cashflow<br>    breakeven_hit = False<br><br>    schedule.append({<br>        &quot;period&quot;: 0,<br>        &quot;installment&quot;: 0.0,<br>        &quot;interest&quot;: 0.0,<br>        &quot;amortization&quot;: 0.0,<br>        &quot;balance&quot;: balance,<br>        &quot;cashflow_cumulative&quot;: 0.0,<br>        &quot;breakeven&quot;: False<br>    })<br><br>    for t in range(1, n_periods + 1):<br>        interest = rate * balance<br>        amortization = installment - interest<br>        balance = balance - amortization<br><br>        cumulative_cf += installment<br><br>        if not breakeven_hit and cumulative_cf &gt;= pv:<br>            breakeven_hit = True<br><br>        schedule.append({<br>            &quot;period&quot;: t,<br>            &quot;installment&quot;: installment,<br>            &quot;interest&quot;: interest,<br>            &quot;amortization&quot;: amortization,<br>            &quot;balance&quot;: balance,<br>            &quot;cashflow_cumulative&quot;: cumulative_cf,<br>            &quot;breakeven&quot;: breakeven_hit<br>        })<br><br>    return pd.DataFrame(schedule).round(2)<br><br><br>df = price_schedule(pv=1000, rate=0.02, n_periods=12)<br>df.set_index(&#39;period&#39;, inplace=True)<br>df</pre><p>As result we get Table 2, below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*UezEyfRprYasrWXa1EBTRg.png" /><figcaption>Table 2. Breakeven Analysis</figcaption></figure><p>We observe that, with a monthly interest rate of 2% over a 12-month horizon, the breakeven point occurs at the 11th installment.</p><blockquote>Should we charge more for our services?</blockquote><blockquote>Well, as an economist, it depends…</blockquote><p>Assuming the customer pays all that is due, the bank makes money, exactly through the spread.</p><blockquote>But what happens if the customer does not pay the full agreement?<br>Then the bank loses money and must recognize the total unpaid amount as a loss.</blockquote><p>Now, assume that the customer paid up to the 11th installment. At this point in the contract, the bank has just covered its funding costs, resulting in zero economic profit.</p><p>If payments exceed the breakeven point, the bank generates profit. If the customer pays less than that, the bank incurs a loss.</p><h4>Risk</h4><p>At this point, the concept of risk becomes central. Any contract carries an intrinsic uncertainty about whether the borrower will pay more than the breakeven point or default before reaching it.</p><p>There are several ways of analyzing risk, but here we focus on default risk, a situation in which the customer stops repaying the bank. This event can occur at any period over the life of the contract.</p><p>The break-even point is just a rule of thumb that indicates whether, at the moment the customer stopped paying, the contract had already generated profit or resulted in a loss.</p><p>At my job, I work with machine learning models to evaluate risk, yet complex, they all follow a basic framework:</p><ol><li>We define a target problem (here, the probability of default).</li><li>We build features that help explain that problem.</li><li>We train a model that learns a function mapping known features to the probability of that event occurring.</li><li>Finally, we classify all contracts into risk bands, which we call ratings.</li></ol><p>We are not interested here in how to build a model, but in the final step of classification. That said, there are many features that can help explain the probability of a customer not paying us back:</p><p>Some examples include borrower income level, debt-to-income ratio, historical payment behavior, credit bureau scores, employment stability, utilization of existing credit lines, and past delinquency or default history, age, sex, region and many others.</p><p>From now on, we assume a model that predicts the probability of not paying us back over a given period of time, and outputs five risk bands from A to E, with E being the riskiest.</p><p>Also, consider our cost of funding (c) is 1.5% per month and the spread we want is 3%. That said, we could establish a general policy, where all contracts must start with a interest rate (i) of 4.5% as described in Equation 12, above.</p><p>Summarizing that information in a portfolio of 1,000 customers, we obtain a hypothetical distribution shown in Table 3 below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/197/1*3-jCB84qRhvNoLTCj_rL4w.png" /><figcaption>Table 3. Hypothetical Credit Portfolio</figcaption></figure><p>Table 3 presents a hypothetical credit portfolio distributed across risk ratings from A to E.</p><p>The allocation is intentionally skewed toward safer borrowers, with a higher concentration in rating A and progressively smaller shares in lower-quality ratings.</p><p>This reflects a standard risk management assumption where most approved customers are expected to belong to lower-risk segments, while higher-risk bands represent a smaller fraction of the total portfolio.</p><blockquote>Should we apply the same interest rate to every contract?</blockquote><p>The answer is definitely no, because riskier customers have an inherently higher probability of default. That is also the reason we created a model in the first place.</p><p>This can be estimated by simply measuring historical default rates across ratings from A to E over time by dividing the number of defaulted contracts by the total number of contracts.</p><p>Now let’s add the probability of default of each rating, Table 4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*UJIuajj3RwULY39HccgGXQ.png" /><figcaption>Table 4. Hypothetical Credit Portfolio with Default Probabilities</figcaption></figure><p>We learn from it that 50% of the portfolio is composed by ratings A and B, and they are indeed less risky than C, D, and E.</p><p>Also, rating E has a probability of breaking a contract that is approximately 10 times higher than the safest rating A.</p><p>What some banks do at this point is price loans differently based on credit ratings. They follow the intuitive idea that riskier contracts should pay a higher premium to compensate for the higher probability of default.</p><p>However smart this may look, this approach creates a competitiveness problem. An efficient bank, instead of relying on rigid risk-based pricing, optimizes rates based on the trade-off between marginal demand and the expected return from new deals it can originate by offering lower rates.</p><blockquote>In other words, cheaper interest rates may attract more customers, which may increase total revenue.</blockquote><h4>Expected Loss and Recovery</h4><p>While lower pricing can increase origination volume and therefore total interest income, the final profitability of the portfolio is driven by credit risk.</p><blockquote>Some contracts simply stop being paid. They default, and the bank records a loss.</blockquote><p>We can, as a matter of fact, try to anticipate the expected losses (EL) in a given portfolio, by modeling as:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2F4463wNn34WAaeuZZJujQue&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2F4463wNn34WAaeuZZJujQue" width="200" height="96" frameborder="0" scrolling="no"><a href="https://medium.com/media/f25ae9100fd62963de81d60084bfabd3/href">https://medium.com/media/f25ae9100fd62963de81d60084bfabd3/href</a></iframe><p>Where:</p><ul><li>EAD (Exposure at Default)<strong> </strong>is the outstanding balance at the time of default.</li><li>PD (Probability of Default) is the likelihood that a borrower will default within a given time horizon.</li><li>LGD (Loss Given Default) is the proportion of exposure that is not recovered after default</li></ul><p>From Equation 14 above, we denote 3 key concepts that help us to evaluate any credit operation.</p><p>Exposure at Default can be explained as the total amount of money the customer needs to pay back at the moment they’re about to break and stop paying.</p><p>Let’s assume a customer from Table 2 defaults the contract at installment 6. The EAD is calculated as the total outstanding amount remaining to amortize the contract, i.e., the sum of the remaining installments yet to be paid.</p><p>But this is also the current balance (Bₜ) at any given period ​, so we do not need to introduce this as a new variable. For this particular case, EAD is $529.67.</p><p>Now imagine we set up a call center operation to contact the customer and recover part of the outstanding debt through a renegotiation process. At the end of the workout process, we assume that 30% of the exposure is recovered. Therefore, the Loss Given Default (LGD) is 70%.</p><p>We are working with a rating C contract, which has a probability of default (PD) at this period equal to 0.06 (see Table 3).</p><p>By applying Equation 14, the expected loss is then calculated as it follows: Equation 15.</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2F8v8xx4KYNKW9rgp84isFEa&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2F8v8xx4KYNKW9rgp84isFEa" width="225" height="286" frameborder="0" scrolling="no"><a href="https://medium.com/media/be4d3c31ec6e7b7114060feda60e7793/href">https://medium.com/media/be4d3c31ec6e7b7114060feda60e7793/href</a></iframe><p>On a contract with an outstanding exposure of $529.67, at installment 6, given a 6% probability of default and a 70% loss given default, the bank expects to lose approximately $22.25.</p><p>In equilibrium, loan pricing must incorporate expected credit losses into the required spread such that the expected return covers funding costs, operating costs, and credit risk, ensuring non-negative expected profit.</p><blockquote>In a nutshell, instead of simply increasing interest rates for riskier profiles, the bank should optimize pricing to ensure that all expected losses are properly covered.</blockquote><p>Another exercise may be helpful for clarification. Imagine now that all contracts have the same loan balance, across ratings A to E, and that all contracts default at installment 9, with the probability of default following Table 3.</p><p>In Python, we can represent this setup as follows:</p><pre>def expected_loss_table():<br>    data = {<br>        &quot;rating&quot;: [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;, &quot;E&quot;],<br>        &quot;PD&quot;: [0.01, 0.02, 0.04, 0.06, 0.10],<br>        &quot;share&quot;: [0.30, 0.25, 0.20, 0.15, 0.10]<br>    }<br><br>    df = pd.DataFrame(data)<br><br>    EAD = 1000<br>    LGD = 0.70  # 70% loss given default (30% recovery)<br><br>    df[&quot;EAD&quot;] = EAD<br>    df[&quot;LGD&quot;] = LGD<br><br>    # Expected Loss per rating: EL = EAD × PD × LGD<br>    df[&quot;EL&quot;] = df[&quot;EAD&quot;] * df[&quot;PD&quot;] * df[&quot;LGD&quot;]<br><br>    # Portfolio Expected Loss contribution<br>    df[&quot;Portfolio_EL&quot;] = df[&quot;EL&quot;] * df[&quot;share&quot;]<br><br>    total_EL = df[&quot;Portfolio_EL&quot;].sum()<br><br>    return df, total_EL<br><br>df, total_EL = expected_loss_table()<br>df</pre><p>Running the notebook will produce Table 5, below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*BuD_0MiD49VuzIswoJzVAg.png" /><figcaption>Table 5. Ratings Expected Loss (EL)</figcaption></figure><p>The table highlights how Expected Loss (EL) increases with worsening ratings, while the weighted contribution (wEL) reflects both risk and portfolio composition.</p><p>Even though higher-rated contracts dominate in volume, lower-rated segments contribute disproportionately to total expected loss due to their higher PD. Since EAD and LGD are constant in this exercise, the only factor driving the portfolio’s expected loss is PD.</p><p>Summing the weighted expected loss gives the total amount we expect to lose for every $1,000 lent, which equals $24.5. This represents the risk component that should be incorporated when defining the spread (s).</p><blockquote>But how can we estimate the spread based on the risk?</blockquote><h4>Survival of the Contract</h4><p>Pricing the spread correctly demands we consider risk in the price system we discussed above.</p><p>We do that by estimating the survival of the contract — the probability that a loan remains active (i.e., the borrower continues paying) over time. To understand this, we use survival curves, which show how this probability evolves across periods.</p><p>At each period, the contract either survives or defaults. If we define PD ​ as the probability of default at time t, then the probability of surviving that period is given by Equation 16 :</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2FvU97x4mJhxysQpVLkcV1QD&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FvU97x4mJhxysQpVLkcV1QD" width="200" height="96" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae9b7bed2f4fa937960529ae1b53dadb/href">https://medium.com/media/ae9b7bed2f4fa937960529ae1b53dadb/href</a></iframe><p>The survival of the contract up to time t, denoted S(t), is the probability that the contract has not defaulted in any previous period. This is computed as the product of all survival probabilities up to that point, Equation 17:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2Fv83VsqZTGngoCd3RiKyz4N&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2Fv83VsqZTGngoCd3RiKyz4N" width="200" height="96" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b0a060d1bef5c53dbced8ceeefce9f4/href">https://medium.com/media/5b0a060d1bef5c53dbced8ceeefce9f4/href</a></iframe><p>This means that survival decreases over time as the risk of default accumulates. Each period’s default risk compounds, reducing the likelihood that the contract remains active.</p><p>As intuitive as the concept is, it becomes harder to visualize when time is introduced. Previously, PD was treated as a static measure by rating (A to E), but now we incorporate the key idea that risk evolves over time.</p><blockquote>The longer the contract horizon (i.e., the greater the number of installments), the higher the cumulative probability that the customer defaults before reaching breakeven.</blockquote><p>For simplification, we model default as a time-dependent process in which a contract has a total probability of default over a fixed horizon T, denoted by PD (See Table 3).</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2FiyCJjtprwYzrfy13iNhhLa&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FiyCJjtprwYzrfy13iNhhLa" width="200" height="96" frameborder="0" scrolling="no"><a href="https://medium.com/media/a14c43c8e83a354fa3e855d8a5653126/href">https://medium.com/media/a14c43c8e83a354fa3e855d8a5653126/href</a></iframe><p>This total risk is decomposed into period-by-period events through a constant hazard rate <em>h</em>, Equation 18, which represents the conditional probability of default in period t, given survival up to that point.</p><blockquote>We are distributing the total default probability over time using a constant hazard rate, so that the sum of period-by-period default events equals the total PD.</blockquote><blockquote>In real life, however, these probabilities are not given by a hazard rate. We’ll cover that later.</blockquote><p>Now we can write some code that gives an intuitive look at the survival of the contract:</p><pre><br>import numpy as np<br><br>def hazard_survival_curve(pd_total=0.10, n_periods=12, n_contracts=10000):<br>    h = 1 - (1 - pd_total) ** (1 / n_periods)<br><br>    period = np.arange(0, n_periods + 1)<br>    survival = (1 - h) ** period<br>    PDt = np.r_[0.0, survival[:-1] * h]<br><br>    defaults = np.rint(PDt * n_contracts).astype(int)<br>    survivors = n_contracts - np.cumsum(defaults)<br><br>    df = pd.DataFrame({<br>        &quot;period&quot;: period,<br>        &quot;hazard %&quot;: np.round(h * 100, 2),<br>        &quot;survival %&quot;: np.round(survival * 100, 2),<br>        &quot;PDt %&quot;: np.round(PDt * 100, 2),<br>        &quot;defaults&quot;: defaults,<br>        &quot;survivors&quot;: survivors<br>    }).set_index(&quot;period&quot;)<br><br>    return df<br><br>df_E = hazard_survival_curve()<br>df_E</pre><p>If we run it for rating E with a total PD of 10%, we get Table 6, below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*XhIH-vAnz-IQAJELqh0gSg.png" /><figcaption>Table 6. Survival Curve — Rating E (Constant Hazard)</figcaption></figure><p>From Table 6, we see that in the first installment the survival percentage is 99.13%, and it decreases as the period increases. Also, period t = 0 denotes when the deals were closed, thus they are the total number of contracts.</p><p>At the end of 12 installments, the survival percentage is 90%, meaning that the PD for rating E equals 10%.</p><p>Note also that PDₜ​ is the probability of the contract defaulting at the period t. As a final insight for this section, we conclude that the time horizon<strong> </strong>matters. Therefore, the spread should be priced accordingly.</p><blockquote>Hi customer, how many installments would you like?<br>Hmm… 10 installments, so the interest we are charging is…</blockquote><blockquote>But with 12, Let’s say…</blockquote><p>Now, let’s build a function that plots survival curves for ratings from A to E, following the hazard rate and using the function hazard_survival_curve.</p><pre>import pandas as pd<br>import numpy as np<br>import plotly.express as px<br><br>def plot_survival_ratings():<br>    pd_ratings = {<br>        &quot;A&quot;: 0.01,<br>        &quot;B&quot;: 0.02,<br>        &quot;C&quot;: 0.04,<br>        &quot;D&quot;: 0.06,<br>        &quot;E&quot;: 0.10<br>    }<br><br>    colors = {<br>        &quot;A&quot;: &quot;green&quot;,<br>        &quot;B&quot;: &quot;blue&quot;,<br>        &quot;C&quot;: &quot;yellow&quot;,<br>        &quot;D&quot;: &quot;orange&quot;,<br>        &quot;E&quot;: &quot;red&quot;<br>    }<br><br>    df_all = pd.concat(<br>        [<br>            hazard_survival_curve(pd_total=pd, n_periods=12)[[&quot;survival %&quot;]].assign(rating=r)<br>            for r, pd in pd_ratings.items()<br>        ]<br>    ).reset_index()<br><br>    fig = px.line(<br>        df_all,<br>        x=&quot;period&quot;,<br>        y=&quot;survival %&quot;,<br>        color=&quot;rating&quot;,<br>        color_discrete_map=colors<br>    )<br><br>    fig.update_layout(<br>        template=&quot;simple_white&quot;,<br>        xaxis_title=&quot;Installments&quot;,<br>        yaxis_title=&quot;Survival (%)&quot;,<br>        legend_title=&quot;&quot;<br>    )<br><br>    fig.update_traces(line=dict(width=2))<br><br>    return df_all, fig<br><br><br>df_plot, fig = plot_survival_ratings()<br>fig</pre><p>Running the code above should print us Figure 2:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*hVycZQsy5Tp4B8KNgudEuw.png" /><figcaption>Figure 2. Survival Curves by Credit Rating (A–E)</figcaption></figure><p>Although the survival curve for rating A sits consistently above rating E, this is a direct consequence of A having a lower total probability of default over the horizon.</p><p>In other words, the vertical separation between the curves reflects differences in credit quality.</p><p>However, the <em>shape</em> of all curves remains structurally similar: they decay in a smooth and almost linear-looking exponential pattern due to the assumption of a<strong> </strong>constant hazard rate<strong>,</strong> which implies that default risk is memoryless and does not depend on how long the loan has been active.</p><p>In real credit portfolios, risk is rarely constant over time. Borrowers tend to deteriorate or become more fragile as time progresses, especially in unsecured lending. This means hazard is typically time-dependent and increasing, not flat.</p><p>A more realistic framework is the Weibull survival model, where hazard evolves with time, Equation 19:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2FuiVvBsTFZUsJjb1Trn2baA&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FuiVvBsTFZUsJjb1Trn2baA" width="200" height="96" frameborder="0" scrolling="no"><a href="https://medium.com/media/7054f51d0acaf65d4d4b6a419ab618c5/href">https://medium.com/media/7054f51d0acaf65d4d4b6a419ab618c5/href</a></iframe><p>where:</p><ul><li>t is the period;</li><li>λ is the scale parameter, representing the baseline risk level</li><li>k is the shape parameter, governing how the hazard evolves over time.</li></ul><p>Now if k &gt; 1, the hazard increases monotonically with time, aligning well with credit reality, where risk tends to accumulate as borrowers age.</p><p>That means we are penalizing time — therefore, the hazard is no longer constant. The longer the contract, the higher the risk.</p><p>A few changes in function hazard_survival_curveshould be enough to incorporate this new dynamics into our framework.</p><pre>import numpy as np<br>import pandas as pd<br><br>def hazard_survival_curve(pd_total=0.10, n_periods=12, n_contracts=10000, hazard_type=&#39;exponential&#39;):<br>    if hazard_type == &#39;exponential&#39;:<br>        h = 1 - (1 - pd_total) ** (1 / n_periods)<br>    elif hazard_type == &#39;weibull&#39;:<br>        k = 1.5<br>        lambda_param = (-np.log(1 - pd_total)) ** (1/k) / n_periods<br>        h = lambda_param * k * (lambda_param * 1) ** (k - 1)  # hazard at t=1<br>    else:<br>        raise ValueError(&quot;hazard_type must be &#39;exponential&#39; or &#39;weibull&#39;&quot;)<br><br>    period = np.arange(0, n_periods + 1)<br>    <br>    if hazard_type == &#39;exponential&#39;:<br>        survival = (1 - h) ** period<br>        PDt = np.r_[0.0, survival[:-1] * h]<br>        hazard_series = np.full(n_periods + 1, h)<br>        hazard_series[0] = 0.0<br>    else:  # weibull<br>        survival = np.exp(-(lambda_param * period) ** k)<br>        PDt = np.r_[0.0, survival[:-1] - survival[1:]]<br>        hazard_series = np.r_[0.0, lambda_param * k * (lambda_param * period[:-1]) ** (k - 1)]<br><br>    defaults = np.rint(PDt * n_contracts).astype(int)<br>    survivors = n_contracts - np.cumsum(defaults)<br><br>    df = pd.DataFrame({<br>        &quot;period&quot;: period,<br>        &quot;hazard %&quot;: np.round(hazard_series * 100, 2),<br>        &quot;survival %&quot;: np.round(survival * 100, 2),<br>        &quot;PDt %&quot;: np.round(PDt * 100, 2),<br>        &quot;defaults&quot;: defaults,<br>        &quot;survivors&quot;: survivors<br>    }).set_index(&quot;period&quot;)<br><br>    return df<br><br># Usage:<br># df_E = hazard_survival_curve(hazard_type=&#39;exponential&#39;)<br>df_E = hazard_survival_curve(hazard_type=&#39;weibull&#39;)</pre><p>And now calling up the plot plot_survival_curves with hazard_type set to weibull should produce Figure 3, below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*P-ORHqDg1oYoDyTWNcKmEw.png" /><figcaption>Figure 3. Survival Curves by Credit Rating (A–E) — Weibull</figcaption></figure><p>Note that the behavior is essentially the same, but risk is now penalized and PDₜ increases over time, Table Also, it looks more like a curve than a flat line. The final PD continues to be the one we set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*H5LRQiG7C4I-NXtSlL40eQ.png" /><figcaption>Table 7. Survival Curve — Rating E (Weibull)</figcaption></figure><p>As shown in Table 7, the hazard rate varies over time, but it is calibrated to produce a monotonic increase in PDₜ.</p><p>Under the proposed framework, the number of survivors at the 12th installment remains 9,000, so the cumulative PD over the period stays at 10%.</p><h4><em>Expected Loss Spread</em></h4><p>Now we have all the pieces to optimize the spread at least to breakeven. That means every $1.00 of loans is supported by a risk model, and the spread we charge is calibrated to cover expected losses.</p><p>We will observe realized losses, since contracts will continue to default in practice, but the pricing ensures that, in expectation, the portfolio remains profitable by charging each operation the minimum required spread to offset credit risk.</p><blockquote>The money the bank loses is covered by the revenues that all contracts generate.</blockquote><blockquote>Thus, we achieve predictable revenue.</blockquote><p>The formula to take expected losses into consideration when calculating the spread, Equation 20, is depicted below:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2FvpnJWUoYSSYTyvXUdzYaUp&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FvpnJWUoYSSYTyvXUdzYaUp" width="200" height="167" frameborder="0" scrolling="no"><a href="https://medium.com/media/d03f508daedea34adafd26f64e5bfae7/href">https://medium.com/media/d03f508daedea34adafd26f64e5bfae7/href</a></iframe><ul><li>s is the minimum spread required to cover expected losses.</li><li>PDₜ​ is the probability of default at period t.</li><li>LGD is the loss given default.</li><li>Bₜ​ is the outstanding balance (EAD) at period t.</li><li>T is the total number of periods.</li></ul><p>The core idea is that part of the spread covers risk, and the other part ensures business profitability by shifting the spread upward. This works essentially as a securitization mechanism, defining the spread that at least covers the expected losses.</p><p>Keeping it at this breakeven level guarantees competitiveness, but expected revenues would be zero, since the spread only covers losses, with no margin for profit.</p><blockquote>Yes, the whole paper is a minimization problem.</blockquote><blockquote>God save the long-dead microeconomists!</blockquote><p>However, banks should make money, so they must define a portion of the spread as the profit required by the business — and this additional component is mainly the expected return on the operation.</p><p>If they do so, competitiveness is slightly sacrificed, but since the price they charge reflects the products and services they offer, and therefore, the quality and quantity of customers they acquire.</p><p>Now, one thing is important: even though the risk increases with time, the outstanding balance Bₜ​ decreases with each installment. This brings us a counterintuitive result:</p><p>We are essentially assuming that longer contracts are riskier than shorter ones. However, as the number of installments increases, the average outstanding balance decreases over time.</p><p>When we compute the weighted average spread, which is weighted by Bₜ​ (See Equation 20), the resulting breakeven spread ends up being <em>lower</em> for longer contracts.</p><blockquote>Why?</blockquote><blockquote>Because the spread is not calculated per period; it is a single spread applied to the entire contract.</blockquote><p>The formula averages the expected losses over the entire life of the loan, weighted by the outstanding balance. Since the balance declines over time, the losses in later periods carry less weight, reducing the overall spread.</p><p>In other words:</p><ul><li>Longer contracts → more time for risk to accumulate → higher PDₜ​.</li><li>But also → more periods with low outstanding balance → lower weighted average loss.</li><li>The latter effect dominates → breakeven spread decreases with contract length.</li></ul><p>This is not a flaw. It is a direct consequence of defining the spread as a constant rate applied to the declining balance.</p><p>Finally, let’s calculate the breakeven spread for ratings A to E, considering this new survival curve, and update our pricing table.</p><p>First we need a python function that calculates the spread (s):</p><pre><br>def expected_loss_spread(default_probability, n_periods=12, loss_given_default=0.45, hazard_type=&#39;weibull&#39;):<br>    df = hazard_survival_curve(default_probability, n_periods, n_contracts=10000, hazard_type=hazard_type)<br>    PDt = df[&#39;PDt %&#39;].values / 100<br>    Bt = np.array([n_periods - t + 1 for t in range(n_periods + 1)]) / n_periods<br>    Bt[0] = 0<br>    expected_loss = PDt * loss_given_default * Bt<br>    s = np.sum(expected_loss[1:]) / np.sum(Bt[1:])<br>    return round(s * 10000, 2) # bps 100 bps = 1,00% p.m.<br><br>expected_loss_spread(default_probability=0.02, n_periods=12, loss_given_default=0.70, hazard_type=&#39;weibull&#39;)</pre><p>The expected_loss_spread function implements Equation 20 by computing the minimum spread required to cover expected credit losses over the life of the contract, taking into account both the timing of defaults and the amortization profile of the loan.</p><p>If we run it for rating A with a 2% PD over 12 installments, we get a spread of 9.53 bps (1 bps = 0.01% p.m.), following the standard nomenclature used by banks.</p><p>Converting that spread to an annualized rate, we come up with approximately 1,50 % per year for rating A which is quite competitive.</p><p>Now let’s check how the entire portfolio behaves after we calculate all the spreads:</p><pre>def spread_table(ratings, loss_given_default=0.45, max_periods=12, hazard_type=&#39;weibull&#39;):<br>    results_bps = {}<br>    results_annualized = {}<br>    for t in range(1, max_periods + 1):<br>        results_bps[t] = {}<br>        results_annualized[t] = {}<br>        for rating, default_probability in ratings.items():<br>            s_bps = expected_loss_spread(default_probability, n_periods=t, loss_given_default=loss_given_default, hazard_type=hazard_type)<br>            results_bps[t][rating] = round(s_bps, 2)<br>            <br>            # Converte para % a.a. (juros compostos mensais)<br>            s_decimal = s_bps / 10000<br>            s_annualized = (1 + s_decimal) ** 12 - 1<br>            results_annualized[t][rating] = round(s_annualized * 100, 2)<br>    <br>    df_bps = pd.DataFrame(results_bps).T<br>    df_bps.index.name = &#39;Installments&#39;<br>    df_bps.columns = [f&#39;{r}&#39; for r in ratings.keys()]<br>    <br>    df_annualized = pd.DataFrame(results_annualized).T<br>    df_annualized.index.name = &#39;Installments&#39;<br>    df_annualized.columns = [f&#39;{r}_p.a.&#39; for r in ratings.keys()]<br>    <br>    return df_bps, df_annualized<br><br><br>ratings = {<br>    &#39;A&#39;: 0.02,<br>    &#39;B&#39;: 0.05,<br>    &#39;C&#39;: 0.10,<br>    &#39;D&#39;: 0.20,<br>    &#39;E&#39;: 0.35<br>}<br><br># call<br>table_bps, table_per_year = spread_table(ratings, <br>                                         loss_given_default=0.7, <br>                                         max_periods=12, <br>                                         hazard_type=&#39;weibull&#39;)</pre><p>The spread_table function calculates the minimum spread required to cover expected credit losses for each credit rating across different contract lengths.</p><p>It works by iterating over a range of installment periods (from 1 to max_periods) and, for each period, computing the spread for every rating using the expected_loss_spread function.</p><p>The result is returned in two formats: basis points (bps) per month and annualized percentage rates, which are more intuitive for comparing with other financial products.</p><p>Under the hood, the function also converts the monthly spread to an annualized rate assuming monthly compounding, so the output is immediately useful for pricing and decision‑making.</p><p>Here I focus on the annualized percentage rates, since they are more intuitive for designing commercial offers, as presented in Table 8, below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*G9tsU4gpOwJNDaRDM_HZjw.png" /><figcaption>Table 8. Annualized ELS by Rating and Installments (% p.a.)</figcaption></figure><p>First, spreads increase consistently with credit risk. For any given installment period, the spread rises monotonically from rating A to rating E.</p><p>For example, at 12 installments, rating A requires only 1.15% p.a., while rating E requires 23.71% p.a., roughly 20 times higher. This reflects the fact that riskier borrowers have a higher probability of default and therefore require a higher premium to compensate the bank for expected losses.</p><p>Second, spreads decrease as the number of installments increases. For rating E, the spread drops from 1,286.86% p.a. for a single installment to 23.71% p.a. for 12 installments.</p><p>This happens because the exposure at risk is amortized over time, the outstanding balance shrinks with each payment, reducing the bank’s potential loss. In other words, the risk is diluted as the borrower gradually pays down the principal.</p><p>Finally, the table also shows that the benefit of extending the contract is greater for riskier borrowers. For rating A, moving from 1 to 12 installments reduces the spread by nearly 94% (from 18.16% to 1.15% p.a.).</p><p>For rating E, the reduction is even more dramatic — from 1,286.86% to 23.71% p.a., a drop of over 98%.</p><p>This suggests that offering longer terms to higher-risk segments can significantly reduce the required spread, making credit more accessible while still covering expected losses.</p><p>Now consider some scenarios in which the bank representative is talking to two different customers with different ratings. The first is a low risk profile and the second a high one.</p><p>Also keep in mind that funding costs and profitability are not yet present in these examples:</p><ul><li>Scenario 1 — Rating A Client (wants fewer installments)</li><li>Scenario 2 — Rating E Client (wants 1 installment)</li></ul><p>For scenario 1, the bank operator should apply the strategy as such:</p><blockquote>Hi there! I see you’d like to take the loan in 4 installments, right? Look, for your profile we can do that, let’s say 3.64% per year.</blockquote><blockquote>Is it out of your budget? May I suggest 9 installments, that gives us 1.75% per year.</blockquote><blockquote>Deal!</blockquote><p>Now moving to scenario 2, the conversation goes like:</p><blockquote>I understand you’d like to pay in just 1 installment, right? Look, unfortunately we do not have this offer right now (implicitly, over 1,200% per year).</blockquote><blockquote>Now I can offer you a better deal starting from 5 installments (implicitly, 67% per year). Do you prefer 12? That’s even better the final rate would be 23.71% per year.</blockquote><h4>Funding Cost and Target Profitability Calibration</h4><p>So far, we have determined how the offer should be made by the representative, considering that the spread is 100% driven by risk optimization.</p><p>However, that is not enough, as we still need to account for funding costs and the expected profitability of the business.</p><p>We do this by decomposing Equation 12 into an additional component representing the desired profitability:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2FoiKSUDiqiFD1rZZUD7MteA&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FoiKSUDiqiFD1rZZUD7MteA" width="200" height="96" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ea62b013288b6a6ead1fb292eb16c71/href">https://medium.com/media/1ea62b013288b6a6ead1fb292eb16c71/href</a></iframe><p>where:</p><ul><li>i is the loan interest rate.</li><li>c is the cost of funding.</li><li>sₑₗ is the expected loss spread.</li><li>r is the required profitability or the premium</li></ul><p>Now, r is defined by the business itself, and it may vary according to risk if deemed profitable. However, with that, the framework no longer minimizes the interest rate, which violates our assumptions in all previous sections.</p><p>There is a way to calculate r based on the desired ROE (Return on Equity) and leverage.</p><p>ROE is simply the return the bank generates on the money its shareholders have invested. It is one of the most important metrics in banking because it tells investors how effi<strong>c</strong>iently their capital is being used. A 20% ROE, for example, means that for every $100 of shareholder capital the bank generates $20 in profits.</p><p>Leverage, on the other hand, represents the bank’s ability to fund a loan portfolio that is larger than its own equity base, by using deposits and other raised funds.</p><p>Let’s make this concrete. Suppose the bank has R$ 10 billion available to lend. Of this total, R$ 2 billion is the bank’s own capital, and the remaining R$ 8 billion comes from investors — deposits, savings, and other funding sources. This means the bank is operating with a leverage of 5x.</p><p>If the bank earns a 2% return on the R$ 10 billion it lends, it generates R$ 200 million in profit. But that R$ 200 million is earned on only R$ 2 billion of its own capital, which translates into a 10% return on equity.</p><p>Without leverage, the same 2% return would have yielded only R$ 40 million on the bank’s own R$ 2 billion.</p><p>With that in mind, the required profitability can be derived in Equation 22:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2FkKPkMaXwJ1US9i4REofUcD&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FkKPkMaXwJ1US9i4REofUcD" width="200" height="96" frameborder="0" scrolling="no"><a href="https://medium.com/media/374f1d0bbc531b2c9242d518bb880cb0/href">https://medium.com/media/374f1d0bbc531b2c9242d518bb880cb0/href</a></iframe><p>where:</p><ul><li>ROE is the target return on equity (e.g., 20% per year),</li><li>Leverage is the ratio of total assets to equity (e.g., 5×).</li></ul><p>In our framework, leverage is the mechanism that translates the required profitability premium (r) into a viable return for shareholders, ensuring that the bank’s lending activity remains both competitive and financially sustainable.</p><p>We can write the function r_table to do the job for us:</p><pre>def r_table(roe_values, leverage_values):<br>    data = []<br>    for lev in leverage_values:<br>        row = []<br>        for roe in roe_values:<br>            row.append(roe / lev)<br>        data.append(row)<br>    <br>    df = pd.DataFrame(<br>        data,<br>        index=[f&quot;{lev:.1f}x&quot; for lev in leverage_values],<br>        columns=[f&quot;{roe*100:.0f}%&quot; for roe in roe_values]<br>    )<br>    df.index.name = &quot;Leverage&quot;<br>    df.columns.name = &quot;ROE&quot;<br>    <br>    return (df * 100).round(2)<br><br># call<br>r_table(<br>    roe_values=[0.10, 0.12, 0.15, 0.18, 0.20, 0.25, 0.30],<br>    leverage_values=[5.0, 6.7, 8.3, 10.0, 12.5, 16.7, 20.0]<br>)</pre><p>Running it will produce the Table 9, below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*bmnMTUsMOos040ItM8aLzQ.png" /><figcaption>Table 9. ROE × Leverage Matrix</figcaption></figure><p>Now it’s easy to pick a value for <em>r</em>. Let’s say our bank operates with 10% leverage and generates a 15% ROE.</p><p>By Equation 22, r = 0.15 / 10 = 1.50% per annum.</p><p>This is the number we should add to the cost of funding and the expected loss spread to calculate the final interest rate.</p><p>In other words, the bank needs to earn a 1.50% annual premium on its loan book to deliver a 15% return on equity to its shareholders.</p><p>Now, we must also determine the cost of funding by using a similar approach.</p><p>Just as we decomposed the interest rate into risk and profitability components, we can break down the cost of funding into two main parts: the risk-free rate and the credit spread that reflects the bank’s own cost of raising funds.</p><p>We can express this as Equation 23:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2F8tttDFz1zjTt7RBtgzSYpr&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2F8tttDFz1zjTt7RBtgzSYpr" width="200" height="96" frameborder="0" scrolling="no"><a href="https://medium.com/media/b77a07b84324f6cd23a5ef816b1cfdcc/href">https://medium.com/media/b77a07b84324f6cd23a5ef816b1cfdcc/href</a></iframe><ul><li>c is the total cost of funding.</li><li><em>rf </em>is the risk-free rate.</li><li><em>sb</em>​ is the bank’s credit spread.</li></ul><p>The risk-free rate is the return an investor would expect from a completely safe asset, like a government bond. It represents the baseline cost of money in the economy.</p><p>The bank’s credit spread is an additional premium that investors demand for lending money to the bank, reflecting the bank’s own credit risk and the liquidity of its funding instruments.</p><p>There are mathematical approaches to calculate the bank’s credit spread, but here we simplify the framework by assuming it as a fixed premium over the risk‑free rate.</p><p>In practice, this means the bank pays its investors a rate equal to the risk‑free rate (e.g., SOFR) plus an additional spread.</p><p>By the time of writing, SOFR is approximately 3.62% per annum, implying a monthly rate of about 0.296% under compounding, so that’s the number I’m keeping plus let’s say 0,347% extra for investors (sb).</p><p>I picked that extra because 0.643% monthly is approximately 8.0% per annum, a well-established cost of capital for a medium-sized bank.</p><p>Finally, we can translate all the effort so far into a single final equation representing the interest rate:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2FvCvhajtAQzsjmiKJZq5ijt&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FvCvhajtAQzsjmiKJZq5ijt" width="200" height="96" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe34ece603fe86bbe6ec7b3f905f6ac2/href">https://medium.com/media/fe34ece603fe86bbe6ec7b3f905f6ac2/href</a></iframe><h4>How Much Should the Bank Charge</h4><p>Well, we have covered a lot in the previous sections to answer what initially seemed like a simple, yet surprisingly challenging question.</p><p>We learned that the contract term directly affects the required spread, meaning that loan offers should be tailored not only to the borrower’s risk profile but also to the number of installments.</p><p>We also developed a framework to estimate both the cost of funding and the desired profitability of the lending operation.</p><p>Now, all that remains is to put everything together into a single function capable of pricing the same loan for credit ratings ranging from A to E.</p><p>That is exactly what the function risk_adjusted_price_table does:</p><pre>def risk_adjusted_price_table(<br>    ratings,<br>    principal=1000,<br>    n_periods=12,<br>    funding_cost_annual=0.08,<br>    profitability_annual=0.015,<br>    loss_given_default=0.70,<br>    hazard_type=&quot;weibull&quot;<br>):<br>    funding_cost_monthly = (1 + funding_cost_annual) ** (1 / 12) - 1<br>    profitability_monthly = (1 + profitability_annual) ** (1 / 12) - 1<br><br>    results = []<br><br>    for rating, default_probability in ratings.items():<br><br>        # Expected Loss Spread (monthly)<br>        els_bps = expected_loss_spread(<br>            default_probability=default_probability,<br>            n_periods=n_periods,<br>            loss_given_default=loss_given_default,<br>            hazard_type=hazard_type<br>        )<br><br>        els_monthly = els_bps / 10000<br><br>        # Final lending rate (Equation 24)<br>        final_rate_monthly = (<br>            funding_cost_monthly +<br>            els_monthly +<br>            profitability_monthly<br>        )<br><br>        # Price schedule<br>        schedule = price_schedule(<br>            pv=principal,<br>            rate=final_rate_monthly,<br>            n_periods=n_periods<br>        )<br><br>        installment = schedule.loc[1, &quot;installment&quot;]<br><br>        results.append({<br>            &quot;Rating&quot;: rating,<br>            &quot;Funding Cost (% p.a.)&quot;: round(funding_cost_annual * 100, 2),<br>            &quot;Expected Loss Spread (% p.a.)&quot;: round(((1 + els_monthly) ** 12 - 1) * 100, 2),<br>            &quot;Profitability (% p.a.)&quot;: round(profitability_annual * 100, 2),<br>            &quot;Final Rate (% p.a.)&quot;: round(((1 + final_rate_monthly) ** 12 - 1) * 100, 2),<br>            &quot;Monthly Installment&quot;: round(installment, 2)<br>        })<br><br>    return pd.DataFrame(results).sort_values(&quot;Rating&quot;).reset_index(drop=True)<br><br><br>ratings = {<br>    &quot;A&quot;: 0.02,<br>    &quot;B&quot;: 0.05,<br>    &quot;C&quot;: 0.10,<br>    &quot;D&quot;: 0.20,<br>    &quot;E&quot;: 0.35<br>}<br><br>df_pricing = risk_adjusted_price_table(<br>    ratings=ratings,<br>    principal=1000,<br>    n_periods=12,<br>    funding_cost_annual=0.08,<br>    profitability_annual=0.015,<br>    loss_given_default=0.70,<br>    hazard_type=&quot;weibull&quot;<br>)<br><br>df_pricing</pre><p>The function uses the rating distribution and their corresponding default probabilities as inputs. We assume a one-year loan by setting n_periods to 12 and recreate a lending operation with a principal of $1,000.</p><p>The remaining inputs are exogenous assumptions. We set funding_cost_annual to 8% per year, profitability_annual to 1.5% per year, assume a constant loss_given_default of 70%, and model the survival dynamics using Weibull hazard curves by setting hazard_type to &quot;weibull&quot;.</p><p>Internally, the function reuses the previously developed functions expected_loss_spread and price_schedule, computes the risk-adjusted lending rate according to Equation 24, and finally recalculates the corresponding Price installment for each credit rating.</p><p>The result is Table 10, below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*XDOdNn9xRA7Vta3ts4JQhQ.png" /><figcaption>Table 10. Risk-Adjusted Loan Pricing by Credit Rating</figcaption></figure><p>For this configuration, the columns Final Rate (% p.a.) and Monthly Installment, respectively, determine the annual interest rate charged for each credit rating and the corresponding fixed installment paid by the borrower.</p><p>We observe that the annual interest rate for rating E is approximately 3.25 times that of rating A.</p><blockquote>In other words, for every $1.00 of annual interest charged to a rating A borrower, the bank charges approximately $3.25 to a rating E borrower to compensate for the substantially higher expected credit risk.</blockquote><p>We have done it. We have successfully translated default risk into loan pricing.</p><p>In this particular example, every contract remains economically viable. Even the 35.38% annual interest rate charged to rating E is within a range that could reasonably be observed in the market.</p><h4>Predictable Revenue</h4><p>One of the main conclusions of this framework is that, once funding costs and expected losses have been incorporated into the lending rate, the remaining profitability component becomes predictable.</p><p>Recall that the final lending rate was decomposed into three parts: the funding cost, the expected loss spread, and the required profitability. The first compensates investors who finance the operation, the second offsets expected credit losses, and only the third represents the bank’s expected economic profit.</p><p>Since the expected loss spread was calibrated to compensate for future defaults, the lending portfolio is expected to break even on credit risk. As a result, every dollar collected through the profitability premium contributes directly to the bank’s earnings.</p><p>For a single contract, the expected net profit (E[Π]) can therefore be expressed as :</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2Fi1KV1THm3u3USGHiR4D8oR&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2Fi1KV1THm3u3USGHiR4D8oR" width="200" height="96" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d7a8ec08fbe66886d0bce0975a2ae69/href">https://medium.com/media/0d7a8ec08fbe66886d0bce0975a2ae69/href</a></iframe><p>where r is the required profitability premium and Bₜ₋₁ is the outstanding balance before installment t.</p><p>The equation highlights an important property of the proposed framework. Profit is earned only while the contract remains alive and is proportional to the outstanding balance. As the borrower amortizes the loan, the balance decreases and so does the profit generated by the operation.</p><p>When applied to a sufficiently diversified portfolio, individual defaults become part of the expected behavior already incorporated into pricing. Consequently, although some contracts will inevitably generate losses, the portfolio as a whole produces a stable and predictable stream of earnings driven by the profitability premium.</p><p>With this concept, we can estimate the total expected profit for any new contract. Since credit risk and expected losses are already embedded in the pricing, what remains is the net profitability of the business.</p><h4><strong>Model Limitations</strong></h4><p>Here we start from a theoretical model adjusted for credit default risk in personal loan contracts. We introduce a set of constraints and assumptions in order to build a coherent narrative with a clear beginning, middle, and end.</p><p>In real-world or production settings, the story is slightly different from the one we present here. The core principles remain valid, but there are inherent weaknesses that need to be addressed when the portfolio is simulated as a whole.</p><p>In this section, I introduce some of these limitations, which will be further explored in Part 2 of this article.</p><p>First, credit card operations follow the same conceptual framework described here, but the expected loss model introduces several nuances. For instance:</p><p>The EAD is the customer’s own outstanding balance immediately prior to default. Between the moment a customer stops paying a credit card bill and the point at which they are officially classified as defaulted, there is an accrual period in which interest continues to accumulate, artificially increasing the observed balance.</p><p>There is both voluntary and involuntary churn, which means the survival-based approach does not strictly correspond to a simple “survives vs. defaults” event. For example, a customer may not transact in the following month but can still “reactivate” or survive in a subsequent period.</p><p>The customer may finance a purchase, causing the outstanding balance to be carried over through monthly invoices. This type of revolving credit increases profitability as long as the customer fully repays the debt.</p><p>However, the customer may also utilize the credit limit continuously and delay default by paying only the minimum invoice amount. In this scenario, the account remains active but deteriorates over time, surviving in a degraded state.</p><p>Additionally, in this framework we assume exogenous variables to enable risk-level comparisons. In practice, however, LGD is itself model-dependent, as customers exhibit heterogeneous propensities to repay their obligations.</p><p>Thus, LGD can be directly linked to the origination risk model of the loan, however, we build its on model based on the recovery capacity of each customer profile, what we call a collection model.</p><p>Under a non-constant LGD assumption, the intuition still holds that lower-risk customers tend to recover more of their defaulted balance. However, deterioration in repayment capacity can increase losses to a level where pricing is no longer sufficient to support a realistic offer.</p><p>Finally, and most importantly, PD is not constant over time and cannot be properly represented by a simple hazard rate. In theory, we often work backwards: we start from an observed outcome and calibrate a rate that maps to that final state.</p><p>In reality, although cumulative PD is always increasing, the marginal PD of each contract may fluctuate, introducing an additional dynamic component.</p><p>Furthermore, the probability of default (PD) is time-dependent, as exogenous macroeconomic conditions can systematically shift credit risk across the financial system.</p><p>All of these topics will be partially addressed in Part 2 of this article, where we simulate a loan portfolio under non-constant LGD and non-stationary PD.</p><h4>Final Thoughts</h4><p>This article develops a complete framework for credit pricing by linking financial mathematics, risk modeling, and portfolio economics into a unified structure.</p><p>Starting from compound interest and the Price amortization system, we show how loan cash flows are structured and how breakeven emerges from the interaction between installments, funding costs, and time.</p><p>We then extend the model to incorporate credit risk through expected loss (PD, LGD, and EAD), showing how defaults reshape profitability and why pricing must move beyond flat interest rates to risk-adjusted lending. Survival analysis further introduces the time dimension of credit risk, highlighting that default is not static but evolves over the life of the contract.</p><p>By combining survival dynamics with expected loss modeling, we derive a spread that compensates for credit risk while maintaining economic viability. However, true profitability only emerges when funding costs and required return on equity are included, leading to a final risk-adjusted pricing equation that decomposes interest rates into funding, risk, and profit components.</p><p>The main conclusion is that credit pricing is fundamentally a constrained optimization problem: banks must balance risk compensation, capital return requirements, and competitiveness while accounting for the amortizing nature of exposure over time. Longer contracts dilute exposure but extend risk duration, creating a non-trivial trade-off between time and default probability.</p><p>Overall, the model shows how predictable revenue can be achieved when expected losses are properly priced, turning credit risk from an uncertainty into a quantifiable component of loan pricing.</p><p>Finally, optimizing credit offer interest rates to achieve a competitive market position while preserving the bank’s target profitability enables broader credit expansion, making financing more accessible across the economy and supporting financial inclusion, particularly for underserved segments.</p><h4><strong>References</strong></h4><p>Brealey, R. A., Myers, S. C., &amp; Allen, F. <em>Principles of Corporate Finance</em>. McGraw-Hill.</p><p>Hull, J. C. <em>Options, Futures, and Other Derivatives</em>. Pearson.</p><p>Basel Committee on Banking Supervision (BCBS). <em>International Convergence of Capital Measurement and Capital Standards (Basel II/III)</em>.</p><p>Duffie, D., &amp; Singleton, K. J. <em>Credit Risk: Pricing, Measurement, and Management</em>. Princeton University Press.</p><p>Altman, E. I. <em>Financial Ratios, Discriminant Analysis and the Prediction of Corporate Bankruptcy</em>. Journal of Finance.</p><p>Klein, J. P., &amp; Moeschberger, M. L. <em>Survival Analysis: Techniques for Censored and Truncated Data</em>. Springer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=819226ff3749" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/how-banks-should-lend-your-money-819226ff3749">How Banks Should Lend Your Money</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[Man Against the Machine but with Poems]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://levelup.gitconnected.com/man-against-the-machine-but-with-poems-74e8867495b4?source=rss-59d66406fdbf------2"><img src="https://cdn-images-1.medium.com/max/1315/1*BFXbk9oSbOomp2JqCEcGzA.png" width="1315"></a></p><p class="medium-feed-snippet">Evaluating Human and AI Poetry with DeepSeek</p><p class="medium-feed-link"><a href="https://levelup.gitconnected.com/man-against-the-machine-but-with-poems-74e8867495b4?source=rss-59d66406fdbf------2">Continue reading on Level Up Coding »</a></p></div>]]></description>
            <link>https://levelup.gitconnected.com/man-against-the-machine-but-with-poems-74e8867495b4?source=rss-59d66406fdbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/74e8867495b4</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[poetry]]></category>
            <dc:creator><![CDATA[Guilherme Ziegler]]></dc:creator>
            <pubDate>Mon, 29 Jun 2026 19:44:10 GMT</pubDate>
            <atom:updated>2026-07-07T20:21:57.859Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[How to Build a Table of Contents for your Article On Medium]]></title>
            <link>https://levelup.gitconnected.com/how-to-build-a-table-of-contents-for-your-article-in-medium-0747ad771087?source=rss-59d66406fdbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/0747ad771087</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[writing]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Guilherme Ziegler]]></dc:creator>
            <pubDate>Fri, 26 Jun 2026 19:35:00 GMT</pubDate>
            <atom:updated>2026-07-01T18:44:16.250Z</atom:updated>
            <content:encoded><![CDATA[<h4>A small hack to make your big story easy to follow</h4><p>Medium is a fantastic platform for sharing ideas, but one thing it lacks is a native Table of Contents feature. Long-form articles — especially those with many sections, equations, and figures — can feel overwhelming without a clear navigation structure. Readers often scroll endlessly, looking for a specific topic or formula.</p><p>In this article, I’ll show you a simple and effective hack to build a Table of Contents for your Medium stories using Python and BeautifulSoup. This approach works even for draft articles, and it will save you hours of manual linking.</p><h4>Table of Contents</h4><p><strong>Topics<br></strong><a href="#6927">How to build a table of contents for your article in Medium</a><br><a href="#05d4">Why a Table of Contents?</a><br><a href="#4dcb">The Hack: How It Works</a><br><a href="#4dcb">The Python Solution</a><br><a href="#4834">Step 1: Save Your Article as HTML </a><br><a href="#02ad">Step 2: Run the Python Script</a> <br><a href="#00e6">Step 3: Copy and Paste into Medium</a></p><p><strong>Figures<br></strong><a href="#021f">Figure 1. Random Figure. Source: ChatGPT</a><br><a href="#4971">Figure 2. Editing the Table of Contents</a></p><h4>Why a Table of Contents?</h4><p>A Table of Contents (TOC) improves the reader experience by:</p><ul><li>Providing an overview of the article’s structure.</li><li>Allowing quick navigation to specific sections.</li><li>Reducing friction for readers who want to jump to a particular topic.</li><li>Making long-form content more digestible and professional.</li></ul><p>Medium does not automatically generate TOCs, but you can create one manually using anchor links. The trick is to use the unique IDs that Medium assigns to each heading, equation, and figure.</p><h4>The Hack: How It Works</h4><p>Every heading, image, and embed in Medium has a unique HTML ID. These IDs are generated automatically when you publish or save a draft. They look like #91d6 or #heading-1. By linking to these IDs, you can create a TOC that scrolls the reader directly to the corresponding section.</p><p>The challenge is finding these IDs — Medium does not display them in the editor. This is where our Python script comes in.</p><h4>The Python Solution</h4><p>We’ll use BeautifulSoup to parse the HTML of your Medium article (saved as a .html file) and extract all the elements that matter: headings, equations, tables, and figures. The script then generates a formatted TOC with the correct anchor links.</p><p>First of all let’s add some random picture here and try to add it inside the table of content, Figure 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xfuJCWqaLnWRHpMT8ApY7Q.png" /><figcaption>Figure 1. Random Figure. Source: ChatGPT</figcaption></figure><p>Now lets follow the next steps to get it in the previous table of content section we definied earlier.</p><h4>Step 1: Save Your Article as HTML</h4><ol><li>Open your Medium draft or published article in a browser.</li><li>Right-click and select “Save As…” (or press Ctrl + S).</li><li>Choose “Web Page, HTML Only” and save the file.</li></ol><p>I did while writting and got a html file named:</p><pre>html_file = &quot;How to Build a Table of Contents for your Article in Medium _ by Guilherme Ziegler _ Jun, 2026 _ Level Up Coding&quot;</pre><h4>Step 2: Run the Python Script</h4><p>Here’s the complete script:</p><pre>from bs4 import BeautifulSoup<br>import re<br><br>def extract_elements(html_path):<br>    &quot;&quot;&quot;<br>    Extracts all elements with IDs from a Medium HTML file:<br>    equations, tables, figures, and headings.<br>    Returns a dictionary with categorized elements.<br>    &quot;&quot;&quot;<br>    with open(html_path, &quot;r&quot;, encoding=&quot;utf-8&quot;) as f:<br>        html = f.read()<br>    <br>    soup = BeautifulSoup(html, &#39;html.parser&#39;)<br>    elements = {&#39;equations&#39;: [], &#39;tables&#39;: [], &#39;figures&#39;: [], &#39;headings&#39;: []}<br>    <br>    # Extract equations, tables, and figures<br>    for figure in soup.find_all(&#39;figure&#39;):<br>        figcaption = figure.find(&#39;figcaption&#39;)<br>        if not figcaption:<br>            continue<br>        <br>        title = figcaption.get_text(strip=True)<br>        <br>        # Find the ID from the previous sibling (usually a &lt;p&gt; tag)<br>        prev = figure.find_previous_sibling()<br>        element_id = prev.get(&#39;id&#39;) if prev and prev.get(&#39;id&#39;) else None<br>        <br>        # If no ID found, try the next &lt;p&gt; tag<br>        if not element_id:<br>            next_p = figure.find_next(&#39;p&#39;)<br>            if next_p and next_p.get(&#39;id&#39;):<br>                element_id = next_p.get(&#39;id&#39;)<br>        <br>        if not element_id:<br>            continue<br>        <br>        if &#39;Equation&#39; in title or &#39;Eq.&#39; in title:<br>            elements[&#39;equations&#39;].append({&#39;title&#39;: title, &#39;id&#39;: element_id})<br>        elif &#39;Table&#39; in title or &#39;Tab.&#39; in title:<br>            elements[&#39;tables&#39;].append({&#39;title&#39;: title, &#39;id&#39;: element_id})<br>        elif &#39;Figure&#39; in title or &#39;Fig.&#39; in title:<br>            elements[&#39;figures&#39;].append({&#39;title&#39;: title, &#39;id&#39;: element_id})<br>    <br>    # Extract headings (H1, H2, H3)<br>    for tag in [&#39;h1&#39;, &#39;h2&#39;, &#39;h3&#39;]:<br>        for element in soup.find_all(tag):<br>            text = element.get_text(strip=True)<br>            if text and element.get(&#39;id&#39;):<br>                elements[&#39;headings&#39;].append({<br>                    &#39;title&#39;: text,<br>                    &#39;id&#39;: element.get(&#39;id&#39;)<br>                })<br>    <br>    # Add any important H4 headings manually if needed<br>    # Example: elements[&#39;headings&#39;].append({&#39;title&#39;: &#39;Price (French Amortization) System&#39;, &#39;id&#39;: &#39;e29f&#39;})<br>    <br>    return elements<br><br>def generate_toc(elements):<br>    &quot;&quot;&quot;<br>    Generates a formatted Table of Contents from the extracted elements.<br>    &quot;&quot;&quot;<br>    print(&quot;## Table of Contents\n&quot;)<br>    <br>    print(&quot;### Topics\n&quot;)<br>    for h in elements[&#39;headings&#39;]:<br>        print(f&quot;- {h[&#39;title&#39;]} (#{h[&#39;id&#39;]})&quot;)<br>    <br>    print(&quot;\n### Equations\n&quot;)<br>    for eq in elements[&#39;equations&#39;]:<br>        print(f&quot;- {eq[&#39;title&#39;]} (#{eq[&#39;id&#39;]})&quot;)<br>    <br>    print(&quot;\n### Tables\n&quot;)<br>    for tb in elements[&#39;tables&#39;]:<br>        print(f&quot;- {tb[&#39;title&#39;]} (#{tb[&#39;id&#39;]})&quot;)<br>    <br>    print(&quot;\n### Figures\n&quot;)<br>    for fig in elements[&#39;figures&#39;]:<br>        print(f&quot;- {fig[&#39;title&#39;]} (#{fig[&#39;id&#39;]})&quot;)<br><br>def save_toc_to_file(elements, output_path=&quot;toc_output.txt&quot;):<br>    &quot;&quot;&quot;<br>    Saves the Table of Contents to a text file.<br>    &quot;&quot;&quot;<br>    with open(output_path, &quot;w&quot;, encoding=&quot;utf-8&quot;) as f:<br>        f.write(&quot;## Table of Contents\n\n&quot;)<br>        <br>        f.write(&quot;### Topics\n&quot;)<br>        for h in elements[&#39;headings&#39;]:<br>            f.write(f&quot;- {h[&#39;title&#39;]} (#{h[&#39;id&#39;]})\n&quot;)<br>        <br>        f.write(&quot;\n### Equations\n&quot;)<br>        for eq in elements[&#39;equations&#39;]:<br>            f.write(f&quot;- {eq[&#39;title&#39;]} (#{eq[&#39;id&#39;]})\n&quot;)<br>        <br>        f.write(&quot;\n### Tables\n&quot;)<br>        for tb in elements[&#39;tables&#39;]:<br>            f.write(f&quot;- {tb[&#39;title&#39;]} (#{tb[&#39;id&#39;]})\n&quot;)<br>        <br>        f.write(&quot;\n### Figures\n&quot;)<br>        for fig in elements[&#39;figures&#39;]:<br>            f.write(f&quot;- {fig[&#39;title&#39;]} (#{fig[&#39;id&#39;]})\n&quot;)<br>    <br>    print(f&quot;✅ TOC saved to {output_path}&quot;)</pre><p>The first function, extract_elements, does the heavy lifting. It opens the HTML file you saved from your Medium article, scans through the code, and picks out every element that has an ID — headings, equations, tables, and figures. For each one, it stores both the title and the corresponding ID, so we know exactly where to link later.</p><p>The second function, generate_toc, takes that information and turns it into a clean, formatted Table of Contents. It prints the TOC directly to your screen, organized by categories, with each item displayed as a clickable-looking link. You can simply copy the output and paste it straight into your Medium article — no extra formatting needed.</p><p>The third function, save_toc_to_file, does the same thing but saves the TOC to a text file instead. This is useful if you want to edit the list before pasting it, or if you&#39;d like to keep a backup for future reference.</p><h4>Step 3: Copy and Paste into Medium</h4><p>The output will look like this:</p><pre>## Table of Contents<br><br>### Topics<br><br>- How to build a table of contents for your article in Medium (#6927)<br>- Table of Contents (#963f)<br>- Why a Table of Contents? (#05d4)<br>- The Hack: How It Works (#4dcb)<br>- The Python Solution (#4abc)<br>- Step 1: Save Your Article as HTML (#4834)<br>- Step 2: Run the Python Script (#02ad)<br>- Step 3: Copy and Paste into Medium (#00e6)<br>- Final Thoughs (#b2b4)<br><br>### Equations<br><br><br>### Tables<br><br><br>### Figures<br><br>- Figure 1. Random Figure (#021f)<br>- Figure 2. Editing the Table of Contents (#4971)<br><br>✅ TOC saved to toc_output.txt</pre><blockquote>Bingo, Tada, Et voilà, Abracadabra!</blockquote><p>Now, all you have to do is copy this into your Table of Contents and replace the number inside the brackets with the actual link — as shown in Figure 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*kPVnU6ORv3a0D13BGtCPhQ.png" /><figcaption>Figure 2. Editing the Table of Contents</figcaption></figure><h4>Final Thoughs</h4><p>Well, that was quick! Not my usual writing style, but I thought it could improve the writing experience for some of you who write like I do.</p><p>Happy writing! 🚀</p><p><em>P.S. If you’d like to see the full Python code in action, check out my article “</em><a href="https://medium.com/@guilherme.ziegler/819226ff3749"><em>How Banks Should Lend Their Money</em></a><em>”, where I used this exact method to build a complete Table of Contents for over 25 equations, 8 tables, and 2 figures.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0747ad771087" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/how-to-build-a-table-of-contents-for-your-article-in-medium-0747ad771087">How to Build a Table of Contents for your Article On Medium</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[To Bet Or Not To Bet, That is a Math Question]]></title>
            <link>https://levelup.gitconnected.com/to-bet-or-not-to-bet-that-is-a-math-question-d5f8d14a7718?source=rss-59d66406fdbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5f8d14a7718</guid>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[games]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Guilherme Ziegler]]></dc:creator>
            <pubDate>Mon, 15 Jun 2026 03:50:31 GMT</pubDate>
            <atom:updated>2026-06-29T11:56:28.343Z</atom:updated>
            <content:encoded><![CDATA[<h4>The Mathematics of Casino Games</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lo5azFIyeb2y2g4CYZrKfQ.jpeg" /><figcaption><strong>Figure 1. </strong>To Bet or Not to Bet: That Is a Math Question</figcaption></figure><h4><a href="https://medium.com/gitconnected/how-to-build-a-table-of-contents-for-your-article-in-medium-0747ad771087">Table of Contents</a></h4><p><strong>Topics</strong><br><a href="#a64a">Introduction</a><br><a href="#a02f">Article Structure</a> <br><a href="#1d53">Symbols and Weights</a><br><a href="#bdcd">Winning Positions</a><br><a href="#1cbb">Expected Payout</a><br><a href="#e3a3">RTP (Return to Player)</a><br><a href="#a00b">Building a Slot Machine with Python and Streamlit</a><br><a href="#84f9">Required Libraries</a><br><a href="#f2b0">Initial Setup and Parameters</a><br><a href="#5b6f">Game Functions</a><br><a href="#8cf8">Streamlit Integration</a><br><a href="#3dee">Final Thoughts</a><br><a href="#9826">References</a></p><p><strong>Equations</strong><br><a href="#aabc">Equation 1. Probability of Symbol i</a><br><a href="#ee6a">Equation 2. Probability of a Symbol Combination</a><br><a href="#3d19">Equation 3. Probability of a Winning Line</a><br><a href="#2822">Equation 4. Probability of at Least One Winning Line</a><br><a href="#85ae">Equation 5. Expected Payout per Winning Line</a><br><a href="#aa36">Equation 6. Expected Payout for a Tiger Winning Position</a><br><a href="#4066">Equation 7. RTP (Return to Player)</a><br><a href="#36b8">Equation 8. Empirical RTP from Five Spins</a></p><p><strong>Figures</strong><br><a href="#6750">Figure 1. To Bet or Not to Bet: That Is a Math Question</a><br><a href="#1289">Figure 2. Winning Positions in a 3 × 3 Game</a><br><a href="#d370">Figure 3. Multiplayer Simulation with a $10 Bet and 2,000 Spins</a><br><a href="#a993">Figure 4. Simulating a Game with a Changing RTP</a></p><h4>Introduction</h4><p>In recent years, betting has evolved into a global digital industry, raising significant public health concerns. The widespread availability of online platforms and mobile access has made gambling more accessible than ever, effectively creating what experts describe as a “casino in your pocket” (WHO, 2024).</p><p>Among the various forms of gambling, slot machines, particularly digital ones, are considered especially risky. Their rapid gameplay, continuous reinforcement, and instant rewards are strongly linked to addictive behaviors, which makes them one of the main drivers of problem gambling worldwide (Techopedia, 2024).</p><p>The scale of the issue is significant. Global estimates suggest that around 1.2% of adults suffer from gambling disorder, while many others experience financial, psychological, and social harm due to gambling-related activities (WHO, 2024).</p><p>At its core, the question is whether betting can generate consistent long-term returns. The most rigorous way to answer this is through mathematics.</p><p>Casino games are designed around an inherent statistical advantage known as the house edge, which ensures that, over time, expected returns are negative for the player.</p><p>While short-term wins are possible and often emphasized, probability theory makes it clear that repeated play leads to predictable losses rather than sustainable gains.</p><p>For those familiar with my previous articles, I am an economist and data scientist working in financial risk, and I enjoy raising thought-provoking questions for discussion.</p><p>In this article, we explore the key mathematical principles that demonstrate why consistent long-term profits from betting are unlikely. To make this concrete, we also build a simple online casino using Python and Streamlit.</p><p>We do this by:</p><ul><li>Explaining the math and statistics behind long-term returns in digital slot machines.</li><li>Coding a basic casino model in Python and running the game in Streamlit, which is engaging to play.</li><li>Running simulations for multiple players on a single slot machine.</li></ul><h4>Article Structure</h4><p>This article has three sections:</p><ol><li>Maths and equations.</li><li>Python functions to run the game.</li><li>Streamlit Integration.</li></ol><p>The first section presents mathematical theory behind online betting, especially in casino systems.</p><p>The second demonstrates how to build a simple slot machine for experimental purposes, covering the core backend logic that powers the game.</p><p>The third focuses on a basic frontend implementation to render the application for single-player and multiplayer modes, where I demonstrate some insights about betting in the short and long term.</p><h4>Symbols and Weights</h4><p>In a slot game, symbols represent the outcome of a single spin. Each time the slot is played, every symbol has a probability of appearing on the screen.</p><p>This probability is determined by a set of predefined weights, in other words, how rare each symbol is relative to the others.</p><p>To make this clear, consider a machine with seven different symbols, ordered by rarity: tiger, gold, clover, star, seven, wild, and jackpot.</p><p>Also, let’s assume default weights are given as follows:</p><pre>SYMBOLS = [&quot;tiger&quot;, &quot;gold&quot;, &quot;clover&quot;, &quot;star&quot;, &quot;seven&quot;, &quot;wild&quot;, &quot;jackpot&quot;]<br><br>SYMBOL_EMOJI = {&quot;tiger&quot;:&quot;🐅&quot;,&quot;gold&quot;:&quot;💰&quot;,&quot;clover&quot;: &quot;🍀&quot;,<br>                &quot;star&quot;:&quot;⭐&quot;,&quot;seven&quot;:&quot;7️⃣&quot;,&quot;wild&quot;:&quot;🎰&quot;,<br>                &quot;jackpot&quot;:&quot;💎&quot;}<br><br>DEFAULT_WEIGHTS = [5, 5, 5, 5, 1, 0.3, 0.5]</pre><p>The initial weight configuration is heavily skewed toward low-tier symbols, with <em>tiger, gold, clover,</em> and <em>star</em> all assigned equal and dominant weights (5), meaning they will appear very frequently and define most of the player experience.</p><p>In contrast, higher-value symbols like <em>seven</em> (1), <em>jackpot</em> (0.5), and especially <em>wild</em> (0.3) are significantly rarer, which is a typical design choice to preserve excitement and control payouts.</p><blockquote>Think of weights as “tickets in a draw.” The more tickets a symbol has, the more often it shows up.</blockquote><p>Instead of working with probabilities for each symbol, we normalize the weights to get them, Equation 1:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2FKXyg4aLyh3oCX1KFVEYqL&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FKXyg4aLyh3oCX1KFVEYqL" width="277" height="96" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1de56f2a3a7a8464b5ac9bdc1976440/href">https://medium.com/media/a1de56f2a3a7a8464b5ac9bdc1976440/href</a></iframe><ul><li><em>pi</em> is the probability of symbol <em>i</em> appearing;</li><li><em>wi</em>​ is the initial weight assigned to symbol <em>i</em> (controls how frequent it is);</li><li><em>N </em>is the number of initial symbols (5 in this case) ;</li><li><em>J</em> is the index used to iterate over all symbols;</li><li>And the term in the <em>summation </em>represents the total weight across all symbols, acting as the normalization factor.</li></ul><blockquote>Intuitively, you take the weight of one symbol and divide it by the total weight of all symbols to get its probability.</blockquote><blockquote>We could start directly with probabilities, some would need to be extremely small, making them difficult to discuss.</blockquote><p>Let’s take the tiger and jackpot as examples (see Equation 2):</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2FjCWcnyS5j2PVhBFv26YPoz&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FjCWcnyS5j2PVhBFv26YPoz" width="378" height="295" frameborder="0" scrolling="no"><a href="https://medium.com/media/22523b918beb00836a580bbcdde51cd1/href">https://medium.com/media/22523b918beb00836a580bbcdde51cd1/href</a></iframe><p>The probability of getting one tiger is 18.66% while the probability of one jackpot is 1.87%, way rarer.</p><h4>Winning Positions</h4><p>As the saying goes:</p><blockquote>As the saying goes:<br>One swallow does not make a summer.<br>Nor does a tiger alone.</blockquote><p>This brings up the concept of winning positions.</p><p>A winning position is a rule that establishes how many matching symbols must appear together, and in which positions, for a prize to be paid.</p><p>Usually, this number is three for common slot machines, but it can be set to any value. In a game based on a 1 × 3 matrix, the columns indicate the positions where a symbol can appear. A win occurs when three matching symbols are displayed on the screen simultaneously.</p><p>Since all 3 symbols have the same probability of appearing once, we come up with Equation 3:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2F6EgKQPc2LXnq7SEfmHnoyX&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2F6EgKQPc2LXnq7SEfmHnoyX" width="419" height="227" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ba6fcd0c701c3c6095576f1ab8bc2ad/href">https://medium.com/media/6ba6fcd0c701c3c6095576f1ab8bc2ad/href</a></iframe><p>For this particular case a jackpot winning position happens approximately once in 153,846 chances.</p><blockquote>Why is the probability of a <strong>wild </strong>lower than that of a <strong><em>jackpot</em></strong>?</blockquote><blockquote>In this game, the <strong>wild </strong>symbol acts as a substitute, meaning it can complete a winning position when combined with a matching pair of another symbol. Because of this flexibility, it contributes to many more winning combinations than a regular symbol.</blockquote><blockquote>To keep the game balanced, the <strong>wild </strong>must appear less frequently than the <strong>jackpot</strong>. Even though it shows up less often, when it does appear, it significantly increases the chances of forming a winning position.</blockquote><p>Since we have defined a winning position in this 1 x 3 matrix game, adding more lines increases the overall chance of winning. Each line is <em>independent</em>, meaning the outcome of one line does not affect another.</p><p>However, these events are<strong><em> </em></strong><em>not mutually exclusive</em>, since multiple lines can win at the same time. Because of that, we cannot simply sum their probabilities.</p><p>Instead, the correct approach is to compute the probability of winning in at least one line using the<em> complement rule, </em>by calculating the probability that all three lines lose simultaneously and subtracting it from one.</p><p>Therefore, the probability of getting at least one winning line with a <em>3 </em>x <em>3</em> matrix game is given by Equation 4:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2FtTcgNFt9TQM72VUYbygbfj&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FtTcgNFt9TQM72VUYbygbfj" width="318" height="141" frameborder="0" scrolling="no"><a href="https://medium.com/media/4940842ae2feb480939cabdfc59629e0/href">https://medium.com/media/4940842ae2feb480939cabdfc59629e0/href</a></iframe><p>Where i represents any symbol, and L is the number of winning lines — here, 3 horizontal lines. The exponent 3 comes from Equation 3, since a winning line requires three identical symbols. The term inside the brackets is the probability of losing on a single line.</p><p>Now that we understand the classic example, let’s add some more fun to the game. Considering only the chance to win horizontally is not ideal in terms of user experience and gameplay. We need to add more fun so that the slot machine becomes more attractive to players.</p><p>One way to do so is to define a couple of additional winning positions. For now, we are focused on horizontal lines, but we could also consider moving vertically, in terms of columns, as well as diagonals, and maybe some left and right triangles to keep the mood high.</p><p>Here is a representation of all possible winning lines in a 3 × 3 game, Figure 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*WqwH7lKdByi-4EML6MivRg.png" /><figcaption>Figure 2. Winning Positions in a 3 × 3 Game</figcaption></figure><p>We see that there are 4 possible winning positions, represented by rectangles: V (vertical), H (horizontal), D (diagonals), and &gt; (left triangle).</p><p>Each <em>V</em> can occur 3 times, since there are 3 columns; the same goes for <em>H</em>, with 3 horizontal lines. In a matrix, there are only 2 possible diagonals, and the triangle can occur on the left side, as depicted above, but also on the right side.</p><p>Thus, summing 3V + 3H + 2D + 2&gt; gives 10 winning positions in a single spin.</p><blockquote>Wherever the odds are for each symbol to appear, there are 10 possible configurations that will pay the prize.</blockquote><p>From that we define another hyperparameter and can update the initialization of the game:</p><pre>SYMBOLS = [&quot;tiger&quot;, &quot;gold&quot;, &quot;clover&quot;, &quot;star&quot;, &quot;seven&quot;, &quot;wild&quot;, &quot;jackpot&quot;]<br>pyth<br>SYMBOL_EMOJI = {&quot;tiger&quot;:&quot;🐅&quot;,&quot;gold&quot;:&quot;💰&quot;,&quot;clover&quot;: &quot;🍀&quot;,<br>                &quot;star&quot;:&quot;⭐&quot;,&quot;seven&quot;:&quot;7️⃣&quot;,&quot;wild&quot;:&quot;🎰&quot;,<br>                &quot;jackpot&quot;:&quot;💎&quot;}<br><br>DEFAULT_WEIGHTS = [5, 5, 5, 5, 1, 0.3, 0.5]<br><br>WINNING_POSITIONS = 10</pre><h4>Expected Payout</h4><p>Previously, we defined how to win in the game, but how much a win pays is yet to be set.</p><p>Since each symbol has a certain rarity of being displayed on the screen, it is intuitive to assume that the rarer the symbol, the higher the payout.</p><p>So, taking tiger, gold, clover, star, and seven as examples, we could assume that the star pays more than all of them. However, since tiger, gold, and clover are equally frequent in the game, they should pay the same, right?</p><p>That makes sense, but once again, our game would become boring. Therefore, we must configure a hyperparameter that determines the payout for each symbol in a winning position, while still encouraging the player to root for the higher-paying symbol, even when the odds are the same.</p><p>This is achieved by setting default multipliers as follows:</p><pre>DEFAULT_MULTIPLIERS = {&quot;tiger&quot;: 12, <br>                       &quot;gold&quot;: 14, <br>                       &quot;clover&quot;: 16, <br>                       &quot;star&quot;: 18, <br>                       &quot;seven&quot;: 25, <br>                       &quot;wild&quot;: 0, <br>                       &quot;jackpot&quot;: 0}</pre><p>Note now that star is as well as frequent as tiger but pays additional 6 units in return. Seven is 5 times rarer than the precedent ones, and pays additional 13 units when compared with tiger.</p><blockquote>Why do <strong>wild </strong>and <strong>jackpot </strong>pay nothing back?</blockquote><blockquote>As mentioned above, the <strong>wild </strong>works as a substitute, so on its own it pays nothing. We must ensure that whenever a winning position can be formed using a <strong>wild</strong>, the highest possible prize is paid.</blockquote><blockquote>That said, in a case where both a <strong>tiger </strong>winning position and a <strong>seven </strong>winning position could be formed using a single <strong>wild</strong>, we assume it will form the higher-paying combination, and in this case, bind it to that outcome.</blockquote><blockquote>The <strong>jackpot</strong> has a similar behavior: it pays nothing directly because, when it appears in a winning position, the player receives the accumulated prize, which is funded by a fraction of each bet.</blockquote><blockquote>In this case, the rarer the odds of a winning position, the higher the total prize paid out.</blockquote><p>We covered that each symbols pays back differently, but they always should pay back more than the overall bet for a winning position.</p><p>We define 10 as the number of winning positions, so when we bet, let’s say, $10 per spin, we are dividing the value of bet for the number of 10 possible winning positions.</p><blockquote>It means that for each $10 bet, we are allocating $1 to a winning position that, when displayed on the screen, is multiplied by the default multiplier.</blockquote><blockquote>Thus, if we win with tiger, we get $12 back; if we win with clover, we get $16 back; and of course, if we win with both, the total payout is $28 from a $10 bet.</blockquote><blockquote>In terms of the risk–reward ratio, we have 1:2.6, for each dollar we bet, we expect to receive $2.6 back.</blockquote><p>Note that default multipliers are hyperparameters, and each should be set such that the multiplier times 10% of the total bet exceeds the original bet. This is a default constraint for the total number of winning positions we have.</p><p>To make this clear, tiger pays $12 for each $1 when the total bet is $10. Therefore, when a single tiger wins, the minimum payout is $12 × $1, which must be greater than — and indeed is greater than — $10.</p><p>We covered that each symbols pays back differently, but they always should pay back more than the overall bet for a winning position.</p><p>We define 10 as the number of winning positions, so when we bet, let’s say, $10 per spin, we are dividing the value of bet for the number of 10 possible winning positions.</p><blockquote>It means that for each $10 bet, we are allocating $1 to a winning position that, when displayed on the screen, is multiplied by the default multiplier.</blockquote><blockquote>Thus, if we win with tiger, we get $12 back; if we win with clover, we get $16 back; and of course, if we win with both, the total payout is $28 from a $10 bet.</blockquote><blockquote>In terms of the risk–reward ratio, we have 1:2.6, for each dollar we bet, we expect to receive $2.6 back.</blockquote><p>Note that default multipliers are hyperparameters, and each should be set such that the multiplier times 10% of the total bet exceeds the original bet. This is a default constraint for the total number of winning positions we have.</p><p>To make this clear, tiger pays $12 for each $1 when the total bet is $10. Therefore, when a single tiger wins, the minimum payout is $12 × $1, which must be greater than — and indeed is greater than — $10.</p><p>Since we intuitively understood the dynamics of the payouts, let’s formalize the expected payout for any winning lines in Equation 5:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2Fbu618gPVX3sb6t2gCd13Zk&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2Fbu618gPVX3sb6t2gCd13Zk" width="200" height="325" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ca5bbe35c7aae03db5bccae9ce41719/href">https://medium.com/media/2ca5bbe35c7aae03db5bccae9ce41719/href</a></iframe><p>Where:</p><ul><li><em>E[payout]</em> is the expected total payout;</li><li><em>B</em> is the total bet per spin (e.g., $10);</li><li><em>W</em> is the total number of possible winning positions (e.g., 10);</li><li><em>k</em> is the number of winning positions observed in the experiment (e.g., 1);</li><li><em>mi</em>​ is the multiplier paid when symbol <em>i</em> forms a winning position.</li></ul><p>Now, as an example, for one winning position formed by three tigers, with a total bet of $10 and 10 possible winning positions, we obtain an expected payout of $12 (see Equation 6).</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2FjvrRKk62LK395xxkpNRXqu&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FjvrRKk62LK395xxkpNRXqu" width="259" height="280" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6928c7fcdac1e2b477aecd0eddbbea4/href">https://medium.com/media/d6928c7fcdac1e2b477aecd0eddbbea4/href</a></iframe><h4>RTP (Return to Player)</h4><p>We have covered symbols and their weights, winning positions, and expected payouts — all the elements needed to estimate the Return to Player (RTP) in the long run.</p><p>For any given spin, there are only two possible outcomes: either the player loses the entire bet or wins an amount greater than the original stake.</p><p>Since each symbol has an associated probability (pi) and we have defined all possible winning positions (wp), RTP represents the average amount of money returned to the player over many spins.</p><p>To compute the Return to Player (RTP), we take the expected payout over all possible winning outcomes.</p><p>In this setup, each winning position receives 10% of the total bet, and a win requires three identical symbols. Therefore, the probability of a winning combination for symbol <em>i</em> is <em>pi³ </em>(see Equation 1)<em>.</em></p><p>Each symbol also has an associated multiplier <em>mi​</em>, which defines its payout. By combining these elements, the RTP simplifies to:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2F4bgif2rDn3S6k92ZofYheE&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2F4bgif2rDn3S6k92ZofYheE" width="200" height="157" frameborder="0" scrolling="no"><a href="https://medium.com/media/81b17071a43f644d62934c352eebca4b/href">https://medium.com/media/81b17071a43f644d62934c352eebca4b/href</a></iframe><p>This means the RTP is simply the sum, over all symbols, of the probability of hitting three of that symbol multiplied by its respective payout multiplier.</p><p>In other words, RTP represents the average return per unit bet in the long run.</p><p>There are three possible outcomes for the RTP in a slot machine game:</p><ul><li>If it is greater than 1, the player wins more than they bet.</li><li>If it is equal to 1, the player breaks even over time — a scenario that offers little incentive to play.</li><li>If it is less than 1, the player loses more money than they win in the long run.</li></ul><blockquote>Yes, it does. Since the RTP is set slightly below 1, the game is designed to make players feel like they are winning — because each individual win pays more than the original bet. However, wins are rare enough that the total return remains below 1 over time.</blockquote><blockquote>Remember those hyperparameters from earlier? They are carefully calibrated to create the feeling of “I might win today.” In the short run, it is entirely possible to achieve high returns due to randomness, driven by the symbol weights. However, over time, the player typically gives back all winnings and eventually loses the initial stake.</blockquote><blockquote>Furthermore, some games can be configured to have an RTP greater than 1 for a limited number of spins, and then revert to below 1 in order to recover the house’s expected profit.</blockquote><p>In practice, let us assume 5 spins, each with a $10 bet, where each spin either returns a payout or 0 (see Equation 7). This empirically simulates the process.</p><p>For these 5 spins, the payouts are 12, 0, 16, 0, and 20, summing to $48 returned out of $50 wagered. The resulting RTP in this case is 0.96, which is quite close to what slot machines are typically calibrated to achieve.</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2FhSvNtq113vrBqYm9BwMBzH&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FhSvNtq113vrBqYm9BwMBzH" width="200" height="96" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb4e85fcec90a2a4d13370e3929a0a3f/href">https://medium.com/media/bb4e85fcec90a2a4d13370e3929a0a3f/href</a></iframe><p>For 5 spins, the payouts are 12, 0, 16, 0, and 20, summing to $48 returned out of $50 wagered. The resulting RTP is 0.96, which is quite close to what slot machines are typically calibrated to achieve.</p><p>The winning rate in this case is 3 out of 5, meaning the player wins 60% of the spins, yet still loses $2 over those 5 spins. In the long run, if this RTP remains constant, after more 44 spins the player would be expected to lose the entire initial amount wagered.</p><blockquote>So, Good luck!</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*TSzQKVXesv_sdbnTco2gUQ.gif" /></figure><h4>Coding a Slot Machine in Python and Streamlit</h4><p>Based on what we’ve built so far, here’s a clear way to guide the reader through the code:</p><p>We’ve already covered the core logic behind a slot machine game. Now, it’s time to translate those concepts into a working web application using Python.</p><p>Some parts of the code reuse ideas explained in earlier sections, so they’ll be referenced briefly to avoid unnecessary repetition.</p><p>This section is organized into the following topics:</p><ul><li>Required libraries.</li><li>Initial setup and parameters.</li><li>Game functions.</li><li>Streamlit interface.</li></ul><h4>Required Libraries</h4><p>Below is the complete list of libraries used in this project, organized by their role in the application:</p><pre>import streamlit as st<br><br>import pandas as pd<br>import numpy as np<br><br>import plotly.express as px<br>import matplotlib.pyplot as plt<br>from matplotlib.animation import FuncAnimation, PillowWriter<br>import plotly.graph_objects as go<br><br>from scipy.optimize import minimize<br><br>import random<br>import time<br>import hashlib<br><br>from typing import List, Tuple<br>from collections import Counter</pre><p>Streamlit powers the web interface, handling user input, layout, and real-time interaction.</p><p>Pandas and NumPy support data handling and numerical operations, making it easy to manage game state and calculations.</p><p>Plotly and Matplotlib are used for visualization, Plotly for interactive charts within the app, and Matplotlib for more controlled or animated graphics. SciPy provides optimization tools, useful for tuning parameters and simulations.</p><p>Finally, standard libraries like random (game randomness), time (timing control), and hashlib (deterministic hashing) support core game mechanics.</p><h4>Initial Setup and Parameters</h4><p>We start by defining the symbol system, which represents the core of the slot machine. Each symbol has a name, a visual emoji representation, a payout multiplier, and a probability weight that controls how often it appears.</p><pre><br>SYMBOLS = [&quot;tiger&quot;, &quot;gold&quot;, &quot;clover&quot;, &quot;star&quot;, &quot;seven&quot;, &quot;wild&quot;, &quot;jackpot&quot;]<br>SYMBOL_EMOJI = {&quot;tiger&quot;:&quot;🐅&quot;,&quot;gold&quot;:&quot;💰&quot;,&quot;clover&quot;:&quot;🍀&quot;,&quot;star&quot;:&quot;⭐&quot;,&quot;seven&quot;:&quot;7️⃣&quot;,&quot;wild&quot;:&quot;🎰&quot;,&quot;jackpot&quot;:&quot;💎&quot;}<br>DEFAULT_MULTIPLIERS = {&quot;tiger&quot;: 12, &quot;gold&quot;: 14, &quot;clover&quot;: 16, &quot;star&quot;: 18, &quot;seven&quot;: 25, &quot;wild&quot;: 0, &quot;jackpot&quot;: 0}<br>DEFAULT_WEIGHTS = [5, 5, 5, 5, 1, 0.3, 0.5]<br><br>INITIAL_BALANCE = 1000<br>WINNING_POSITIONS = 10</pre><ul><li>SYMBOLS: defines all possible outcomes in the slot machine, representing the full set of symbols that can appear during a roll.</li><li>SYMBOL_EMOJI: maps each symbol to its visual representation, used to render the interface in a more intuitive and engaging way.</li><li>DEFAULT_MULTIPLIERS: controls the payout value associated with each symbol, directly impacting reward calculation when winning combinations occur.</li><li>DEFAULT_WEIGHTS: defines the probability distribution for each symbol, determining how frequently each outcome appears during random selection.</li><li>INITIAL_BALANCE: sets the starting amount available to the player before any bets are placed or rounds are played.</li><li>WINNING_POSITIONS: defines how many positions are evaluated in the game grid when checking for winning combinations.</li></ul><p>These parameters act as the foundation of the game, ensuring consistency across each run.</p><p>The <em>Wild </em>and <em>Jackpot </em>symbols are special cases: they are reserved to modify gameplay dynamics. The Wild increases the chances of forming winning combinations, while the Jackpot is tied to the highest reward, representing the grand prize for a lucky outcome.</p><p>I previously configured the game to make it fun and balanced to play. This initial configuration can be adjusted by the game owner, depending on the desired experience or difficulty.</p><p>In the next sections, I will show a step-by-step approach to optimize these parameters for a target RTP (Return to Player). For now, we will assume they represent a fair starting point.</p><h4>Game Functions</h4><p>Now, let’s move on to the core functions of the application. We gradually increase in complexity as we proceed.</p><pre>def generate_seed() -&gt; str:<br>    return str(random.random())<br><br>def hash_seed(seed: str) -&gt; str:<br>    return hashlib.sha256(seed.encode()).hexdigest()</pre><p>The first function generate_seed() creates a random value using random.random() and converts it into a string. It simply returns a random number as text.</p><p>The second function hash_seed() takes a seed, encodes it with seed.encode(), and then applies hashlib.sha256() to generate a fixed-length hash. The result is returned as a hexadecimal string using .hexdigest().</p><pre>def spin(seed: str, weights: List[float]) -&gt; List[str]:<br>    rng = random.Random(seed)<br>    return rng.choices(SYMBOLS, weights=weights, k=9)</pre><p>spin() simulates a random &quot;spin&quot; using a controlled seed. It creates a deterministic random generator with random.Random(seed).</p><p>It then uses rng.choices() to select 9 items from SYMBOLS, following the probability distribution defined by weights.</p><p>The result is a list of 9 randomly chosen symbols, in other words, the output of a user interaction with the slot machine.</p><pre>def get_positions(grid: List[List[str]]) -&gt; List[List[str]]:<br>    positions = []<br>    positions.extend(grid)<br>    for col in range(3):<br>        positions.append([grid[row][col] for row in range(3)])<br>    positions.append([grid[i][i] for i in range(3)])<br>    positions.append([grid[i][2-i] for i in range(3)])<br>    positions.append([grid[0][0], grid[1][1], grid[2][0]])<br>    positions.append([grid[0][2], grid[1][1], grid[2][2]])<br>    return positions</pre><p>get_positions() is built to extract all possible winning patterns from a 3x3 grid in a single spin. We can classify these patterns into four groups:</p><ul><li>Vertical lines (V): 3 columns → each column forms one possible line.</li><li>Horizontal lines (H): 3 rows → each row is already included directly from the grid.</li><li>Diagonals (D): 2 main diagonals.</li><li>Triangles (&gt;): 2 additional asymmetric patterns formed by selecting corners with the center.</li></ul><p>So the function collects:</p><ul><li>3 vertical positions by iterating over columns.</li><li>3 horizontal positions directly from the grid.</li><li>2 diagonal positions.</li><li>2 triangular patterns (left and right skewed combinations).</li></ul><p>In total, that results in 10 possible winning positions per spin, represented as different ways of traversing the same 3x3 matrix.</p><p>We now move to the function calculate_payout.</p><pre><br>def calculate_payout(<br>    result: List[str],<br>    bet: float,<br>    multipliers: dict,<br>    size: int,<br>    show_winning_positions: bool = True<br>    ) -&gt; float:<br>    <br>    grid = [result[i:i+size] for i in range(0, size * size, size)]<br>    positions = get_positions(grid)<br>    <br>    bet_per_position = bet / len(positions)<br>    payout = 0.0<br>    winning_positions = []<br><br>    def is_full_line(line, symbol):<br>        return all(s == symbol or s == &quot;wild&quot; for s in line)<br><br>    def evaluate_line(line):<br>        nonlocal payout<br><br>        if line.count(&quot;jackpot&quot;) == len(line):<br>            line_payout = st.session_state.jackpot<br>            payout += line_payout<br>            st.session_state.jackpot = 0<br>            winning_positions.append(f&quot;JACKPOT line = ${line_payout:.2f}&quot;)<br>            return<br><br>        wild_count = line.count(&quot;wild&quot;)<br>        non_wild = [s for s in line if s not in (&quot;wild&quot;, &quot;jackpot&quot;)]<br><br>        if not non_wild:<br>            return<br><br>        unique_symbols = set(non_wild)<br>        line_len = len(line)<br><br>        if len(unique_symbols) == 1:<br>            symbol = non_wild[0]<br>            total_count = non_wild.count(symbol) + wild_count<br><br>            if total_count == line_len:<br>                line_payout = bet_per_position * multipliers.get(symbol, 0)<br>                payout += line_payout<br>                winning_positions.append(f&quot;{symbol} line = {line_payout:.2f}&quot;)<br><br>        elif len(unique_symbols) == 2 and wild_count &gt; 0:<br>            best_payout = 0<br>            best_symbol = None<br><br>            for symbol in unique_symbols:<br>                count = non_wild.count(symbol)<br>                total_count = count + wild_count<br><br>                if total_count == line_len:<br>                    line_payout = bet_per_position * multipliers.get(symbol, 0)<br>                    if line_payout &gt; best_payout:<br>                        best_payout = line_payout<br>                        best_symbol = symbol<br><br>            if best_payout &gt; 0:<br>                payout += best_payout<br>                winning_positions.append(f&quot;{best_symbol} line (with wild) = {best_payout:.2f}&quot;)<br><br>    for line in positions:<br>        evaluate_line(line)<br><br>    if show_winning_positions and winning_positions:<br>        st.write(&quot;Winning positions:&quot;)<br>        for wl in winning_positions:<br>            st.write(f&quot;  {wl}&quot;)<br><br>    return payout</pre><p>This function is responsible for calculating the total payout of a spin in a grid-based slot system. The grid is first reconstructed from the flat result list into a square matrix of dimension size × size, splitting the symbols into rows of equal length.</p><p>All possible winning patterns are extracted through get_positions(grid), which returns every predefined payline, including rows, columns, diagonals, and the additional custom winning configurations introduced earlier.</p><p>The total bet is evenly distributed across all available winning positions, producing the value bet_per_position used during the evaluation of each payline. Since a single spin contains ten possible winning positions, each position receives one tenth of the total wager.</p><p>Each payline is evaluated independently through the nested evaluate_line() function.</p><p>The highest-priority case occurs when an entire line is composed of “jackpot” symbols. In this situation, the accumulated value stored in st.session_state.jackpot is awarded to the player and immediately reset to zero, representing the highest possible payout in the game.</p><p>For regular evaluations, the function separates “wild” symbols from the remaining symbols while ignoring “jackpot” in the standard payout calculation. Lines containing only wilds or jackpot symbols are skipped because they do not define a valid paying combination.</p><p>When a line contains a single non-wild symbol together with optional wild symbols, the function verifies whether the wilds complete the entire line. If they do, the payout is computed using the corresponding value stored in the multipliers dictionary.</p><p>A second case occurs when a line contains exactly two distinct symbols together with one or more wilds. In this situation, both possible winning combinations are evaluated, and the function automatically selects the configuration producing the highest payout. This guarantees that the player always receives the most valuable valid combination.</p><p>After all paylines have been processed, the function optionally displays every winning position together with its corresponding payout whenever show_winning_positions is enabled.</p><p>The accumulated payout for the entire spin is returned.</p><p>play_round() combines all previous components into a single gameplay cycle, executing one complete spin from seed generation to payout calculation.</p><pre>def play_round(bet: float, weights: List[float], multipliers: dict, show_winning_positions: bool = True) -&gt; Tuple[List[str], float, str, str]:<br>    seed = generate_seed()<br>    hashed = hash_seed(seed)<br>    result = spin(seed, weights)<br>    payout = calculate_payout(result, bet, multipliers, size=SIZE)<br>    return result, payout, hashed, seed</pre><p>play_round() starts by generating a random seed using generate_seed(), then creates a secure representation of it with hash_seed(seed).</p><p>It then uses the seed to drive spin(seed, weights), producing the final result, which is the grid outcome based on weighted randomness.</p><p>It calculates the final payout using calculate_payout(), passing the result, bet, multipliers, and the fixed grid SIZE.</p><p>It returns:</p><ul><li>The result (spin outcome).</li><li>The payout (total winnings).</li><li>The hashed seed (for verification).</li><li>And the original seed (for reproducibility).</li></ul><p>For each spin that a user plays, the expected return for the player (RTP) is estimated by dividing the total_payout by the total_bet. However, RTP can also be estimated over repeated trials using the estimate_rtp function, which simulates multiple spins to approximate long-term return behavior.</p><pre>def estimate_rtp(weights: List[float], <br>                 multipliers: dict, <br>                 n_samples: int = 20000, <br>                 bet: float = 1.0) -&gt; float:<br>    returns = []<br>    for _ in range(n_samples):<br>        seed = generate_seed()<br>        result = spin(seed, weights)<br>        payout = calculate_payout(result, bet, multipliers, size=SIZE, show_winning_positions=False)<br>        returns.append(payout)<br>    return np.mean(returns) / bet</pre><p>It simulates many rounds of the game, calculates the average payout from those simulations, and divides it by the bet value. This provides an approximation of the long-term return rate of the game.</p><p>Particularly, it is used to optimize weights and multipliers in the optimize_RTP function, shown below:</p><pre>def optmize_RTP(rtp_target, symbols: List[str],<br>                weight_bounds=(0.1,10.0),<br>                multiplier_bounds=(1.0,50.0),<br>                n_iters=800,<br>                candidates_per_iter=5,<br>                beam_width=5,<br>                step_size=0.1,<br>                default_weights=DEFAULT_WEIGHTS,<br>                default_multipliers=DEFAULT_MULTIPLIERS,<br>                lock_weights=False,<br>                lock_multipliers=False,<br>                lock_wild=True,<br>                lock_jackpot=True):<br><br>    n_symbols = len(symbols)<br><br>    base_w = np.array(default_weights) if default_weights is not None else np.ones(n_symbols)<br>    base_m = np.array(list(default_multipliers.values())) if default_multipliers is not None else np.ones(n_symbols)<br><br>    if not lock_weights:<br>        base_w = base_w / np.sum(base_w)<br><br>    wild_idx = symbols.index(&quot;wild&quot;)<br>    jackpot_idx = symbols.index(&quot;jackpot&quot;)<br><br>    def simulate(w, m):<br>        return estimate_rtp(w, dict(zip(symbols, m)), n_samples=500)<br><br>    def mutate(w, m, scale):<br>        new_w = w.copy()<br>        new_m = m.copy()<br><br>        if not lock_weights:<br>            noise_w = np.random.normal(0, scale, n_symbols)<br>            new_w = new_w * (1 + noise_w)<br>            new_w = np.clip(new_w, weight_bounds[0], weight_bounds[1])<br>            new_w = new_w / np.sum(new_w)<br><br>        if not lock_multipliers:<br>            noise_m = np.random.normal(0, scale, n_symbols)<br>            new_m = np.clip(new_m * (1 + noise_m), multiplier_bounds[0], multiplier_bounds[1])<br><br>        if lock_wild:<br>            new_w[wild_idx] = w[wild_idx]<br>            new_m[wild_idx] = m[wild_idx]<br><br>        if lock_jackpot:<br>            new_w[jackpot_idx] = w[jackpot_idx]<br>            new_m[jackpot_idx] = m[jackpot_idx]<br><br>        return new_w, new_m<br><br>    def evaluate(w, m):<br>        rtp = simulate(w, m)<br>        err = abs(rtp - rtp_target)<br>        return err, rtp<br><br>    beam = []<br>    init_err, init_rtp = evaluate(base_w, base_m)<br>    beam.append((init_err, init_rtp, base_w, base_m))<br><br>    history = []<br><br>    for i in range(n_iters):<br>        candidates = []<br><br>        for err, rtp, w, m in beam:<br>            for _ in range(candidates_per_iter):<br>                w_new, m_new = mutate(w, m, step_size)<br><br>                if lock_weights:<br>                    w_new = w<br>                if lock_multipliers:<br>                    m_new = m<br><br>                err_new, rtp_new = evaluate(w_new, m_new)<br>                candidates.append((err_new, rtp_new, w_new, m_new))<br><br>        candidates.sort(key=lambda x: x[0])<br>        beam = candidates[:beam_width]<br><br>        best_err, best_rtp, best_w, best_m = beam[0]<br>        history.append({<br>            &quot;rtp&quot;: best_rtp,<br>            &quot;error&quot;: best_err<br>        })<br><br>        if best_err &lt; 0.01:<br>            return best_w, best_m, best_rtp, history<br><br>        if i % 50 == 0:<br>            step_size *= 0.9<br><br>    return beam[0][2], beam[0][3], beam[0][1], history</pre><p>It searches for an optimal combination of symbol weights and multipliers that best match a target RTP value.</p><p>It starts by initializing the system with default weights and multipliers, converting them into NumPy arrays. If weights are not locked, they are normalized so that their sum equals 1, ensuring a valid probability distribution across all symbols.</p><p>It identifies the special symbols “wild” and “jackpot” by their indices, since they can optionally be locked during optimization to preserve game balance constraints.</p><p>The process is driven by a simulated evaluation function:<br>simulate(w, m) calls estimate_rtp using 500 simulated samples, returning an empirical RTP based on the current configuration of weights and multipliers.</p><p>To explore the solution space, a mutate function introduces controlled random variations into both weights and multipliers. Gaussian noise is applied, and values are clipped within predefined bounds.</p><p>If weights or multipliers are locked, they remain unchanged. Wild and jackpot symbols can also be explicitly frozen to prevent distortion of core game mechanics.</p><p>This allows controlled variation in the system without drifting away from the original target RTP. A key issue in this optimization is degeneracy: if both weights and multipliers are left fully flexible, the algorithm tends to collapse into a trivial solution.</p><p>In practice, it often converges by fixing one side of the system (for example, making all weights nearly uniform and compensating only through multipliers, or the opposite).</p><p>While this still satisfies the numerical RTP constraint, it undermines the structural integrity of the game design. The optimization effectively reduces the problem to a single adjustable axis, which removes meaningful interaction between symbol frequency and payout design.</p><p>To avoid this behavior, the system introduces controlled restrictions such as parameter locks and bounded perturbations. These constraints force the optimizer to distribute changes across both weights and multipliers instead of over-optimizing a single dimension.</p><p>Additionally, specific symbols like “wild” and “jackpot” can be locked independently to preserve core gameplay mechanics and prevent instability in critical reward paths. This is crucial to make the game more attractive to players and to control how many jackpots are paid by spins.</p><p>Each candidate configuration is evaluated using an error metric defined as the absolute difference between the simulated RTP and the target RTP.</p><p>The optimization itself follows a beam search strategy:</p><ul><li>It maintains a population (beam) of the best configurations.</li><li>At each iteration, it generates multiple mutated candidates per beam element.</li><li>Candidates are ranked by error and only the best ones are kept.</li></ul><p>Over time, the search gradually refines solutions, and the step_size is reduced every 50 iterations to stabilize convergence.</p><p>If a configuration achieves an error below 0.01, the function terminates early and returns the best weights, multipliers, achieved RTP, and full optimization history.</p><p>Finally, if convergence is not reached within the maximum number of iterations, the best configuration found in the beam is returned along with its performance history.</p><pre>def plot_trajectory(all_runs, change_spin=None):<br><br>    fig = go.Figure()<br><br>    colors = px.colors.qualitative.Dark24<br><br>    for i, run in enumerate(all_runs):<br>        fig.add_trace(go.Scatter(<br>            x=list(range(len(run))),<br>            y=run,<br>            mode=&#39;lines&#39;,<br>            name=f&#39;Sim {i+1}&#39;,<br>            opacity=0.85 if i &lt; 5 else 0.5,<br>            line=dict(<br>                width=2 if i &lt; 5 else 1,<br>                color=colors[i % len(colors)]<br>            )<br>        ))<br><br>    if change_spin is not None:<br>        fig.add_vline(<br>            x=change_spin,<br>            line_dash=&quot;dash&quot;,<br>            line_color=&quot;red&quot;,<br>            annotation_text=f&quot;Parameter change at spin {change_spin}&quot;,<br>            annotation_position=&quot;top right&quot;<br>        )<br><br>    fig.update_layout(<br>        title=&quot;Balance Trajectory Over Time&quot;,<br>        xaxis_title=&quot;Spins&quot;,<br>        yaxis_title=&quot;Balance ($)&quot;,<br>        hovermode=&#39;x unified&#39;,<br>        template=&#39;plotly_white&#39;,<br>        legend=dict(<br>            yanchor=&quot;top&quot;,<br>            y=1,<br>            xanchor=&quot;left&quot;,<br>            x=1.02,<br>            borderwidth=1,<br>            font=dict(size=10)<br>        ),<br>        margin=dict(t=50, l=50, r=150, b=50)<br>    )<br><br>    fig.update_xaxes(showgrid=True, gridwidth=0.2)<br>    fig.update_yaxes(showgrid=True, gridwidth=0.2)<br><br>    st.plotly_chart(fig, use_container_width=False)</pre><p>This function visualizes how the player’s balance evolves over time across multiple simulations. It’s used to give a visual representation of multiplay simulations, in section four of this article.</p><p>It receives all_runs, where each run is a list representing balance changes over spins.</p><p>For each run, it adds a line plot using Plotly, where:</p><ul><li>x represents the spin index</li><li>y represents the balance at each spin</li></ul><p>Each simulation is drawn with a different color to allow comparison between trajectories.</p><p>If change_spin is provided, a vertical dashed red line is added to indicate the point where a parameter change happened in the game.</p><p>The result is a visual representation of volatility, risk, and long-term behavior of the game balance over time.</p><h4>Streamlit Integration</h4><p>Streamlit runs the script from top to bottom on every interaction, so we need session_state to persist variables across reruns.</p><p>Each object below is initialized only if it doesn’t already exist, and then Streamlit keeps it stored in memory during the session.</p><p>This setup defines the core state of the slot machine:</p><pre>st.title(&quot;Slot Machine PRO - With Wild &amp; Jackpot&quot;)<br><br>if &quot;weights&quot; not in st.session_state: st.session_state.weights = DEFAULT_WEIGHTS<br>if &quot;multipliers&quot; not in st.session_state: st.session_state.multipliers = DEFAULT_MULTIPLIERS.copy()<br>if &quot;balance&quot; not in st.session_state: st.session_state.balance = INITIAL_BALANCE<br>if &quot;history&quot; not in st.session_state: st.session_state.history = []<br>if &quot;jackpot&quot; not in st.session_state: st.session_state.jackpot = 1000<br>if &quot;jackpot_contribution&quot; not in st.session_state: st.session_state.jackpot_contribution = 0.02<br>if &quot;payouts_multi&quot; not in st.session_state: st.session_state.payouts_multi = []<br>if &quot;rtp_history&quot; not in st.session_state: st.session_state.rtp_history = []<br>if &quot;total_bet&quot; not in st.session_state: st.session_state.total_bet = 0<br>if &quot;total_payout&quot; not in st.session_state: st.session_state.total_payout = 0streamlit integration</pre><p>A quick discussion on the parameters not covered before:</p><p>balance tracks the player’s current money, which increases or decreases after each spin depending on the payout.</p><p>history stores game events over time, recording what happened in each spin.</p><p>jackpot stores the current jackpot pool; it starts at $1,000 and grows by a fraction of each bet placed.</p><p>jackpot_contribution defines how much each bet feeds the jackpot; in this case, 2% of the bet value is added per spin.</p><p>payouts_multi and rtp_history track performance metrics over time.</p><p>total_bet and total_payout accumulate the total amount wagered by the user and the total amount returned by the game.</p><p>Once initialized, these values are automatically preserved and updated through st.session_state, allowing the application to maintain state across reruns instead of resetting every interaction.</p><p>Next we divide our application in 3 distinct tabs:</p><pre>tab_game, tab_sim, tab_opt, = st.tabs([&quot;Game&quot;,&quot;RTP Optimization&quot;,&quot;Monte Carlo Simulation&quot;])</pre><p>used to create a better user experience.</p><p>In tab_game, we render the slot game animation, the current balance, the total jackpot amount, and the action buttons for single spin and multi-spin.</p><pre>with tab_game:<br>    col_jackpot, col_balance = st.columns(2)<br>    with col_jackpot:<br>        st.metric(&quot;💎 JACKPOT&quot;, f&quot;${st.session_state.jackpot:.2f}&quot;)<br>    with col_balance:<br>        st.metric(&quot;💰 BALANCE&quot;, f&quot;${st.session_state.balance:.2f}&quot;)<br><br>    grid_placeholders = []<br>    for _ in range(3):<br>        cols = st.columns(3)<br>        row_placeholders = []<br>        for col in cols:<br>            row_placeholders.append(col.empty())<br>        grid_placeholders.append(row_placeholders)<br><br>    col_buttons = st.columns(3)<br>    with col_buttons[0]:<br>        bet = st.number_input(&quot;Bet&quot;, 1, 500, 10)<br>        spin_clicked = st.button(&quot;Spin&quot;)<br><br>    with col_buttons[1]:<br>        multi_spin_count = st.number_input(<br>            &quot;Number of spins&quot;,<br>            min_value=2,<br>            max_value=1000,<br>            value=10,<br>            key=&quot;multi_spin_count&quot;<br>        )<br>        multi_spin_clicked = st.button(&quot;Multi Spin&quot;)<br><br>    if spin_clicked and st.session_state.balance &gt;= bet:<br>        jackpot_contribution = bet * st.session_state.jackpot_contribution<br>        st.session_state.jackpot += jackpot_contribution<br>        st.session_state.balance -= jackpot_contribution<br><br>        result, payout, seed_hash, seed = play_round(<br>            bet,<br>            st.session_state.weights,<br>            st.session_state.multipliers,<br>            show_winning_positions=True<br>        )<br><br>        delay = 0.03<br><br>        grid_len = SIZE * SIZE<br>        for _ in range(15):<br>            fake = random.choices(SYMBOLS, k=grid_len)<br>            grid_fake = [fake[i:i+SIZE] for i in range(0, grid_len, SIZE)]<br><br>            for i in range(SIZE):<br>                for j in range(SIZE):<br>                    symbol = grid_fake[i][j]<br>                    grid_placeholders[i][j].markdown(<br>                        f&quot;&lt;h1 style=&#39;text-align: center;&#39;&gt;{SYMBOL_EMOJI[symbol]}&lt;/h1&gt;&quot;,<br>                        unsafe_allow_html=True<br>                    )<br><br>            time.sleep(delay)<br>            delay *= 1.1<br><br>        grid_result = [result[i:i+SIZE] for i in range(0, grid_len, SIZE)]<br><br>        for i in range(SIZE):<br>            for j in range(SIZE):<br>                symbol = grid_result[i][j]<br>                grid_placeholders[i][j].markdown(<br>                    f&quot;&lt;h1 style=&#39;text-align: center;&#39;&gt;{SYMBOL_EMOJI[symbol]}&lt;/h1&gt;&quot;,<br>                    unsafe_allow_html=True<br>                )<br><br>        st.write(f&quot;Payout: {round(payout, 2)}&quot;)<br><br>        st.session_state.balance += payout - bet<br>        st.session_state.history.append({<br>            &quot;result&quot;: result,<br>            &quot;payout&quot;: payout,<br>            &quot;seed_hash&quot;: seed_hash,<br>            &quot;seed&quot;: seed<br>        })<br><br>        st.session_state.total_bet += bet<br>        st.session_state.total_payout += payout<br><br>        current_rtp = (<br>            st.session_state.total_payout / st.session_state.total_bet<br>            if st.session_state.total_bet &gt; 0 else 0<br>        )<br>        st.session_state.rtp_history.append(current_rtp)<br><br>    if multi_spin_clicked and st.session_state.balance &gt;= bet:<br>        spins_to_do = multi_spin_count<br><br>        temp_balance = st.session_state.balance<br>        temp_jackpot = st.session_state.jackpot<br><br>        new_history = []<br>        total_bet_this = 0<br>        total_payout_this = 0<br><br>        for _ in range(spins_to_do):<br>            if temp_balance &lt; bet:<br>                break<br><br>            jack_contrib = bet * st.session_state.jackpot_contribution<br>            temp_jackpot += jack_contrib<br>            temp_balance -= jack_contrib<br><br>            result, payout, seed_hash, seed = play_round(<br>                bet,<br>                st.session_state.weights,<br>                st.session_state.multipliers,<br>                show_winning_positions=False<br>            )<br><br>            temp_balance += payout - bet<br><br>            new_history.append({<br>                &quot;result&quot;: result,<br>                &quot;payout&quot;: payout,<br>                &quot;seed_hash&quot;: seed_hash,<br>                &quot;seed&quot;: seed<br>            })<br><br>            total_bet_this += bet<br>            total_payout_this += payout<br><br>        if new_history:<br>            st.session_state.balance = temp_balance<br>            st.session_state.jackpot = temp_jackpot<br><br>            st.session_state.history.extend(new_history)<br><br>            st.session_state.total_bet += total_bet_this<br>            st.session_state.total_payout += total_payout_this<br><br>            current_rtp = (<br>                st.session_state.total_payout / st.session_state.total_bet<br>                if st.session_state.total_bet &gt; 0 else 0<br>            )<br>            st.session_state.rtp_history.append(current_rtp)<br><br>            st.success(f&quot;Completed {len(new_history)} spins.&quot;)<br>            st.rerun()<br><br>    if st.session_state.history:<br>        all_payouts = [h[&quot;payout&quot;] for h in st.session_state.history]<br><br>        col1, col2 = st.columns([2, 1])<br><br>        with col1:<br>            st.write(&quot;Payout Distribution Histogram&quot;)<br>            chart_data = pd.Series([round(p, 1) for p in all_payouts]).value_counts().sort_index()<br>            st.bar_chart(chart_data)<br><br>        with col2:<br>            st.write(&quot;Payout Statistics&quot;)<br>            st.write(f&quot;Total spins: {len(all_payouts)}&quot;)<br>            st.write(f&quot;Average payout: {round(np.mean(all_payouts), 2)}&quot;)<br>            st.write(f&quot;Max payout: {round(np.max(all_payouts), 2)}&quot;)<br>            st.write(f&quot;Min payout: {round(np.min(all_payouts), 2)}&quot;)<br>            st.write(f&quot;Std dev: {round(np.std(all_payouts), 2)}&quot;)<br>            st.write(f&quot;Zero payouts: {sum(1 for p in all_payouts if p == 0)}&quot;)<br><br>            winning_spins = sum(1 for p in all_payouts if p &gt; 0)<br>            st.write(f&quot;Winning spins: {winning_spins} ({round(winning_spins/len(all_payouts)*100, 1)}%)&quot;)<br><br>        if st.session_state.rtp_history:<br>            st.write(&quot;Cumulative RTP Curve&quot;)<br>            rtp_df = pd.DataFrame({<br>                &quot;Spins&quot;: range(1, len(st.session_state.rtp_history)+1),<br>                &quot;RTP&quot;: st.session_state.rtp_history<br>            })<br>            st.line_chart(rtp_df.set_index(&quot;Spins&quot;))<br><br>    else:<br>        st.write(&quot;No spins yet. Press SPIN to start!&quot;)<br><br>    if st.button(&quot;Reset&quot;):<br><br>        st.cache_data.clear()<br>        st.cache_resource.clear()<br><br>        st.session_state.balance = INITIAL_BALANCE<br>        st.session_state.history = []<br>        st.session_state.jackpot = 1000<br>        st.session_state.payouts_multi = []<br>        st.session_state.rtp_history = []<br>        st.session_state.total_bet = 0<br>        st.session_state.total_payout = 0<br><br>        if &quot;weights&quot; in st.session_state:<br>            del st.session_state.weights<br>        if &quot;multipliers&quot; in st.session_state:<br>            del st.session_state.multipliers<br>        if &quot;all_runs&quot; in st.session_state:<br>            del st.session_state.all_runs<br><br>        st.rerun()</pre><p>At the top of the interface, the current jackpot and player balance are displayed as live metrics. These values are continuously read from st.session_state, ensuring they reflect the true game state after every interaction.</p><p>Below that, a 3x3 grid of placeholders is created. This grid acts as the visual canvas for the slot machine, where each cell is dynamically updated during spins to simulate reel movement and final symbol placement.</p><p>The player can interact with the system by setting a bet value and choosing between a single Spin or a Multi Spin operation. These two modes share the same underlying game logic but differ in execution flow and performance cost.</p><p>When a single spin is triggered, a portion of the bet is first allocated to the jackpot via jackpot_contribution, and deducted from the player’s balance. The play_round() function then generates the outcome, including the symbol grid, payout, and cryptographic seed values.</p><p>Before revealing the final result, a short animation plays where random symbols are rapidly displayed in the grid, simulating reel motion. Once the animation ends, the final grid is rendered and the true result is revealed.</p><p>The player’s balance is then updated based on payout - bet, and all relevant state variables such as history, payouts_multi, total_bet, and total_payout are updated. The system also recalculates and stores the cumulative RTP in rtp_history, allowing long-term performance tracking.</p><p>The multi-spin mode executes the same logic repeatedly in a loop, but without UI animation to improve performance. It uses temporary balance and jackpot variables to simulate the full sequence safely before committing changes to st.session_state. At the end of execution, the application is refreshed using st.rerun() to reflect all updates.</p><p>After gameplay, the analytics section visualizes the system’s behavior over time. It includes a payout distribution chart, summary statistics such as mean, variance, and win rate, and a cumulative RTP curve that shows how the game converges over time.</p><p>Finally, the reset functionality restores the entire game state, clearing balance progression, jackpot accumulation, and all historical tracking data, effectively restarting the simulation from its initial configuration.</p><p>To make it easier to follow, below there is a quick video of the application where I simulate individual spins as well as multi-spin runs.</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DFo8mT8bFnMI&amp;type=text%2Fhtml&amp;schema=youtube&amp;display_name=YouTube&amp;src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FFo8mT8bFnMI%3Ffeature%3Doembed" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/728719f0d50757c6e9bb2d25cade3589/href">https://medium.com/media/728719f0d50757c6e9bb2d25cade3589/href</a></iframe><p>As we start slowly with only a few spins, there is a strong effect of luck on whether we make or lose money.<br> <br>As soon as we start adding multispins, the RTP begins to converge toward a previously established configuration, driven by the fixed setup of weights and multipliers.</p><p>If we keep the game running for a sufficient number of spins, the RTP will stabilize below 1, let’s say around 0.96. This means that, over time, all money wagered is expected to be lost, with the house retaining the edge.</p><p>Of course, due to randomness, within a limited number of spins a player can be profitable and even beat the house. However, if they continue playing in an attempt to increase profits, they will eventually return to their starting balance.</p><p>As the risk of ruin starts to kick in, the player may begin to irrationally chase the big wins they experienced before — wins that are, and have always been, rare.</p><blockquote>That is precisely how gambling works: randomness creates the illusion that a few lucky players can make a lot of money, but nothing is said about when a lucky player decides to stop. In reality, for every player who manages to “break the bank,” the house has already made far more money from the losses of everyone else.</blockquote><p>In this game, we don’t even consider the commission, which is a fraction of each bet returned to the house. In other words, it doesn’t matter who wins or loses, as long as the house keeps making money.</p><blockquote>In a way, all the money that enters may eventually leave the system, but the house always keeps the fees.</blockquote><blockquote>So, how does the house always win?</blockquote><p>We intuitively demonstrated that no matter how lucky players are, if the RTP is configured to negative returns, the house will eventually take all the money from a user.</p><p>Now, let’s prove it mathematically by running a multi-player system that simulates the house perspective of the game.</p><p>We achieved that in tab_sim, as depicted below:</p><pre>with tab_sim:<br>    st.write(f&quot;Jackpot pool: ${st.session_state.jackpot:.2f}&quot;)<br>    st.subheader(&quot;Monte Carlo Simulation for Current Weights/Multipliers&quot;)<br><br>    enable_change = st.checkbox(&quot;Change parameters during simulation&quot;)<br><br>    col_change1, col_change2 = st.columns(2)<br>    with col_change1:<br>        change_spin = st.number_input(<br>            &quot;Spin number to change&quot;,<br>            min_value=1,<br>            max_value=50000,<br>            value=1000,<br>            disabled=not enable_change<br>        )<br><br>    with col_change2:<br>        new_rtp_target = st.number_input(<br>            &quot;Target RTP after change&quot;,<br>            min_value=0.5,<br>            max_value=2.0,<br>            value=1.05,<br>            step=0.01,<br>            disabled=not enable_change<br>        )<br><br>    st.checkbox(&quot;Create gif&quot;, key=&quot;create_gifs&quot;)<br><br>    bet = st.number_input(&quot;Simulation Bet&quot;, 1, 500, 10, key=&quot;sim_bet&quot;)<br>    n_rounds = st.number_input(&quot;Rounds per simulation&quot;, 10, 50000, 2000)<br>    n_simulations = st.number_input(&quot;Number of simulations&quot;, 1, 50, 10)<br><br>    if st.button(&quot;Run Simulations&quot;):<br><br>        all_runs = []<br>        event_counter = Counter()<br>        jackpot_events = []<br><br>        initial_weights = st.session_state.weights<br>        initial_multipliers = st.session_state.multipliers<br><br>        new_weights = None<br>        new_multipliers_dict = None<br>        new_rtp_value = None<br><br>        if enable_change:<br>            with st.spinner(f&quot;Optimizing parameters for RTP = {new_rtp_target:.2%}...&quot;):<br><br>                w_opt, m_opt, new_rtp_value, _ = optmize_RTP(<br>                    new_rtp_target,<br>                    SYMBOLS,<br>                    weight_bounds=(0.1, 10.0),<br>                    multiplier_bounds=(1.0, 50.0),<br>                    n_iters=800,<br>                    candidates_per_iter=5,<br>                    beam_width=5,<br>                    default_weights=st.session_state.get(&quot;weights&quot;, DEFAULT_WEIGHTS),<br>                    default_multipliers=st.session_state.get(&quot;multipliers&quot;, DEFAULT_MULTIPLIERS)<br>                )<br><br>                if w_opt is not None:<br>                    new_weights = w_opt<br>                    new_multipliers_dict = dict(zip(SYMBOLS, m_opt))<br>                    st.success(f&quot;New parameters ready. Achieved RTP: {new_rtp_value:.2%}&quot;)<br>                else:<br>                    st.error(&quot;Optimization failed. Running without change.&quot;)<br>                    enable_change = False<br><br>        total_bets_all_sims = 0<br>        total_payouts_all_sims = 0<br>        total_jackpots = 0<br>        total_spins_all_sims = 0<br>        simulations_with_jackpot = []<br><br>        for sim_idx in range(n_simulations):<br><br>            current_weights = np.array(initial_weights)<br>            current_multipliers = dict(initial_multipliers)<br><br>            balance = INITIAL_BALANCE<br>            balances = [balance]<br><br>            change_applied = False<br>            sim_jackpot_count = 0<br>            sim_spins = 0<br>            jackpot_spins = []<br><br>            sim_total_bet = 0<br>            sim_total_payout = 0<br><br>            for spin_num in range(1, n_rounds + 1):<br><br>                if balance &lt; bet:<br>                    break<br><br>                sim_spins += 1<br><br>                if enable_change and not change_applied and spin_num &gt;= change_spin and new_weights is not None:<br>                    current_weights = np.array(new_weights)<br>                    current_multipliers = dict(new_multipliers_dict)<br>                    change_applied = True<br><br>                jack_contrib = bet * st.session_state.jackpot_contribution<br>                st.session_state.jackpot += jack_contrib<br>                balance -= jack_contrib<br><br>                result, base_payout, _, _ = play_round(<br>                    bet,<br>                    current_weights,<br>                    current_multipliers,<br>                    show_winning_positions=False<br>                )<br><br>                payout = base_payout<br><br>                grid = [result[i:i+3] for i in range(0, 9, 3)]<br>                positions = get_positions(grid)<br><br>                jackpot_hit = any(line.count(&quot;jackpot&quot;) == 3 for line in positions)<br>                if jackpot_hit:<br>                    sim_jackpot_count += 1<br>                    jackpot_spins.append(spin_num)<br>                    jackpot_events.append((sim_idx + 1, spin_num))<br><br>                balance += payout - bet<br>                balances.append(balance)<br><br>                sim_total_bet += bet<br>                sim_total_payout += payout<br><br>                key = &quot;&quot;.join(sorted(result))<br>                event_counter[key] += 1<br><br>            all_runs.append(balances)<br>            total_bets_all_sims += sim_total_bet<br>            total_payouts_all_sims += sim_total_payout<br>            total_jackpots += sim_jackpot_count<br>            total_spins_all_sims += sim_spins<br><br>            if sim_jackpot_count &gt; 0:<br>                simulations_with_jackpot.append((sim_idx + 1, sim_jackpot_count, jackpot_spins))<br><br>        max_len = max(len(r) for r in all_runs)<br>        all_runs = [r + [r[-1]] * (max_len - len(r)) for r in all_runs]<br><br>        df = pd.DataFrame(all_runs).T<br>        final_balances = df.iloc[-1]<br><br>        overall_rtp_sim = total_payouts_all_sims / total_bets_all_sims if total_bets_all_sims &gt; 0 else 0<br><br>        initial_rtp = estimate_rtp(initial_weights, initial_multipliers, n_samples=20000, bet=bet)<br><br>        if enable_change and new_rtp_value is not None:<br>            spins_before = change_spin<br>            spins_after = n_rounds - change_spin<br>            rtp_theo_display = (initial_rtp * spins_before + new_rtp_value * spins_after) / n_rounds<br>        else:<br>            rtp_theo_display = initial_rtp<br><br>        jackpot_frequency = total_spins_all_sims / total_jackpots if total_jackpots &gt; 0 else float(&#39;inf&#39;)<br><br>        jackpot_df = pd.DataFrame(jackpot_events, columns=[&quot;simulation&quot;, &quot;spin&quot;])<br><br>        st.dataframe(pd.DataFrame({<br>            &quot;mean_final_balance&quot;: round(final_balances.mean(), 2),<br>            &quot;min&quot;: round(final_balances.min(), 2),<br>            &quot;max&quot;: round(final_balances.max(), 2),<br>            &quot;std&quot;: round(final_balances.std(), 2),<br>            &quot;total_spins&quot;: total_spins_all_sims,<br>            &quot;total_jackpots&quot;: total_jackpots,<br>            &quot;jackpot_frequency&quot;: f&quot;1 in {int(jackpot_frequency)}&quot; if total_jackpots &gt; 0 else &quot;None&quot;,<br>            &quot;initial_rtp&quot;: round(initial_rtp, 4),<br>            &quot;opt_rtp_value&quot;: round(new_rtp_value, 4) if new_rtp_value is not None else round(initial_rtp, 4),<br>            &quot;rtp_theoretical_est&quot;: round(rtp_theo_display, 4),<br>            &quot;rtp_simulation&quot;: round(overall_rtp_sim, 4)<br>        }, index=[0]))<br><br>        st.subheader(&quot;Jackpot Events&quot;)<br>        st.dataframe(jackpot_df)<br><br>        st.session_state.all_runs = all_runs<br>        st.session_state.jackpot_events = jackpot_events<br><br>        plot_trajectory(all_runs, change_spin if enable_change and new_weights is not None else None)l_runs, change_spin if enable_change and new_weights is not None else None)</pre><p>This section runs a Monte Carlo simulation of the game using the current weights and multipliers, allowing us to observe how the system behaves under repeated random outcomes.</p><p>The simulation is built around multiple configurable parameters. It starts by displaying the current jackpot pool and then allows the user to define whether the system should dynamically change parameters during execution.</p><p>If enabled, a target RTP and a spin threshold are used to trigger an optimization step that recalibrates weights and multipliers mid-simulation.</p><p>Each simulation independently initializes the player’s balance and repeatedly executes spins until either the balance is insufficient or the maximum number of rounds is reached.</p><p>During each spin, the bet contributes partially to the jackpot pool, while the remaining amount is used in the gameplay outcome, which is generated based on the current configuration of symbols, weights, and multipliers.</p><p>The system also tracks key financial and statistical metrics such as total bet volume (total_bet), total payouts (total_payout), jackpot occurrences, and balance evolution across all simulations. When jackpot conditions are met, the event is recorded and later aggregated to estimate frequency and distribution patterns.</p><p>At the end of the execution, all simulation trajectories are aligned and analyzed together. This allows us to compute summary statistics such as mean, minimum, maximum, and standard deviation of final balances, as well as empirical RTP derived from observed payouts versus total bets.</p><p>In addition, theoretical RTP values are computed both for the initial configuration and, if applicable, for the dynamically adjusted system. This enables a direct comparison between expected performance and simulated outcomes under stochastic conditions.</p><p>Finally, the results are visualized through balance trajectories over time, optionally marking the point at which parameter changes occur, providing a clear view of how system behavior evolves under both static and adaptive configurations.</p><p>If you run all those steps, Streamlit will render a Monte Carlo Simulation tab as the Video 2, below:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D3SKThOwm8gE&amp;type=text%2Fhtml&amp;schema=youtube&amp;display_name=YouTube&amp;src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F3SKThOwm8gE%3Ffeature%3Doembed" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/691c075b00a19d7d128babe6d66f8b19/href">https://medium.com/media/691c075b00a19d7d128babe6d66f8b19/href</a></iframe><p>Now consider the showed paramegers such as:</p><ul><li>Any initial player bet is set to $10.</li><li>Each simulation runs 2,000 spins.</li><li>The total number of simulations is 10.</li></ul><p>And you may come up with a possible simulation as Figure 3 below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*zDb32jMT2l1beA_Prg0duw.png" /><figcaption>Figure 3. Multiplayer Simulation with a $10 Bet and 2,000 Spins</figcaption></figure><p>We can learn from that figure that, across the 10 simulated games, the balance tends to reach zero around 400 spins. However, some lucky runs, such as Sim 1, are able to temporarily recover losses through short winning streaks.</p><p>We can also observe the effect of the jackpot mechanism (Sim 5), which shifts a losing trajectory into a temporarily winning position, reinforcing the perception that a few players can win significantly while others lose.</p><p>Nevertheless, given enough time, even Sim 5’s final balance converges back toward zero, assuming the RTP remains unchanged throughout the process.</p><p>In general, the system recorded a total of 6,419 spins and 2 jackpot events, resulting in a jackpot frequency of approximately 1 in 3,209 spins.</p><p>Only 2 simulations experienced at least one jackpot occurrence, specifically Sim 5 and Sim 7, each with a single jackpot hit at spins 874 and 319 respectively.</p><p>The final balance distribution shows a mean final balance of $7.02, with values ranging from a minimum of $2.6 to a maximum of $9.8. The standard deviation is $2.4, indicating a moderate dispersion across simulation outcomes.</p><p>From a probabilistic standpoint, the initial RTP and all derived RTP measures remain consistent at approximately 0.8663, confirming that both the theoretical and simulated RTP converge closely.</p><p>The observed RTP from the simulation is 0.8653, which is extremely close to the expected value, reinforcing the stability of the model under repeated trials.</p><p>From this, we can conclude that the system behaves consistently under stochastic conditions, with empirical outcomes closely matching theoretical expectations.</p><p>However, this also highlights the structural asymmetry of the game: over time, the house retains a persistent advantage.</p><blockquote>Finally, does the house always win?</blockquote><blockquote>Yes, it does!</blockquote><blockquote>But how?</blockquote><p>To understand this, we need to look at tab_opt, which searches for the optimal configuration of weights and multipliers, ensuring that the system is tuned in a way that guarantees long-term profitability for the house.</p><pre><br>with tab_opt:<br>    st.subheader(&quot;Adjust game for RTP&quot;)<br>    target_rtp = st.number_input(&quot;Target RTP&quot;, 0.0, 2.0, 0.96, 0.01)<br>    min_weight = st.number_input(&quot;Min weight&quot;, 0.1, 10.0, 0.2)<br>    max_weight = st.number_input(&quot;Max weight&quot;, 0.1, 10.0, 6.0)<br>    min_multiplier = st.number_input(&quot;Min multiplier&quot;, 1.0, 50.0, 1.5)<br>    max_multiplier = st.number_input(&quot;Max multiplier&quot;, 1.0, 50.0, 30.0)<br><br>    if st.button(&quot;Optimize RTP Parameters&quot;):<br>        with st.spinner(&quot;Optimizing parameters...&quot;):<br>            w_opt, m_opt, rtp_achieved, history = optmize_RTP(<br>                target_rtp,<br>                n_symbols=len(SYMBOLS),<br>                weight_bounds=(min_weight, max_weight),<br>                multiplier_bounds=(min_multiplier, max_multiplier),<br>                n_restarts=20<br>            )<br>        <br>        if w_opt is not None: <br>            st.write(&quot;**Optimized Parameters**&quot;)<br>            st.write(f&quot;**Achieved RTP:** {rtp_achieved:.4f}&quot;)<br>            st.write(f&quot;**Target RTP:** {target_rtp:.4f}&quot;)<br>            st.write(f&quot;**Error:** {abs(rtp_achieved - target_rtp):.4f}&quot;)<br>            <br>            results_df = pd.DataFrame({<br>                &#39;Symbol&#39;: SYMBOLS,<br>                &#39;Weight&#39;: [f&#39;{x:.2f}&#39; for x in w_opt],<br>                &#39;Multiplier&#39;: [f&#39;{x:.2f}&#39; for x in m_opt]<br>            })<br>            st.dataframe(results_df, hide_index=True)<br>            <br>            st.session_state.weights = w_opt<br>            st.session_state.multipliers = dict(zip(SYMBOLS, m_opt))<br>    <br>            if history:<br>                df_hist = pd.DataFrame({<br>                    &quot;attempt&quot;: range(1, len(history) + 1),<br>                    &quot;rtp&quot;: [h[&quot;rtp&quot;] for h in history]<br>                })<br><br>                best_idx = (df_hist[&quot;rtp&quot;] - target_rtp).abs().idxmin()<br><br>                fig = px.line(<br>                    df_hist,<br>                    x=&quot;attempt&quot;,<br>                    y=&quot;rtp&quot;,<br>                    markers=True<br>                )<br><br>                fig.add_scatter(<br>                    x=[df_hist.loc[best_idx, &quot;attempt&quot;]],<br>                    y=[df_hist.loc[best_idx, &quot;rtp&quot;]],<br>                    mode=&quot;markers&quot;,<br>                    marker=dict(size=14, color=&quot;gold&quot;, line=dict(width=2, color=&quot;black&quot;)),<br>                    name=f&#39;Best: {df_hist.loc[best_idx, &quot;rtp&quot;]:.3f}&#39;<br>                )<br><br>                fig.add_hline(<br>                    y=target_rtp,<br>                    line_dash=&quot;dash&quot;,<br>                    annotation_text=f&quot;Target: {target_rtp:.3f}&quot;<br>                )<br><br>                fig.add_hrect(<br>                    y0=target_rtp * 0.99,<br>                    y1=target_rtp * 1.01,<br>                    opacity=0.2<br>                )<br><br>                fig.update_layout(<br>                    title=&quot;RTP Optimization Progress&quot;,<br>                    xaxis_title=&quot;Optimization Attempt&quot;,<br>                    yaxis_title=&quot;RTP&quot;<br>                )<br><br>                st.plotly_chart(fig, use_container_width=True)<br>    else:<br>        st.error(&quot;Optimization failed. Try adjusting bounds.&quot;)</pre><p>If a slot game operates legally under national regulations, the RTP must be transparent and clearly presented to players, since it is, after all, a game of chance.</p><p>However, many online platforms operate outside proper regulation, where the house can adjust the RTP dynamically. This can be used to offer higher returns at the beginning and, as the player becomes more engaged, shift the system toward a lower RTP by making high-paying symbols rarer or reducing multipliers.</p><p>This section, tab_opt, is responsible for actively tuning the game configuration in order to match a target RTP.</p><p>The user defines a desired target_rtp, along with constraints for weights and multipliers through min_weight, max_weight, min_multiplier, and max_multiplier. These bounds control the search space in which the optimization algorithm operates.</p><p>Once triggered, the system calls optmize_RTP, which attempts multiple configurations (n_restarts) to find a combination of weights and multipliers that produces an RTP as close as possible to the target. The result includes the optimized parameters (w_opt, m_opt), the achieved rtp_achieved, and a history of attempts.</p><p>If a valid solution is found, the system reports the achieved RTP, compares it to the target_rtp, and displays the absolute error. It also presents a structured view of each Symbol alongside its corresponding Weight and Multiplier.</p><p>The optimized parameters are then persisted into st.session_state.weights and st.session_state.multipliers, meaning all subsequent simulations and game executions will use this updated configuration.</p><p>Additionally, if optimization history is available, the process is visualized over time. Each attempt is plotted against its resulting RTP, highlighting the best approximation found. A reference line marks the target_rtp, along with a tolerance band, making it easy to assess convergence and stability.</p><p>If no valid configuration is found within the defined bounds, the system returns an error, indicating that the search space may need adjustment.</p><p>When rendering it in Streamlit, we come up with Video 3, below:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DCFDE3rNties&amp;type=text%2Fhtml&amp;schema=youtube&amp;display_name=YouTube&amp;src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FCFDE3rNties%3Ffeature%3Doembed" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b54b4338e57a97e1b43851a404cd7831/href">https://medium.com/media/b54b4338e57a97e1b43851a404cd7831/href</a></iframe><p>Now consider, an experiment where:</p><ul><li>We optimize the initial parameters to achieve a positive RTP of 1.05.</li><li>Players are then allowed to play 500 spins under this initial configuration.</li><li>After that, the RTP is re-optimized to a decreasing return, for example 0.95.</li><li>Players then continue for another 500 spins under the new configuration.</li></ul><p>The outcome is shown in Figure 4 below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*oX5yPCcSt_ob9RIYfy31Ww.png" /><figcaption>Figure 4.<strong> </strong>Simulating a Game with a Changing RTP</figcaption></figure><p>What we observe is that, among a small group of players, a significant portion initially becomes profitable, benefiting from the early positive return environment. However, after the parameter shift at 500 spins, the system starts to gradually reverse these gains.</p><p>By the end of 1,000 spins, the distribution of outcomes changes drastically: some players experience full ruin, some return close to their initial balance of $1,000.00, and only a small fraction remains profitable.</p><p>Most importantly, the system naturally drifts toward a state where losses dominate over time. As the process continues, the expected equilibrium is that almost all players eventually lose their gains and return value back to the house.</p><blockquote>Many days of struggle, a few days of glory.</blockquote><blockquote>Well, not for the house.</blockquote><h3>Final Thoughts</h3><p>This article covered the basic concepts of gambling games, explaining how over time the player tends to lose more money than they win.</p><p>It aimed to contextualize the emotions and passions of players, who in moments of euphoria and wins tend to believe that the machine is fair and that luck favors the brave and the bold.</p><p>However, in the long run, uncertainty is structured in a way that returns less than what is wagered, and the player eventually reaches ruin.</p><p>Here we demonstrated that no matter how lucky players are they end up to give all their savings to the house.</p><p>This context raises the question of whether casino games should be permitted in modern society. They function as entertainment, yet mathematically they are structured toward long-term ruin, economically they transfer wealth from many to a few, and politically they can reinforce existing financial power structures.</p><p>These broader implications will be examined in future work on online betting.</p><p>Thanks for reading! If you enjoyed this article, feel free to give it a clap.</p><h4>References</h4><p>WORLD HEALTH ORGANIZATION (WHO). <em>Gambling</em>. Geneva: WHO, 2024. Available at: <a href="https://www.who.int/news-room/fact-sheets/detail/gambling">https://www.who.int/news-room/fact-sheets/detail/gambling</a>. Accessed on: 26 Mar. 2026.</p><p>TECHOPEDIA. <em>Gambling Addiction Statistics 2024</em>. Available at: <a href="https://www.techopedia.com/gambling-addiction-statistics">https://www.techopedia.com/gambling-addiction-statistics</a>. Accessed on: 26 Mar. 2026.</p><p>GROCHOWSKI, John. Double the Luck. <em>SCCG Management</em>, New York, 2025. Available at: <a href="https://sccgmanagement.com/">https://sccgmanagement.com</a>.</p><p>PLAYTECH. Gold Trio Jackpot &amp; Gold Trio 10,000 — Technical Specifications. <em>Gaming Intelligence</em>, London, 2025. Available at: <a href="https://www.gamingintelligence.com/">https://www.gamingintelligence.com</a>.</p><p><a href="https://smzone.com.au/">SMZONE.COM.AU</a>. The Science of Winning: Insights into Online Slot Machine Performance. <a href="https://smzone.com.au/"><em>smzone.com.au</em></a>, Randwick, 2025. Available at: <a href="https://smzone.com.au/">https://smzone.com.au</a>.</p><p>MICROGAMING. Game Provider RTP and Volatility Data. In: <em>Top 5 Game Providers Behind Goldwin Casino’s Exciting Selection</em>. <a href="https://bdvo.org/"><em>bdvo.org</em></a>, 2026. Available at: <a href="https://archive2021.bdvo.org/">https://archive2021.bdvo.org</a>.</p><p>NETENT. Game Provider Technical Documentation. In: <em>Top 5 Game Providers Behind Goldwin Casino’s Exciting Selection</em>. <a href="https://bdvo.org/"><em>bdvo.org</em></a>, 2026. Available at: <a href="https://archive2021.bdvo.org/">https://archive2021.bdvo.org</a>.</p><p>ECOGRA. Testing Standards and RNG Certification. In: <a href="https://eebguide.eu/">eebguide.eu</a>. <em>All Slots New Game Genres To Try This Year</em>, 2026. Available at: <a href="https://eebguide.eu/">https://eebguide.eu</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5f8d14a7718" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/to-bet-or-not-to-bet-that-is-a-math-question-d5f8d14a7718">To Bet Or Not To Bet, That is a Math Question</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[The Greatest Show On Earth In Python]]></title>
            <link>https://levelup.gitconnected.com/the-greatest-show-on-earth-in-python-ad8ae6bc1cc7?source=rss-59d66406fdbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad8ae6bc1cc7</guid>
            <category><![CDATA[genetics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[biology]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Guilherme Ziegler]]></dc:creator>
            <pubDate>Wed, 18 Mar 2026 15:15:51 GMT</pubDate>
            <atom:updated>2026-03-20T11:56:38.708Z</atom:updated>
            <content:encoded><![CDATA[<h4>The dance of the selfish genes — Part 2</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yO0rMjr1wZW_ewIiEtEzfw.png" /><figcaption>Figure 1. Inside the Fishbowl. Adapted from <a href="https://virtualbiologylab.org/ModelsHTML5/PopGenFishbowl/PopGenFishbowl.html"><strong>PopGen Fishbowl</strong></a></figcaption></figure><p>Now that we are done with, let’s say, a semester of population genetics classes, dicucessed in <a href="https://medium.com/python-in-plain-english/the-greatest-show-on-earth-in-python-fac0077a7582">part one</a>, it’s time to have some fun and run a few simulations.</p><p>Before you move forward make sure you are confortable with the concepts of evolution, natural selection, Hardy-Weinberg Principle, selective pressure, mutations and genetic drift. Without them, it is going to be hard to keep up, so maybe revisit part one again.</p><p>Let me introduce the PopGen<strong> </strong>class, which is based on the work available in the virtual lab. I tried to reproduce the effects as faithfully as possible, but you may notice some small differences if you run the<a href="http://PopGen Fishbowl"> lab simulations.</a></p><p>After you’re comfortable with all the code described in the next sections, we’ll simulate life as realistically as possible, following the simulations below:</p><ul><li><strong>Sim 1:</strong> Simulating a single gene under Hardy-Weinberg equilibrium.</li><li><strong>Sim 2:</strong> Simulating a single gene under the effect of natural selection.</li><li><strong>Sim 3:</strong> Simulating a single gene with natural selection and drift.</li><li><strong>Sim 4:</strong> Simulating a single gene with natural selection and drift — early extinction.</li><li><strong>Sim 5</strong>: Simulating a single gene with natural selection, drift and unidirectional mutation.</li><li><strong>Sim 6</strong>: Simulating a single gene with natural selection, drift and mutation for 3 alleles.</li><li><strong>Sim 7:</strong> Simulation two genes populational dynamics all events included</li></ul><h4>The PopGen class</h4><p>Now let’s discuss the face of the PopGen class. For that I will assume you know a bit of python and you are able to install any libraries we need.</p><p>Anyhow, we are mainly dealing with</p><pre># data manipulation<br>import numpy as np<br>import pandas as pd<br><br>#plots<br>import matplotlib.pyplot as plt<br>import plotly.express as px<br><br># creating animated gifts<br>from matplotlib.patches import Patch<br>from matplotlib.animation import FuncAnimation<br></pre><p>Must of PopGen documentation is written in docstrings, but I will discuss some specifics as we advance. I’m also assuming you know how classes work in python, mainly reagarding the selfconstruct.</p><p>Now let’s have a look at how PopGen works:</p><pre>class PopGen:<br>    &quot;&quot;&quot;<br>    A class to simulate population genetics over multiple generations, including<br>    effects such as selection, genetic drift, mutation, founder events, and bottlenecks.<br>    <br>    Args:<br>          num_genes (int): Number of genes in the population.<br>          alleles_per_gene (list, optional): List of alleles for each gene.<br>          alleles_frequency (list, optional): Initial frequency of each allele.<br>          selective_pression (np.array, optional): Array specifying selection strength for each genotype.<br>          generations (int, optional): Number of generations to simulate. Defaults to 1000.<br>          brood_size (int, optional): Number of offspring per mating pair. Defaults to 2.<br>          pop_size (int, optional): Population size per generation. Defaults to 100.<br>          pop_threshold (int, optional): Maximum allowed population size. Defaults to 10000.<br>          brood_size (int, optional): Number of offspring per mating pair. Defaults to 2.<br>          death_rate (float, optional): Probability of death per individual. Defaults to 0.05.<br>          allow_mutation (bool, optional): Enable mutations. Defaults to False.<br>          p_mutation (list, optional): List of mutation probabilities. Defaults to None.<br>          allow_drift (bool, optional): Enable genetic drift. Defaults to False.<br>          founder_prob (float, optional): Probability of a founder event. Defaults to 0.0.<br>          founder_intensity (int, optional): Size of founder population. Defaults to None.<br>          bottleneck_prob (float, optional): Probability of a bottleneck. Defaults to 0.0.<br>          bottleneck_intensity (float, optional): Size during a bottleneck event. Defaults to None.<br>          bottleneck_start (int, optional): Generation when bottleneck may start. Defaults to 5.<br>          bottleneck_prob (float, optional): Probability of a bottleneck. Defaults to 0.0.         <br>          seed (int, optional): Random seed for reproducibility. Defaults to None.<br>        <br>    Internal attributes:<br>        founder_has_occurred (bool): Tracks if a founder event has already occurred.<br>        bottleneck_has_occurred (bool): Tracks if a bottleneck has already occurred.<br>        genotypes (list): List of all possible genotypes.<br>        genotype_frequency (list): Frequency of each genotype in the population.<br>        history (list): Stores population history across generations.<br>        sub_populations (list): Stores subpopulations if needed.<br>    &quot;&quot;&quot;<br>    def __init__(self, <br>         num_genes: int = 1,<br>         alleles_per_gene: list = None, <br>         alleles_frequency: list = None,<br>         selective_pression: np.array = None,               <br>         generations: int = 1000, <br>         founder_intensity: int = None,<br>         founder_prob: float = 0.0, <br>         bottleneck_intensity: float = None,<br>         bottleneck_start: int = 5, <br>         bottleneck_prob = 0.0,<br>         allow_drift: bool = False,<br>         allow_mutation: bool = False,<br>         p_mutation: list = None,<br>         brood_size: int = 2,<br>         pop_size: int = 100,<br>         pop_threshold: int = 10000,<br>         death_rate: float = 0.005,<br>         seed: int = None):</pre><p>For any given population, we must define the number of genes in the population. This can be easily done by setting the parameter num_genes to at least 1. Then we define a list to store both the initial alleles per gene and their frequencies. Naturally, alleles_frequency and alleles_per_gene are of the same length.</p><p>Each gene can experience a distinct selective pressure, represented as a list selective_pressure , a list of arrays each contains the fitness values for all possible genotypes of that gene, defining how selection acts on the population. The size of each array must be equal to the number of alleles that make a gene.</p><p>Next, we need to set the total number of generations the simulation will run, as well as the initial pop_size, both integers. Most biological processes follow a logistic growth pattern, limited by the carrying capacity, pop_threshold.</p><p>To be honest, in this case the population follows a linear growth rate determined by the parameter brood_size, which represents the number of offspring produced by a pair of parents. Also, parents do not form the next generation.</p><p>These parameters are all we need to start a simulation, however there are a couple more parameters that states how evoluation will work. One of the most importants is allow_mutations , a boolean that will decide either the frequencies change from one allele to another.</p><p>If set to True, it will generate automatically rate of mutations. We can define this with the parameter p_mutations , a list of arrays. Again, when passed, the size of each array must be equal to the number of alleles that make a gene.</p><p>Next, we have the parameters that allow the simulation of genetic drift. For starters, allow_drift introduce random noise to the alleles frequency in each genaration, used generally to simulate the effect of randomness.</p><p>The parameter founder_prob defines the probability that a founder event occurs, and founder_intensity specifies the share of the original population that forms the founder population.</p><p>Values close to 1 apply a drastic reduction to the effect size as smaller founder sizes amplify the effects of genetic drift and increase the likelihood of allele fixation or loss in the new population.</p><p>Also, bottleneck_prob represents the probability of a population bottleneck occurring, bottleneck_start indicates the generation when the bottleneck may begin and bottleneck_intensity determines the population size during the bottleneck.</p><p>It works exactly like founder_intensity, however, bottlenecks tend to be more intense than founder effects, as a large part of the population dies. They could also last for more than one generation. Here, for simplicity, we assume bottlenecks and the founder effect act quite similarly.</p><p>Finally, a seed can be used to make any experiment reproducible and maintain consistency while changing a few parameters.</p><p>Before we move forward to populating generations, let’s check the internal variables that store important data as the number of generations progresses:</p><pre>self.genotypes = []  <br>self.genotype_frequency = []<br>self.sim= [] <br><br>if self.seed is not None:<br>  np.random.seed(self.seed)<br><br>self.populate_gen()<br>self.apply_Hardy_Weinberg()</pre><p>The lists genotypes, genotype_frequency, history are used to track different metrics of the population over generations.</p><p>All of them store information as generation goes on, with special regards to sim that saves the overall simulation history, including allele frequencies and other metrics discussed later on.</p><p>Finally, for the initial generation, two important methods are called: populate_gen and apply_Hardy_Weinberg, both described in detail later. The first initializes the simulation by generating the genotypes of the population, while the second computes their corresponding parental (allele) frequencies under Hardy–Weinberg equilibrium.</p><h4>Populating a simulation</h4><p>Now let’s move to the method populate_gen , below, which defines all genotypes considered in population.</p><pre>def populate_gen(self):<br>    &quot;&quot;&quot;<br>    Initializes the genetic population by creating genotypes, allele frequencies, <br>    and fitness matrices for each gene.  <br>    The method performs the following steps:<br>    1. Defines gene names as uppercase letters (A, B, C, ...) based on the number of genes (`self.num_genes`).<br>    2. Initializes `alleles_per_gene` with 2 alleles per gene if not provided.<br>    3. Initializes `alleles_frequency` with random frequencies using a Dirichlet distribution if not provided.<br>    4. For each gene:<br>    - Generates all possible genotypes by combining alleles.<br>    - Classifies each genotype as &quot;Homozygous&quot; or &quot;Heterozygous&quot;.<br>    - Generates a random fitness matrix if `selective_pression` is not defined.<br>    5. Stores the genotypes in `self.genotypes`.<br>    6. Updates `self.selective_pression` and `self.alleles_frequency` with the generated values.<br>    Attributes affected:<br>        self.genotypes (list): List of lists containing genotypes for each gene.<br>        self.alleles_frequency (list): List of allele frequency arrays for each gene.<br>        self.selective_pression (list): List of fitness arrays for each gene.<br>    &quot;&quot;&quot;<br>    gene_names = [chr(65 + i) for i in range(self.num_genes)]<br>    selective_pression = self.selective_pression or []<br>    genotypes_list = []<br>    if self.alleles_per_gene is None:<br>        self.alleles_per_gene = [2 for _ in range(self.num_genes)]<br>    if self.alleles_frequency is None:<br>        self.alleles_frequency = []<br>    for i, gene_name in enumerate(gene_names):<br>        num_alleles = self.alleles_per_gene[i]<br>        genes = [<br>            [f&#39;{gene_name}{a1}{a2}&#39;, &#39;Homozygous&#39; if a1 == a2 else &#39;Heterozygous&#39;]<br>            for a1 in range(1, num_alleles + 1)<br>            for a2 in range(a1, num_alleles + 1)<br>        ]<br>        genotypes_list.append(genes)<br>        if self.selective_pression is None:<br>            fitness_matrix = np.random.uniform(0, 1, size=len(genes))<br>            selective_pression.append(fitness_matrix)<br>        if len(self.alleles_frequency) &lt; self.num_genes:<br>            frequencies = np.random.dirichlet(np.ones(num_alleles))<br>            self.alleles_frequency.append(frequencies)<br>    self.genotypes = genotypes_list<br>    self.selective_pression = selective_pression</pre><p>Mainly, the method atributes a letter to each gene we are trying to populate. Let’s assume that:</p><pre>num_genes = 2<br>alleles_per_gene = [2, 3]<br><br>freq_allele_1 = np.array([0.45, 0.55])<br>freq_allele_2 = np.array([0.3, 0.3, 0.4])<br>alleles_frequency = [freq_allele_1, freq_allele_2]<br><br>selective_pression_gene_1 = np.array([1, 0.95, 0.90]) <br>selective_pression_gene_2 = np.array([0.97, 0.96, 0.5, 1, 0.9, 0.86])<br>selective_pression = [selective_pression_gene_1, selective_pression_gene_2]</pre><p>We have 2 genes, the first gene has 2 alleles, and the second gene has 3 alleles. The allele frequencies for gene 1 are given as a list of two floats summing to 1, and the allele frequencies for gene 2 are given as a list of three floats, also summing to 1.</p><p>When we initialize a population, we assign a letter to each gene and a number to each allele. So, the first gene has 2 alleles, which we label as 1 and 2, giving two different copies for gene A.</p><p>The second gene is labeled B. Since it has 3 alleles, we label them B1, B2, and B3.</p><p>The genotype consists of all possible combinations of the alleles. For gene A, the genotypes are A11, A12, and A22. For gene B, the genotypes are B11, B12, B13, B22, B23, and B33, thefore the final amount of genotypes are given by multipliying the number of alleles per 2.</p><p>Each genotype has a relative fitness compared to the fittest. For gene A, genotype A11 has the highest reproductive success of 1, while the others are expressed relative to it. For gene B, the fittest is B22.</p><p>Also, populate_gen classifies all genotypes in h<em>omozygous </em>and h<em>eterozygous</em>,<em> </em>although this part is simply to easyly keep track of whats is going on.</p><p>The method thus aims to recover the selective pressures, but if selective_pressure is not informed it will be randomly generated by sampling a random number from 0 to 1, where 1 is the fittest and 0 is a letal allele, that is the case when the invidivual does not survive.</p><p>When the initial frequencies are not passed, the dirichlet([2, 1, 1]) distribution generates random probability vectors where the first element tends to have higher probability than the others, while ensuring all values are positive and sum to exactly 1.</p><p>The reason we impose selective pressure is that, without it, the population would remain in Hardy–Weinberg equilibrium, a scenario that could be simulated by setting the selective pressure as a vector of ones for each genotype.</p><p>This causes selection to act equally on all genotypes, thereby maintaining Hardy–Weinberg equilibrium.</p><h4>Evolving</h4><p>Next, we have the soul of our code, which is the method evolve . It controls how the allelic frequencies change over each generation.</p><pre>def evolve(self):<br>    &quot;&quot;&quot;<br>    Simulates the evolution of the population over a specified number of generations.<br><br>    In each generation, the following processes are applied in order:<br>    - Selection<br>    - Founder effect<br>    - Bottleneck effect<br>    - Population update<br>    - Mutation (if allowed)<br>    - Genetic drift (if allowed)<br>    - Population update<br>    - Hardy-Weinberg equilibrium adjustments<br>    - Selection<br><br>    The sim of the population is recorded for each generation, including:<br>    - Allele frequencies<br>    - Genotypes<br>    - Fitness per gene<br>    - Effects of founder and bottleneck events<br>    - Population size<br><br>    &quot;&quot;&quot;<br><br>    for generation in range(1, self.generations + 1):<br>        <br>        self.apply_selection()<br>        self.alleles_frequency, founder_effect = self.apply_populational_effect(<br>            effect_type=&#39;founder&#39;<br>        )<br>        <br>        self.alleles_frequency, bottleneck_effect = self.apply_populational_effect(<br>            effect_type=&#39;bottleneck&#39;,<br>            current_generation=generation<br>        )<br>        <br>        self.update_population()<br>        <br>        if self.allow_drift:<br>            self.alleles_frequency = self.apply_drift()<br>        <br>        if self.allow_mutation:<br>            self.alleles_frequency = self.apply_mutation()<br>        <br>        self.apply_Hardy_Weinberg()<br>        <br>        self.sim.append({<br>            &#39;generation&#39;: generation,<br>            &#39;alleles_frequencies&#39;: [freq.copy() for freq in self.alleles_frequency],<br>            &#39;genotypes&#39;: [genotype for genotype in self.genotypes],<br>            &#39;genotypes_frequencies&#39;: self.genotype_frequency.copy(),<br>            &#39;fitness&#39;: [self.calculate_fitness(i) for i in range(self.num_genes)],<br>            &#39;founder_effect&#39;: founder_effect,<br>            &#39;bottleneck_effect&#39;: bottleneck_effect,<br>            &#39;population_size&#39;: self.pop_size,<br>            &#39;fix_generation&#39;: [<br>                generation if np.any(freq &gt;= 0.999) else None <br>                for freq in self.alleles_frequency<br>            ]<br>        })</pre><p>The evolve method carries within it seven different evolutionary processes that are applied in sequence for each generation.</p><p>First, apply_selection applies natural selection to the current generation, updating genotype and allele frequencies based on fitness differences.</p><p>Next, a founder effect is simulated through apply_populational_effect(effect_type=&#39;founder&#39;), adjusting allele frequencies according to the founder event.</p><p>Then, a bottleneck effect is applied with apply_populational_effect(effect_type=&#39;bottleneck&#39;), accounting for population size reduction in the current generation.</p><p>After these populational effects, update_population updates the population state using the resulting allele frequencies.</p><p>If genetic drift is enabled, apply_drift introduces stochastic fluctuations in allele frequencies.</p><p>If mutation is allowed, apply_mutation modifies allele frequencies according to the mutation rate.</p><p>Finally, apply_Hardy_Weinberg enforces Hardy–Weinberg equilibrium, generating genotype frequencies for the next generation.</p><p>This sequence ensures that all major evolutionary forces are incorporated into each generation. The results of each generation are stored inside sim , a list to keep track of the whole processs.</p><p>Mutations can occur at any time during the life cycle of an individual. In fact, when cells replicate and divide, small errors accumulate at a very low rate.</p><p>In reproductive cells, called gametes, mutations can activate, deactivate, or regulate gene expression, a process that ultimately affects protein production and therefore the structure and function of life.</p><p>Some new combinations of genes make an individual more or less adapted to its environment. If it reproduces more successfully, its newly acquired traits are passed on to the next generation; otherwise, they disappear.</p><blockquote><strong>Remember the mantra born, grow, survive, mate and go on!</strong></blockquote><p>That is exactly what the evolve method implements. First, individuals are born and grow, forming a new generation.</p><p>During this phase, demographic events such as founder effects or population bottlenecks may occur, drastically reducing or reshaping the pool of survivors.</p><p>The surviving individuals then mate, but the resulting genetic composition is no longer neutral: natural selection acts by favoring the relatively fittest individuals under selective pressure.</p><p>Across generations, stochastic forces also play an important role. Genetic drift introduces random fluctuations in allele frequencies, while mutations generate small genetic changes that, when favored by natural selection, can accumulate and drive evolutionary dynamics over time.</p><h4>Keeping track of evolution</h4><p>Since we understood how population evolve, now we must be able to retrieve allellic information over each generation, achieved by the get_allele_frequencies method.</p><pre>def get_allele_frequencies(self, gene_index):<br>    &quot;&quot;&quot;<br>    Calculates the frequencies of each allele for a given gene based on the genotypes <br>    and their respective frequencies. Homozygous genotypes contribute fully to a single <br>    allele, while heterozygous genotypes split their contribution equally between the two alleles. <br>    Frequencies are then normalized so that they sum to one, and the result is stored for the specified gene.<br>    &quot;&quot;&quot;<br>    genotype_frequency = self.genotype_frequency[gene_index]<br>    genotypes = self.genotypes[gene_index]<br>    num_alleles = self.alleles_per_gene[gene_index]<br>    allele_frequencies = np.zeros(num_alleles)<br>    for position, genotype in enumerate(genotypes):<br>        genotype_str = genotype[0]<br>        genotype_count = genotype_frequency[position]<br>        alleles = [int(char) for char in genotype_str if char.isdigit()]<br>        if len(alleles) == 2:<br>            if alleles[0] == alleles[1]:<br>                allele_index = alleles[0] - 1<br>                allele_frequencies[allele_index] += genotype_count<br>            else:<br>                for allele in alleles:<br>                    allele_frequencies[allele - 1] += genotype_count / 2<br>    total = np.sum(allele_frequencies)<br>    if total &gt; 0:<br>        allele_frequencies /= total<br>    self.alleles_frequency[gene_index] = allele_frequencies</pre><p>The get_allele_frequencies calculates the frequencies of each allele for a given gene based on the genotypes and their respective frequencies.</p><p>For each genotype, it identifies the individual alleles and distributes the genotype frequency accordingly:</p><ol><li>homozygous genotypes contribute fully to a single allele</li><li>heterozygous genotypes split their contribution equally between the two alleles.</li></ol><p>After processing all genotypes, the function normalizes the allele frequencies so that they sum 1, ensuring a proper probability distribution.</p><p>Finally, the resulting frequencies are stored for the specified gene, allowing the simulation to track how allelic composition changes over generations.</p><h4>The math of evolution</h4><p>In this section, we discuss the seven methods shown above, each with its own particularities.</p><p>I’ve kept the same order in which they appear in the evolve method. Here, we’ll get a bit more technical with coding than before, so pay close attention!</p><h4>Populational effects</h4><p>To begin, we describe how the apply_populational_effect method operates.</p><pre>def apply_populational_effect(self, effect_type=&#39;founder&#39;, current_generation=None):<br>    &quot;&quot;&quot;<br>    Apply a population-level effect (founder or bottleneck) to allele frequencies.<br>    <br>    This unified function handles both founder effects and bottleneck effects<br>    using the same Wright-Fisher based stochastic sampling approach.<br>    <br>    Parameters<br>    ----------<br>    effect_type : str, default=&#39;founder&#39;<br>        Type of effect to apply: &#39;founder&#39; or &#39;bottleneck&#39;.<br>    current_generation : int, optional<br>        Current generation number (required for bottleneck effect checking).<br>        <br>    Returns<br>    -------<br>    tuple: (updated_allele_frequencies, effect_occurred_flag)<br>        Updated allele frequencies and flag indicating effect occurrence (1) or not (0).<br>        <br>    Notes<br>    -----<br>    - Founder effect: Uses absolute founder_size (e.g., 50 individuals) <br>    to set new population size.<br>    - Bottleneck effect: Uses bottleneck_intensity (fraction that dies, e.g., 0.9 = 90% die) <br>    to calculate new population size.<br>    - Both effects apply Wright-Fisher sampling noise to evolvable alleles.<br>    - Fixed alleles (freq ≥ 0.999) and lost alleles (freq ≤ 0.001) are preserved.<br>    &quot;&quot;&quot;<br>    <br>    if effect_type == &#39;founder&#39;:<br>        # Founder effect uses absolute population size<br>        if self.founder_size is None:<br>            return self.alleles_frequency, 0<br>            <br>        new_pop_size = min(self.pop_size, self.founder_size)<br>        prob = self.founder_prob<br>        has_occurred = self.founder_has_occurred<br>        start_gen = None  # Founder can occur at any generation<br>        <br>    elif effect_type == &#39;bottleneck&#39;:<br>        # Bottleneck effect uses intensity (fraction that dies)<br>        if self.bottleneck_intensity is None:<br>            return self.alleles_frequency, 0<br>            <br>        new_pop_size = max(1, int(self.pop_size * (1 - self.bottleneck_intensity)))<br>        prob = self.bottleneck_prob<br>        has_occurred = self.bottleneck_has_occurred<br>        start_gen = self.bottleneck_start<br>        <br>    else:<br>        raise ValueError(f&quot;Unknown effect type: {effect_type}. Use &#39;founder&#39; or &#39;bottleneck&#39;.&quot;)<br>    <br>    if has_occurred:<br>        return self.alleles_frequency, 0<br>    <br>    if effect_type == &#39;bottleneck&#39; and current_generation is not None:<br>        if current_generation &lt; start_gen:<br>            return self.alleles_frequency, 0<br>    <br>    if np.random.random() &gt; prob:<br>        return self.alleles_frequency, 0<br>    <br>    if effect_type == &#39;founder&#39;:<br>        self.founder_has_occurred = True<br>    else:<br>        self.bottleneck_has_occurred = True<br>    <br>    self.pop_size = new_pop_size<br>    <br>    # Apply Wright-Fisher sampling noise to allele frequencies<br>    new_freqs = []<br>    for allele in self.alleles_frequency:<br>        new_allele = allele.copy()<br>        <br>        # Identify evolvable alleles (not fixed/lost)<br>        mask_evolvable = (allele &gt; 0.001) &amp; (allele &lt; 0.999)<br>        idx_evolvable = np.where(mask_evolvable)[0]<br>        <br>        if len(idx_evolvable) &gt; 0:<br>            p_evolvable = allele[mask_evolvable]<br>            <br>            # Calculate Wright-Fisher sigma for each evolvable allele<br>            N_eff = 2 * self.pop_size  # Diploid population<br>            sigma = np.sqrt(p_evolvable * (1 - p_evolvable) / N_eff)<br>            noise = np.random.normal(0, sigma)<br>            noise = noise - np.mean(noise)<br>            p_perturbed = p_evolvable + noise<br>            p_perturbed = np.clip(p_perturbed, 0, 1)  <br>            <br>            new_allele[mask_evolvable] = p_perturbed<br>            sum_fixed_lost = new_allele[~mask_evolvable].sum()<br>            sum_evolvable = p_perturbed.sum()<br>            <br>            if sum_evolvable &gt; 0:<br>                scaling_factor = (1 - sum_fixed_lost) / sum_evolvable<br>                new_allele[mask_evolvable] = p_perturbed * scaling_factor<br>            else:<br>                new_allele[mask_evolvable] = (1 - sum_fixed_lost) / len(idx_evolvable)<br>        <br>        new_freqs.append(new_allele)<br>    <br>    return new_freqs, 1</pre><p>This unified method is responsible for simulating population-level demographic events that alter allele frequencies, namely founder effects and bottleneck effects, using a Wright–Fisher–based stochastic framework.</p><p>The method receives an argument effect_type, which determines whether a founder or bottleneck effect is applied. If the effect type is set to &#39;founder&#39;, the population reduction is governed by an absolute founder size (self.founder_size).</p><p>In this case, the new population size is defined as the minimum between the current population size and the specified founder size.</p><p>Founder events can occur at any generation and are evaluated probabilistically using self.founder_prob. Each population can experience a founder event only once, as tracked by self.founder_has_occurred.</p><p>When the effect type is &#39;bottleneck&#39;, the population reduction is controlled by self.bottleneck_intensity, which represents the fraction of individuals that die during the event.</p><p>Bottlenecks can only occur after a predefined generation (self.bottleneck_start) and are also restricted to a single occurrence per population, tracked by self.bottleneck_has_occurred.</p><p>As with the founder effect, the occurrence in a given generation is determined probabilistically using self.bottleneck_prob.</p><p>If the demographic event is triggered, the population size is updated accordingly and stochastic sampling noise is applied to allele frequencies following Wright–Fisher assumptions.</p><p>Only evolvable alleles — those with frequencies strictly between 0.001 and 0.999 — are perturbed. Alleles that have reached fixation or have been lost are preserved and remain unchanged throughout the process.</p><p>For evolvable alleles, the method computes allele-specific variance based on the effective population size of a diploid population. Random noise is drawn from a normal distribution with this variance and adjusted to ensure zero net change in total frequency.</p><p>The perturbed frequencies are clipped to remain within valid bounds and rescaled so that the full set of alleles continues to sum to one, while preserving the contribution of fixed and lost alleles.</p><p>Finally, the method returns the updated allele frequencies along with a flag indicating whether a demographic effect occurred.</p><blockquote><strong>Why do small populations dramatically reshape allele frequencies?</strong></blockquote><p>Because genetic drift is modeled as a binomial sampling process (Fisher 1930; Wright, 1931), the change in allele frequency each generation follows directly from the properties of the binomial distribution and is expressed mathematically by the variance of the change in allele frequency:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2FsBtwhW8Cq8LZP7xSnEA76x&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FsBtwhW8Cq8LZP7xSnEA76x" width="200" height="153" frameborder="0" scrolling="no"><a href="https://medium.com/media/96c877b5452ad4179bcbe7e72a246380/href">https://medium.com/media/96c877b5452ad4179bcbe7e72a246380/href</a></iframe><p>where:</p><ul><li><em>Var(Δp)</em> is the variance of the change in allele frequency from one generation to the next. It quantifies how much random genetic drift is expected to shift the allele frequency.</li><li><em>p</em> is the current allele frequency in the population.</li><li><em>1 − p</em><strong> </strong>is<strong> </strong>the complementary allele frequency (the frequency of the alternative allele)</li><li><em>2N</em> is twice the effective population size, where <em>Ne</em> represents the number of individuals that effectively contribute genes to the next generation.</li></ul><p>A smaller N increases genetic drift and therefore increases the variance.</p><p>From the Wright–Fisher drift variance equation, we can derive the standard deviation as:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2Fpnrp3K1Kj9CzhMgRADhha6&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2Fpnrp3K1Kj9CzhMgRADhha6" width="200" height="96" frameborder="0" scrolling="no"><a href="https://medium.com/media/1bf8c21933a34af79d489acc6534b4ac/href">https://medium.com/media/1bf8c21933a34af79d489acc6534b4ac/href</a></iframe><p>In computational simulations, drift is often implemented by adding normally distributed random noise whose magnitude decreases as population size increases:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2FcELhURAacat9kk8reWisZt&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FcELhURAacat9kk8reWisZt" width="200" height="158" frameborder="0" scrolling="no"><a href="https://medium.com/media/21d555bdcbcde43ef3c514ae3c79f23b/href">https://medium.com/media/21d555bdcbcde43ef3c514ae3c79f23b/href</a></iframe><p>Where random noise is added to the allele frequency from a normal distribution with mean 0 and standard deviation <strong>σ</strong>.</p><p>As <strong>σ</strong> increases, we apply a larger standard deviation to a reduced <strong>N</strong>, thereby amplifying the effect.</p><h4>Updating the population</h4><p>Moving on, let’s look at the update_population method, which is quite straightforward to understand:</p><pre>def update_population(self):<br>    &quot;&quot;&quot;<br>    Updates the population size for the next generation based on the survival rate,<br>    reproduction, and a maximum population threshold. Calculates the number of survivors,<br>    forms mating pairs, estimates the number of descendants, and updates `self.pop_size`.<br>    &quot;&quot;&quot;<br>    survivors = int(self.pop_size * (1 - self.death_rate))<br>    pairs = survivors // 2<br>    descendants = pairs * self.brood_size<br>    self.pop_size = min(descendants, self.pop_threshold)</pre><p>The function calculates the number of survivors by subtracting those who randomly die, based on the self.death_rate, from the current population size (self.pop_size).</p><p>Then, mating pairs are formed by dividing the survivors by two, since two parents are needed to produce offspring.</p><p>Next, the number of descendants is calculated for each pair according to the self.brood_size, and the population size is updated, ensuring it does not exceed the self.pop_threshold.</p><p>Because the death rate is random, this method does not directly impact the evolutionary process. Parents still mate randomly, so only the offspring frequencies are required to preserve the population’s evolutionary dynamics.</p><p>This function is particularly useful for tracking self.pop_size over time, helping us observe how founder and bottleneck effects shape the population.</p><p>When populations grow rapidly toward the environmental carrying capacity, they reach a plateau. This means mortality is still occurring, but the offspring produced are enough to maintain the population at that level. Thus, the population reaches its limit, resembling a logistic growth pattern even without explicitly fitting a logistic function</p><p>Next, we turn to the apply_Hardy_Weinberg function, which calculates genotype frequencies for each gene in a population based on their corresponding allele frequencies.</p><pre>def apply_Hardy_Weinberg(self):<br>    &quot;&quot;&quot;<br>    Calculates the genotype frequencies for each gene based on allele frequencies,<br>    applying the Hardy-Weinberg principle. The resulting frequencies are normalized<br>    so that their sum equals 1 and stored in `self.genotype_frequency`.<br>    &quot;&quot;&quot;<br>    self.genotype_frequency = []<br>    for gene_idx, frequencies in enumerate(self.alleles_frequency):<br>        num_alleles = self.alleles_per_gene[gene_idx]<br>        frequencies = np.array(frequencies)<br>        <br>        genotype_frequencies = []<br>        <br>        for i in range(num_alleles):<br>            for j in range(i, num_alleles):<br>                if i == j:<br>                    freq = frequencies[i] * frequencies[j]<br>                else:<br>                    freq = 2 * frequencies[i] * frequencies[j]<br>                genotype_frequencies.append(freq)<br>        <br>        genotype_frequencies = np.array(genotype_frequencies)<br>        total = genotype_frequencies.sum()<br>        if total &gt; 0:<br>            genotype_frequencies /= total<br>            <br>        self.genotype_frequency.append(genotype_frequencies)</pre><p>This method applies the principles of the Hardy-Weinberg equilibrium, which states that allele and genotype frequencies in a population will remain constant from generation to generation in the absence of evolutionary influences.</p><p>For each gene, the function first retrieves the number of alleles (num_alleles) and the corresponding allele frequencies (frequencies).</p><p>Next, the function generates all possible genotype combinations. It iterates through each pair of alleles, calculating the genotype frequency as follows:</p><ol><li>For homozygous genotypes, the frequency is the square of the allele frequency.</li><li>For heterozygous genotypes, the frequency is doubled to account for the two possible allele arrangements.</li></ol><p>All genotype frequencies for a gene are collected into a list and then converted into a NumPy array.</p><p>After calculating the raw genotype frequencies, the function normalizes them by dividing each frequency by the total sum. This ensures that the sum of all genotype frequencies for a gene equals 1.</p><p>Finally, the normalized genotype frequencies are appended to the class attribute self.genotype_frequency, creating a structured representation of genotype distributions across all genes.</p><p>As we discussed, the frequencies produced by this method are theoretical and do not represent a real evolutionary process. However, they are important to ensure that the proportion of genotypes is preserved in the next generation.</p><p>Now, let’s check how natural selection affects allelic frequencies over time by analyzing the apply_selectionmethod.</p><pre>def apply_selection(self):<br>    &quot;&quot;&quot;<br>    Apply natural selection to the population by updating genotype and allele frequencies.    <br>    For each gene:<br>    1. The genotype frequencies are multiplied by the corresponding fitness values <br>       from the selective pressure matrix.<br>    2. The result is normalized by the mean fitness to ensure frequencies sum to 1.<br>    3. The updated genotype frequencies are stored.<br>    4. Allele frequencies are recalculated from the new genotype frequencies.<br>    This process models how selection changes the genetic composition of the population<br>    over time, favoring genotypes with higher fitness.<br>    &quot;&quot;&quot;<br>    for i in range(len(self.alleles_frequency)):<br>        genotype_frequency = self.genotype_frequency[i]<br>        fitness_matrix = self.selective_pression[i]<br>        # Calculate mean fitness<br>        w_bar = np.sum(genotype_frequency * fitness_matrix)<br>        if w_bar &lt; 1e-10:<br>            # Avoid division by zero if mean fitness is extremely low<br>            continue<br>        # Apply selection and normalize<br>        genotype_freq_selected = (genotype_frequency * fitness_matrix) / w_bar<br>        self.genotype_frequency[i] = genotype_freq_selected<br>        # Update allele frequencies based on selected genotypes<br>        self.get_allele_frequencies(i)</pre><p>This function applies natural selection to the population. For each gene (indexed by i), it first multiplies the genotype frequencies (self.genotype_frequency[i]) by the corresponding fitness values from the selective pressure matrix (self.selective_pression[i]). This step models the advantage or disadvantage of each genotype.</p><p>Next, the product is normalized by the mean fitness (w_bar) to ensure the updated genotype frequencies sum to 1. The resulting genotype frequencies (genotype_freq_selected) are then stored back in self.genotype_frequency[i].</p><p>Finally, the allele frequencies for the gene are recalculated by calling self.get_allele_frequencies(i). This process simulates how selection gradually changes the genetic composition of the population, favoring genotypes with higher fitness and reshaping the distribution of alleles over time.</p><p>Next, we discuss the method calculate_fitness, which helps us track how the overall fitness of each allele changes from one generation to the next.</p><pre>def calculate_fitness(self, gene_index):<br>    &quot;&quot;&quot;<br>    Calculates the average fitness of each allele for a given gene based on genotype frequencies<br>    and the selective pressures acting on each genotype. The method considers how each allele<br>    contributes to the fitness of the genotypes it is part of and returns the mean fitness per allele.  <br>    Parameters:<br>    - gene_index (int): Index of the gene for which allele fitness is being calculated.<br>    Returns:<br>    - allele_avg_fitness (np.ndarray): Array containing the average fitness of each allele.<br>    &quot;&quot;&quot;<br>    genotype_frequency = self.genotype_frequency[gene_index]<br>    fitness_matrix = self.selective_pression[gene_index]<br>    genotypes = self.genotypes[gene_index]<br>    num_alleles = self.alleles_per_gene[gene_index]<br>    <br>    allele_fitness = np.zeros(num_alleles)<br>    allele_counts = np.zeros(num_alleles)<br>    <br>    for idx, genotype in enumerate(genotypes):<br>        alleles = [int(char) for char in genotype[0] if char.isdigit()]<br>        freq = genotype_frequency[idx]<br>        fit = fitness_matrix[idx]<br>        <br>        for allele in alleles:<br>            allele_index = allele - 1<br>            allele_fitness[allele_index] += freq * fit<br>            allele_counts[allele_index] += freq<br>    <br>    allele_avg_fitness = np.zeros(num_alleles)<br>    for i in range(num_alleles):<br>        if allele_counts[i] &gt; 1e-6: <br>            allele_avg_fitness[i] = allele_fitness[i] / allele_counts[i]<br>        else:<br>            allele_avg_fitness[i] = 0  <br>    <br>    return allele_avg_fitnes</pre><p>It evaluates how natural selection affects allelic frequencies by calculating the average fitness of each allele for a specific gene (gene_index).</p><p>It starts by retrieving the genotype frequencies (self.genotype_frequency[gene_index]), the fitness values for each genotype (self.selective_pression[gene_index]), and the list of genotypes (self.genotypes[gene_index]). It also determines the number of alleles for the gene (self.alleles_per_gene[gene_index]).</p><p>For each genotype, the function extracts the alleles and calculates their contribution to fitness. Each allele accumulates the product of the genotype’s frequency (genotype_frequency[idx]) and its fitness (fitness_matrix[idx]).</p><p>The function also keeps track of how often each allele appears, storing this in allele_counts.</p><p>Finally, the function computes the average fitness for each allele by dividing the total fitness contribution by the allele count.</p><p>If an allele does not appear in any genotype, its average fitness is set to 0. The resulting array, allele_avg_fitness, represents how strongly selection favors or disfavors each allele in the current generation.</p><blockquote><strong>Why do we count the times an allele appear?</strong></blockquote><p>This step is crucial for normalizing the results so that they make evolutionary sense. In the PopGen class, we process the population genotype by genotype. I chose this approach because it is easier to explain the underlying biological processes.</p><p>However, the calculation could also be written in terms of a genotype matrix. In that case, we would need to explicitly account for the contribution of each genotype to each allele.</p><blockquote><strong>How does calculating allele fitness differ from applying selection to change the allelic frequencies?</strong></blockquote><p>Allele frequencies and allele fitness are related, but they measure different aspects of the population.</p><p>Allele frequencies show how common each allele is in the population at a given generation. They reflect the result of selection, drift, and other processes, but they don’t tell you directly how advantageous each allele is.</p><p>Allele fitness, on the other hand, combines the genotype frequencies with the fitness values of each genotype. It measures how much each allele contributes to reproductive success, giving a direct view of its adaptive value in that generation.</p><p>In short, frequencies tell you how many alleles are present, while fitness tells you how well each allele performs under selection.</p><p>Of course, allele frequencies increase when the genotypes containing them are positively selected by natural selection, considering no other forces are involved.</p><p>Next, we move to mutations, personally one of my favourite fields in evolution.</p><pre><br>def apply_mutation(self):<br>    &quot;&quot;&quot;<br>    Apply mutations to allele frequencies using mutation matrix M.<br>    <br>    Equation: f&#39; = f × M, where f is allele frequencies vector.<br>    <br>    Parameters<br>    ----------<br>    alleles_frequency : list of arrays<br>        Current allele frequencies per gene.<br>    p_mutation : list of 2D arrays, optional<br>        Mutation matrices per gene. Two formats accepted:<br>        <br>        1. Complete transition matrix (rows sum to 1):<br>        [[0.999, 0.001], # allele 1: stays 0.999, mutates to 2: 0.001<br>        [0.002, 0.998]]  # allele 2: mutates to 1: 0.002, stays 0.998<br>        <br>        2. Mutation rate matrix (diagonal = 0):<br>        [[0.000, 0.001], # allele 1 → allele 2 rate = 0.001<br>        [0.002, 0.000]]  # allele 2 → allele 1 rate = 0.002<br>        <br>        If None, creates random small mutation rates.<br><br>    Returns<br>    -------<br>    list of numpy arrays<br>        Updated allele frequencies after mutation.<br>    &quot;&quot;&quot;<br>    new_freqs = []<br>    <br>    for gene_idx, freqs in enumerate(self.alleles_frequency):<br>        freqs = np.array(freqs).copy()<br>        n_alleles = len(freqs)<br>        <br>        if self.p_mutation is None:<br>            # Create random mutation matrix with small rates<br>            M = np.random.uniform(0.001, 0.01, (n_alleles, n_alleles))<br>            np.fill_diagonal(M, 0)  # Make diagonal 0 for rate matrix<br>        else:<br>            M = np.array(self.p_mutation[gene_idx], dtype=float)<br>            <br>            if M.shape != (n_alleles, n_alleles):<br>                raise ValueError(f&quot;Matrix shape {M.shape} doesn&#39;t match {n_alleles} alleles&quot;)<br>            <br>            if np.any(M &lt; 0):<br>                raise ValueError(&quot;Mutation probabilities cannot be negative&quot;)<br>        <br>        # Convert rate matrix (diagonal=0) to transition matrix<br>        if np.allclose(np.diag(M), 0, atol=1e-10):<br>            M = M.copy()<br>            for i in range(n_alleles):<br>                total_mut_rate = M[i].sum()<br>                if total_mut_rate &lt;= 1:<br>                    M[i, i] = 1 - total_mut_rate<br>                else:<br>                    M[i] = M[i] / total_mut_rate<br>                    M[i, i] = 1 - M[i].sum() + M[i, i]<br>        else:<br>            # Ensure rows sum to 1<br>            row_sums = M.sum(axis=1)<br>            if not np.allclose(row_sums, 1, atol=1e-10):<br>                M = M / row_sums[:, np.newaxis]<br>        <br>        # Apply mutation: f&#39; = f × M<br>        new_freq = freqs @ M<br>        <br>        total = new_freq.sum()<br>        if total &gt; 1e-10:<br>            new_freq = new_freq / total<br>        else:<br>            new_freq = freqs.copy()<br>        <br>        new_freqs.append(new_freq)<br>    <br>    return new_freqs</pre><p>The function aplly_mutation checks either the parameter p_mutationwas passed when the simulation started. As described above when explaing the evolve method, it’s a list of lists, each one containing the probabilities of one allele changing to another and vice-versa.</p><p>To clarify, let’s consider a genotype with genes A and B. The gene A has 2 alleles while gene B has 3 copies of them.</p><p>The param p_mutation should be passed as a matrix representation of all possible mutations, equation 4.</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2FcGP7HnfTap9morYF1Xgb1j&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FcGP7HnfTap9morYF1Xgb1j" width="200" height="251" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad7501f2aa28de18ac141273f49aef32/href">https://medium.com/media/ad7501f2aa28de18ac141273f49aef32/href</a></iframe><p>Thus, for gene B, the element in row 3 and column 2 represents the probability that allele 3 mutates to allele 2.</p><p>Note, however, that the diagonal is always 0 because the probability of an allele changing into itself is null.</p><p>Well, this is essentially a trick to avoid typing large and complicated matrices.</p><p>In practice, we use a transition matrix to compute the effect of mutations, where the diagonal zeros are replaced by one minus the probability of an allele changing into any other allele, as shown in Equation 5 below.</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2FwZKZs4HB2QQupYg7c28hss&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FwZKZs4HB2QQupYg7c28hss" width="200" height="160" frameborder="0" scrolling="no"><a href="https://medium.com/media/39ad9b1df560687c71c16b8c20408970/href">https://medium.com/media/39ad9b1df560687c71c16b8c20408970/href</a></iframe><p>In code, the matrices are represented as a list of arrays:</p><pre>p_mutation = [<br>    # Gene A (2 alleles) — mutation rate matrix<br>    [<br>        [0.0,   0.001],<br>        [0.002, 0.0  ]<br>    ],<br>    # Gene A — transition matrix<br>    #   [0.999, 0.001],<br>    #   [0.002, 0.998]<br><br>    # Gene B (3 alleles) — mutation rate matrix<br>    [<br>        [0.0,   0.003, 0.002],<br>        [0.001, 0.0,   0.004],<br>        [0.002, 0.003, 0.0  ]<br>    ]<br>]<br><br>    # Gene B — transition matrix<br>    #   [0.995, 0.003, 0.002],<br>    #   [0.001, 0.995, 0.004],<br>    #   [0.002, 0.003, 0.995]<br><br></pre><p>Taking gene A as an example, the remaining probability in the first row (diagonal element) is given by one minus the probability of allele 1 mutating into allele 2 (<em>p12</em>), thus 0.999.</p><p>Loaking at Gene B, there is a 0.2% chance allele 3 mutates to allele 1 (<em>p31</em>) and a 0.2% of chance that it mutates to allele 2 (<em>p32</em>). Therefore, the zero in diagonal [3, 3] assumes the value of 0.995.</p><p>If the user does not provide p_mutation, the function generates small random probabilities between 0.001 and 0.005 to all alleles, so that the effect of mutation, when allowed by self.allow_mutation is random.</p><p>After all mutation events are applied, the function normalizes the allele frequencies so that they sum to one. The updated frequencies for each gene are then added to the list of new frequencies.</p><p>Mutations can reintroduce alleles into populations that were previously fixed. Therefore, if the newly generated frequencies for any gene fall below the 99.9% threshold, this can trigger another fixation process over subsequent generations.</p><blockquote><strong>Keep mutation rate low otherwise your population will perform a lively dance.</strong></blockquote><p>We also allow some random noise to be applied in each generation. This logic is implemented in the apply_drift method below:</p><pre>def apply_drift(self, alleles_frequency):<br>    &quot;&quot;&quot;<br>    Apply genetic drift to the population, but do not alter alleles that are fixed (1) or lost (0).  <br>    Parameters<br>    ----------<br>    alleles_frequency : list of np.arrays<br>        Current allele frequencies for each gene.<br>    Returns<br>    -------<br>    list of np.arrays<br>        Updated allele frequencies after applying drift.<br>    &quot;&quot;&quot;<br>    new_freqs = []<br>    for allele in alleles_frequency:<br>        if np.any((allele &gt; 0.001) &amp; (allele &lt; 0.999)):<br>            counts = np.random.multinomial(self.pop_size, allele) + 1e-9<br>            new_freq = counts / counts.sum()<br>        else:<br>            new_freq = allele.copy()<br>        new_freqs.append(new_freq)<br>    return new_freqs</pre><p>that simulates genetic drift, an additional noise added to the allelic frequencies.</p><p>The function goes through each gene one by one. If a gene has not reached fixation, it applies drift by randomly sampling new allele counts from a multinomial distribution, using the population size (self.pop_size) and the current allele frequencies as probabilities.</p><p>A very small number (1e-9) is added to avoid zero frequencies, and then the counts are normalized so that they sum to one.</p><p>If a gene is already fixed, its allele frequencies are left unchanged and simply copied to the new list.</p><p>Since drift acts as random noise added to allele frequencies, once a gene is fixed, the effect of drift is null.</p><blockquote><strong>Why do we apply noise to the simulation?</strong></blockquote><p>This is mainly a matter of style. Without it, the plots would look overly smooth, resembling a denoised series rather than showing the natural fluctuations of the population.</p><p>Therefore we add it so that the whole simulation process looks like more natural.</p><p>In fact, when population is small drift can change frequencies in a way that natural selection can not compete, and that’s fun to show.</p><p>To conclude the PopGen class, there are a few methods that handle plotting the simulation. Since they are not essential from a genetic perspective, I will simply list them below without detailed explanations.</p><pre>def plot_frequencies(self):<br>    &quot;&quot;&quot;<br>    Plot the evolution of allele frequencies for all genes in the population sim.  <br>    This method calls `_plot_single_population` with the full sim of the population <br>    and the title &quot;Original Population&quot;. It visualizes how each allele&#39;s frequency changes <br>    over generations.<br>    &quot;&quot;&quot;<br>    self._plot_single_population(self.sim, &quot;Original Population&quot;)<br><br>def _plot_single_population(self, sim, title):<br>    &quot;&quot;&quot;<br>    Plot allele frequencies over generations for each gene.<br>    Parameters<br>    ----------<br>    sim : list of dicts<br>        The historical data of the population, where each entry contains:<br>        - &#39;generation&#39;: the generation number<br>        - &#39;frequencies&#39;: a list of allele frequencies for each gene<br>        - &#39;genotypes&#39;: optional list of genotype labels<br>    title : str<br>        The title for the plot.<br>    Notes<br>    -----<br>    - Each gene is plotted separately.<br>    - The plot uses Plotly Express line charts with alleles distinguished by color.<br>    - Y-axis is fixed between 0 and 1.<br>    &quot;&quot;&quot;<br>    generations = [entry[&#39;generation&#39;] for entry in sim]<br>    for gene_idx in range(len(sim[0][&#39;frequencies&#39;])):<br>        alleles_frequency = np.array([entry[&#39;frequencies&#39;][gene_idx] for entry in sim])<br>        genotypes = sim[0][&#39;genotypes&#39;][gene_idx]<br>        gene_name = genotypes[0][0]<br>        num_alleles = self.alleles_per_gene[gene_idx]<br>        allele_labels = [f&#39;{gene_name[0]}{i + 1}&#39; for i in range(num_alleles)]<br>        df = pd.DataFrame({<br>            &#39;Generation&#39;: np.repeat(generations, num_alleles),<br>            &#39;Allele&#39;: np.tile(allele_labels, len(generations)),<br>            &#39;Frequency&#39;: alleles_frequency.flatten()<br>        })<br>        fig = px.line(df, x=&#39;Generation&#39;, y=&#39;Frequency&#39;, color=&#39;Allele&#39;,<br>                    title=f&#39;{title} - Allele Frequencies&#39;,<br>                    range_y=[0, 1])<br>        fig.show()<br><br>def plot_population_size(self):<br>    &quot;&quot;&quot;<br>    Plot the total population size over generations.<br>    Notes<br>    -----<br>    - The method uses Plotly Express line charts.<br>    - X-axis represents generations, Y-axis shows the population size.<br>    &quot;&quot;&quot;<br>    df = pd.DataFrame({<br>        &#39;Generation&#39;: [h[&#39;generation&#39;] for h in self.sim],<br>        &#39;Population Size&#39;: [h[&#39;population_size&#39;] for h in self.sim]<br>    })<br>    fig = px.line(df, x=&#39;Generation&#39;, y=&#39;Population Size&#39;,<br>                title=&#39;Population Size Over Generations&#39;)<br>    fig.show()<br><br>def get_sim(popgen):<br>    &quot;&quot;&quot;<br>    Returns the population simulation as a DataFrame, including for each gene <br>    the generation in which it first became fixed (or None if never fixed).<br>    Parameters<br>    ----------<br>    popgen : PopGen<br>        Instance of the PopGen class after simulation.<br>    Returns<br>    -------<br>    pd.DataFrame<br>        DataFrame with columns: generation, genotypes, frequencies, <br>        fitness, founder_effect, bottleneck_effect, population_size, fix_generation.<br>    &quot;&quot;&quot;<br>    num_genes = len(popgen.alleles_frequency)<br>    first_fix_gen = [None] * num_genes<br>    rows = []<br>    for entry in popgen.sim:<br>        freqs = [np.round(freq, 4).tolist() for freq in entry[&#39;frequencies&#39;]]<br>        fitness = [np.round(fit, 4).tolist() for fit in entry[&#39;fitness&#39;]]<br>        genotypes = [[g[0] for g in gene_list] for gene_list in entry[&#39;genotypes&#39;]]<br>        fix_gen = []<br>        for i, freq in enumerate(entry[&#39;frequencies&#39;]):<br>            if first_fix_gen[i] is None and np.any(freq &gt;= 0.999):<br>                first_fix_gen[i] = entry[&#39;generation&#39;]<br>            elif first_fix_gen[i] is not None and np.any((freq &gt; 0) &amp; (freq &lt; 1)):<br>                pass<br>            fix_gen.append(first_fix_gen[i])<br>        rows.append({<br>            &#39;generation&#39;: entry[&#39;generation&#39;],<br>            &#39;genotypes&#39;: genotypes,<br>            &#39;frequencies&#39;: freqs,<br>            &#39;fitness&#39;: fitness,<br>            &#39;founder_effect&#39;: entry.get(&#39;founder_effect&#39;, None),<br>            &#39;bottleneck_effect&#39;: entry.get(&#39;bottleneck_effect&#39;, None),<br>            &#39;population_size&#39;: entry.get(&#39;population_size&#39;, None),<br>            &#39;fix_generation&#39;: fix_gen<br>        })<br>    sim_df = pd.DataFrame(rows)<br>    return sim_df<br><br>def create_allele_and_population_gif(self, filename=&quot;allele_and_population.gif&quot;):<br>    import matplotlib.pyplot as plt<br>    from matplotlib.animation import FuncAnimation<br>    from matplotlib.patches import Patch<br>    import numpy as np<br>    fig = plt.figure(figsize=(3.5*self.num_genes + 4, 4.5))<br>    gs = fig.add_gridspec(1, self.num_genes + 1, width_ratios=[4]*self.num_genes + [5])<br>    axes = [fig.add_subplot(gs[0, i]) for i in range(self.num_genes + 1)]<br>    gene_colors = [<br>        plt.cm.viridis(np.linspace(0, 1, len(self.sim[0][&#39;frequencies&#39;][i])))<br>        for i in range(self.num_genes)<br>    ]<br>    for gene_idx in range(self.num_genes):<br>        colors = gene_colors[gene_idx]<br>        legend_patches = [Patch(facecolor=colors[i], label=f&quot;A{i+1}&quot;) for i in range(len(colors))]<br>        axes[gene_idx].legend(handles=legend_patches, title=&quot;Alleles&quot;, loc=&quot;upper right&quot;, fontsize=8)<br>    def update(frame):<br>        entry = self.sim[frame]<br>        generation = entry[&#39;generation&#39;]<br>        for gene_idx, freqs in enumerate(entry[&#39;frequencies&#39;]):<br>            ax = axes[gene_idx]<br>            ax.clear()<br>            bottom = 0<br>            colors = gene_colors[gene_idx]<br>            for allele_idx, freq in enumerate(freqs):<br>                ax.bar(1, freq, bottom=bottom, color=colors[allele_idx], alpha=0.85)<br>                bottom += freq<br>            ax.set_xlim(0.5, 1.5)<br>            ax.set_ylim(0, 1)<br>            ax.set_xticks([1])<br>            ax.set_xticklabels([chr(65 + gene_idx)], fontsize=12, fontweight=&#39;bold&#39;)<br>            ax.set_title(f&quot;Gene {chr(65 + gene_idx)} Generation {generation}&quot;, fontsize=12, fontweight=&#39;bold&#39;)<br>            ax.set_ylabel(&quot;Freq&quot;, fontsize=10)<br>            ax.grid(True, alpha=0.3)<br>            legend_patches = [Patch(facecolor=colors[i], label=f&quot;{i+1}&quot;) for i in range(len(colors))]<br>            ax.legend(handles=legend_patches, title=&quot;Alleles&quot;, loc=&quot;upper right&quot;, fontsize=8)<br>        ax_pop = axes[-1]<br>        ax_pop.clear()<br>        gens = [h[&#39;generation&#39;] for h in self.sim[:frame+1]]<br>        pops = [h[&#39;population_size&#39;] for h in self.sim[:frame+1]]<br>        ax_pop.plot(gens, pops, color=&#39;tab:blue&#39;, marker=&#39;o&#39;)<br>        ax_pop.set_xlim(0, self.sim[-1][&#39;generation&#39;])<br>        ax_pop.set_ylim(0, max([h[&#39;population_size&#39;] for h in self.sim])*1.1)<br>        ax_pop.set_xlabel(&quot;Generation&quot;, fontsize=10)<br>        ax_pop.set_ylabel(&quot;Population&quot;, fontsize=10)<br>        ax_pop.set_title(&quot;Population Size&quot;, fontsize=12, fontweight=&#39;bold&#39;)<br>        ax_pop.grid(True, alpha=0.3)<br>    anim = FuncAnimation(fig, update, frames=len(self.sim), interval=250)<br>    anim.save(filename, writer=&#39;pillow&#39;, fps=6, dpi=100)<br>    plt.close(fig)</pre><p>This section of the article is dedicated to see for real dynamics of population evolving. I will begin slowly and then make some comparisons.</p><h4>Simulating a single gene under Hardy-Weinberg equilibrium — Sim 1</h4><p>Let’s start by defining some paramentes for <strong>Sim </strong>1:</p><ul><li>Gene A.</li><li>Alleles 1 and 2.</li><li>Initial frequencies ppp and qqq of 0.55 and 0.45.</li><li>100 simulated generations.</li><li>No mutations allowed.</li><li>No genetic drift allowed.</li><li>Mortality rate of 10%.</li><li>Brood size of 4.</li><li>Initial population size of 10.</li><li>Environmental capacity of 1000.</li><li>Seed 34.</li></ul><pre>num_genes = 1<br>alleles_per_gene = [2]<br>freq_alleles_gene_1 = np.array([0.55, 0.45])<br>alleles_frequency = [freq_alleles_gene_1]<br>selective_pression_gene_1 = np.array([1, 1, 1]) # no adaptative sucess means no selective pressure.<br>selective_pression = [selective_pression_gene_1]<br><br>popgen = PopGen(<br>    num_genes=num_genes,<br>    alleles_per_gene=alleles_per_gene,<br>    alleles_frequency=alleles_frequency,<br>    selective_pression=selective_pression,<br>    generations=100,<br>    allow_drift=False,<br>    allow_mutation=False,<br>    founder_prob=0.00,<br>    founder_intensity= 0.0,<br>    brood_size=4,<br>    death_rate = 0.1,<br>    pop_size=10,<br>    pop_threshold=1000,<br>    seed=34<br>)<br>popgen.evolve()<br>popgen.plot_frequencies()<br>popgen.plot_population_size()</pre><p>We can see from the configuration that allele frequencies will not change, so we are starting with a Hardy-Weinberg equilibrium, <strong>Sim 1</strong>, below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o7q7U9QLp102q3pZMdBTRQ.png" /><figcaption><strong>Sim 1</strong>. Simulating a population in Hardy-Weinberg equilibrium. Source: popgen.plot_frequencies()</figcaption></figure><p>This is a theorerical result, so let’s spice things a bit more.</p><h4>Simulating a single gene under the effect of natural selection — sim 2</h4><p>Now consider just a few changes to our previous pipeline:</p><ul><li>introduce a selective pressure for A11, A12 and A22.</li><li>increase generations to 350</li></ul><pre>selective_pression_gene_1 = np.array([1, 0.95, 0.90])<br>generations=350</pre><p>Now, natural selection favors the A11 variant slightly more than A12, and A12 slightly more than A22. The effects, drift and mutations are still turned off.</p><p>We come up with <strong>Sim 2</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FS3O0zjlMWelq1AfAJka9A.png" /><figcaption><strong>Sim 2. </strong>Applying pressure to A11 variant. Source: popgen.plot_frequencies()</figcaption></figure><p>Now we can see that fixation actually happens (allele 1 &gt; 0.999) by generation 131. In other words, natural selection has favored this variant, making it the only one left in the population.</p><p>From here on, I’ll share each simulation results as an animated GIF.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*i_Ao1dipOnzEGgmOcHoezQ.gif" /><figcaption><strong>Sim 2</strong>. Evolution of gene A with selective pressure: fixation of allele 1 at generation 131.</figcaption></figure><p>Analyzing the sim 2 gives us two direct conclusions:</p><ol><li>First, the population grows rapidly until it reaches the environment’s carrying capacity. After that, mortality continues to affect each generation, but the number of offspring consistently reaches the limit, allowing the population to stabilize and settle into a plateau.</li><li>Second, allele frequencies change faster at the beginning, but fixation takes more generations as it approaches 0.999. This is because variant A12 has also an elevated fitness, while allele 2 “hides” its frequency within this variant, slowing down the final steps of fixation. We see that in the bar representing the genotypes.</li></ol><h4>Simulating a single gene with natural selection and drift — Sim 3</h4><p>Now let’s assume genetic drift is allowed, so we need to change some parameters:</p><ul><li>There is genetic drift through the founder effect, bottleneck effect, and random noise.</li><li>The founder probability is only 2% in each generation.</li><li>The founder population size is 5, that means we are reshaping the whole population and drift can play a huge part in the final outcome.</li><li>The bottleneck happens at generation 7.</li><li>The bottleneck intensity is severe, so that 90% of individuals die.</li><li>The bottleneck probability is 1, because we want to guarantee that it occurs at generation 10.</li></ul><pre>popgen = PopGen(<br>    num_genes=num_genes,<br>    alleles_per_gene=alleles_per_gene,<br>    alleles_frequency=alleles_frequency,<br>    selective_pression=selective_pression,<br>    allow_drift=True,<br>    founder_prob=0.02,<br>    founder_size= 5,<br>    bottleneck_start=7,<br>    bottleneck_intensity= 0.9,<br>    bottleneck_prob= 1,<br>    generations = 350,<br>    brood_size=4,<br>    death_rate = 0.1,<br>    pop_size=10,<br>    pop_threshold=1000,<br>    seed=42<br>)<br><br>popgen.evolve()<br>popgen.plot_alleles_frequencies()<br>popgen.plot_population_size()</pre><p>As despicted we are giving major importance to botth population effects. We come up with sim 3, below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*kjYQ1Z7BT7raUX2BI_obFw.gif" /><figcaption><strong>Sim 3</strong>. Evolution of gene A with drift: fixation of allele 1 at generation 164.</figcaption></figure><p>To help us see more detail, I provide a closer look at the dynamics of <strong>Sim 3.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SUn5VBEG_q-xTLqpLIeO4g.png" /><figcaption><strong>Sim 3</strong>. Detailed allele frequencies and population size.</figcaption></figure><p>Analyzing <strong>Sim 3</strong> provides some interesting insights:</p><ol><li>The bottleneck has little effect in changing initial frequencies. That could be explained by randomness and because it lasts only 1 generation. Anyhow, the path of evoluation in early generations is still to favor allele A1.</li><li>In each generation, frequencies change slightly, and this is caused by the random noise introduced by drift. As the population grows, these changes become diluted.</li><li>At generation 71, a founder event occurs, and the population size drops to only 8 individuals. This drastic event increases the frequency of allele 2 from 0.04 to 0.25, almost fivefold. At generation 79, randomness plays a role, and the A2 frequency reaches its peak of 0.77, acting as an evolutionary reset.</li><li>After this population event, evolution once again follows its path, and fixation of A1 occurs at generation 164.</li></ol><h4>Sim 4: Simulating a single gene with natural selection and drift — early extinction.</h4><p>If the founder effect occurs too early and the population size is too small to reproduce, the new population may be unable to generate more individuals than the death rate. In this case, the only possible outcome is extinction.</p><p>For S<strong>im 4</strong>, lets just change 3 parameters:</p><ul><li>Bottleneck now starts at generation 4.</li><li>The number of generations simulated is reduced to 30.</li><li>The brood size is now 3.</li></ul><pre>popgen = PopGen(<br>    num_genes=num_genes,<br>    alleles_per_gene=alleles_per_gene,<br>    alleles_frequency=alleles_frequency,<br>    selective_pression=selective_pression,<br>    allow_drift=True,<br>    founder_prob=0.02,<br>    founder_size= 5,<br>    bottleneck_start=4,<br>    bottleneck_intensity= 0.9,<br>    bottleneck_prob= 1,<br>    generations = 30,<br>    brood_size=3,<br>    death_rate = 0.1,<br>    pop_size=10,<br>    pop_threshold=1000,<br>    seed=70<br>)<br><br>popgen.evolve()<br>popgen.plot_alleles_frequencies()<br>popgen.plot_population_size()</pre><p>We come up with a nice simulation leading to extinction:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*NFiGsokDpLpoYenWucgvnA.gif" /><figcaption><strong>Sim 4</strong>. Evolution of gene A with natural selection and drift — extinction event.</figcaption></figure><p>In other words, a bottleneck effect can hypothetically lead to species extinction when the population produces fewer descendants than the number of individuals that die.</p><p>Additionally, in the presence of deleterious alleles, especially if they reach high frequencies, the population may fail to survive, leading to the same outcome.</p><p>Of course, natural selection will never favor a deleterious allele, but it can remain hidden, as shown before, and genetic drift can increase its frequency to a level at which reproduction may become impossible.</p><p>The math of this particular scenario is easy to follow: with a bottleneck starting at generation 4, 90% of 17 individuals die, so only one individual remains. This individual is, of course, unable to reproduce alone, and the entire population is led to extinction.</p><p><strong>Sim 4</strong> is illustrative, as the population begins very small and does not have time to flourish, but the principle involved persists. A bottleneck can last several generations and be caused by catastrophic events such as the meteor that ended the dinosaur empire on Earth. 🦖☄️</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*nM0grl6hkwaBctoW.gif" /></figure><p><strong>Simulating a single gene with natural selection, drift and unidirectional mutation — Sim 5</strong></p><p>Next, what if we let mutations play their part in evolution? For that purpose, let us configure Simulation 5 as follows:</p><ul><li>Bottleneck probability of 1% starting at least at 50th generation with a intensity of 90%.</li><li>The founder size is 20 and the probability is only 1%</li><li>Generations are now 1000 and brood size is 4.</li><li>Allele 1 can change to 2 with a probability of 0.02%, but allele 2 never changes back to 1, so we have a unidirectional mutation.</li></ul><p>We could write the changes as:</p><pre>p_mutation = [<br>    [0.000, 0.002],<br>    [0.000, 0.000]<br>]<br><br>popgen = PopGen(<br>    num_genes=num_genes,<br>    alleles_per_gene=alleles_per_gene,<br>    alleles_frequency=alleles_frequency,<br>    selective_pression=selective_pression,<br>    allow_mutation=True,<br>    allow_drift=True,<br>    founder_prob=0.01,<br>    founder_size= 20,<br>    bottleneck_start=50,<br>    bottleneck_intensity= 0.9,<br>    bottleneck_prob= 0.01,<br>    generations = 1000,<br>    brood_size=4,<br>    death_rate = 0.1,<br>    pop_size=10,<br>    pop_threshold=1000,<br>    seed=42<br>)<br><br>popgen.evolve()<br>popgen.plot_alleles_frequencies()<br>popgen.plot_population_size()</pre><blockquote><strong>What happens when evolution favors the brave but mutations favor the weak?</strong></blockquote><p>As we know previously, A1 is being favored by natural selection and ends up fixated in previous generations. However, nos there is a unidirectional mutation that changes A1 to A2, but A2 never changes back to A1.</p><p>There are mainly 3 possible scnearios:</p><ol><li>If the effect of natural selection surpasses the mutation rate, then A1 still heads toward fixation.</li><li>If they are equal, then fixation does not occur, and the population evolves without a clear direction.</li><li>If mutations have a stronger effect than the adaptive fitness advantage of A1 (which is extremely rare), then A2 will be favored and could become fixed through population effects or drift.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*7IZeorNiVhPZCH_xhk6NVw.gif" /><figcaption><strong>Sim 5. </strong>Evolution of one single gene with drift and unidirectional mutation</figcaption></figure><p>If you are patient enough to check 1,000 generations, you will conclude that:</p><ol><li>Since allele A1 changes to A2 with a probability of 1%, and the effect of natural selection favoring allele A1 is too small for its frequency to increase significantly, there is no fixation.</li><li>Also, allele A1 frequency is never lower than 5%, so even though drift plays a role, it cannot alone fix the population.</li><li>The population effects still occur, but they have little impact on the course of evolution. Only an extraordinarily improbable and very extreme event could change the frequency of one allele directly to 100%</li></ol><p>Here we simulated a very peculiar example: as evolutionary forces push A1 frequency upward, mutation from A1 to A2 is stronger then the path of evolution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*LN-4sZUXWi0d8WfUQLdPZQ.png" /><figcaption><strong>Sim 5</strong>. Detailed allele frequencies over 1,000 generations.</figcaption></figure><p>Again, this experiment is designed to illustrate the forces of evolution. In real life, mutations most of the time cause problems for survival. When they do not, they may create a new adaptive trait that can be positively selected by the environment.</p><h4>Simulating a single gene with natural selection, drift and mutation for 3 alleles.</h4><p>So now, what if we had 3 instead of 2 alleles? The parameters would just need to be adjusted to accommodate that, especially regarding selective pressure.</p><p>Please note that selective pressure is given as a list following the order<br> [A11, A12, A13, A22, A23, A33], so that A22 now occupies the fourth position.</p><p>We also establish that variants A13, A23, and A33 have lower reproductive success than the previous ones, so we are still favoring allele 1.</p><p>The initial frequencies are adjusted to divide the original population equally.</p><p>Mutations occur randomly from one generation to another, but we do not control how they happen. In fact, because they are random, we would expect some noise but no particular direction apart from the path of evolution.</p><p>Here, again, we are simulating one population and following it until the generations are over.</p><p>In biology, we have a phenomenon called speciation, which takes place when different subspecies are isolated in particular environments. That said, selective pressure varies, and the subspecies evolve to eventually become two different new species.</p><p>The parameters that change are:</p><ul><li>The number of alleles is set to 3.</li><li>We define a new selective pressure, one value from 0 to 1 for each genotype.</li><li>The initial allele frequencies are now three, still summing to 1.</li><li>Allow mutation is set to True, since we do not provide a mutation matrix.</li><li>The number of generations is now 270.</li><li>The remaining parameters follow Simulation 5.</li></ul><pre>num_genes = 1<br>alleles_per_gene = [3]<br># [A11, A12, A13, A22, A23, A33]<br>selective_pression_gene_1 = np.array([1, 0.98, 0.8, 0.95,0.85, 0.8])<br>freq_gene_1= np.array([0.33, 0.33, 0.34])<br>alleles_frequency = [freq_gene_1]<br><br>selective_pression_gene_1 = np.array([1, 0.98, 0.8, 0.95,0.85, 0.8 ])<br>freq_gene_1= np.array([0.33, 0.33, 0.34])<br><br>alleles_frequency = [freq_gene_1]<br>selective_pression = [selective_pression_gene_1]<br><br>popgen = PopGen(<br>    num_genes=num_genes,<br>    alleles_per_gene=alleles_per_gene,<br>    alleles_frequency=alleles_frequency,<br>    selective_pression=selective_pression,<br>    allow_mutation=True,<br>    allow_drift=True,<br>    founder_prob=0.01,<br>    founder_size= 20,<br>    bottleneck_start=50,<br>    bottleneck_intensity= 0.9,<br>    bottleneck_prob= 0.01,<br>    generations=270,<br>    brood_size=4,<br>    death_rate = 0.1,<br>    pop_size=10,<br>    pop_threshold=1000,<br>    seed=42<br>)<br><br>popgen.evolve()<br>popgen.plot_alleles_frequencies()<br>popgen.plot_population_size()</pre><p>Let’s have a close look at sim 5 below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*YsfuxLkFMvLDfV4LGHUxZg.gif" /><figcaption><strong>Sim 6. </strong>Simulating a single gene with natural selection, drift and mutation for 3 alleles.</figcaption></figure><p>It’s fun to see that:</p><ol><li>After 270 generations, no allele has become fixed. At the beginning, all three alleles suffer from negative selective pressure and their frequencies decrease, although they persist in heterozygous genotypes A13 and A23.</li><li>A bottleneck occurs at generation 10, slightly increasing allele 1 and reducing allele 2, while allele 3 is already maintained at low frequency.</li><li>A founder effect appears at generation 91, almost fixing allele 1 in the population.</li></ol><ul><li>After that, the population reaches a balance, and all three alleles are still present.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gWLb2vmfUyH0xtfiSBgHyw.png" /><figcaption><strong>Sim 7. </strong>Detailed allele frequencies and population size.</figcaption></figure><h4><strong>Simulating two genes populational dynamics all events included</strong></h4><p>For the grand finale, let’s add one more gene and some pre defined mutations to our population.</p><p>It’s your job trying to explaing whats going on. New parameters are as follow:</p><pre> <br>num_genes = 2<br>alleles_per_gene = [2, 3]<br>freq_allele_1 = np.array([0.3, 0.7])<br>freq_allele_2 = np.array([0.25, 0.5, 0.25])<br>alleles_frequency = [freq_allele_1, freq_allele_2]<br>selective_pression_gene_1 = np.array([1, 0.90, 0.95]) <br>selective_pression_gene_2 = np.array([0.997, 0.996, 0.0995, 1, 0.996, 0.978])<br>selective_pression = [selective_pression_gene_1, selective_pression_gene_2]<br>p_mutation = [<br>    [<br>        [0.0, 0.01],<br>        [0.0, 0.0]<br>    ],<br>    [<br>        [0., 0.003, 0.005],<br>        [0.002, 0., 0.002],<br>        [0.007, 0.001, 0.]<br>    ]<br>]<br><br>popgen = PopGen(<br>    num_genes=num_genes,<br>    alleles_per_gene=alleles_per_gene,<br>    alleles_frequency=alleles_frequency,<br>    selective_pression=selective_pression,<br>    generations=500,<br>    allow_drift=True,<br>    allow_mutation=True,<br>    p_mutation=p_mutation,<br>    founder_prob=0.02,<br>    founder_size= 10,<br>    bottleneck_start=10,<br>    bottleneck_intensity= 0.9,<br>    bottleneck_prob= 1,<br>    brood_size=4,<br>    death_rate = 0.1,<br>    pop_size=30,<br>    pop_threshold=1000,<br>    seed=42<br>    )<br><br>popgen.evolve()<br>popgen.plot_alleles_frequencies()<br>popgen.plot_population_size()</pre><p>The result of simulation 7 is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fJ32Ho-KHgHwZ1vHPDuRfg.gif" /><figcaption><strong>Sim 7.</strong> Two genes with everything going on.</figcaption></figure><p>So, if you made it to the end and want to check whether you understood this paper, feel free to comment on this final result, I’ll reply to your comment.</p><p>Also, I would very much appreciate a clap, so this paper could reach other people.</p><p>In this two-part paper, I revisited my days as a biologist and explored the key concepts of evolution as they truly are: a mathematical process involving millions of genes like these. Some of them have multiple copies of different alleles that, under certain circumstances, can be selected by the environment.</p><p>Life itself, in all the diversity we observe, emerges from such a random yet elegant process. Each adaptation is the result of many genes segregating, with their expression intertwining with the environment.</p><p>I am very happy to complete this work. It required time and effort to reproduce even a simplified version of the process, bringing together what I have learned from my time as a biology student to my work as a machine learning professional.</p><p>Now I can return to numbers and the random nonsense of financial time series, which, unlike evolution, are going nowhere.</p><p>See you, folks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad8ae6bc1cc7" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/the-greatest-show-on-earth-in-python-ad8ae6bc1cc7">The Greatest Show On Earth In Python</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[The Greatest Show On Earth In Python]]></title>
            <link>https://python.plainenglish.io/the-greatest-show-on-earth-in-python-fac0077a7582?source=rss-59d66406fdbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/fac0077a7582</guid>
            <category><![CDATA[biology]]></category>
            <category><![CDATA[genetics]]></category>
            <category><![CDATA[computational-genomics]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[simulation]]></category>
            <dc:creator><![CDATA[Guilherme Ziegler]]></dc:creator>
            <pubDate>Sat, 07 Feb 2026 12:55:55 GMT</pubDate>
            <atom:updated>2026-03-19T11:39:41.719Z</atom:updated>
            <content:encoded><![CDATA[<h4>The dance of the selfish genes Part 1</h4><p>For those who follow my work on Medium it’s been a while! I’ve been busy finishing my thesis on neural networks to complete my second major in Economics. Now that things are back on track, I finally found some time to write again.</p><p>For this comeback, I decided to take a journey far back in time, to my days as a biology student, when I was first captivated by the wonders of evolution and the secrets hidden in population genetics.</p><p>In this series of two articles, we’ll run simulations in Python to explore how genetic frequencies change across generations in a population, hopefully capturing the main processes that shape life as we know it.</p><p>The inspiration for this work comes from <em>Population Genetics Virtual Biology Lab</em>, specifically the <a href="https://virtualbiologylab.org/ModelsHTML5/PopGenFishbowl/PopGenFishbowl.html"><strong>PopGen Fishbowl</strong></a>, an agent-based population genetics simulation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yO0rMjr1wZW_ewIiEtEzfw.png" /><figcaption>Figure 1. Inside the Fishbowl. Adapted from <a href="https://virtualbiologylab.org/ModelsHTML5/PopGenFishbowl/PopGenFishbowl.html"><strong>PopGen Fishbowl</strong></a></figcaption></figure><p>It simulates the color variations in a population of koi fish, a domesticated ornamental breed of wild carp. The Kohaku variety, in particular, displays three distinct forms: solid red (deep orange), solid white, and mottled orange and white (Gomelsky, 2015).</p><p>The program provides tools to conduct virtual experiments that violate all the assumptions of the Hardy–Weinberg theory including small population size, selection, mutation, migration, and non-random mating.</p><p>I first came across it while studying population genetics, and I was fascinated by how the fish populations in the virtual tank evolved over time sometimes even leading to what looked like the first steps of speciation.</p><h4>How This Work is Organized</h4><p>Because it became too big, I’m dividing it into two parts: In part one, I will discuss the biological aspects of evolution in a mathematical way.</p><p>In <a href="https://levelup.gitconnected.com/the-greatest-show-on-earth-in-python-ad8ae6bc1cc7?postPublishedType=repub">part two</a>, I’ll present the PopGen class and some simulations. Feel free to move to it if you are familiar with key biological concepts and the math associated with them, such as:</p><ul><li>Evolution,</li><li>Genes and alleles,</li><li>Hardy–Weinberg principle,</li><li>Mutations,</li><li>Genetic drift,</li><li>The Founder effect,</li><li>The Bottleneck effect,</li><li>Migration,</li><li>Non- random mating.</li></ul><p>In the second part, we implement a Python class called <strong>PopGen</strong>, which allows us to simulate evolutionary dynamics in any given population.</p><p>Also, I run some pretty cool experiments and discuss how various natural phenomena can result in distinct evolutionary trajectories. See you there.</p><h4>What is Evolution?</h4><p>Evolution is the process by which life changes over time. At its core, it explains how the incredible diversity of life on Earth, from microscopic bacteria to towering redwoods and complex animals, has arisen.</p><p>At the heart of evolution is <em>natural selection</em>: the idea that individuals with traits better suited to their environment are more likely to survive and reproduce, passing those advantageous traits to the next generation.</p><p>Over many generations, this process can lead to significant changes in populations, sometimes resulting in the emergence of entirely new species.</p><h4>The Structure of Life</h4><p>DNA (Deoxyribonucleic Acid)<strong> </strong>is the molecule that carries the genetic blueprint of all living things. Its elegant double-helix structure stores the information needed to build and sustain life, written in a code of four chemical bases A, T, C, and G that pair together like steps in a twisted ladder.</p><p>This vast molecule is carefully organized into <em>chromosomes, </em>long, coiled strands of DNA housed within the cell nucleus. Each chromosome contains thousands of genes, short segments of DNA that encode instructions for traits or proteins, from the color of a flower’s petals to the shape of a bird’s beak, or even the way our cells process energy.</p><p>Different versions of a gene are known as <em>alleles</em><strong><em>, </em></strong>subtle variations in the DNA sequence that create the endless diversity of life within a species. They are the reason why one person has green eyes and another brown, why some plants resist drought while others do not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/1*tG2zowPJp7D5lanhSXKJZQ.png" /><figcaption>Figure 2. Two Alleles in a chromosome</figcaption></figure><p>From Figure 2, we can observe a chromosome carrying two alleles for a specific pigmentation gene, labeled <em>R</em> and <em>r</em>, respectively. To maintain consistency with our previous koi fish population example, let’s assume that <em>R</em> represents the allele for the orange color and <em>r</em> for the white color.</p><p>Therefore, the chromosome depicted above would produce a mottled orange-and-white pattern. Since it carries two different alleles for the pigmentation gene, the individual possessing this chromosome is referred to as <em>heterozygous</em>.</p><p>An individual may also carry two identical copies of a gene’s alleles, referred to as <em>homozygous.</em></p><p>These combinations form what we know as the <em>genotype </em>of an individual, and in this case <em>Rr </em>originates the<em> </em>orange-and-white pattern, RR the oragange and rr the white.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*T85QuVPHUEoIZzbxZVfMRQ.png" /><figcaption>Figure 3. Ilustrative Koi fish genotype. Atapted from <a href="https://virtualbiologylab.org/ModelsHTML5/PopGenFishbowl/PopGenFishbowl.html"><strong>PopGen Fishbowl</strong></a></figcaption></figure><p>The manifestation of the genotype, that is, its biological effect, is called the <em>phenotype</em>. In some cases, one genotype can be dominant over another, meaning that the presence of a single dominant allele is sufficient to determine the phenotype.</p><blockquote><strong>So, What Is Evolution Again?</strong></blockquote><p>Evolution is, at its core, the change in allele frequencies from one generation to the next.</p><p>In other words, it’s a gentle dance of genes, where some versions step forward, others fade away, and together they shape the rhythm of life as populations slowly transform over time.</p><p>Thinking of koi fish, it is about how many <em>orange</em>, <em>white</em>, and <em>mottled</em> fish we will have swiming in the fishbowl after parents mate.</p><h4>Hardy-Weinberg</h4><p>Now that we know how to dance, let’s learn a bit more about the musicians Godfrey Hardy and Wilhelm Weinberg, who independently developed mathematical descriptions of the relationship between allele and genotype frequencies.</p><p>The <em>Hardy-Weinberg model</em> considers a gene with two alleles and predicts that the proportions of alleles and genotypes will remain constant from one generation to the next, as long as the following conditions are met:</p><ul><li>The population is sufficiently large,</li><li>There is no migration into or out of the population,</li><li>No mutations occur,</li><li>Mating is random,</li><li>All genotypes have the same fitness (are equally viable).</li></ul><p>Now imagine a group of female fish mating randomly with male fish. The color a fish has does not affect its reproductive success, colors cannot change except through reproduction, and there are enough fish to establish a stable population.</p><p>Let <em>p</em> be the proportion of the allele <em>R</em> and <em>q</em> the proportion of the allele <em>r,</em> the sum of the allele frequencies must be 1, so:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2Ff4jp5bFnrxVs8h9JvumKQn&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2Ff4jp5bFnrxVs8h9JvumKQn" width="200" height="136" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7840a7a9a6081b97b945db42aa2c30c/href">https://medium.com/media/d7840a7a9a6081b97b945db42aa2c30c/href</a></iframe><p>Now consider the mating of two <em>Rr</em> individuals, each passing either an <em>R</em> or an <em>r</em> allele to the next generation, and that the parents generate a brood size of four new individuals. By the <em>Punnett </em>table below, Figure 4,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/246/1*zD6HbmPRTurDWGR7Reu6BA.png" /><figcaption><strong>Figure 4.</strong> Punnett table for two <em>heterozygous</em> Koi Fish</figcaption></figure><p>the offspring will include one <em>RR</em> individual, one rr, and two <em>Rr</em>. Rewriting it in terms of <em>p</em> and <em>r:</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2FtdW7L9Uwczx2PtBkA3aXPU&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FtdW7L9Uwczx2PtBkA3aXPU" width="200" height="136" frameborder="0" scrolling="no"><a href="https://medium.com/media/1bcc60e3b7de14dbd9eafb8bde483f8a/href">https://medium.com/media/1bcc60e3b7de14dbd9eafb8bde483f8a/href</a></iframe><p>In other words, for any given number of mating fish and any future number of generations, the frequencies do not change, and the population is in Hardy–Weinberg equilibrium.</p><blockquote><strong>So does the koi fish population evolve?</strong></blockquote><p>Yes, it does. But since all genotypes have the same overall fitness, they remain in a fixed proportion of 1 orange, 1 white, and 2 mottled individuals.</p><p>In other words, the frequencies fluctuate through reproduction, but the outcome of evolution is predictable. In nature, of course, this is almost never the case.</p><h4>Natural Selection</h4><p>Since we understood that without any forces acting on individuals the path of evolution is stability and balance, how do actual populations evolve? The key concept we need to address this question is survival of the fittest.</p><p>Individuals with higher fitness, meaning better adaptation to their environment, are more likely to survive, reproduce, and pass on their advantageous traits.</p><p>An adaptation is a trait that increases an organism’s chances of surviving and reproducing in its environment, but make no mistake: adaptations arise as a result of reproduction. They reflect how different the next generation becomes from its parents.</p><p>Back to the koi fish example, imagine that the orange color made fish more capable of finding a mate, so that most new parents would be orange fish. As a result, the offspring would show a change in the frequency of allele R, and therefore more individuals would be orange.</p><p>That is exactly the key concept of natural selection. Natural selection happens when certain traits give individuals an advantage in survival or reproduction, causing those traits to become more common in the next generations. Over time, even small advantages accumulate, shifting allele frequencies and gradually changing the entire population.</p><h4><strong>Mutation</strong></h4><p>Mutations, though rare, can change allele proportions. A mutation is a random change in DNA that creates a new version of a gene or alters an existing one.</p><p>Most mutations have little or no effect, but occasionally a mutation produces a trait that affects survival or reproduction. When that happens, the new allele can spread through the population over generations, becoming an important source of evolutionary change.</p><p>Some mutations, of course, are deleterious and cause the death of an individual in a way that prevents it from passing any genes forward at all. As a result, fewer individuals carrying that harmful allele will reproduce, leading to changes in the offspring’s allele frequencies.</p><p>Mutation can be expressed as a relative probability of changing of one allele to another. In terms of <em>R</em> and <em>r</em>, we can write the chance of <em>R</em> become <em>r </em>and vice versa, equation 3, below:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2FhsVLWzk3onTTbh7hfmK9vo&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FhsVLWzk3onTTbh7hfmK9vo" width="200" height="174" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3b6ca13194920f3fca90c11a3e3120e/href">https://medium.com/media/a3b6ca13194920f3fca90c11a3e3120e/href</a></iframe><p>We can write mutation in terms of the allelic frequencies <em>p</em> an <em>q</em>:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2FhdoDypBF8ZUQE1cZcH498J&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FhdoDypBF8ZUQE1cZcH498J" width="200" height="172" frameborder="0" scrolling="no"><a href="https://medium.com/media/c67a2aab66b0a5b32c275d83c221fcdd/href">https://medium.com/media/c67a2aab66b0a5b32c275d83c221fcdd/href</a></iframe><p>where:</p><ul><li><em>μ</em> is the fraction of all <em>R</em> alleles that turn into <em>r,</em></li><li><em>ν</em> is the fraction of all <em>r</em> alleles that turn into<em> R,</em></li><li><em>p</em> -(1-<em>μ)</em> are <em>R </em>alleles that remain <em>R,</em></li><li><em>q</em> -(1-<em>ν</em>) are <em>r</em> alleles that remain <em>r,</em></li><li><em>qν </em>are <em>r </em>allele<em>s </em>that mutated into <em>R,</em></li><li><em>pμ </em>are <em>R</em> allele<em>s </em>that mutated into <em>r .</em></li></ul><p>Equation 4 above is actually quite intuitive. We are updating the value of <em>p</em> by removing the <em>R</em> alleles that mutated into r and adding the <em>r</em> alleles that mutated into <em>R</em>, while keeping in mind that the total frequency must remain 1, as stated in Equation 1.</p><p>Now back to the koi fish example, imagine that the frequency of <em>p</em> is 0.55 and the frequency of <em>q</em> is 0.45.</p><p>Also, let’s assume that μ is 0.002 and <em>ν</em> is 0.0, so the <em>R</em> allele can change to <em>r</em>, but <em>r</em> never changes back to <em>R</em>, thus a unidirectional mutation.</p><p>By aplying equation 4, we can recalcutate <em>p</em> frequency as:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2FmvrevynPWPjUoSWx9GSxYp&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FmvrevynPWPjUoSWx9GSxYp" width="274" height="208" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f2753b406f1e2246e9c355fb74055ce/href">https://medium.com/media/3f2753b406f1e2246e9c355fb74055ce/href</a></iframe><p>Since, no<em> r</em> mutates to <em>R,</em> the <em>p’</em> is just how much <em>R</em> still remain the population.</p><p>Mutation plays a key role in evolution by introducing changes in alleles. These changes create new genetic variations in a population, which can be acted upon by natural selection and other evolutionary forces such as genetic drift.</p><h4>Genetic Drift</h4><p>Genetic drift causes random changes in the frequencies of alleles within a population.</p><p>Unlike natural selection, these changes occur by chance and are not related to the adaptive value of the alleles. Drift is especially pronounced in small populations, where the effects of random events, such as which individuals survive or reproduce, can significantly alter allele frequencies.</p><h4><strong>The Founder Effect</strong></h4><p>The founder effect occurs when a small group of individuals becomes isolated from a larger population and establishes a new population. Because this small group carries only a fraction of the genetic variation found in the original population, the allele frequencies in the new population can differ dramatically from those of the source population.</p><p>Over time, this reduced genetic diversity can lead to unique evolutionary paths, causing the new population to become genetically distinct simply due to the randomness of which individuals happened to found it.</p><p>To simply ilustrate the founder effect, let’s consider a original population of 60 all colored koi fish. Also, we are assuming it starts from a H-W equilibrium, so that motted fish are twice the proportion the orange and white ones, figure 6.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*A4C32I7e3Awd4lFIvsmtEg.png" /><figcaption><strong>Figure 6</strong>. The founder effect ilustrated.</figcaption></figure><p>Imagine three different populations, each one founded by a different combination of individuals from the original population, with population sizes of 4, 7, and 6, respectively.</p><p>Intuitively, there is a drastic reduction in the size of the original population, which can be obtained by taking 1 minus the fraction of each founder population size relative to the original size, resulting in reductions of 93.3%, 88.3%, and 90.0%.</p><p>In these scenarios, randomness can play a key role in changing allelic frequencies simply because the founder groups are small samples of the original population, taken in particular and sometimes unrepresentative ways.</p><p>Take the first founded population: all koi fish are orange, therefore the frequency of <em>p</em> is 1. In this case, all future generations (as long as <em>R</em> does not mutate to <em>r</em>) will have the genotype <em>RR</em> and the orange color. When the frequency of an allele reaches 1, it is said to be fixed<strong> </strong>in the population.</p><p>Now, looking at the second founded population, we can easily determine the frequencies of <em>p</em> and <em>r</em> by examining its phenotypes: 2 orange, 3 mottled, and 2 white individuals.</p><p>First, we must reconstruct the genotypes, resulting in 2 <em>RR</em>, 3 <em>Rr</em>, and 2 <em>rr</em> individuals. Each individual has 2 alleles, so the total number of alleles in the population is multiplicated by 2.</p><p>The homozygotes <em>RR</em> and rr each contribute two copies of <em>R</em> and <em>r</em>, respectively. The heterozygotes <em>Rr</em> contribute one <em>R</em> and one <em>r</em>.</p><p>So we can summarize the frequency <em>p</em> and <em>r</em> of the alleles as equation 6, below:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2FqtgGauoc1sZVZ61VGQhzDB&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FqtgGauoc1sZVZ61VGQhzDB" width="252" height="213" frameborder="0" scrolling="no"><a href="https://medium.com/media/369480599b98b9855b0afd9c0f56f423/href">https://medium.com/media/369480599b98b9855b0afd9c0f56f423/href</a></iframe><p>where</p><ul><li><em>n(RR)</em> is the number of orange fish</li><li><em>n(rr)</em> is the number of white fish</li><li>and <em>n(Rr)</em> is the number of mottled fish</li></ul><p>Adding all numbers, we come up with <em>p</em> as 0.5, equation 7, below:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2FubFiDvcSGGosFBA1S42ktu&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FubFiDvcSGGosFBA1S42ktu" width="200" height="303" frameborder="0" scrolling="no"><a href="https://medium.com/media/018d58cf8772b5fe50b365de8cd96de8/href">https://medium.com/media/018d58cf8772b5fe50b365de8cd96de8/href</a></iframe><p>Therefore, as the frequencies sum 1,<em> q </em>is also 0.5.</p><p>Now, if we repeat the same process for third founded population, which has 1 <em>RR</em>, 3 <em>rr</em> and 2 <em>Rr</em> , we find out <em>p </em>to be 0.33 a drastric change from its original frequency of 0.55.</p><p>In a nutshell, the founder effect can cause distortions in allele frequencies that are then carried on to future generations. It affects small populations more strongly, and in extreme cases, it can even lead to fixation.</p><p><strong>The Bottleneck Effect <br></strong>Population bottlenecks occur when a population’s size is reduced for at least one generation. Because genetic drift acts more quickly to reduce genetic variation in small populations, undergoing a bottleneck can reduce a population’s genetic variation by a lot, even if the bottleneck doesn’t last for very many generations (UCMP, 2025)<em>.</em></p><p>It has a similar effect to the founder effect. In fact, a bottleneck can lead to a founder effect, however, in this case, a single population is drastically reduced in size due to catastrophic events, such as earthquakes, volcanic eruptions, floods, fires, disease outbreaks, and humans.</p><p>The bottleneck can occur as a single, abrupt event or persist across several generations, depending on the severity and duration of the population reduction.</p><h3><strong>Other evolutionary mecanisms</strong></h3><h4>Migration</h4><p>Migration refers to the movement of individuals (and their alleles) into or out of a population. When individuals from another population enter the population in question, they can <strong>a</strong>lter the allele frequencies. This can happen in two ways:</p><ol><li>Introduction of new alleles: Migrants may carry alleles that were previously absent in the population, increasing genetic diversity.</li><li>Change in existing allele proportions: Even if the alleles are already present, the relative frequencies may shift if the migrant population has different allele frequencies.</li></ol><p>In our Koi fish example, we assume that no individuals can leave or enter the fishbowl, so migration does not play a role in evolution for this population.</p><p>Migration becomes particularly important when a different population introduces alleles that are previously unknown, which can disrupt the existing allele frequencies and potentially affect evolutionary outcomes.</p><h4><strong>Non-Random Mating</strong></h4><p>Non-random mating occurs when individuals in a population choose mates based on genotype or phenotype rather than mating randomly. This behavior influences genotype frequencies but generally does not change allele frequencies, since no allele has an inherent advantage simply due to mate choice.</p><p>For example, let’s assume most orange fish prefer to mate with white fish (negative assortative mating). In the next generation, there will be an increase in the number of heterozygotes <em>Rr</em>, so the number of mottled fish would increase over time.</p><p>On the other hand, if mottled fish tend to prefer orange fish, this will also increase heterozygosity in the population.</p><p>However, no alleles are lost or gained in this population, so the overall allele frequencies remain the same.</p><p>In other words, non-random mating reorganizes alleles into different genotypes without altering the total number of each allele in the population. Over time, this can change the distribution of phenotypes (e.g., more mottled fish), but it does not directly drive evolution unless combined with other forces such as selection, mutation, or migration.</p><blockquote><strong>What if genotypes have different overhall fitness?</strong></blockquote><p>When genotypes have different fitness, non-random mating can indirectly affect allele frequencies by increasing the proportion of certain genotypes through mate choice, and if those genotypes have higher survival or reproductive success, the alleles they carry will become more common over time.</p><p>For example, if orange koi <em>RR </em>prefer to mate with other orange fish, increasing the number of <em>RR </em>offspring, and if <em>RR </em>individuals also survive better than <em>Rr </em>or <em>rr</em>, then both non-random mating and differential fitness will increase the frequency of the <em>R</em> allele over time, causing evolutionary change in the population.</p><h4>The maths of natural selection</h4><p>For this section of the article, we have a mantra to keep in mind, that summarizes the general evolutionary pathway.</p><ol><li>Individuals are born and grow.</li><li>Unpredictable events occur, and unfortunately, some of them die.</li><li>Those who survive reproduce, passing their alleles on to the next generation.</li><li>The cycle of life then continues, repeating this process over successive generations.</li></ol><p>That sad, a key concept must be presented, wich is relative fitness, a measure of how successful a genotype is at surviving and reproducing compared to other genotypes in the population.</p><p>It is usually expressed relative to the fittest genotype, which is assigned a value of 1, while other genotypes are scaled accordingly. It’s expressed as the numer of offspring of a genotype divided by the number of offspring of the fittest genotype, equation 8.</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2FqsF297NLZZ2ehwzpQ2DnMe&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FqsF297NLZZ2ehwzpQ2DnMe" width="378" height="197" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9b83937109e9fa47e8d6095cb82b703/href">https://medium.com/media/c9b83937109e9fa47e8d6095cb82b703/href</a></iframe><p>In the case of koi fish, assuming the orange fish is now the fittest in its environment, we set its fitness to 1 and express the relative fitness of all other genotypes by dividing their reproductive sucess by that of the orange fish.</p><p>This is a vector for <em>RR</em>, <em>Rr</em>, and <em>rr</em>, which tells us how strongly each genotype is selected in the next generation, equation 9.</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2FAXKyFi3MdeVoAz4PVXjWY&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FAXKyFi3MdeVoAz4PVXjWY" width="201" height="182" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a58d207fd87c8a2878532fea0ad1964/href">https://medium.com/media/6a58d207fd87c8a2878532fea0ad1964/href</a></iframe><p>From now on, W will be referred to as the fitness matrix, and using it we can simulate natural selection in the next generations of our model population.</p><p>For that porpose we need to stabilish the genotypes frequencies in each generation. That could be given as:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2FuuR5anuNQ4qAD7UYytAoVN&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FuuR5anuNQ4qAD7UYytAoVN" width="200" height="182" frameborder="0" scrolling="no"><a href="https://medium.com/media/e94a74fba552b01052a577c72f5a725e/href">https://medium.com/media/e94a74fba552b01052a577c72f5a725e/href</a></iframe><p>By G and and W pointwise multiplication, we come up with the weighted fitness genotype contribuition in the population, equation 11:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2F8sDkSWhAqQrepF3Lskb8BC&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2F8sDkSWhAqQrepF3Lskb8BC" width="257" height="182" frameborder="0" scrolling="no"><a href="https://medium.com/media/bfd636514e0363196d8e8d0d0b25c835/href">https://medium.com/media/bfd636514e0363196d8e8d0d0b25c835/href</a></iframe><p>Now, if we sum the all thrree resulting elements in eqution 11, we obtain the mean fitness of all the genotypes in a population,</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2FsGnzBcGMJhr7iLNghFzzwL&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FsGnzBcGMJhr7iLNghFzzwL" width="200" height="96" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a7da484f032cebc2adaf2cd2b12de4d/href">https://medium.com/media/5a7da484f032cebc2adaf2cd2b12de4d/href</a></iframe><p>where W is bar 0.982, a number that not necessary adds to 1.</p><p>We use it now to estimate the new genotypes frequencies after the selection has occured, equation 13.</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2F9CViy1pJn7rE1jHAwnVpqf&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2F9CViy1pJn7rE1jHAwnVpqf" width="296" height="151" frameborder="0" scrolling="no"><a href="https://medium.com/media/809931e64057557f873a2c1b25181161/href">https://medium.com/media/809931e64057557f873a2c1b25181161/href</a></iframe><p>This transformation guarantees that all frequencies are back to 1.</p><p>Now remember that:</p><ol><li>each <em>RR</em> contributes fully with an <em>R</em>,</li><li>each <em>rr</em> contributes fully with and <em>r,</em></li><li>and since <em>Rr</em> can either pass a <em>R </em>or<em> r, </em>each contribute with only half the genotype frequency.</li></ol><p>The updated allelic frequencies <em>p′</em> and <em>q′</em> can therefore be calculated as follows, following Fisher (1930) and Wright (1931):</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2FqXQ8Zj6n3t4cLuCPHgzYFn&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FqXQ8Zj6n3t4cLuCPHgzYFn" width="288" height="151" frameborder="0" scrolling="no"><a href="https://medium.com/media/3bce78cbddd3c20771430b2f5640b999/href">https://medium.com/media/3bce78cbddd3c20771430b2f5640b999/href</a></iframe><p>And thus, the cycle of life continues to turn.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*nuGOKwPwz0nWMgpILoU8Tg.gif" /></figure><p>This article established the key biological concepts that readers need to understand in order to follow the PopGen class and the simulations presented in part two.<br> <br>Thank you for reading, and if you enjoyed it, feel free to leave a clap. Part two is already available. See you there.</p><h3>References</h3><p><strong>DE KOCK, S.; GOMELSKY, B.</strong> <em>Japanese ornamental koi carp: origin, variation and genetics.</em> In: <strong>Biology and Ecology of Carp.</strong> Boca Raton: CRC Press, 2015. DOI: 10.1201/b18547–4.</p><p><strong>FISHER, R. A.</strong> <em>The genetical theory of natural selection.</em> Oxford: Clarendon Press, 1930.</p><p><strong>UNIVERSITY OF CALIFORNIA MUSEUM OF PALEONTOLOGY.</strong> <em>Bottlenecks and founder effects.</em> Understanding Evolution, Berkeley, CA. Available at: <a href="https://evolution.berkeley.edu/bottlenecks-and-founder-effects/">https://evolution.berkeley.edu/bottlenecks-and-founder-effects/</a>.</p><p><strong>VIRTUAL BIOLOGY LAB.</strong> <em>PopGen Fishbowl: agent-based population genetics simulation.</em> Available at: <a href="https://virtualbiologylab.org/ModelsHTML5/PopGenFishbowl/PopGenFishbowl.html">https://virtualbiologylab.org/ModelsHTML5/PopGenFishbowl/PopGenFishbowl.html</a>.</p><p><strong>WRIGHT, S.</strong> Evolution in Mendelian populations. <em>Genetics</em>, v. 16, p. 97–159, 1931.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fac0077a7582" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/the-greatest-show-on-earth-in-python-fac0077a7582">The Greatest Show On Earth In Python</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Target Classification Tool for Candlestick Patterns in Streamlit]]></title>
            <link>https://medium.datadriveninvestor.com/target-classification-tool-for-candlestick-patterns-in-streamlit-7b1e19ff6212?source=rss-59d66406fdbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b1e19ff6212</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[candlesticks]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Guilherme Ziegler]]></dc:creator>
            <pubDate>Mon, 16 Sep 2024 10:59:14 GMT</pubDate>
            <atom:updated>2024-09-23T13:04:30.375Z</atom:updated>
            <content:encoded><![CDATA[<h4>A step-by-step guide</h4><p>In this three-part series, I train a neural network to identify candlestick patterns.</p><p>In part one, we are going to develop a classification tool for candle patterns using streamlit.</p><p><a href="https://streamlit.io/">Streamlit</a> is an open-source Python library that allows users to create interactive web applications for data science and machine learning projects with some effort.</p><p>For this particular case, we are not deploying an app, but will configure it to run locally and store our classifications in our project directory.</p><p>In part two, I will use the target information to train and test a recorrent neural network that can identify candlestick for any asset.</p><p>Lastely, in part three I will show backtest strategies for finantial marketing and mesure how trained patterns perform in terms of risk return trade-off.</p><p>If you are not familiar with my work, you know so far I have been working on the field of risk and return for portfolio investing.</p><p>Please feel confortable to see my previous <a href="https://medium.com/@guilherme.ziegler">publications </a>in which I optimize portfolio allocation strategies.</p><h4>What are we covering here?</h4><p>By the end of this reading, you will be able to:</p><ul><li>Process financial data into normalized OHLC vectors,</li><li>Plot customized candlesticks to help you classify patterns,</li><li>Render a local Streamlit app that classifies targets for a neural network model,</li><li>Organize files for the current step in this project pipeline.</li></ul><h4>A Quick Review On Candlesticks</h4><p>When we think about finantial market, two straighfoward topics come to to mind: fundamental analysis and technical analysis.</p><p>Fundamental analysis focuses on evaluating an asset’s intrinsic value by examining economic, financial, and other qualitative and quantitative factors. As economists, we run through income statement, balance sheet, and cash flow statement mainly to determine the fair value of a company.</p><p>On the other hand, technical analysis are about studying historical price movements and trading volumes to predict future price trends. It relies on chart patterns, technical indicators, and price action rather than underlying economic conditions.</p><p>A candlestick is a graphical representation used in financial charts to display price movements over a specific time period. Each candlestick provides four key pieces of information for a selected timeframe:</p><ul><li>the opening price,</li><li>the closing price,</li><li>the highest price,</li><li>and the lowest price.</li></ul><p>This is usually translated to finantial data as OHLC (open, high, low, close) variables and can be retrieved from yahoo finance or trading softwares.</p><p>One candlestick consists of three main components:</p><ul><li>The body, which is the difference between the close and open prices.</li><li>The upper wick, which is the difference between the highest price and the maximum value among the open and close prices.</li><li>The lower wick, which is the difference between the the minimum value among the open and close prices and the lowest price.</li></ul><blockquote>“The candlestick method provides a visual insight into market psychology by reflecting price movements over a specific time period” (Nison, Japanese Candlestick Charting Techniques, 1991). This method became a fundamental tool for traders globally.</blockquote><p>Depending on the type of candlestick and its position relative to the previous ones, a candlestick pattern forms, which can indicate either the continuation or reversal of a trend.</p><p>If the closing price is higher than the opening price, the body is typically shown in a lighter color (often white or green), signaling a bullish movement. Conversely, if the closing price is lower than the opening price, the body is displayed in a darker color (such as black or red), reflecting a bearish movement.</p><p>The length and position of the shadows offer further insights into volatility and price action, see figure 1 below for a representation of a candlestick.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*nzkcHB3mWZjnamnMm52QAw.png" /><figcaption><strong>Figure 1.</strong> Simple example of bullish and bearish candlesticks</figcaption></figure><p>For those new to candlestick trading, <a href="https://medium.com/@inbox.artem?source=post_page-----f3d2068ad4bb--------------------------------">Artem Stepanenko</a> provides a comprehensive schematic of patterns in his work.</p><h4>Setting Our Goals</h4><p>For this article, we aim to:</p><ol><li>Develop an application to structure targets for a recurrent neural network (RNN).</li><li>Identify and categorize candlestick patterns</li><li>Process and normalize targets to ensure consistency across various assets, dealing with intrinsict data volatility.</li></ol><h4>Setting Streamlit Up</h4><p>For the first step of this project, we are going to generate a Python file and name it CandleClassifier , but first let’s have a look at how this project is structured:</p><pre>/pyquant<br>├── classifications<br>│   ├── patterns # a map to render patterns in streamlit<br>│   └── target <br>│       ├── pattern1 # store images used to classify the pattern<br>│       │   ├── 0<br>│       │   └── 1<br>├── CSV<br>│   └── prices_volume.csv<br>├── pkl<br>│   ├── candles<br>│   └── target<br>│       ├── pattern1 # store a list of vectors for each pattern<br>│       │   ├── 0<br>│       │   └── 1<br>├── scripts<br>    └── CandleClassifier.py</pre><ul><li>classifications<strong>:</strong> This folder is used to store image information related to the candlestick patterns we are classifying. It contains:</li><li>patterns: Stores a map of the candlestick patterns we are working with, which is used for rendering patterns in Streamlit.</li><li>target<strong>: </strong>Contains the images that we are going to classify in this project, organized by pattern type.</li></ul><p>Each target that matches a class will be further processed into a list and saved in the pkl folder to be transformed into tensors.</p><p>Intuitively, scripts has the streamlit appliaction we are rendering and csv contains the data we are reading and processing into candles.</p><p>For this work I am retrieving data from<a href="https://www.metatrader5.com/en"> MetaTrader 5</a> , a powerful platform widely known among traders. The Data is stored in the prices_volume csv file.</p><p>Next, we have to import everything we need:</p><pre>import streamlit as st<br>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import matplotlib.patches as patches<br>import os<br>from io import BytesIO<br>from PIL import Image<br>import picklepy</pre><p>We now can move to the folder scripts, open a python terminal and then run streamlit locally with the command:</p><pre>streamlit run .\CandleClassifier.py </pre><p>The command above may vary depending on how you set your working directory.</p><p>This will render a locally hosted application, so that we can move foward.</p><h4>Processing OHLC Vectors</h4><p>The main issue to robustly detect candlestick patterns is the intrinsic volatility of the data.</p><p>Take the hammer pattern as an example, which can be represented by the OHLC vector [100, 102, 95, 102], figure 2, below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/84/1*6C-1fYPYH85E9aK8kcv-FQ.png" /><figcaption><strong>Figure 2.</strong> An elegant hammer pattern</figcaption></figure><p>It has a head composed by the body and a handle defined by the lower wick. We could try to define a mathematical equation to find it as:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2Fqztv8mDAqwuV5gv86v6r9f&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2Fqztv8mDAqwuV5gv86v6r9f&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="439" height="295" frameborder="0" scrolling="no"><a href="https://medium.com/media/46c4770d3b64a355685bf1e26d39f1b9/href">https://medium.com/media/46c4770d3b64a355685bf1e26d39f1b9/href</a></iframe><p>where the handle is the lower wick and the head is the body.</p><p>To classify the pattern as a hammer we still need the handle to be at least 3 times the body and the body to be at least 10% of the price range, otherwise, we may end up with a division tending to positive infinite.</p><p>If we apply equation 1 we would achieve something like figure 3, below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/97/1*9vGwWLvkhP-YjGnKZ4HxIQ.png" /><figcaption><strong>Figure 3</strong>. Minimal viable hammer</figcaption></figure><p>This particular ilustration was generated with the OHLC vector [100, 102, 82, 102].</p><p>Note in this case we only pushed the low to a limit where the body is at least 10% of the price change:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FwyJPYbeKA58Z4WSApnzQr8&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2FwyJPYbeKA58Z4WSApnzQr8&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="333" height="96" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c28cb516b4ebf74077a6266eef231bb/href">https://medium.com/media/9c28cb516b4ebf74077a6266eef231bb/href</a></iframe><p>However, there are over 60 different candlestick patterns, some formed by combinations of candles, making it an exhaustive task to define them mathematically.</p><p>Hopefully, we now can use the power of neural networks to helps us achieve the task of identifying complexes data patterns.</p><p>Yet to do so, and to succeed in any machine learning project, we still need to be able to accurately define our targets.</p><p>Back to the hammer example, as we are dealing with just one candle, we could summarize it as a vector. Furthermore, we could set its lowest value to 0 and its highest to 1, resulting in a normalized vector to be used in any further analyses we intend to conduct.</p><p>The OHLC vector [100, 102, 95, 102] in Figure 2 can be normalized as shown in Equation 3.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FeFLMdSp5XjeB1CV1qW62h3&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2FeFLMdSp5XjeB1CV1qW62h3&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="373" height="455" frameborder="0" scrolling="no"><a href="https://medium.com/media/07c8ab8862d526300be8d2f6e1848aed/href">https://medium.com/media/07c8ab8862d526300be8d2f6e1848aed/href</a></iframe><p>Now this process is understood, a pattern is still a combination of candles so that we need to normalize more than one candle at once.</p><p>Fortunatelly, the approach does not change for more than one candle.</p><p>The normalize_candles function performs Min-Max normalization, which is the same as what you would achieve using a MinMaxScaler from libraries such as scikit-learn.</p><pre>def normalize_candles(ohlc_data: np.array) -&gt; np.array:   <br>    &quot;&quot;&quot;<br>    Normalizes an OHLC (Open, High, Low, Close) data vector to a range of [0, 1].<br><br>    This function performs Min-Max normalization on the input OHLC data. It scales the values such that <br>    they fit within the range [0, 1], where the smallest value in the input becomes 0 and the largest value becomes 1.<br>    The normalized values are then rounded to 5 decimal places.<br><br>    Parameters:<br>    ohlc_data (numpy.ndarray): A numpy array containing the OHLC data to be normalized. The array should be one-dimensional.<br><br>    Returns:<br>    numpy.ndarray: A numpy array containing the normalized OHLC data, with values scaled to the range [0, 1] and rounded to 5 decimal places.<br><br>    Example:<br>    &gt;&gt;&gt; import numpy as np<br>    &gt;&gt;&gt; ohlc_data = np.array([100, 102, 95, 102])<br>    &gt;&gt;&gt; normalize_candles(ohlc_data)<br>    array([0.71429, 1.     , 0.     , 1.     ])<br>    &quot;&quot;&quot;<br>    min_value = ohlc_data.min()<br>    max_value = ohlc_data.max()<br>    scaled_values = (ohlc_data - min_value) / (max_value - min_value)<br>    scaled_values_rounded = np.round(scaled_values, 5)<br><br>    return scaled_values_rounded</pre><h4>Ploting Amazing Candlestick</h4><p>The best available tool for plotting candlesticks in python is plotly.graph_objects.Candlestick, allowing users to zoom, pan, and hover for detailed data insights.</p><p>On the other hand, I was almost losing my mind trying to classify patterns by zooming in and out, so I had to try a more effective approach.</p><p>Since I want images that can be used as targets for a machine learning model, I developed my own candlestick function to work with normalized OHLC data presented as it follows:</p><pre>def plot_normalized_candlestick(candle_vectors: np.array) -&gt; BytesIO:<br>    &quot;&quot;&quot;<br>    Plots a candlestick chart based on normalized OHLC data and returns the image as a binary stream.<br><br>    Parameters:<br>    ----------<br>    candle_vectors : np.array<br>        A NumPy array of shape (n, 4), where n is the number of candlesticks. Each row contains four float values representing<br>        the normalized OHLC data for a candlestick in the form (open, high, low, close).<br><br>    Returns:<br>    -------<br>    BytesIO<br>        A binary stream containing the PNG image of the candlestick chart.<br>    <br>    Notes:<br>    -----<br>    - The width of each candlestick is set to 0.2 units, and the spacing between candlesticks is set to 0.3 units.<br>    - Candlesticks are colored green if the close price is higher than or equal to the open price, and red otherwise.<br>    - The function adjusts the y-axis limits based on the minimum and maximum values of the provided OHLC data.<br>    - The plot is saved to a BytesIO buffer and returned as a PNG image.<br>    &quot;&quot;&quot;<br>    fig, ax = plt.subplots(figsize=(len(candle_vectors), len(candle_vectors)))<br>    width = 0.2 <br>    spacing = 0.3 <br><br>    for i in range(len(candle_vectors)):<br>        candle_vector = candle_vectors[i]<br>        adjusted_open, adjusted_high, adjusted_low, adjusted_close = candle_vector<br>        <br>        x = i * spacing<br>        <br>        lower_shadow_min = min(adjusted_open, adjusted_close)<br>        ax.plot([x, x], [adjusted_low, lower_shadow_min], color=&#39;black&#39;, linewidth=1)<br>        <br>        upper_shadow_max = max(adjusted_open, adjusted_close)<br>        ax.plot([x, x], [upper_shadow_max, adjusted_high], color=&#39;black&#39;, linewidth=1)<br>        <br>        color = &#39;green&#39; if adjusted_close - adjusted_open &gt;= 0 else &#39;red&#39;<br>        <br>        if np.round(adjusted_close - adjusted_open, 5) == 0:<br>            ax.plot(<br>                [x - width / 2, x + width / 2], <br>                [adjusted_close, adjusted_close], <br>                color=&#39;black&#39;, <br>                linewidth=1<br>            )<br>        else:<br>            rect = patches.Rectangle(<br>                (x - width / 2, min(adjusted_open, adjusted_close)), <br>                width, <br>                abs(adjusted_open - adjusted_close), <br>                linewidth=0, <br>                edgecolor=&#39;white&#39;, <br>                facecolor=color<br>            )<br>            ax.add_patch(rect)<br>    <br>    adjusted_max_high = max([candle[1] for candle in candle_vectors])<br>    adjusted_min_low = min([candle[2] for candle in candle_vectors])<br>    margin = 0.1<br>    ax.set_xlim(-width, len(candle_vectors) * spacing)<br>    ax.set_ylim(adjusted_min_low - margin, adjusted_max_high + margin)<br>    ax.grid(False)<br>    ax.set_xticks([])  <br>    ax.set_yticks([]) <br>    ax.yaxis.set_ticks_position(&#39;none&#39;)<br>    ax.yaxis.set_tick_params(labelleft=False)<br>    ax.spines[&#39;top&#39;].set_visible(False)<br>    ax.spines[&#39;right&#39;].set_visible(False)<br>    ax.spines[&#39;left&#39;].set_visible(False)<br>    ax.spines[&#39;bottom&#39;].set_visible(False)<br>    buf = BytesIO()<br>    plt.savefig(buf, format=&#39;png&#39;)<br>    buf.seek(0)<br>    plt.close(fig)<br>    <br>    return buf</pre><p>The plot_normalized_candlestick function takes an array as a parameter and returns a BytesIO object that can be rendered as an image in Streamlit.</p><p>I set the figsize to the length of the array to ensure that the entire pattern is properly framed.</p><p>Then, I iterate through candle_vectors to retrieve OHLC information. If the closing price is greater than the opening price, I paint the candle green; otherwise, I paint it red.</p><p>Additionally, if the closing price is equal to the opening price, the function draws a horizontal line across the width of each rectangle to mark Doji patterns.</p><p>The result of plotting a five-candle vector can be seen in Figure 4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*0ocUN1t-mKs1Fb3wPySspg.png" /><figcaption><strong>Figure 4</strong>. Plotting any candlestick pattern</figcaption></figure><h4>Loading Data In Streamlit</h4><p>Next, we are handling a couple of data processing functions we need to load data in streamlit.</p><p>First thing we have to to is to be able to upload a csv file to streamlit. This cand be done by calling function load_csv .</p><pre>def load_csv(file, encoding=&#39;utf-8&#39;, delimiter=&#39;,&#39;):<br>    df = pd.read_csv(file, encoding=encoding, delimiter=delimiter)<br>    df.columns = [col.lower() for col in df.columns]<br>    <br>    if &#39;date&#39; in df.columns and &#39;time&#39; in df.columns:<br>        df[&#39;datetime&#39;] = pd.to_datetime(df[&#39;date&#39;].astype(str) + &#39; &#39; + df[&#39;time&#39;].astype(str), format=&#39;%Y.%m.%d %H:%M&#39;)<br>        df.drop(columns=[&#39;date&#39;, &#39;time&#39;], inplace=True)<br>    elif &#39;date&#39; in df.columns:<br>        df[&#39;datetime&#39;] = pd.to_datetime(df[&#39;date&#39;], format=&#39;%Y.%m.%d&#39;)<br>        df.drop(columns=[&#39;date&#39;], inplace=True)<br>    <br>    df.set_index(&#39;datetime&#39;, inplace=True)<br>    <br>    return df</pre><p>Nonetheless, there are a few regularizations we are making by calling the fucntion. Note we are setting all columns to lower case for better readability and we set a datetime index to the loaded dataframe.</p><p>This is particular important since we are dealing with time spaced data an utterly want to retrieve the data index of when a pattern ocurred.</p><p>The second auxiliar function we need is one to load pkl files:</p><pre>def load_pkl(file_path):<br>    &quot;&quot;&quot;loads .pkl file&quot;&quot;&quot;<br>    with open(file_path, &#39;rb&#39;) as file:<br>        data = pickle.load(file)<br>    return data</pre><p>In this project, all information regarding candlestick patterns are stored in a python dictionaire called candle_patterns_info. I pass it later on to an streamlit expander to help user to get context of classifications.</p><p>Below, a quick look at the structure of the dictionaire:</p><pre><br>candle_patterns_info = {<br>        &quot;Doji&quot;: {<br>        &quot;Type&quot;: &quot;neutral&quot;,<br>        &quot;Image&quot;: &quot;doji.png&quot;,<br>        &quot;Definition&quot;: &quot;A doji has a very small body with shadows of varying lengths on both sides. It represents indecision in the market.&quot;,<br>        &quot;Significance&quot;: &quot;Shows uncertainty in the market and potential reversal or continuation depending on previous trends.&quot;,<br>        &quot;Confidence&quot;: &quot;weak&quot;<br>    },<br>        <br>    &quot;Marubozu&quot;: {<br>        &quot;Type&quot;: &quot;bullish&quot;,<br>        &quot;Image&quot;: &quot;marubozu.png&quot;,<br>        &quot;Definition&quot;: &quot;A Marubozu candle has a long body with no shadows. The opening and closing prices are the highest and lowest points respectively.&quot;,<br>        &quot;Significance&quot;: &quot;Indicates strong momentum in the direction of the body (bullish or bearish).&quot;,<br>        &quot;Confidence&quot;: &quot;strong&quot;<br>    } #...</pre><p>It contains:</p><ul><li>the candle pattern as thekey parameter,</li><li>the type of sign displayed by the pattern: bullish, bearish or neutral,</li><li>the image file associated to this pattern,</li><li>the definition provides a detailed explanation of how the pattern is formed, describing the specific features of the candlestick (e.g., body, shadows) and its implications,</li><li>the confindence specifies the level of certainty with which the pattern is interpreted, typically labeled as strong, moderate, or weak.</li></ul><h4>Saving Data From Streamlit To The Project Directory</h4><p>Once we get our targets from streamlit, we still need to store the classified images as well as the candle vectors for further usage.</p><p>The candle vectors that matched a candlestick pattern are saved back in \pkl\target\pattern1\1 and images are stored in \classifications\target\pattern1\1 .</p><p>To send data from streamlit back to our project directory I wrote functions save_classified_candles and save_classified_images :</p><pre>def save_classified_candles(base_path_target: str, <br>                            pattern_name: str, <br>                            class_label: str, <br>                            candle_size: int, <br>                            vectors: np.array):<br>    &quot;&quot;&quot;Save classified vectors to a PKL file in the target directory.&quot;&quot;&quot;<br>    pattern_path = os.path.join(base_path_target, pattern_name, class_label)<br>    os.makedirs(pattern_path, exist_ok=True)<br>    pkl_file = f&#39;{candle_size}_candles.pkl&#39;<br>    <br>    pkl_path = os.path.join(pattern_path, pkl_file)<br>    <br>    if os.path.exists(pkl_path):<br>        with open(pkl_path, &#39;rb&#39;) as f:<br>            all_classified_vectors = pickle.load(f)<br>    else:<br>        all_classified_vectors = []<br><br>    all_classified_vectors.extend(vectors)<br>    with open(pkl_path, &#39;wb&#39;) as f:<br>        pickle.dump(all_classified_vectors, f)<br>    <br>    st.success(f&#39;Candle vectors saved at {pkl_path}&#39;)</pre><p>The function mainly checks for a path to save the pattern. Evidentially, the pattern_name composes the pattern_path .</p><p>The class_label is a string parameter that tell us if target is 1 or 0, creating a new folder to split the data.</p><p>Finally, the base_path_pattern is where the project is located inside your system.</p><p>The first part of the code set ups the domain, so the second part appends the classified candle vector to a list of previously saved vectors.</p><p>This is a crucial step because, as shown in Figures 2 and 3, a candlestick pattern can exhibit some variation, meaning more than one target could correspond to the same pattern.</p><p>Here, each candlestick pattern must be generated using a specific number of candles (candle_size). This information is vital for target generation, so we include it in the name of the target.</p><p>Note we are using a st.sucess to display the result of the action on the app.</p><p>For saving images we can use function save_clssified_image below:</p><pre>def save_classified_image(buf: BytesIO, <br>                          base_path_figures: str, <br>                          pattern_name: srt, <br>                          class_label: str, <br>                          candle_size: int):<br>    &quot;&quot;&quot;Save the classified image to the figures directory with a unique index.&quot;&quot;&quot;<br>    target_path = os.path.join(base_path_figures, &#39;target&#39;, pattern_name, class_label)<br>    if not os.path.exists(target_path):<br>        os.makedirs(target_path)<br><br>    existing_files = [f for f in os.listdir(target_path) if f.endswith(&#39;.png&#39;)]<br>    indexes = []<br>    for f in existing_files:<br>        try:<br>            prefix = f&quot;{candle_size}_candles_&quot;<br>            if f.startswith(prefix):<br>                idx = int(f[len(prefix):-4])<br>                indexes.append(idx)<br>        except (IndexError, ValueError):<br>            continue<br>    <br>    next_index = max(indexes, default=0) + 1<br>    image_file = f&#39;{candle_size}_candles_{next_index}.png&#39;<br>    image_path = os.path.join(target_path, image_file)<br>    with open(image_path, &#39;wb&#39;) as f:<br>        f.write(buf.getbuffer())<br><br>    st.success(f&quot;Image saved at {image_path}&quot;)</pre><p>The only significant change is that we now save an index for each image we are saving and check if that image already exists in the current folder.</p><p>Of course, the function expects an image exists prior to saving it.</p><h4>Target Classification Tool In Streamlit</h4><p>Now we have covered everything we need it is time to write the main function that will render our streamlit up.</p><p>I break up this code into five steps:</p><ol><li>Defining Streamlit session_state variables,</li><li>Loading and sampling csv data,</li><li>Retrieving normalized candlestick vectors,</li><li>Rendering default candlestick patterns for comparisson,</li><li>Exhibit the candle vector and classify it.</li></ol><h4>Working With Session State</h4><p>If you are still not familiar with Streamlit, everytime you make a change on your application, the whole app gets an update.</p><p>That means in order to save information we need to store it in session state variables, a <a href="https://docs.streamlit.io/develop/api-reference/caching-and-state/st.session_state">class</a> provided by Streamlit to deal with reruns.</p><p>Hopefully, we can easy achieve that by just instanciating theses variables:</p><pre>def main():<br>    candle_info_patterns = load_pkl(&#39;..\\pyquant\\pkl\\candles\\candle_patterns_info.pkl&#39;)<br>    base_path_classifications = &#39;..\\pyquant\\classifications&#39;<br>    base_path_target = &#39;..\\pyquant\\pkl\\target&#39;<br>    <br>    st.title(&#39;Candle Classifier&#39;)<br>    st.session_state.data = None<br><br>    if &#39;candle_vectors&#39; not in st.session_state:<br>        st.session_state.candle_vectors = []<br>    if &#39;current_index&#39; not in st.session_state:<br>        st.session_state.current_index = 0<br>    if &#39;classification&#39; not in st.session_state:<br>        st.session_state.classification = []<br>    if &#39;date&#39; not in st.session_state:<br>        st.session_state.date = []</pre><p>Note we are instanciating four variables to the st.session_state:</p><ul><li>candle_vectors is a np.array that stores the normalized OHLC data</li><li>current_index helps us to move along the data and create interative buttons to navigate next and previous data.</li><li>classification holds the result of our target processing.</li><li>date retrieves the datetime to keep record of when the information was generated.</li></ul><p>Right under the definition of the main function, I have also definied the paths we are loading in this project.</p><p>Now we are all set to work dinamically and upload our variables without losing information when the app reruns.</p><h4>Loading A CSV File</h4><p>Streamlit offers an excellent solution for handling file uploads from our computer through the st.file_uploader, which renders as a widget that allows us to locally select the file we want to upload.</p><pre>st.markdown(&#39;### Upload CSV File&#39;)<br>encoding = st.text_input(&quot;Enter CSV encoding&quot;, value=&#39;utf-16&#39;)<br>uploaded_file = st.file_uploader(&quot;Upload CSV file&quot;, type=[&#39;csv&#39;]) <br><br>if uploaded_file is not None:<br>    st.session_state.data = load_csv(uploaded_file, encoding=encoding, delimiter=&#39;,&#39;)<br>    df = st.session_state.data.copy()<br>    <br>    col1, col2 = st.columns([1, 1])<br>    with col1:<br>        candle_size = st.number_input(&quot;Select number of candles per image&quot;, min_value=1, max_value=100, value=5, step=1)<br>    with col2:<br>        options = [&quot;Random&quot;, &quot;Tail&quot;, &quot;Head&quot;]<br>        order_option = st.selectbox(&quot;Select data order&quot;, options)<br><br>    default_sample_size = 100<br>    sample_size = st.slider(&quot;Select sample size&quot;, min_value=1, max_value=len(df) - 1, value=default_sample_size)<br>    if st.button(&quot;Process&quot;):<br>        max_start_index = len(df) - candle_size<br>        if order_option == &quot;Random&quot;:<br>            sampled_idx = np.random.choice(np.arange(max_start_index + 1), size=sample_size, replace=False)<br>        elif order_option == &quot;Tail&quot;:<br>            sampled_idx= np.arange(len(df) - sample_size, len(df))<br>        else:<br>            sampled_idx = np.arange(sample_size)</pre><p>Then everythime there is a file selected, we run the code above mainly to instanciate how we are processing our uploaded data.</p><p>It is mandatory to set candle_size to at least 1, but most candlestick patters are formed of 3 up to 5 candles.</p><p>Next, we are able to select how many samples we are classifying at once by changing parameter sample_size .</p><p>Additionally, there is a helpful option to sample data randomly, either from the beginning to the end or from the end to the start.</p><p>By clicking proccess button the csv file indexes will be sliced and stored so that we can retrieve candlestick patterns.</p><p>If all has gone right so far you your application should be as displayed in figure 5, below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*zgzc4gX8aWLap-QT9IbQtA.png" /><figcaption><strong>Figure 5</strong>. Processing a CSV file</figcaption></figure><h4>Retrieving Normalized Candlestick Vectors</h4><p>Now we have sampled indexes from our original csv file, we are ready to retrieve OHLC data and generate normalized candle vectors.</p><p>Note the code below is still running nested to the proccess button, so anytime we hit it we get new data changed into candles.</p><pre>st.session_state.candle_vectors = []<br>st.session_state.date = []<br>for start in sampled_idx:<br>    if start + candle_size &lt;= len(df):   <br>        segment = df.iloc[start:start + candle_size].sort_index(ascending=True)<br>        ohlc_data = segment[[&#39;open&#39;, &#39;high&#39;, &#39;low&#39;, &#39;close&#39;]].values<br>        candle_vector = normalize_candles(ohlc_data)<br>        if candle_vector is not None and not any(np.isnan(np.concatenate(candle_vector))):<br>            st.session_state.candle_vectors.append(candle_vector)<br>            st.session_state.date.append(df.index[start])</pre><p>We first reset candle_vectors and date to interate each starting index (start) we stored insample_idx .</p><p>Then we use iloc to slice data from start to candle_size in the original DataFrame, assigning OHLC values to the variable ohlc_data .</p><p>We call function normalize_candles appending its return to candle_vectors . We also save the datetime to keep a record.</p><h4>What To Classify</h4><p>Before plotting each vector in the list of candle_vectors, we need to be able to distinguish what we are actually trying to classify.</p><p>Defining the right target for your objective is, without a doubt, the most important issue when it comes to flaws in machine learning projects.</p><p>Therefore, I manually saved each pattern image and its information to serve as a guideline throughout the process:</p><pre>if st.session_state.data is not None:<br>    st.divider()<br>    st.markdown(&#39;### Classification Tool&#39;)<br><br>    pattern_type = st.selectbox(&quot;Select pattern type&quot;, [&quot;Bullish&quot;, &quot;Bearish&quot;])<br>    pattern_type = pattern_type.lower()  <br>    filtered_patterns = {name: info for name, info in candle_info_patterns.items() if info[&#39;Type&#39;] == pattern_type}<br>    if filtered_patterns:<br>        pattern_name = st.selectbox(&quot;Select pattern name&quot;, list(filtered_patterns.keys()))<br>        <br>        if pattern_name:<br>            with st.expander(pattern_name, expanded=True):<br>                pattern_info = filtered_patterns[pattern_name]<br>                st.write(f&quot;**Definition:** {pattern_info[&#39;Definition&#39;]}&quot;)<br>                st.write(f&quot;**Significance:** {pattern_info[&#39;Significance&#39;]}&quot;)<br>                st.write(f&quot;**Confidence:** {pattern_info[&#39;Confidence&#39;]}&quot;)<br><br>            image_filename = pattern_info.get(&#39;Image&#39;, None)<br>            if image_filename:<br>                image_path = os.path.join(base_path_classifications, f&quot;patterns/{pattern_type}/{image_filename}&quot;)<br>                if os.path.exists(image_path):<br>                    image = Image.open(image_path)<br>                    with st.container():<br>                        st.image(image, caption=f&quot;{pattern_name}&quot;, use_column_width=False, width=150)<br>                else:<br>                    st.write(&quot;Image file not found.&quot;)<br>            else:<br>                st.write(&quot;Pattern name not found in images dictionary.&quot;)<br>    else:<br>        st.write(f&quot;No patterns found for type &#39;{pattern_type}&#39;.&quot;)</pre><p>The above piece of code initialized bullish and bearish patterns from candle_info_patterns dictionaire.</p><p>Each key is a pattern_name used to display information in a st.expander and to show an default image of the pattern.</p><p>The should resume as it follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*DBmRaJtR1NuPtdHV6Pe3wQ.png" /><figcaption><strong>Figure 6</strong>. Classification tool: pattern exhibition</figcaption></figure><h4>Classifying Targets</h4><p>The final step of this initial project is to classify patterns, but before we call function plot_normalized_candlestick we still need to move along each st.session_state.current_index :</p><pre> st.divider()<br>    col1, col2 = st.columns([1, 1])<br>    with col1:<br>        if st.button(&quot;Previous&quot;):<br>            if st.session_state.current_index &gt; 0:<br>                st.session_state.current_index -= 1<br><br>    with col2:<br>        if st.button(&quot;Next&quot;):<br>            if st.session_state.current_index &lt; len(st.session_state.candle_vectors) - 1:<br>                st.session_state.current_index += 1<br>    idx = st.session_state.current_index<br>    if 0 &lt;= idx &lt; len(st.session_state.candle_vectors):<br>        buf = plot_normalized_candlestick(st.session_state.candle_vectors[idx])<br>        col1, col2 = st.columns([1,1])<br>        with col2:<br>            st.markdown(&#39;Current scaled vector&#39;)<br>            st.write(st.session_state.date[idx])<br>            st.dataframe(pd.DataFrame(st.session_state.candle_vectors[idx], columns=[&#39;open&#39;, &#39;high&#39;, &#39;low&#39;, &#39;close&#39;]))<br>        with col1:<br>            with st.container():<br>                if candle_size &lt;= 2:<br>                    st.image(buf, caption=f&quot;Candle Plot {idx + 1}&quot;, use_column_width=False, width=100)<br>                else:<br>                    st.image(buf, caption=f&quot;Candle Plot {idx + 1}&quot;, use_column_width=False, width=300)<br>    else:       <br>        st.write(&quot;Invalid index. Please check the data.&quot;)<br><br>    col1, col2 = st.columns([1,1])<br>    with col1:<br>        classify_pattern = st.selectbox(&quot;Select classification pattern&quot;, list(filtered_patterns.keys()))<br>    with col2:<br>        class_labels = st.radio(&quot;Select target&quot;, options=[&#39;0&#39;, &#39;1&#39;])<br>    <br>    if st.button(&quot;Save&quot;):<br>        target_folder = &#39;target&#39;<br>        save_path = os.path.join(base_path_classifications, target_folder, classify_pattern, class_labels)<br>        <br>        if not os.path.exists(save_path):<br>            os.makedirs(save_path)<br><br>        save_classified_image(buf, base_path_classifications, classify_pattern, class_labels, candle_size)<br>        save_classified_candles(base_path_target, classify_pattern, class_labels, candle_size, [st.session_state.candle_vectors[idx]])<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>What we are doing is just display two buttons Previousand Next that change the current_indexas we click on them.</p><p>Then we assign the variable buf as the return of the function plot_normalized_candlestick passing current_index to st.session_state.candle_vectors list.</p><p>We write the index, and also the respective candle vector, in a pandas DataFrame format.</p><p>Next, we ask the user to clarify information regarding the active classification (classify_pattern), because sometimes we may aim for one thing but end up discovering a another target.</p><p>Finally, class_labels identifies if the target is matched (1) or not (0).</p><p>By hiting the save button we call save_clssified_image and save_clssified_candles and are ready to continue the process of gererating targets for candlestick patterns.</p><h4>A Morning Star Pattern Target Classfication</h4><p>The video shows how would be the whole process of classification for the pattern Morning Star:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FebNHr_rckuA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DebNHr_rckuA&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/297a5814ba33acc5c3afb1b6993bb31a/href">https://medium.com/media/297a5814ba33acc5c3afb1b6993bb31a/href</a></iframe><p>Of course, for that video I was not able to get a posive target for the pattern.</p><h4>Final Considerations</h4><p>In this article we just created a tool to help us geting targets for our machine learning project.</p><p>Candlesticks are scpeacially a complicated task cause they don’t well behave in terms of math.</p><p>Now a massive part of the job is yet to be done. Classifications require time, trained eyes and a lot of patience.</p><p>Hope to be with you soon to put thoses vectors into tensors and run some layers of neurons.</p><p>Also, if you like my work, give me a<strong> clap. </strong>That support makes me keep writing!</p><h4>References</h4><p>Nison, Steve. Japanese Candlestick Charting Techniques: A Contemporary Guide to the Ancient Investment Techniques of the Far East. New York Institute of Finance, 1991.</p><p>Stepanenko, A. (2023, December 7). Creating a Binance Futures Trading Strategy with Japanese Candlestick Signals: A Step-by-Step Guide. Medium.</p><p>MetaTrader<strong> </strong>5. (n.d.). Retrieved September 8, 2024, from <a href="https://www.metatrader5.com/en">MetaTrader 5</a></p><p>Streamlit Team. (n.d.). st.session_state. Streamlit API Reference. Retrieved September 10, 2024, from <a href="https://docs.streamlit.io/develop/api-reference/caching-and-state/st.session_state">https://docs.streamlit.io/develop/api-reference/caching-and-state/st.session_state</a></p><p>Visit us at <a href="https://www.datadriveninvestor.com/"><em>DataDrivenInvestor.com</em></a></p><p>Subscribe to DDIntel <a href="https://www.ddintel.com/"><em>here</em></a>.</p><p>Join our creator ecosystem <a href="https://join.datadriveninvestor.com/"><em>here</em></a>.</p><p>DDI Official Telegram Channel: <a href="https://t.me/+tafUp6ecEys4YjQ1">https://t.me/+tafUp6ecEys4YjQ1</a></p><p>Follow us on <a href="https://www.linkedin.com/company/data-driven-investor"><em>LinkedIn</em></a>, <a href="https://twitter.com/@DDInvestorHQ"><em>Twitter</em></a>, <a href="https://www.youtube.com/c/datadriveninvestor"><em>YouTube</em></a>, and <a href="https://www.facebook.com/datadriveninvestor"><em>Facebook</em></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b1e19ff6212" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/target-classification-tool-for-candlestick-patterns-in-streamlit-7b1e19ff6212">Target Classification Tool for Candlestick Patterns in Streamlit</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[Is Modern Portfolio Theory Dead?]]></title>
            <link>https://medium.datadriveninvestor.com/is-modern-portfolio-theory-dead-17e8970f8f4a?source=rss-59d66406fdbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/17e8970f8f4a</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[portfolio]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[stock-market]]></category>
            <dc:creator><![CDATA[Guilherme Ziegler]]></dc:creator>
            <pubDate>Wed, 28 Aug 2024 15:53:49 GMT</pubDate>
            <atom:updated>2024-11-26T10:58:58.848Z</atom:updated>
            <content:encoded><![CDATA[<p>In my previous article <a href="https://medium.com/datadriveninvestor/coding-markowitzs-efficient-frontier-with-python-and-streamlit-97014e8cb06d?source=your_stories_page-------------------------------------">Coding Markowitz’s Efficient Frontier with Python and Streamlit</a>, I showed how to simulate the best configuration of weights for a chosen portfolio.</p><p>We also used Streamlit to code an app that downloads any ticker from Yahoo Finance and rebalances the allocation of weights in a given portfolio.</p><p>In this sequel, I will implement three python classes: Portfolio, BacktestPortfolios and BacktestAnalysis which allow any investor to test Modern Porfolio Theory (MTO) with a list of randomly generated portfolios.</p><p>For this section, I will not cover how MTO works, so please feel free to read my previous article if you are not familiar with the subject.</p><h4>Setting our goals</h4><p>Our main objective here is to test Modern Portfolio Theory along two years of empirical data, by rebalancing one thousand randomly generated portfolios in different windows of time.</p><p>In each timeframe, we choose the best configuration of weights for the highest S<em>harpe Ratio</em> as well as the <em>lowest portfolio risk</em> and check whether the invested capital increases or shrinks over each step of optimization.</p><p>The question we are trying to answer here is:</p><blockquote>“Can intelligent investors actually beat the market by consistently optimizing a chosen portfolio? What would be the performance of an MTO based strategy considering at least 1,000 random portfolios?”</blockquote><p>The question above evokes many feelings from my childhood. I remember my father, while working on his master’s degree in Finance, using Solver in Excel to optimize a few funds for a major Brazilian bank (Trintinalia, 2016).</p><p>That idea kept me always thinking about whether the previous behavior of the market is consistent enough to make decisions for the near future, as well as the accuracy and replicability of such educated forecasts.</p><h4>How is this paper organized?</h4><p>For the next parts of this paper I aim to:</p><ul><li>In this section, we discuss the implementation of the Python classes Portfolio ,BacktestPortfolios and BacktestAnalysisdemonstrating how these classes provide robust tools for applying Modern Portfolio Theory (MPT).</li><li>Describe how both my dummy and smart optimizers work, and evaluate the performance of my trading strategies.</li><li>Conclude whether the presented optimizers outperform a evenly diversified allocation.</li><li>Provide a Python library for replicable analysis of Markowitz’s Efficient Frontier.</li></ul><h4>Methodology</h4><p>I decided to use the <a href="https://pyportfolioopt.readthedocs.io/en/latest/">PyPortfolioOpt</a> library to calculate the weights that yield the highest Sharpe Ratio and lowest risk because it does a better job than I can in evaluating the Efficient Frontier (EF).</p><p>However, displaying the EF requires a covariance matrix with a convex solution, which is not always the case.</p><p>To address this issue, I developed my own simulation algorithm. It focuses on approximating the desired configuration of weights when calculations fail, similar to a variation of the code presented in my previous article.”</p><h4>Adopted premises</h4><ul><li>For this paper, I have not implemented constraints on the maximum and minimum values of weights, despite their sum needing to equal 1. The reason for that is that restrictions are just as good as guessing, and if I was going to test MPT, a guess is just not scientific.</li><li>The risk-free rate is zero due to the fact that the max_sharpe from <a href="https://pyportfolioopt.readthedocs.io/en/latest/">pyportfolioopt</a> EfficentFrontier needs at least one expected positive return to be greater than the risk-free rate.</li><li>The baseline strategy is to allocate weights equally to the number of assets in a portfolio, i.e., with five assets, the weight of each asset would be 20% of the total invested capital.</li><li>The calculation of weights does not take into consideration previous data points, so an optimization in the current step does not consider the returns and risk of those that came before.</li><li>The cost of allocation is not taken into consideration as I am comparing the returns of one portfolio with different strategies.</li></ul><h4>Pipeline of optimizations</h4><p>A simple ilustration of the pipeline is presented in figure 1, below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FsU47PEIdFWKNBCxIkILew.png" /><figcaption><strong>Figure 1</strong>. Visualization of chunks</figcaption></figure><p>For steps, we use a time window in days (i) that increases linearly with the number of optimizations, following an arithmetic progression.</p><p>The total number of optimization steps can be found by dividing the length of each portfolio’s returns <em>(s) </em>by the size of the time window <em>(i)</em>. The final step <em>(s/i) </em>size<em> </em>must be shortened, however, if the ratio is not an integer.</p><p>All combinations of portfolios were previously set to encompass two trading years of data.</p><p>I addressed the issue of positive and negative risk by implementing a dummy algorithm that strictly adheres to the Efficient Frontier (EF) allocation.</p><p>Additionally, I developed a smart version of it, which optimizes the portfolio only when returns are positive in a given step.</p><blockquote>“Intelligent investors should avoid losses when the bear is panicking the market. Well, actually they don’t, because mainly they are investing for the faith in the intrinsic value. Or at least they should.”</blockquote><h4>What does the code do?</h4><p>1. Downloading S&amp;P500 daily returns over the last two years.</p><p>2. Combining five randomly assets into a portfolio until 1,000 portfolios are generated.</p><p>3. Breaking down each portfolio into chunks of time windows of 30, 60, 90, 120, 150, and 180 days.</p><p>4. Using pyportfolioopt or the class Portfolio function simulate_frontierto determine the best weights for each chunk.</p><p>5. Calculating the return of each step compared to the initial amount of capital invested.</p><p>6. Repeating the previous pipeline for 1,000 portfolios and ploting the probability of each stragety outperform the evenly diversified allocation.</p><h4>Class Portfolio</h4><p>The class Portfolio is designed to optimize any investment portfolio. its parameters are:</p><ul><li>data (DataFrame) containing historical prices of assets,</li><li>the amount of invested_capital (float)</li><li>and the window_size (int) in days.</li></ul><pre>def __init__(self, data, invested_capital = 100000,  window_size=30):<br>    self.invested_capital = invested_capital<br>    self.data = data<br>    self.window_size = window_size</pre><p>Its self atributes are intuitive and can be retrieved as it follows:</p><pre># general processing atributes<br>self.chunk_dfs = self.process_data(window_size)<br>self.prices = self.get_prices()<br>self.names = self.get_asset_names()<br>self.dates  = self.get_last_dates()<br>self.sharpe_weights = self.get_weights()<br># optimization strategies and their self methods<br>self.sharpe_weights, self.max_sharpe_risk  = self.get_opt_values()<br>self.min_risk_weights, self.min_risk = self.get_opt_values(objective = &#39;risk&#39;)<br>self.max_sharpe = self.dummy_balancer(method = &#39;sharpe&#39;)<br>self.min_risk_control = self.dummy_balancer(method = &#39;risk_control&#39;)<br>self.min_risk = self.dummy_balancer(method = &#39;risk&#39;) <br>self.even_weights = self.dummy_balancer(method = &#39;even&#39;)<br>self.smart_max_sharpe_control = self.smart_balancer(method=&#39;sharpe_control&#39;)<br>self.smart_max_sharpe = self.smart_balancer(method = &#39;sharpe&#39;)<br>self.smart_min_risk_control = self.smart_balancer(method = &#39;risk_control&#39;)<br>self.smart_min_risk = self.smart_balancer(method = &#39;risk&#39;)<br>self.smart_even_weights = self.smart_balancer(method = &#39;even&#39;)<br># evaluation methods<br>self.portfolio_ROI  = self.get_portfolio_ROI()<br>self.plot_ROI = self.plot_ROI_over_time()</pre><p>Now, we are closely examining all of the above methods. For this overview, I instantiate the class Portfolio with a randomly generated portfolio. The outputs will be presented in the next sections.</p><p>As you may notice, in most of the methods inside Portfolio, I use the constructor self to access attributes and methods of the class. From now on, I will omitself as a parameter.</p><h4>Processing methods</h4><p>To break down any given portfolio into chunks of a specified window size, I wrote the function process_data presented below</p><pre>def process_data(self, window_size):    <br>    &quot;&quot;&quot;<br>    Processes data into chunks<br>    <br>    Parameters:<br>    - window_size: Size of the window.<br>    <br>    Returns:<br>    - List of DataFrames representing data chunks.<br>    &quot;&quot;&quot;<br>    chunk_dfs = []<br>    for i in range(0, len(self.data), window_size):<br>        if i + window_size &lt;= len(self.data):<br>            chunk_df = self.data.iloc[i:i+window_size].copy()<br>        else:<br>            chunk_df = self.data.iloc[i:].copy()<br>        chunk_dfs.append(chunk_df)<br>    return chunk_dfs</pre><p>It receives window_size to move along the dataframe indexes.</p><p>Note that the attribute self.data is within the method and contains the Adjusted Close Prices for the assets that compose the portfolio.</p><p>Overall, process_data slices the portfolio using window_size as the step for the for loop. It first checks if i + window_size is within the length of the portfolio. If so, it increments the number of days linearly until it reaches the last date.</p><p>The parameter self.data must be indexed with datetime values and contain all close prices for the portfolio (see Fig. 2).&quot;</p><p>This version clarifies the function’s purpose and how it operates on the portfolio data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*-ryR3V9-0zmtsGmtOcMxQA.png" /><figcaption><strong>Figure 2</strong>. Example of input for the data parameter</figcaption></figure><p>Once this is done, the function process_data returns a list chunk_dfs, stored in the attribute chunk_dfs, which is initialized by the code line:</p><pre>self.chunk_dfs = self.process_data(window_size)</pre><p>After slicing the portfolio, Portfolio initializes the accessory methods get_prices, get_asset_name, and get_last_dates, as follows:</p><pre>def get_prices(self):<br>    &quot;&quot;&quot;<br>    Gets the the last prices for each chunk.<br>    <br>    Returns:<br>    - List of last prices for each chunk.<br>    &quot;&quot;&quot;<br>    prices = []<br>    for chunk_df in self.chunk_dfs:<br>        last_values = chunk_df.iloc[-1].values<br>        prices.append(last_values)<br>    return np.array(prices)<br><br>def get_last_dates(self):<br>    &quot;&quot;&quot;<br>    Gets the last index for each chunk.<br>    <br>    Returns:<br>    - List of last indices for each chunk.<br>    &quot;&quot;&quot;<br>    last_indices = []<br>    for chunk_df in self.chunk_dfs[1:]:<br>        last_index = chunk_df.index[-1]<br>        last_index_date_only = str(last_index).split()[0]<br>        last_indices.append(last_index_date_only)<br>    return last_indices<br><br>def get_asset_name(self, string =&#39;_Close&#39; ):<br>    &quot;&quot;&quot;<br>    Gets the names of assets.<br><br>    Returns:<br>    - List of asset names.<br>    &quot;&quot;&quot;<br>    names = []<br>    df = self.chunk_dfs[0]<br>    for column in df.columns:<br>        if  string in column:<br>            names.append(column.replace(string, &#39;&#39;))<br>        else:<br>            names.append(column)<br>    return names</pre><p>These functions retrieve information from the chunk_dfs list. To optimize performance, each final price of the chunked dataframe is stored using the get_prices function. Similarly, for efficiency in optimization, the retrieval of the last dates occurs in the get_last_dates function.</p><p>As we aim to test over 1,000 portfolios, saving their names is mandatory for more detailed analyses. Note that get_asset_name appends columns that have _Close. All returns are stored in their respective self variables.</p><h4>Getting the best weights</h4><p>Next, I present two functions that decide which weights to use in each chunk dataframe: get_opt_values and simulate_frontier.</p><pre>def get_opt_values(self, lower_bound=0.00, upper_bound=1, objective=&#39;sharpe&#39;):<br>    <br>    &quot;&quot;&quot;<br>    Calculate optimal portfolio weights for each chunk of data using mean-variance optimization.<br><br>    Parameters:<br>    lower_bound : float, optional<br>        The minimum bound for the weights. Default is 0.00.<br>    upper_bound : float, optional<br>        The maximum bound for the weights. Default is 1.<br>    objective : str, optional<br>        The objective for optimization. Can be &#39;sharpe&#39; for maximizing the Sharpe ratio<br>        or &#39;min_volatility&#39; for minimizing portfolio volatility. Default is &#39;sharpe&#39;.<br>    Returns:<br>    np.array<br>        A numpy array of optimal weights for each chunk of data.<br>    &quot;&quot;&quot; <br>    <br>    opt_weights = []<br>    pfl_risk = []<br>    <br>    for i, chunk_df in enumerate(self.chunk_dfs):<br>        try: <br>            mu = expected_returns.mean_historical_return(chunk_df)<br>            S = risk_models.sample_cov(chunk_df)<br>            ef = EfficientFrontier(mu, S, weight_bounds=(lower_bound, upper_bound))<br>            if objective == &#39;sharpe&#39;:<br>                ef.max_sharpe(risk_free_rate=0)<br>            else:<br>                ef.min_volatility()<br>            cleaned_weights = ef.clean_weights()<br>            weights = [weight for _, weight in cleaned_weights.items()]<br><br>            risk = ef.port_volatility()<br>            opt_weights.append(weights)<br>            pfl_risk.append(risk)<br><br>        except Exception as e:<br>            <br>            #print(f&quot;Error calculating optimal weights for chunk {i} \n Trying to simulate closest weights&quot;)<br>            if objective == &#39;sharpe&#39;:<br>                simulated_max_sharpe_w, simulated_max_sharpe_risk  = self.simulate_frontier(chunk_df, risk_free_rate=0, objective=objective)<br>                opt_weights.append(simulated_max_sharpe_w)<br>                pfl_risk.append(simulated_max_sharpe_risk)<br>            else:<br>                simulated_lowest_risk_w, simulated_lowest_risk = self.simulate_frontier(chunk_df, objective=objective)<br>                opt_weights.append(simulated_lowest_risk_w)<br>                pfl_risk.append(simulated_lowest_risk)<br><br>    optimal_weights = [weights for weights in opt_weights if weights is not None]<br>    optimal_risk = [risk for risk in pfl_risk if risk is not None]<br>    <br>    return  np.array(optimal_weights),  np.array(optimal_risk)</pre><p>The get_opt_valuesfunction receives lower_bound (float), upper_bound (float), and objective (string) as parameters. Default values are 0 and 1, respectively, which means that the weights of all assets in a given portfolio may vary between these bounds.</p><p>In essence, this allows the EfficientFrontier method to calculate the optimal weights freely. If the function chooses to allocate weights closer to the upper bound, it implies that other components of the portfolio will be closer to the lower bound.</p><p>For instance, setting the upper bound to 20% and the lower bound to zero for a portfolio with five assets would result in any optimization allocating weights of 20%.</p><p>The parameter objective is used to instruct the function on how to optimize the weights. The default value is sharpe which calls the method max_sharpe; any other string would call min_volatility.</p><p>Initially, I attempt optimization using PyPortfolioOpt. However, if an exception occurs, I optimize by simulate_frontier.</p><p>Finally, the function returns a NumPy array of the optimal weights and the portfolio risk for each chunk in chunk_dfs.</p><h4>What if we fail?</h4><p>If it’s not possible to obtain optimized weights by simply calling get_weights, the function then calls simulate_frontier. This function takes the chunk_df that failed to optimize and attempts to generate the best weights by simulating the Efficient Frontier.</p><p>For a detailed explanation of the entire optimization process, you can refer to my previous article on this topic.</p><p>By default, I set risk_free_rate to zero, trading_days to 252, and perform 10,000 simulations for each chunk_df.</p><p>The objective parameter is initially set to &#39;Sharpe&#39;, although this is determined by the get_weights function. Subsequently, I store the weights in variables simulated_max_sharpe_w or simulated_lowest_risk_w, depending on our objective.</p><pre>def simulate_frontier(self, chunk_df, risk_free_rate=0, trading_days=252, simulations=10000, objective=&#39;sharpe&#39;):<br>    &quot;&quot;&quot;<br>    Simulates optimal asset allocation based on the Sharpe ratio within a <br>    specified tolerance range, and selects the one with the highest Sharpe <br>    Ratio.<br><br>    Parameters:<br>    - chunk_df: DataFrame containing asset prices.<br>    - risk_free_rate: Risk-free rate.<br>    - trading_days: Number of trading days.<br>    - simulations: Number of simulations.<br>    - sharpe_tolerance: Tolerance range for the Sharpe ratio.<br>    - objective: &#39;sharpe&#39; or &#39;risk&#39; to specify whether to maximize Sharpe ratio or minimize risk.<br><br>    Returns:<br>    - Numpy array representing optimal weights <br>    - Numpy array representing optimal portfolio risk<br>    &quot;&quot;&quot;<br>    max_sharpe_ratio = -np.inf<br>    min_positive_sd = np.inf<br>    optimal_weights = None<br>    num_assets = len(chunk_df.columns)<br>    simple_returns = chunk_df.pct_change().dropna().mean() * trading_days<br>    cov_matrix = chunk_df.pct_change().dropna().cov() * trading_days<br><br>    for _ in range(simulations):<br>        weights = np.random.random(num_assets)<br>        weights /= np.sum(weights)<br>        returns = np.dot(weights, simple_returns)<br>        var = np.dot(weights.T, np.dot(cov_matrix, weights))<br>        sd = np.sqrt(var)<br><br>        if objective == &#39;sharpe&#39;:<br>            sharpe_ratio = (returns - risk_free_rate) / sd<br>            if sharpe_ratio &gt; max_sharpe_ratio:<br>                max_sharpe_ratio = sharpe_ratio<br>                optimal_weights = weights<br>        elif objective == &#39;risk&#39;:<br>            if sd &gt; 0 and sd &lt; min_positive_sd:<br>                min_positive_sd = sd<br>                optimal_weights = weights<br>                <br>        else:<br>            raise ValueError(&quot;Objective must be either &#39;sharpe&#39; or &#39;risk&#39;.&quot;)<br>    <br>    return optimal_weights, sd</pre><h4>Dummy and smart optimizers</h4><p>Now, I will explain how the dummy optimization works. The fundamental premise behind any dummy strategy is:</p><blockquote>“Always trade when the optimization says you should”</blockquote><p>Meaning that, even if we get losses in the optimization, we will still rebalance the portfolio according to the best weight configuration we obtained.</p><p>To clarify this concept, consider the random portfolio shown in Figure 2 during the 13th step of optimization for the max_sharpe strategy (see Fig. 3).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*dzQgM62xpWyOhbl44i-1zg.png" /><figcaption><strong>Figure 3</strong>. Random portfolio optimization by dummy optimizer, 13th step.</figcaption></figure><p>As I did not impose any constraints on weights, our allocation was concentrated entirely (100%) in Simon Property Group, Inc. for the previous period (column weights_t12).</p><p>In the subsequent optimization round, the dummy balancer allocated 21% of the invested capital to Jabil Inc. and the remaining 79% to Etsy, Inc. (column weights_t13).</p><p>Analyzing the price changes, we observe that the prices of these assets chosen in the 13th step have increased, resulting in profits. However, since we had allocated zero funds to them in the 12th step, we did not benefit from these gains.</p><p>On the contrary, PTC Inc. experienced a drop in its price, so not having any funds allocated to it was beneficial.</p><p>Additionally, by selling 100% of Simon Property Group, Inc., we incurred a loss of 29 cents, as the price dropped from 169.64 to 169.35.</p><p>In conclusion, one strategy succeeds when total capital increases and fails when it decreases. Therefore, by always trading on gains or losses we are losing the chance to keep a lucrative position.</p><p>This is precisely the concept of my smart optimizer. It reallocates portfolio weights only when prices rise, exposing itself to the risk of downturns. Still, if rebalances following optimization best weights.</p><p>By only reallocating gains, I ensure that the total amount of capital increases through the optimization process. However, the portfolio remains vulnerable to systematic risk, and the total capital can decrease as a result.</p><p>In other words, the smart optimizer would refrain from trading in the 13th step because prices have fallen for Simon Property Group, Inc,</p><h4>Optimization strategies</h4><p>For both dummy and smart optimizers I defined four different strategies that are set with parameter method:</p><ol><li>sharpe takes the weights that achieve the highest Sharpe Ratio, representing the optimal balance of risk and return for a given portfolio</li><li>riskselects the weights that minimize portfolio risk, without emphasizing returns.</li><li>even allocates weights evenly among the assets in the portfolio.</li><li>sharpe_controland risk_control allocate weights only for the first step of the optimization, keeping them to all chunks.</li></ol><p>The last two are baseline strategies used for comparison, allowing us to observe how optimization over different time windows diverges from an initial point in time.</p><p>To clarify, we maintain the same weights from the first step and retain them until the end. If optimizing over time windows proves superior to a single optimization, we should observe a noticeable deviation in ROI over time.</p><h4>Dummy optimization</h4><p>Next, I will go through the functions dummy_balancer and smart_balancer below.</p><pre>def dummy_balancer(self, method=&#39;sharpe&#39;):<br>    &quot;&quot;&quot;<br>    Adjusts the weights of a portfolio based on the specified method.<br><br>    Parameters:<br>    - method (str, optional): The balancing method to use. <br><br>    Possible values are:<br>    - &#39;sharpe&#39;: Uses the Sharpe weights.<br>    - &#39;risk&#39;: Uses the minimum risk weights.<br>    - &#39;sharpe_control&#39;: Uses the Sharpe weights of the first optimization<br>    - &#39;even&#39;: Distributes the weights equally among the assets.<br>    - &#39;risk_control&#39;: <br><br>    Returns:<br>    - simple_weights_balanced_portfolio (list of pandas.DataFrame): <br>    A list of DataFrames, each containing the prices, weights, quantities,<br>    and capital invested for each asset in each period.<br>    &quot;&quot;&quot;<br>    # retrieving last prices<br>    prices = self.prices<br>    if method == &#39;sharpe&#39;:<br>        weights = self.sharpe_weights<br>    elif method == &#39;risk&#39;:<br>        weights = self.min_risk_weights<br>    elif method == &#39;even&#39;:<br>        weights = np.full_like(prices, 1 / prices.shape[1])<br>    elif method == &#39;risk_control&#39;:<br>        weights = np.full_like(prices, self.min_risk_weights[0])<br>    elif method == &#39;sharpe_control&#39;:        <br>        weights = np.full_like(prices, self.sharpe_weights[0])<br>    else:  <br>        raise f&#39;Method {method} is not valid&#39;<br>    total_capital = np.zeros_like(prices) <br>    quantities = np.zeros_like(prices)<br>    simple_weights_balanced_portfolio = []<br>    <br>    for i in range(1, len(weights)):<br>        df = pd.DataFrame()<br>        quantities[i-1] = self.invested_capital * weights[i-1] / prices[i-1] <br>        total_capital[i] = quantities[i-1] * prices[i]   <br>        quantities[i] = np.sum(total_capital[i]) * weights[i] / prices[i]<br>        df[f&#39;prices_t{i-1}&#39;] = prices[i - 1]<br>        df[f&#39;prices_t{i}&#39;] = prices[i]<br>        df[f&#39;weights_t{i-1}&#39;] = weights[i-1]<br>        df[f&#39;weights_t{i}&#39;] = weights[i]<br>        df[f&#39;funds_t{i}&#39;] = prices[i] * quantities[i]<br>        df[f&#39;quantities_t{i-1}&#39;] = quantities[i-1]<br>        df[f&#39;quantities_bought_t{i}&#39;] = quantities[i] - quantities[i-1]<br>        df[f&#39;quantities_t{i}&#39;] = quantities[i]<br>        df[f&#39;invested_capital_t{i-1}&#39;] = quantities[i-1] * prices[i-1]<br>        df[f&#39;invested_capital_t{i}&#39;] = total_capital[i]<br>        df[f&#39;cumulative_capital_t{i-1}&#39;] = df[f&#39;invested_capital_t{i-1}&#39;].cumsum()<br>        df[f&#39;cumulative_capital_t{i}&#39;] = df[f&#39;invested_capital_t{i}&#39;].cumsum()<br>        df.index = self.names<br>        simple_weights_balanced_portfolio.append(df)<br>    return simple_weights_balanced_portfolio</pre><p>The first part of the function defines an elif clause to choose weights based on the method passed as a parameter.</p><p>Note that we define a self attribute for each method and optimizer.</p><pre>self.min_risk_weights = self.get_weights(objective = &#39;risk&#39;)<br>self.max_sharpe_control= self.dummy_balancer(method=&#39;sharpe_control&#39;)<br>self.max_sharpe = self.dummy_balancer(method = &#39;sharpe&#39;)<br>self.min_risk_control = self.dummy_balancer(method = &#39;risk_control&#39;)<br>self.min_risk = self.dummy_balancer(method = &#39;risk&#39;) <br>self.even_weights = self.dummy_balancer(method = &#39;even&#39;)<br>self.smart_max_sharpe_control = self.smart_balancer(method=&#39;sharpe_control&#39;)<br>self.smart_max_sharpe = self.smart_balancer(method = &#39;sharpe&#39;)<br>self.smart_min_risk_control = self.smart_balancer(method = &#39;risk_control&#39;)<br>self.smart_min_risk = self.smart_balancer(method = &#39;risk&#39;)<br>self.smart_even_weights = self.smart_balancer(method = &#39;even&#39;)</pre><p>Therefore, the attribute self.even_weights, for example, assigns the self.dummy_balancer function with the method even.</p><p>The second part of the function involves the mathematical operations required to optimize a chunk_df.</p><pre>total_capital = np.zeros_like(prices) <br>quantities = np.zeros_like(prices)<br>simple_weights_balanced_portfolio = []<br># Looping optimizations<br>for i in range(1, len(weights)):<br>    df = pd.DataFrame()<br>    quantities[i-1] = self.invested_capital * weights[i-1] / prices[i-1] <br>    total_capital[i] = quantities[i-1] * prices[i]   <br>    quantities[i] = np.sum(total_capital[i]) * weights[i] / prices[i]<br>    df[f&#39;prices_t{i-1}&#39;] = prices[i - 1]<br>    df[f&#39;prices_t{i}&#39;] = prices[i]<br>    df[f&#39;weights_t{i-1}&#39;] = weights[i-1]<br>    df[f&#39;weights_t{i}&#39;] = weights[i]<br>    df[f&#39;funds_t{i}&#39;] = prices[i] * quantities[i]<br>    df[f&#39;quantities_t{i-1}&#39;] = quantities[i-1]<br>    df[f&#39;quantities_bought_t{i}&#39;] = quantities[i] - quantities[i-1]<br>    df[f&#39;quantities_t{i}&#39;] = quantities[i]<br>    df[f&#39;invested_capital_t{i-1}&#39;] = quantities[i-1] * prices[i-1]<br>    df[f&#39;invested_capital_t{i}&#39;] = total_capital[i]<br>    df[f&#39;cumulative_capital_t{i-1}&#39;] = df[f&#39;invested_capital_t{i-1}&#39;].cumsum()<br>    df[f&#39;cumulative_capital_t{i}&#39;] = df[f&#39;invested_capital_t{i}&#39;].cumsum()<br>    df.index = self.names<br>    simple_weights_balanced_portfolio.append(df)<br>return simple_weights_balanced_portfolio</pre><p>First, we initialize total_capital and quantities using np.zeros_like(prices), which creates an array of zeros with the same shape and data type as the input prices.</p><p>Next, we initialize simple_balanced_portfolio as an empty list to store the results of the optimization.</p><p>Then, we assume the first round of weights to be our initial allocation. Since there is no need for optimization at index 0, we define a loop starting from index 1 up to the length of weights.</p><p>Now, let’s examine how the quantities can be calculated, as shown in equation 1 below:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2Fu3eiX3ny8iDjEdHWhdo4mK&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2Fu3eiX3ny8iDjEdHWhdo4mK&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="683" height="112" frameborder="0" scrolling="no"><a href="https://medium.com/media/a37591d3fb21aa853ad24674126d2247/href">https://medium.com/media/a37591d3fb21aa853ad24674126d2247/href</a></iframe><p>where the summation represents the total sum of the funds for all assets <em>i</em> from <em>1</em> to <em>n</em>. This sum is then multiplied by the weight of each specific asset <em>i</em> and divided by its price.</p><p>For the dummy optimizer, the total capital will always match the amount of funds available for rebalancing; thus, we do not need a separate variable for funds.</p><p>So, the total quantities of each asset in a portfolio are calculated by multiplying the invested_capital by the ratio of weights to prices in a given period.</p><p>To calculate the total_capital, we multiply the quantities we had in the previous period by the price we have in the current period, as shown in equation 2.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FumPSsgmUvApSgopEzFDvxJ&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2FumPSsgmUvApSgopEzFDvxJ&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="338" height="169" frameborder="0" scrolling="no"><a href="https://medium.com/media/b752ce6d8e3729bd7da963f42db20a5f/href">https://medium.com/media/b752ce6d8e3729bd7da963f42db20a5f/href</a></iframe><p>Finally, for each optimization step, we check whether total_capital increases or decreases and apply the rule described in Equation 1 accordingly.</p><p>The quantities bought for each step are determined by subtracting the quantities in the current period from those in the previous period. Since we are adjusting both losing and winning positions, our primary focus remains on the total capital. Naturally, we only purchase the differences.</p><p>The remainder of the function simply creates a dataframe with all calculated information and stores it inside simple_balanced_portfolio.</p><h4>Smart optimization</h4><p>The smart_balancer follows the same basic logic as described in dummy optimization, so I will focus on the differences between the two functions:</p><pre>def smart_balancer(self, method=&#39;sharpe_control&#39;):<br>    prices = self.prices<br>    if method == &#39;sharpe&#39;:<br>        weights = self.sharpe_weights<br>    elif method == &#39;risk&#39;:<br>        weights = self.min_risk_weights<br>    elif method == &#39;even&#39;:<br>        weights = np.full_like(prices, 1 / prices.shape[1])<br>    elif method == &#39;risk_control&#39;:<br>        weights = np.full_like(prices, self.min_risk_weights[0])<br>    else:<br>        weights = np.full_like(prices, self.sharpe_weights[0])<br><br>    sold_all = np.zeros_like(prices)<br>    funds = np.zeros_like(prices)<br>    total_capital = np.zeros_like(prices)<br>    quantities = np.zeros_like(prices)<br>    smart_weights_balanced_portfolio = []<br>    <br>    for i in range(len(weights)):<br>        df = pd.DataFrame()<br>        if i == 0:<br>            quantities[0] = self.invested_capital * weights[i] / prices[i]<br>            total_capital[0] = self.invested_capital * weights[i]<br>        else:<br>            for j in range(0, len(prices[i])):<br>                if prices[i][j] &gt; prices[i - 1][j]:<br>                    funds[i][j] = (prices[i][j]) * quantities[i - 1][j]<br>                    sold_all[i][j] = 1<br>                else:<br>                    funds[i][j] = 0<br>                    sold_all[i][j] = 0<br>                    <br>            total_funds = np.sum(funds[i])<br>            quantities[i] = total_funds * weights[i] / prices[i]<br><br>            for k in range(0, len(prices[i])):<br>                if sold_all[i][k] == 0:<br>                    quantities[i][k] += quantities[i - 1][k]<br>                    total_capital[i][k] = quantities[i - 1][k] * prices[i - 1][k] + quantities[i][k] * prices[i][k]<br>                else:<br>                    total_capital[i][k] = quantities[i][k] * prices[i][k]<br>           <br>            df[f&#39;opt_weights{i}&#39;] =  weights[i]<br>            df[f&#39;prices_t{i-1}&#39;] = prices[i - 1]<br>            df[f&#39;prices_t{i}&#39;] = prices[i]<br>            df[f&#39;weights_t{i-1}&#39;] = weights[i-1]<br>            df[f&#39;weights_t{i}&#39;] = total_capital[i] / np.sum(total_capital[i]) <br>            df[f&#39;funds_t{i}&#39;] = funds[i]<br>            df[f&#39;quantities_t{i-1}&#39;] = quantities[i - 1]<br>            df[f&#39;quantities_t{i}&#39;] = quantities[i]<br>            df[f&#39;invested_capital_t{i-1}&#39;] = quantities[i - 1] * prices[i - 1]<br>            df[f&#39;invested_capital_t{i}&#39;] = total_capital[i]<br>            df[f&#39;cumulative_capital_t{i-1}&#39;] = df[f&#39;invested_capital_t{i-1}&#39;].cumsum()<br>            df[f&#39;cumulative_capital_t{i}&#39;] = df[f&#39;invested_capital_t{i}&#39;].cumsum()<br>            df.index = self.names<br>            smart_weights_balanced_portfolio.append(df)<br><br>    return smart_weights_balanced_portfolio</pre><p>We need to initialize two additional lists: sold_all and funds:</p><p>sold_all tracks when we sell all quantities of an asset, while funds stores the funds generated from those sales.</p><pre>sold_all = np.zeros_like(prices)<br>funds = np.zeros_like(prices)<br>total_capital = np.zeros_like(prices) <br>quantities = np.zeros_like(prices)<br>smart_weights_balanced_portfolio = []</pre><p>Next, we calculate initial quantitiesand total_capitalfor the first index. Then, we check if each asset has experienced a positive change in prices.</p><pre>for j in range(0, len(prices[i])):<br>    if prices[i][j] &gt; prices[i - 1][j]:<br>        funds[i][j] = (prices[i][j]) * quantities[i - 1][j]<br>        sold_all[i][j] = 1<br>    else:<br>        funds[i][j] = 0<br>        sold_all[i][j] = 0 </pre><p>We set sold_all to 0 when the current price is lower than the previous price and to 1 when there are gains.</p><p>Essentially, we obtain funds from gains and maintain the quantities in the current period the same as in the previous period if we are losing money. However, we still rebalance the portfolio with optimized weights, so quantities for assets where we lose money may also increase.</p><p>The vector operation below helps us understand the sold_all process, using prices for any given current and previous periods.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2F4TRv9LGqbF51Xysmd6j1sA&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2F4TRv9LGqbF51Xysmd6j1sA&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="428" height="228" frameborder="0" scrolling="no"><a href="https://medium.com/media/89d05ee47597350e395ca57f2599fd6a/href">https://medium.com/media/89d05ee47597350e395ca57f2599fd6a/href</a></iframe><p>Analyzing the first line, we see that the current price of $43 is greater than the previous price of $40. Therefore, the sold_all vector gets the value of one in the first row.</p><p>On the contrary, row number 3 shows an example where the current price is less than the previous price. Therefore, sold_all is set to zero in this row.</p><p>Furthermore, it is intuitive that fundsare the product of previous quantities and the current price, only when sold_all is one.</p><p>By funds, I mean all the capital available to reallocate without losing money. This is precisely where risk-return optimization intersects with real-life trading:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FkZNxLmukybdRSfEjJJ8i1s&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2FkZNxLmukybdRSfEjJJ8i1s&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="472" height="228" frameborder="0" scrolling="no"><a href="https://medium.com/media/096ae775369fdd8c9bc4f419696aef93/href">https://medium.com/media/096ae775369fdd8c9bc4f419696aef93/href</a></iframe><p>In summary, the funds total $303 in the example above, which is the available capital for reallocating weights in a given portfolio. Therefore, the quantities to be bought are given by:</p><pre>quantities[i] =  np.sum(funds[i]) * weights[i] / prices[i]</pre><p>It’s important to note that we need to sum each row of funds before multiplying by the weight-price ratio, equation 1.</p><p>Since we are only reallocating gains, the weights of each asset in the portfolio will not match the Efficient Frontier allocation. Instead, they will be a weighted average of previous and current weights, weighted by quantities.</p><blockquote>In a nutshell, we sum our gains and allocate them to the best weights possible. As a result, we aim to improve the overall risk-return ratio within the portfolio without liquidating losing positions.</blockquote><pre>quantities[i] =  np.sum(funds[i]) * weights[i] / prices[i]                   <br>for k in range(0, len(prices[i])):<br>    if sold_all[i][k] == 0:<br>        quantities[i][k] += quantities[i-1][k]<br>        total_capital[i][k]  = quantities[i-1][k] * prices[i-1][k] + quantities[i][k] * prices[i][k]<br>    else:<br>        total_capital[i][k] = quantities[i][k] * prices[i][k]<br>weights[i] = (total_capital[i] / np.sum(total_capital[i]))</pre><p>Next, we utilize sold_all to update quantities in the current period by adding quantities from the previous period where sold_all is zero.</p><p>Note that when we have gains from assets, mathematically we only need to sell everything and rebuy it with the new weights. Since we do not sell anything when we have losses, we must increment the optimized quantities from the previous ones.</p><p>Additionally, in this scenario, total_capital is given by:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FdeZFvSjV9BZiKYzjc9psT7&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2FdeZFvSjV9BZiKYzjc9psT7&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="503" height="135" frameborder="0" scrolling="no"><a href="https://medium.com/media/efb160d57ea1cdf7cd42c659d7c7704c/href">https://medium.com/media/efb160d57ea1cdf7cd42c659d7c7704c/href</a></iframe><p>Finally, the portfolio weights are updated by dividing each asset’s total capital by the sum of total capital across the entire portfolio, but we keep track of the optimized weight in column opt_weights.</p><h4>Return over investment</h4><p>To conclude class Portfolio, we still need to analyze the results. The most effective metric is calculating the return on investment (ROI), as per equation 7, for each strategy.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FdXJ7u9pCfmtSiqDRv3PBYU&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2FdXJ7u9pCfmtSiqDRv3PBYU&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="683" height="112" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e8d0d4dff53049e88d28e7ff3a53135/href">https://medium.com/media/2e8d0d4dff53049e88d28e7ff3a53135/href</a></iframe><p>Since we have segmented the portfolio into chunks, each chunk has its own ROI, always compared to the invested capital.</p><p>The function get_portfolio_ROIdoes the calculation of ROI for each optimization strategy:</p><pre>def get_portfolio_ROI(self):<br>    optimal_ROI = []<br>    portfolios = [<br>        (&quot;sharpe_control&quot;, self.max_sharpe_control),<br>        (&quot;sharpe&quot;, self.max_sharpe),<br>        (&quot;min_risk_control&quot;, self.min_risk_control),<br>        (&quot;min_risk&quot;, self.min_risk),<br>        (&quot;even_weights&quot;, self.even_weights),<br>        (&quot;smart_sharpe_control&quot;, self.smart_max_sharpe_control),<br>        (&quot;smart_max_sharpe&quot;, self.smart_max_sharpe),<br>        (&quot;smart_min_risk_control&quot;, self.smart_min_risk_control),<br>        (&quot;smart_min_risk&quot;, self.smart_min_risk),<br>        (&quot;smart_even_weights&quot;, self.smart_even_weights)<br>    ]<br>    num_periods = len(portfolios[0][1])<br>    <br>    for i in range(num_periods):<br>        opt_ROI = {} <br>        for name, portfolio in portfolios:<br>            this_opt = portfolio[i][f&#39;cumulative_capital_t{i+1}&#39;].iloc[-1]<br>            previous_opt = portfolio[i][f&#39;cumulative_capital_t{i}&#39;].iloc[-1] if i &gt; 0 else self.invested_capital<br>            previous_ROI = this_opt / previous_opt<br>            latest_ROI = this_opt / self.invested_capital<br>            opt_ROI[name] = {<br>                &quot;previous_ROI&quot;: round(previous_ROI, 4),<br>                &quot;lastest_ROI&quot;: round(latest_ROI, 4)<br>            }<br>        optimal_ROI.append(opt_ROI)<br><br>   return optimal_ROI</pre><p>For each strategy, it calculates previous_ROIand latest_ROI which are respectively:</p><ol><li>the total capital of the current optimization divided by the total capital of the previous optimization</li><li>the total capital of the current optimization divided by the initial invested capital.</li></ol><p>Finally, we can plot our results for a given portfolio:</p><pre><br>  def plot_ROI_over_time(self, return_type=&#39;portfolio_ROI&#39;, method=&#39;smart&#39;):<br>      if return_type == &#39;portfolio_ROI&#39;:<br>          df = self.portfolio_ROI<br>      elif return_type == &#39;optimization_ROI&#39;:<br>          df = self.optimization_ROI<br>      else:<br>          raise ValueError(&quot;Invalid return_type. Use &#39;portfolio_ROI&#39; or &#39;optimization_ROI&#39;.&quot;)<br>      columns_to_plot = [col for col in df.columns if method in col]<br><br>      fig, ax = plt.subplots(figsize=(10, 6))<br>      for column in columns_to_plot:<br>          ax.plot(df.index, df[column], label=column)<br>      ax.set_xlabel(&#39;Date&#39;)<br>      ax.set_ylabel(&#39;ROI&#39;)<br>      ax.set_title(&#39;ROI Over Time for Different Strategies&#39;)<br>      ax.legend()<br>      ax.grid(True)<br>      ax.set_xticks(df.index)<br>      ax.set_xticklabels(self.dates, rotation=45)<br>      <br>      return fig</pre><h4>Random portfolio outcome</h4><p>Let’s have a look at one random portfolio as I showed in figure 3.</p><p>For this test I am going to set parameters to default as it follows:</p><pre>data = random_p<br>invested_capital = 100000,  <br>window_size=30<br>pf1 = Portfolio(random_p)<br>pf1.plot_ROI</pre><p>When I call the plot_ROI, I obtain the ROI for all smart strategies of the random portfolio I passed, as shown in Figure 3 below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*wHlAkXxxaRcMR419EjoGUQ.png" /><figcaption><strong>Figure 4.</strong> ROI of smart strategies for a random portfolio, window_size = 30 days.</figcaption></figure><p>Note the axis Date moves 30 trading days from one optimization to another.</p><p>To be honest, we cannot make any conclusions just looking at figure 4. However, for this peculiar optimization all strategies seem to converge at the end.</p><p>Also, returns often display patterns in reaction to systemic risk spikes, leading to a tendency for different strategies to exhibit similar behavior.</p><p>This particular example was randomly generated, and Step 14 is presented below for the smart_even_weights strategy. Naturally, all funds are allocated to 20% and split evenly to the assets.</p><pre>pf1.smart_even_weights[13]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FX7_rvYbXkxcx0e3QnlM3A.png" /><figcaption><strong>Figure 5.</strong> Step 13th for strategy smart_even_weights in a random portfolio.</figcaption></figure><h4>Optimizing 1,000 portfolios</h4><p>The Portfolio class is designed to optimize a single portfolio, so to handle more 999 portfolios, we need to use the BackrestPortfolios, designed specifically to instantiate and manage multiple portfolios at once.</p><p>It receives as paramets:</p><ol><li>assetsis the list of assets with adjusted close prices, all having the same length.</li><li>num_combinations defines how many combinations are to be genarated.</li><li>num_assets is the number of assets in each portfolio combination.</li><li>window_size is already known from class Portfolio</li><li>seed initializes a random seed for reproducibility of results.</li></ol><pre>class BacktestPortfolios:<br>    def __init__(self, assets, num_combinations, num_assets, window_size=30, seed=52):<br>        self.assets = assets<br>        self.window_size = window_size<br>        self.num_assets = num_assets<br>        self.num_combinations = num_combinations<br>        self.seed = seed<br>        self.combinations = self.generate_combinations()<br>        self.portfolios = self.analyze_portfolios()<br>        self.smart_strategies, self.dummy_strategies = self.normalize_strategies()       </pre><p>Therefore, considering we set num_combinations to 1,000 and num_assets to 5, we will generate 1,000 portfolios, each containing five assets.</p><p>Additionally, we will optimize using window_size. To keep our results reproducible, seed allows us to generate the same combinations and test different approaches.</p><p>Now let’s have a look at funcion generate_combinations:</p><pre>def generate_combinations(self):<br>  random.seed(self.seed)<br>  combinations = []<br>  for _ in range(self.num_combinations):<br>      shuffled_assets = self.assets[:]<br>      random.shuffle(shuffled_assets)<br>      combination = random.sample(shuffled_assets, self.num_assets)<br>      concatenated_df = pd.concat(combination, axis=1, join=&#39;inner&#39;)<br>      if not concatenated_df.empty:<br>          combinations.append(concatenated_df)<br>  return combinations</pre><p>We use a loop that runs num_combinations times. This loop will generate the desired number of portfolios.</p><p>Inside the loop, we shuffle the list of assets to ensure randomness. This helps in generating unique combinations each time.</p><p>After shuffling, we randomly select a subset of assets. The number of assets in each combination is specified by num_assets.</p><p>We then concatenate the selected assets into a single DataFrame by using inner join to ensure that only the common data points across all selected assets are included.</p><h4>Multiple initialization of Portfolio</h4><p>Once we have generated our portfolio combinations, the next step is to analyze each of them. We do so, by calling analyze_portfolios:</p><pre>def analyze_portfolios(self):<br>  portfolios = {}<br>  for i, df in tqdm(enumerate(self.combinations), total=self.num_combinations):<br>      portfolio_name = f&#39;n_assets_{self.num_assets}_window_size_{self.window_size}_{i}&#39;<br>      try:<br>          portfolios[portfolio_name] = Portfolio(data=df, invested_capital=100000, window_size=self.window_size)<br>      except Exception as e:<br>          print(f&quot;Error analyzing portfolio {portfolio_name}: {e}&quot;)<br>  return portfolios</pre><p>We loop through each portfolio combination stored in self.combinations. The enumerate function provides both the index (i) and the portfolio data (df) for each iteration.</p><p>For each portfolio, we generate a unique name using the attributes we pass on init.</p><p>Finally, we store the analyzed portfolios in a dictionary (portfolios).</p><h4>Evaluating optimizations</h4><p>Each portfolio has been processed through the Portfolio class, which means it inherits all methods from this class.</p><p>As shown in Figure 4, we cannot determine if one strategy outperforms another by examining just one portfolio.</p><p>By normalizing each strategy against a baseline, we can evaluate whether, across a thousand portfolios, each strategy has a higher likelihood of generating returns that exceed the baseline.</p><p>This can be expressed in terms of probability: a successful strategy should have a higher likelihood of outperforming the baseline compared to a less effective strategy.</p><p>Therefore, we can set a threshold for comparison. In this case, I set the threshold to be the probability of exceeding an even allocation, meaning our target will be any normalized ROI greater than 1.</p><p>However, we still need to normalize all tested strategies to a baseline. This is done by calling self.normalize_strategies()below:</p><pre>def normalize_strategies(self, return_type=&#39;portfolio_ROI&#39;,<br>                         roi_type=&#39;lastest_ROI_df&#39;, <br>                         period=&#39;last&#39;):<br>    smart_normalized_strategies = []<br>    dummy_normalized_strategies = []<br>    for _, plf in self.portfolios.items():<br>        roi_data = getattr(plf, return_type)<br><br>        if not roi_data: <br>            continue<br><br>        if period == &#39;last&#39;:<br>            roi_data = [roi_data[-1]]<br><br>        for period_data in roi_data:<br>            smart_denominator = period_data.get(&#39;smart_even_weights&#39;, {}).get(roi_type, 1)<br>            dummy_denominator = period_data.get(&#39;even_weights&#39;, {}).get(roi_type, 1)<br><br>            smart_normalized = {key: value.get(roi_type, 0) / smart_denominator<br>                                for key, value in period_data.items()<br>                                if &#39;smart&#39; in key and &#39;smart_even_weights&#39; not in key<br>                                }<br>            dummy_normalized = {key: value.get(roi_type, 0) / dummy_denominator<br>                                for key, value in period_data.items()<br>                                if &#39;smart&#39; not in key and &#39;even_weights&#39; not in key<br>                                }<br><br>            smart_normalized_strategies.append(smart_normalized)<br>            dummy_normalized_strategies.append(dummy_normalized)<br><br>    return smart_normalized_strategies, dummy_normalized_strategies</pre><p>The function retrieves the last ROI of each strategy in a given portfolio and normalizes it by by smart_even_weights, for smart strategies, and by even_weights for dummy strategies.</p><p>We return the lists smart_normalized_strategies and dummy_normalized_strategiesthat include all data from every strategy across all portfolios instantiated in the BacktestPortfolio class.</p><h4>Putting all together</h4><p>Now let’s instanciate 1,000 portfolios for each window of time we previoes determined:</p><pre>windows = [30, 60, 90, 120, 150, 180]<br>nassets = 5<br>seeds = [37, 42, 10, 20, 30]<br>ncombinations = 200<br><br>backtest_results = {}<br><br>for window in windows:<br>    for seed in tqdm(seeds):<br>        backtest_portfolio = BacktestPortfolios(assets=assets, num_combinations=ncombinations, num_assets=nassets, window_size=window, seed=seed)<br>        backtest_results[f&#39;backtest_window_{window}_seed_{seed}&#39;] = backtest_portfolio<br>        # saving each batch in a pkl file.<br>        with open(f&#39;backtest_{nassets}_assets_for_{ncombinations}_ptf_window_{window}_seed_{seed}.pkl&#39;, &#39;wb&#39;) as f:<br>            pickle.dump(backtest_portfolio, f)</pre><p>Basically, we set a for loop for the windows we are optimizing, ensuring the same seeds. This approach is necessary to track progress since 1,000 portfolios can take over 8 hours to complete.</p><p>That’s also why I wrote the BacktestAnalysis class — to separate the processing from portfolio generation.</p><pre>class BacktestAnalysis:<br>    &quot;&quot;&quot;<br>    A class used to manage and analyze backtest strategies and portfolios.<br><br>    Attributes<br>    ----------<br>    smart_strategies : list or dict<br>        A dictionary to store the smart strategies for each window size. If `load` is True, this will be a<br>        dictionary where the keys are the window sizes, and the values are lists of strategies loaded from pickle files.<br>    dummy_strategies : list or dict<br>        A dictionary to store the dummy strategies for each window size. Similar to `smart_strategies`, this will<br>        be a dictionary if `load` is True.<br>    portfolios : None or dict<br>        A dictionary to store portfolios for each window size if `load` is True. Initialized as `None`.<br>    load : bool<br>        A flag indicating whether to load existing optimizations from pickle files. Defaults to False.<br>    window_size : list<br>        A list of window sizes used for backtesting. Defaults to [30, 60, 90, 120, 150, 180].<br><br>    Methods<br>    -------<br>    load_optimizations():<br>        Loads backtest optimizations from pickle files located in the &#39;../pkl&#39; directory, updating `smart_strategies`,<br>        `dummy_strategies`, and `portfolios` for each window size.<br>    &quot;&quot;&quot;<br><br>    def __init__(self, <br>                 smart_strategies=None,<br>                 dummy_strategies=None, <br>                 load: bool = False, <br>                 window_size: list = None):<br><br>        self.smart_strategies = smart_strategies if smart_strategies else []<br>        self.dummy_strategies = dummy_strategies if dummy_strategies else []<br>        self.portfolios = None<br>        self.load = load<br>        self.window_size = window_size if window_size else [30, 60, 90, 120, 150, 180]<br><br>        if self.load:<br>            self.load_optimizations()<br>    <br>    def load_optimizations(self):<br>        base_dir = &#39;..\\pkl&#39;<br>        all_smart_strategies = {ws: [] for ws in self.window_size}<br>        all_dummy_strategies = {ws: [] for ws in self.window_size}<br>        all_portfolios = {ws: [] for ws in self.window_size}<br>        <br>        for filename in os.listdir(base_dir):<br>            if filename.endswith(&#39;.pkl&#39;):<br>                for ws in self.window_size:<br>                    if f&#39;window_{str(ws)}&#39; in filename:<br>                        file_path = os.path.join(base_dir, filename)<br>                        try:<br>                            with open(file_path, &#39;rb&#39;) as file:<br>                                backtest_portfolio = pickle.load(file)<br>                                all_smart_strategies[ws].extend(backtest_portfolio.smart_strategies)<br>                                all_dummy_strategies[ws].extend(backtest_portfolio.dummy_strategies)<br>                                all_portfolios[ws].extend(backtest_portfolio.portfolios)<br>                                <br>                        except (pickle.UnpicklingError, EOFError, KeyError) as e:<br>                            print(f&quot;Error processing file {filename}: {e}&quot;)<br><br>        self.smart_strategies = all_smart_strategies<br>        self.dummy_strategies = all_dummy_strategies<br>        self.portfolios = all_portfolios</pre><p>The class should be initialized with the returns from the normalize_strategies function.</p><p>However, since I had to run several optimizations across different time windows, which took a few days, I created a function called load_optimizations. This function reads data from any window that I previously saved in a .pkl file like:</p><pre>analysis = BacktestAnalysis(load=True, window_size=[30, 60,90, 120, 150, 180])</pre><p>Now, let’s review its methods:</p><pre>def test_distribution(self, strategy_type=&#39;smart&#39;, keys=&#39;all&#39;, window_size=None):<br>    &quot;&quot;&quot;<br>    Tests the distribution of data from a specified type of strategy (smart or dummy) for normality.<br><br>    Parameters:<br>    strategy_type (str): The type of strategy to test. Either &#39;smart&#39; or &#39;dummy&#39;.<br>    keys (str or list, optional): <br>    The keys to test. If &#39;all&#39;, tests all keys found in the strategies. <br>    If a list of keys, only tests the specified keys. Default is &#39;all&#39;.<br><br>    Returns:<br>    list of dict: A list of dictionaries containing the results of the normality test for each key.<br>        Each dictionary has the following keys:<br>        - &#39;key&#39;: The key being tested.<br>        - &#39;normal&#39;: A boolean indicating if the distribution is normal (p-value &gt; 0.05).<br>        - &#39;p_value&#39;: The p-value from the Shapiro-Wilk test for normality.<br>    &quot;&quot;&quot;<br>    distribution_results = []<br>    <br>    if window_size is None:<br>        window_size = [self.window_size]<br>        <br>    for ws in window_size:<br>        if strategy_type == &#39;smart&#39;:<br>            strategies = []<br>            strategies.extend(self.smart_strategies.get(ws, []))<br>                <br>        elif strategy_type == &#39;dummy&#39;:<br>            strategies = []<br>            strategies.extend(self.dummy_strategies.get(ws, []))<br>        else:<br>            raise ValueError(&quot;Invalid strategy_type. Must be &#39;smart&#39; or &#39;dummy&#39;.&quot;)<br><br>        if keys == &#39;all&#39;:<br>            all_keys = set().union(*(strategy.keys() for strategy in strategies))<br>        else:<br>            all_keys = keys<br>                    <br>        all_data = {key: [] for key in all_keys}<br>        <br>        for strategy in strategies:<br>            for key in all_data.keys():<br>                value = strategy.get(key, None)<br>                if value is not None:<br>                    if isinstance(value, (list, np.ndarray)):<br>                        all_data[key].extend(value)<br>                    else:<br>                        all_data[key].append(value)<br>                            <br>        for key in all_data.keys():<br>            if len(all_data[key]) &gt;= 3:<br>                _, p_value = shapiro(all_data[key])<br>                normal = p_value &gt; 0.05<br><br>                distribution_results.append({<br>                    &#39;key&#39;: key,<br>                    &#39;normal&#39;: normal,<br>                    &#39;p_value&#39;: p_value,<br>                    &#39;window_size&#39;: ws<br>                })<br><br>                if normal:<br>                    self.plot_histogram(data=all_data[key], strategy=f&#39;{strategy_type}_{key}&#39;, window_size=ws)<br>                else:<br>                    self.plot_kde(data=all_data[key], strategy=f&#39;{strategy_type}_{key}&#39;, window_size=ws)<br>            else:<br>                print(f&quot;Insufficient data for key &#39;{key}&#39; to perform normality test.&quot;)<br>            <br>    return distribution_results</pre><p>The function begins by initializing an empty list, distribution_results, to store the collected data for each strategy.</p><p>When key set to default, the function reads self.smart_strategies and self.dummy_strategies retrieving each single strategy for each window in window_size.</p><p>The key can be set to include all strategies that were executed in the Portfolio class.</p><p>Finally, it tests if data points follow a normal distribuition performing a Shapiro-Wilk test. The function interprets the p-value to determine whether the data follows a normal distribution (p-value ≥ 0.05 indicates normality).</p><p>If the data is normally distributed, the function will call self.plot_histogram; otherwise, it will call self.plot_kde passing the strategyand the window_size.</p><pre> def plot_histogram(self, <br>                    data,<br>                    strategy, <br>                    prob=1, <br>                    window_size = None, <br>                    auto_save=True):<br>      &quot;&quot;&quot;<br>      Plots a histogram of initial returns for a specific strategy and adjusts the bar colors based on data quartiles.<br>  <br>      Args:<br>          data (list or array-like): List or array containing the initial return data to be plotted.<br>          strategy (str): The name of the strategy to be included in the chart title and legend.<br>          prob (float, optional): Probability value to highlight with a vertical line on the chart. Default is 1.<br>          auto_save (bool, optional): If True, automatically saves the generated chart as a PNG file. Default is True.<br>  <br>      Returns:<br>          None<br>  <br>      Note:<br>          - The generated chart includes:<br>          - A histogram of the data with bars colored according to quartiles.<br>          - A black line representing the normal distribution fitted to the data.<br>          - A red vertical line indicating the value specified by `prob`.<br>          - The probability of returns greater than `prob` displayed in the legend.<br>  <br>      Example:<br>          &gt;&gt;&gt; plot_histogram(data=[0.1, 0.5, 0.3, 0.7], strategy=&#39;StrategyA&#39;, prob=0.2)<br>      &quot;&quot;&quot;<br>      fig, ax = plt.subplots(figsize=(12, 8))  # Create a figure and axis object<br>  <br>      q1, q2, q3 = np.percentile(data, [25, 50, 75])<br>      n, bins, patches = ax.hist(data, bins=30, alpha=0.7, label=strategy, edgecolor=&#39;black&#39;)<br>  <br>      for patch, bin_left in zip(patches, bins[:-1]):<br>          if bin_left &lt; q1:<br>              patch.set_facecolor(&#39;red&#39;)<br>          elif bin_left &lt; q2:<br>              transition_ratio = (bin_left - q1) / (q2 - q1)<br>              patch.set_facecolor(plt.cm.Blues(transition_ratio))<br>          elif bin_left &lt; q3:<br>              transition_ratio = (bin_left - q2) / (q3 - q2)<br>              patch.set_facecolor(plt.cm.Blues(transition_ratio))<br>          else:<br>              patch.set_facecolor(&#39;blue&#39;)<br>  <br>          mu, std = norm.fit(data)<br>          bin_centers = 0.5 * (bins[:-1] + bins[1:])<br>          p = norm.pdf(bin_centers, mu, std)<br>          p_scaled = p * np.max(n) / np.max(p)<br>          ax.plot(bin_centers, p_scaled, &#39;k&#39;, linewidth=2, label=&#39;Normal Distribution&#39;, alpha=0.5)<br>          ax.axvline(x=1, color=&#39;r&#39;, linestyle=&#39;--&#39;, label=&#39;Value 1&#39;)<br>          probability = np.sum(np.array(data) &gt; prob) / len(data)<br>          ax.legend([f&#39;Probability of returns &gt; 1: {probability:.2f}&#39;])<br>          ax.set_title(f&#39;Histogram of Initial Returns for: {strategy}  for {len(data)} combinations&#39;)<br>          ax.set_xlabel(&#39;Last_ROI&#39;)<br>          ax.set_ylabel(&#39;Frequency&#39;)<br>          ax.set_xlim(min(data) - 0.1 * abs(min(data)), max(data) + 0.1 * abs(max(data)))<br>          ax.set_ylim(0, max(n) + 0.25 * max(n))<br>          ax.grid(True)<br>  <br>          if auto_save:<br>              fig_name = f&#39;backtest_for_{len(data)}_combinations_{window_size}_for_strategy_{strategy}.png&#39;<br>              fig.savefig(fig_name, bbox_inches=&#39;tight&#39;)  # Save the figure with tight bounding box<br>  <br>          plt.show()</pre><p>Mainly, the function plot_histogram and self.plot_kde both take as parameters:</p><ol><li>data from the strategies that follow a normal destribuiton.</li><li>The strategy that will be plotted.</li><li>The threshold for comparison, with prob set to 1.</li><li>window_size is passed by test_distribution function.</li><li>auto_save as a boolean variable set to True to save the figure in a png file.</li></ol><pre>def plot_kde(self, data, strategy, prob=1, auto_save=True):<br>        &quot;&quot;&quot;<br>        Plots a Kernel Density Estimate (KDE) plot of initial returns for a specific strategy and highlights different data quartiles.<br><br>        Args:<br>            data (list or array-like): List or array containing the initial return data to be plotted.<br>            strategy (str): The name of the strategy to be included in the chart title and legend.<br>            prob (float, optional): Probability value to highlight with a vertical line on the chart. Default is 1.<br>            auto_save (bool, optional): If True, automatically saves the generated chart as a PNG file. Default is True.<br><br>        Returns:<br>            None<br><br>        Note:<br>            - The generated chart includes:<br>            - A KDE plot with different shades of blue for different data quartiles.<br>            - A red vertical line indicating the value specified by `prob` and displaying the probability of data greater than `prob`.<br>            - The KDE plot is displayed with appropriate x and y limits, and the chart is saved if `auto_save` is True.<br><br>        Example:<br>            &gt;&gt;&gt; plot_kde(data=[0.1, 0.5, 0.3, 0.7], strategy=&#39;StrategyA&#39;, prob=0.2)<br>        &quot;&quot;&quot;<br>        fig, ax = plt.subplots(figsize=(12, 8))  # Create a figure and axis object<br><br>        kde = gaussian_kde(data)<br>        x_values = np.linspace(min(data) - 0.1 * abs(min(data)), max(data) + 0.1 * abs(max(data)), 1000)<br>        y_values = kde(x_values)<br>        q1, q2, q3 = np.percentile(data, [25, 50, 75])<br>        ax.fill_between(x_values, y_values, where=(x_values &lt; q1), color=plt.cm.Blues(0.2), alpha=0.5)<br>        ax.fill_between(x_values, y_values, where=(x_values &gt;= q1) &amp; (x_values &lt; q2), color=plt.cm.Blues(0.4), alpha=0.5)<br>        ax.fill_between(x_values, y_values, where=(x_values &gt;= q2) &amp; (x_values &lt; q3), color=plt.cm.Blues(0.6), alpha=0.5)<br>        ax.fill_between(x_values, y_values, where=(x_values &gt;= q3), color=plt.cm.Blues(0.8), alpha=0.5)<br>        prob_greater_than = np.sum(np.array(data) &gt; prob) / len(data)<br>        ax.axvline(x=1, color=&#39;r&#39;, linestyle=&#39;--&#39;, label=f&#39;Probability &gt; {prob}: {prob_greater_than:.2f} for {len(data)} combinations&#39;)<br>        ax.set_title(f&#39;KDE Plot - {strategy}&#39;)<br>        ax.set_xlabel(&#39;ROI_initial_period&#39;)<br>        ax.set_ylabel(&#39;Density&#39;)<br>        ax.legend()<br>        ax.set_xlim(min(data) - 0.1 * abs(min(data)), max(data) + 0.1 * abs(max(data)))<br>        ax.set_ylim(0, np.max(y_values) + 0.25 * np.max(y_values))<br>        ax.grid(False)<br><br>        if auto_save:<br>            fig_name = f&#39;backtest_for_{len(data)}_combinations_window_size_{self.window_size[0]}_for_strategy_{strategy}.png&#39;<br>            fig.savefig(fig_name, bbox_inches=&#39;tight&#39;)  # Save the figure with tight bounding box<br><br>        plt.show()</pre><p>They plot the histogram or the Kernel Density Estimate (KDE) when the data is not normally distributed.</p><p>It marks on the graph the probability of the strategy being greater than the chosen threshold, hereby defined as 1.</p><p>As a result, it should produce a graph similar to Figure 6 below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*HgtbokR5QVxywLZvJ3Wz6w.png" /><figcaption><strong>Figure 6.</strong> Probability of strategy smart_max_sharpe outperforms smart_even_weights, window_size = 60 days.</figcaption></figure><p>It is quite intuitive to see that the probability of smart_max_sharpe outperforming the strategy smart_even_weights is 44%, which is less than simply flipping a coin.</p><p>Thus, there is no evidence, after running 1,000 portfolios, that maximizing Sharpe ratio optimization is better than just splitting allocation evenly.</p><p>In my <a href="https://github.com/GuilhermeZiegler/pyquant">github </a>account, you can check for all tests I ran in this article.</p><h4>Is Modern Portfolio Theory Dead after all?</h4><p>Checking all the results of the test in a histogram may not be the easiest way to conclude.</p><p>Therefore, I ran another function inside the BacktestAnalysis class that pivots all probabilities of returns for the given strategies:</p><pre>def get_probabilities(self, strategy=&#39;smart&#39;, prob=1, auto_save=True):<br>    &quot;&quot;&quot;<br>    Computes the probability of metrics exceeding a specified probability threshold for different strategies.<br><br>    Args:<br>        strategy (str, optional): The type of strategy to analyze. Can be &#39;smart&#39; or &#39;dummy&#39;. Default is &#39;smart&#39;.<br>        prob (float, optional): Probability threshold to determine if metrics are considered exceeded. Default is 1.<br><br>    Returns:<br>        pd.DataFrame: A DataFrame with probabilities of metrics exceeding the specified threshold for each strategy key.<br><br>    Note:<br>        - The DataFrame is rounded to three decimal places and includes metrics for each strategy key.<br>        - If `strategy` is &#39;smart&#39;, it uses `self.smart_strategies`; otherwise, it uses `self.dummy_strategies`.<br><br>    Example:<br>        &gt;&gt;&gt; df = get_results(strategy=&#39;smart&#39;, prob=0.2)<br>        &gt;&gt;&gt; print(df)<br>    &quot;&quot;&quot;<br><br>    if strategy == &#39;smart&#39;:<br>        all_strategies = self.smart_strategies<br>    else:<br>        all_strategies = self.dummy_strategies<br><br>    probabilities_dict = {}<br><br>    for key, strategies in all_strategies.items():<br>        metrics = {}<br>        metric_count = {}<br><br>        for strat in strategies:<br>            for metric, value in strat.items():<br>                if metric not in metrics:<br>                    metrics[metric] = 0<br>                    metric_count[metric] = 0<br><br>                if value &gt; prob:<br>                    metrics[metric] += 1<br>                metric_count[metric] += 1<br>        <br>        probabilities = {metric: (metrics[metric] / metric_count[metric] if metric_count[metric] &gt; 0 else 0)<br>                        for metric in metric_count}<br>        <br>        probabilities_dict[key] = probabilities<br><br>    df_probabilities = pd.DataFrame(probabilities_dict).T<br>    df_probabilities = df_probabilities.round(3)<br><br>    if auto_save:<br>        csv_file_name = f&#39;probabilities_greater_than_{prob}_for_{strategy}.csv&#39;<br>        df_probabilities.to_csv(csv_file_name, index=True)<br><br>    return df_probabilities</pre><p>The function above just count the frequencies of returns over one specified probability for each window, then it pivotes it in a pandas DataFrame.</p><p>For dummy strategies, the results are presented as it follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*7gHOdey0poeQMQK9fRbT5g.png" /><figcaption><strong>Figure 7</strong>. Summary for dummy strategies</figcaption></figure><p>We can see from Figure 7 there is a tendency for probability to increase with longer window sizes. This may indicate that fewer optimizations are necessary to achieve a certain degree of risk-return ratio.</p><p>Considering the results for dummy strategies, only the Sharpe strategy underperforms compared to the even weights allocation, apart from window size 150 (p &gt; 1 = 0.649).</p><p>Interestingly, all controls outperform the multiple optimization strategies, such as min_risk and Sharpe. This suggests that a single optimization may outperform multiple optimizations over time.</p><p>This fact is not intuitive and has made me think a lot about its causes. It doesn’t make sense to me because a single-step optimization may place too much weight on just a few assets.</p><blockquote>So, how can it show a greater probability of returns over time?</blockquote><p>The strategies that minimize risk have outperformed all others, strongly supporting modern portfolio theory. This suggests that, contrary to my initial hypothesis, it remains a valuable tool for portfolio optimization.</p><blockquote>Science after all is losing batles to your own imagination.</blockquote><p>That may be true due to the fact that most of managers learn how to optimize following this approach.</p><p>In other words, the market will respond to the action of the agents in accordance to <strong>Rational Expectations Theory.</strong></p><p>If market makers use all available information efficiently and rationally to form their expectations about economic variables, such as prices, interest rates, and economic growth, the fluctuations in the price of the assets may follow this pattern in a vicious cycle.</p><p>Now let’s have a look at the smart strategies, summarized in figure 8.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*YnM3f38uQtsXN7zJL0ScNQ.png" /><figcaption><strong>Figure 8</strong>. Summary for smart strategies</figcaption></figure><p>As we can definitely see from the image above, not a single strategy outperformed smart_even_weights, as the chance of normalized returns greater than one is less than 0.5 for all scenarios.</p><blockquote>So basically, my smart optimizer is not as smart as I initially thought. Well done, Markowitz.</blockquote><p>We still must find out whether smart_even_weights outperforms all dummy strategies or not. This can be achieved by retrieving loading an optimization batch atBacktestPortfolios and retrieving the ROI for all strategies:</p><pre># opens a batch <br>pfl_bath_200 = joblib.load(&#39;..\\pkl\\backtest_5_assets_for_200_ptf_window_30_seed_13.pkl&#39;)<br>data = []<br><br># window size and seed for the previous pkl file<br>window_size = 30<br>nassets = 5<br><br># list to extract all data from get_portfolio_ROI<br># this is possible because BacktestPortfolios inherits all atributes from Portfolio.<br>all_roi = []<br>for i, pfl in enumerate(pfl_bath_200.portfolios.items()):<br>   roi_dict = pfl_bath_200.portfolios[f&#39;n_assets_{nassets}_window_size_{window_size}_{i}&#39;].get_portfolio_ROI()<br>   all_roi.append(roi_dict)<br><br># We now have a list of dictionaires<br># Iterate over each dictionary in the list<br>for idx, item in enumerate(all_roi):<br>    for period, roi_dict in enumerate(item):<br>        for strategy, roi_values in roi_dict.items():<br>            previous_roi = roi_values[&#39;previous_ROI&#39;]<br>            lastest_roi = roi_values[&#39;lastest_ROI&#39;]<br>            data.append({<br>                &#39;Portfolio&#39;: idx,<br>                &#39;Optimization step&#39;: period,<br>                &#39;Strategy&#39;: strategy,<br>                &#39;Previous ROI&#39;: previous_roi,<br>                &#39;Lastest ROI&#39;: lastest_roi<br>            })<br><br>df = pd.DataFrame(data)<br><br>data = []<br><br># Iterate over each dictionary in the list<br>for idx, item in enumerate(all_roi):<br>    for period, roi_dict in enumerate(item):<br>        for strategy, roi_values in roi_dict.items():<br>            previous_roi = roi_values[&#39;previous_ROI&#39;]<br>            lastest_roi = roi_values[&#39;lastest_ROI&#39;]<br>            data.append({<br>                &#39;Portfolio&#39;: idx,<br>                &#39;Optimization step&#39;: period,<br>                &#39;Strategy&#39;: strategy,<br>                &#39;Previous ROI&#39;: previous_roi,<br>                &#39;Lastest ROI&#39;: lastest_roi<br>            })<br><br>df = pd.DataFrame(data)</pre><p>The code above shows how to extract all ROI from each portfolio inside a batch pkl file. Since BacktestPortfolios inherits all atributes from Portfolio, we can acess each portfolio by calling get_portfolio_ROI .</p><p>Next we iterate over each dictionary in the list and extract lastest_ROI storing them into a list of returns by Optimization step as show below, figure 9.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*bFIXi3jAgoONng2o-mEpIg.png" /><figcaption><strong>Figure 9.</strong> Getting returns of each portfolio by optimization step</figcaption></figure><p>Finally, we group our data to get average ROI:</p><pre><br>df = df.groupby([&#39;Optimization step&#39;, &#39;Strategy&#39;], as_index=False).agg({<br>    &#39;Previous ROI&#39;: &#39;mean&#39;,<br>    &#39;Lastest ROI&#39;: &#39;mean&#39;<br>})</pre><p>Then we plot the figure:</p><pre>plt.figure(figsize=(12, 8))<br><br>strategies = df[&#39;Strategy&#39;].unique()<br>colors = plt.cm.get_cmap(&#39;tab10&#39;, len(strategies))<br><br>for i, strategy in enumerate(strategies):<br>    subset = df[df[&#39;Strategy&#39;] == strategy]<br>    plt.scatter(subset[&#39;Optimization step&#39;], subset[&#39;Lastest ROI&#39;], color=colors(i), label=strategy, s=100)<br><br>plt.xticks(range(df[&#39;Optimization step&#39;].min(), df[&#39;Optimization step&#39;].max() + 1, 5))<br><br>plt.xlabel(&#39;Optimization step&#39;)<br>plt.ylabel(&#39;Lastest ROI&#39;)<br>plt.title(&#39;Latest ROI by Optimization step and Strategy&#39;)<br>plt.legend(title=&#39;Strategy&#39;, loc=&#39;upper left&#39;, bbox_to_anchor=(0, 1))<br>plt.grid(False)<br>plt.tight_layout()<br><br>plt.savefig(&#39;latest_roi_by_optimization_step.png&#39;, bbox_inches=&#39;tight&#39;)<br>plt.show()</pre><p>As we can see in figure 10 below, smart_even_weights does outperform even_weights in terms of ROI, and all dummy strategies actually make less profits.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i-nA-FW0dtuX8Uiem-t6bw.png" /><figcaption><strong>Figure 10</strong>. ROI for optimization steps by strategies</figcaption></figure><h4>So, what should an intelligent investor do?</h4><p>Over this paper, I analyzed 1000 randomly generated portfolios from the S&amp;P 500 using different approaches, as extensively shown. I then compared the probability of optimizations outperforming the even allocation strategy.</p><p>This was, for sure, a massive work that took me months to finish. As a critic of Modern Portfolio Theory, I expected smart strategies to outperform both smart and dummy strategies.</p><p>However, I was proven wrong, at least regarding dummy strategies, where MPT dummy strategies outperformed random allocation. Nonetheless, all smart strategies underperformed, even though they yielded a greater return than dummy optimizations.</p><p>There are definitely some complications with backtesting financial data:the timing is important. When the market is bullish, we may expect price recoveries leading us to favor rebalancing gains. In this scenario, I advocate that we should just leave weights evenly distributed and go to the beach.</p><p>Nonetheless, I did not test side or bearish markets to determine whether smart strategies are consistent. Furthermore, I cannot explain why fewer optimizations are better than window-size optimization. A possible cause may be the tendency of MPT to concentrate weights in just a few assets.</p><p><strong>In conclusion</strong>, Modern Portfolio Theory is definitely not dead, but I would not use it for investment strategies.</p><h4>A final look at the effort so far</h4><p>First of all, thanks for reading.</p><p>That was a huge effort to finish this work, so I am glad you read it till here.</p><p>Below, have a look at how many optimizations were made just for a batch of 200 portfolios.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*E2oTZf15P3Xov2RCmC8WNA.png" /><figcaption><strong>Figure 11. </strong>A reminder of the effort so far</figcaption></figure><h4>Criticism of my own work</h4><p>Creating an algorithm that trades for ROI is certainly a different field of knowledge compared to risk-return analysis. Risk-return analyses primarily rely on historical data and are heavily influenced by it; thus, context is crucial.</p><p>Furthermore, optimizations require a large number of data points, but by segmenting the portfolio, we have fewer points available for analysis. For the next implementation, I will increase chunk sizes.</p><p>Finally, adopting any constraints leads the algorithm to overconcentrate allocation, so the results presented here could be proven wrong by adopting them.</p><p>It may still be possible to achieve better results in optimizations by implementing constraints due to reduced extreme allocation decisions and taking advantage of price recoveries.</p><p>As an economist, if we had access to long-term data, everything should theoretically be predictable and reach a stationary point, but real life is far from that ideal.</p><h4>References</h4><p>ZIEGLER TRINTINALIA, Guilherme. <a href="https://medium.com/datadriveninvestor/coding-markowitzs-efficient-frontier-with-python-and-streamlit-97014e8cb06d?source=your_stories_page-------------------------------------">Coding Markowitz’s Efficient Frontier with Python and Streamlit</a>, 2024.</p><p>TRINTINALIA, Clemente. Optimization of a portfolio of investment funds available for investment of the Propher Social Security Systems (RPPS), in Acoodance with aplicable law. (2016).</p><h4>Documentations</h4><p><a href="https://pyportfolioopt.readthedocs.io/en/latest/">PyPortfolioOpt Documentation</a></p><p><a href="https://github.com/GuilhermeZiegler/pyquant">GuilhermeZiegler/pyquant: library for quant trading (github.com)</a></p><p>Visit us at <a href="https://www.datadriveninvestor.com/"><em>DataDrivenInvestor.com</em></a></p><p>Subscribe to DDIntel <a href="https://www.ddintel.com/"><em>here</em></a>.</p><p>Join our creator ecosystem <a href="https://join.datadriveninvestor.com/"><em>here</em></a>.</p><p>DDI Official Telegram Channel: <a href="https://t.me/+tafUp6ecEys4YjQ1">https://t.me/+tafUp6ecEys4YjQ1</a></p><p>Follow us on <a href="https://www.linkedin.com/company/data-driven-investor"><em>LinkedIn</em></a>, <a href="https://twitter.com/@DDInvestorHQ"><em>Twitter</em></a>, <a href="https://www.youtube.com/c/datadriveninvestor"><em>YouTube</em></a>, and <a href="https://www.facebook.com/datadriveninvestor"><em>Facebook</em></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17e8970f8f4a" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/is-modern-portfolio-theory-dead-17e8970f8f4a">Is Modern Portfolio Theory Dead?</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[Coding Markowitz’s Efficient Frontier with Python and Streamlit]]></title>
            <link>https://medium.datadriveninvestor.com/coding-markowitzs-efficient-frontier-with-python-and-streamlit-97014e8cb06d?source=rss-59d66406fdbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/97014e8cb06d</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[investing]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[economics]]></category>
            <dc:creator><![CDATA[Guilherme Ziegler]]></dc:creator>
            <pubDate>Tue, 07 May 2024 01:51:54 GMT</pubDate>
            <atom:updated>2024-09-23T11:19:31.269Z</atom:updated>
            <content:encoded><![CDATA[<h4>An app to help you optimize any portfolio</h4><p>In this series of posts, I will delve into crucial technical skills that every economist should master before graduating from university.</p><p>In this inaugural part, I will walk you through coding Markowitz’s Efficient Frontier using Python and<a href="https://streamlit.io/"> Streamlit.</a></p><p>In part one we will explore how to run simulations to optimize portfolio allocation. In part two we will cover backtesting trading strategies to evaluate the practical applicability of Markowitz’s theory.</p><p>Our primary aim is to decide if we need to rebalance portfolios because of shifts in risk.</p><h4>Introducing the Efficient Frontier</h4><p>The efficient frontier (EF) theory, introduced by Nobel Laureate Harry Markowitz in 1952, is a fundamental concept in modern portfolio theory (MPT). It evaluates portfolios based on their return (y-axis) versus risk (x-axis).</p><p>The compound annual growth rate (CAGR) represents return, while annualized standard deviation indicates risk.</p><p>The efficient frontier visually displays portfolios that maximize returns for a given level of risk. Investors aim to build portfolios that offer<em> h</em>igh returns and low combined risk.</p><p>It relies on statistical covariance among assets to determine if their returns are less synchronized. When assets have lower covariance, it means they are less likely to move in the same direction at the same time, which can result in lower overall portfolio risk. This is because if one asset performs poorly, the other asset may perform well, offsetting some of the losses.</p><h4>Mean Variance Optimization (MVO)</h4><p>MVO is a optimization technique that determines the weights of assets in a portfolio to achieve higher returns with lower risks.</p><p>It relies on historical data to estimate expected returns and covariance matrices. However, it’s important to note that both the variance and returns observed in the past may not necessarily be replicated in the future.</p><p>It assumes that investors make decisions solely based on expected return and risk, ignoring other factors such as taxes, transaction costs, liquidity, technical and fundamental analyses. Consequently, it overlooks asymmetric information such as insider trading.</p><p>However, MVO does not differenciate positive from negative risk. Since investors tend to risk aversion, they might prioritize avoiding negative returns over capturing potential positive returns.</p><p>As the bull gores and the bear swipes downward, investors need to stay, investors are more likely to fear market drawbacks than enjoy gains.</p><h4>Getting to know the Sharpe Ratio</h4><p>In order to get best allocation portfolios we must define three fundamental variables:</p><ul><li>Rp = Expected portfolio return</li><li>Rf = Risk-free rate of return</li><li>StdDev Rp = Standard deviation of portfolio return (or, volatility)</li></ul><p>The expected portfolio return is calculated using empirical data from the past, typically by computing the average of daily logarithmic returns. To annualize this return, it’s common practice to consider 252 trading days</p><p>The risk-free rate of return represents the return in a portfolio attributable to zero risk, such as returns from assets like bonds and other securities.</p><p>Standard deviation is a dispersion metric that shows how much data points deviate from the mean. Variance is calculated by averaging the squared differences between each data point and the mean. In terms of stocks, it can be understood as how much daily returns deviate from the average return.</p><p>As expected returns and standard deviation are determined by empirical market data, it is a significant assumption to expect them to remain constant in the future. This is a key weakness of Modern Portfolio Theory (MPT), as most time series are recognized to be non-stationary stochastic processes.</p><p>An investor who embraces risk would accept higher risk for higher expected returns. Conversely, an investor with risk aversion would prioritize achieving higher returns while considering lower risk.</p><p>We utilize the aforementioned variables to calculate the Sharpe Ratio, a metric that quantifies the relationship between return and risk. Typically, a Sharpe Ratio of one indicates an equal balance between risk and expected returns:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FpBGJbmbDd8RUTvWY3dtCW6&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2FpBGJbmbDd8RUTvWY3dtCW6&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="216" height="157" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc036490dfbe56c8b607e74e588f0c1d/href">https://medium.com/media/bc036490dfbe56c8b607e74e588f0c1d/href</a></iframe><p>While the Sharpe Ratio offers a standardized measure of the risk-return tradeoff, portfolios are typically optimized for maximum Sharpe Ratio.</p><p>However, investors still have the flexibility to choose their preferred level of risk and calculate the weight compositions that generate the desired return.</p><h4>Seting streamlit up</h4><p>To start this project, you need to have some familiarity with Streamlit. I will not be covering how to build your application in Streamlit here since they have an <a href="https://pytechacademy.medium.com/streamlit-app-deployment-step-by-step-guide-to-streamlit-cloud-37c7eb2687d6">excellent tutorial</a> to guide you through the process.</p><p>An important hint, though, is how to use Streamlit’s session state to retrieve, save, and modify data throughout the project. For that, we are going to use the following code:</p><pre>import streamlit as st<br>import pandas as pd<br>class SessionState:<br>    def __init__(self, **kwargs):<br>        for key, val in kwargs.items():<br>            setattr(self, key, val)<br>@st.cache(allow_output_mutation=True)<br>def get_session():<br>    return SessionState(df=pd.DataFrame())<br>session_state = get_session()<br># Creating a dictionary with some data<br>data = {<br>    &#39;Name&#39;: [&#39;John&#39;, &#39;Anna&#39;, &#39;Peter&#39;, &#39;Linda&#39;],<br>    &#39;Age&#39;: [28, 35, 40, 25]<br>}<br># Creating a DataFrame with the data<br>df = pd.DataFrame(data)<br># Assigning this DataFrame to session_state<br>session_state.df = df</pre><p>This code defines the SessionState class, allowing us to store Python objects within it. By invoking the get_session function, we can retrieve any Python objects saved in the session state. In this example, a Pandas DataFrame named df is defined. The code then assigns this DataFrame to the attribute session_state.df within the session state.</p><h4>Basic libraries for the project</h4><pre>import streamlit as st  # library for building interactive web apps<br>import pandas as pd  # Pandas library for data manipulation and analysis<br>import numpy as np  # NumPy library for numerical computing<br>from datetime import date  # Importing date class from datetime module for handling dates<br># Libraries for retrieving and downloading data<br>import requests  # Making HTTP requests<br>from io import BytesIO  # Working with binary data streams<br>import yfinance as yf  # Yahoo Finance library for retrieving financial data<br>import base64  # Encoding and decoding binary data to/from ASCII<br># Plotting libraries<br>import plotly.express as px  # Plotly Express for creating interactive plots<br>import plotly.graph_objects as go  # Plotly Graph Objects for creating more customizable plots</pre><p>First of all, if your are using Streamlit to render an application you may want to open files from github. The function below loads data from a GitHub URL using the raw URL format.</p><pre>def load_data_from_github(url):<br>    response = requests.get(url)<br>    content = BytesIO(response.content)<br>    data = pd.read_pickle(content)<br>    return data</pre><p>It is quite handy to load into your project unchanging data files like dictionaries, pickle, parquet and even csv. It definitely saves you some lines in your code.</p><h4>Retriving data</h4><p>For convenience, we are using the &#39;yfinance&#39; library to retrieve data from the stock market. Its syntax requires either a list separated by commas or a dictionary iteration looping each key.</p><pre>def download_data(data, period=&#39;1y&#39;):<br>    dfs = []<br>    if isinstance(data, dict):<br>        for name, ticker in data.items():<br>            ticker_obj = yf.Ticker(ticker)<br>            hist = ticker_obj.history(period=period) # timeframe<br>            hist.columns = [f&quot;{name}_{col}&quot; for col in hist.columns]  # Add prefix to the name<br>            hist.index = pd.to_datetime(hist.index.map(lambda x: x.strftime(&#39;%Y-%m-%d&#39;)))<br>            dfs.append(hist)<br>    elif isinstance(data, list):<br>        for ticker in data:<br>            ticker_obj = yf.Ticker(ticker)<br>            hist = ticker_obj.history(period=period)<br>            hist.columns = [f&#39;{ticker}_{col}&#39; for col in hist.columns]  # Add prefix to the name<br>            hist.index = pd.to_datetime(hist.index.map(lambda x: x.strftime(&#39;%Y-%m-%d&#39;)))<br>            dfs.append(hist)  <br><br>    combined_df = pd.concat(dfs, axis=1, join=&#39;outer&#39;)  # Use join=&#39;outer&#39; to handle different data indices<br>    return combined_df</pre><p>As we are rendering some Streamlit widgets, I allow users to decide which method they are more comfortable with. The Streamlit code to choose assets assumes that you have defined and stored a combination of tickers in a dataframe.</p><p>For the purpose of improving features, I have enabled the download option to retrieve all available historical data. This includes open, closing, maximum, and minimum prices, as well as adjusted prices. Occasionally, we also receive volume, dividend yield, stock splits, and capital gains information. However, we will focus on working with the Adjusted Close price column.</p><p>For this project, I have constructed four dictionaries containing tickers for the B3 BOVESPA, S&amp;P500, NASDAQ, commodities, cryptocurrencies, and USD pairs.</p><p>Additionally, I have implemented functionalities that allow the user to choose the timeframe for the data, as well as perform resampling, missing values treatment, and rolling average calculations. However, these aspects of the code are not covered in this article, but feel free to use them.</p><pre># select box widget to choose timeframes<br>selected_timeframes = st.selectbox(&#39;Select Timeframe:&#39;, [&#39;1d&#39;, &#39;5d&#39;, &#39;1mo&#39;, &#39;3mo&#39;, &#39;6mo&#39;, &#39;1y&#39;, &#39;2y&#39;, &#39;5y&#39;, &#39;10y&#39;, &#39;ytd&#39;, &#39;max&#39;], index=7)<br># creating a dictionary of dictionaries with all available tickers<br>assets_list = {&#39;CURRENCIES&#39;: currencies_dict, &#39;CRYPTO&#39;: crypto_dict, &#39;B3_STOCKS&#39;: b3_stocks, &#39;SP500&#39;: sp500_dict, &#39;NASDAQ100&#39;: nasdaq_dict, &#39;indexes&#39;: indexes_dict}<br># combining dictionaries when the user selects one or more in assets_list<br>selected_dict_names = st.multiselect(&#39;Select dictionaries to combine&#39;, list(assets_list.keys()))<br>combined_dict = {}<br>for name in selected_dict_names:<br>    dictionary = assets_list.get(name)<br>    if dictionary:<br>        combined_dict.update(dictionary)<br># dictionary to actually store retrieved data<br>selected_ticker_dict = {}<br># looping through the chosen tickers<br>if selected_dict_names:<br>    # the list to iterate over tickers<br>    tickers = st.multiselect(&#39;Asset Selection&#39;, list(combined_dict.keys()))<br>    if tickers and st.button(&quot;Download data&quot;):<br>        for key in tickers:<br>            if key in combined_dict:<br>                selected_ticker_dict[key] = combined_dict[key]<br>        # Assigning data object as the result of the function download_data<br>        session_state.data = download_data(selected_ticker_dict, selected_timeframes)<br># Handle tickers entered manually<br>type_tickers = st.text_input(&#39;Enter Tickers (comma-separated):&#39;)<br>if type_tickers and st.button(&quot;Download data&quot;):<br>    tickers = [ticker.strip() for ticker in type_tickers.split(&#39;,&#39;)]<br>    # doing the same for tickers separated by commas<br>    session_state.data = download_data(tickers, selected_timeframes)</pre><p>If you have done everything correctly, you should be able to render the widget and get a result like this:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F-RVYQR4BQkw%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D-RVYQR4BQkw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F-RVYQR4BQkw%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/070c4d98fcb3cae14f0d4a557f41a008/href">https://medium.com/media/070c4d98fcb3cae14f0d4a557f41a008/href</a></iframe><h4>Simulating the Frontier</h4><p>This is probably one of my favorite sections, where we delve into portfolio simulations. Firstly, there are various methods to apply MVO (Mean-Variance Optimization). I opted for the traditional approach, but you can easily accomplish the task using <a href="https://pypi.org/project/pyportfolioopt/">pyportfolioopt</a>.</p><p><a href="https://medium.com/@bohmian?source=post_page-----80492b83912a--------------------------------">Damian Boh</a> did an excellent job in his post titled ‘<a href="https://medium.datadriveninvestor.com/easily-optimize-a-stock-portfolio-using-pyportfolioopt-in-python-80492b83912a">Easily Optimize a Stock Portfolio using PyPortfolioOpt in Python</a>.’ While we are covering similar topics, if you are pressed for time to complete the task, you can refer to his writings. As a keepsake, I will provide you with a quick overview.</p><pre>from pypfopt.efficient_frontier import EfficientFrontier<br>from pypfopt import risk_models<br>from pypfopt import expected_returns<br>import pandas as pd<br># Sample stock data (replace it with Close prices downloaded from yahoo finance)<br>stock_data = {<br>    &quot;AAPL&quot;: [0.1, 0.05, 0.08, 0.12, 0.07],<br>    &quot;GOOG&quot;: [0.05, 0.06, 0.07, 0.08, 0.09],<br>    &quot;MSFT&quot;: [0.06, 0.04, 0.08, 0.07, 0.05]<br>}<br>stocks_df = pd.DataFrame(stock_data)<br># Calculate expected returns and sample covariance matrix<br>mu = expected_returns.mean_historical_return(stocks_df)<br>S = risk_models.sample_cov(stocks_df)<br># Create the Efficient Frontier object<br>ef = EfficientFrontier(mu, S)<br># Optimize for maximum Sharpe ratio<br>weights = ef.max_sharpe()<br># Clean the weights (optional)<br>cleaned_weights = ef.clean_weights()<br># Print the cleaned weights<br>print(cleaned_weights)<br># Plot the efficient frontier<br>ef.portfolio_performance(verbose=True)<br># all done!</pre><h4>Another way of doing it</h4><p>It is also possible to use a solver and implement a minimize function. This will save you a lot of time, even though on my 16GB RAM computer, 10,000 simulations took only about one minute to complete. Regardless, applying MVO relies on:</p><ul><li>Estimating the annualized returns of the assets.</li><li>Calculating the portfolio variance.</li><li>Finding the covariance between each pair of assets in your portfolio.</li><li>Calculating the Sharpe Ratio and determining the optimal weights for each asset that maximize it.</li><li>At least these constraints are necessary: the sum of weights must equal one and be greater than zero (short trading is not allowed in this tutorial).</li></ul><p>See below how to implement the code:</p><pre>import numpy as np<br>import cvxpy as cp<br># Risk-free rate<br>risk_free_rate = 0.05<br># Number of assets<br>n_assets = len(expected_returns)<br># Define variables<br>weights = cp.Variable(n_assets)<br># Portfolio expected return<br>portfolio_return = expected_returns @ weights<br># Portfolio volatility (standard deviation)<br>portfolio_volatility = cp.sqrt(cp.quad_form(weights, covariance_matrix))<br># Portfolio Sharpe Ratio<br>portfolio_sharpe_ratio = (portfolio_return - risk_free_rate) / portfolio_volatility<br># Define objective function (maximize Sharpe Ratio)<br>objective = cp.Maximize(portfolio_sharpe_ratio)<br># Define constraints<br>constraints = [<br>    cp.sum(weights) == 1,  # sum of weights equals 1 (fully invested)<br>    weights &gt;= 0  # weights are non-negative<br>]<br># You can add more constraints here, such as minimum and maximum weights,<br># target return, etc.<br># Solve the optimization problem<br>problem = cp.Problem(objective, constraints)<br>problem.solve()</pre><h4>Finally the Frontier</h4><p>As intelligent investors, our focus lies in constructing a diversified portfolio with positive returns. To achieve this, we define returns as the logarithmic transformation of tomorrow’s adjusted close price divided by today’s adjusted close price.</p><p>Essentially, it breaks down as follows:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FpRzf1jgxXMKe71fEte4qPF&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2FpRzf1jgxXMKe71fEte4qPF&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="210" height="136" frameborder="0" scrolling="no"><a href="https://medium.com/media/a66e62040668d1dc4a761afefe4b00fd/href">https://medium.com/media/a66e62040668d1dc4a761afefe4b00fd/href</a></iframe><p>The underlying concept here is to calculate rate of growth and the pace at which this rate occurs. In essence, we are computing the first derivative of adjusted prices.</p><p>The code below calculates and plots the log returns for my test portfolio. I selected Banco do Brasil (BBAS3.SA) , Biogen (BIIB), Apple (AAPL) e Google (GOOG).</p><pre>def logreturns(df):<br>    # Separating the close price in this case<br>    df.columns = df.columns.str.split(&#39;_&#39;).str[0]<br>    log_returns = np.log(df)<br>    log_returns = df.iloc[:, 0:].pct_change()<br>    fig = px.line(log_returns, x=log_returns.index, y=log_returns.columns[0:].split(&#39;_&#39;)[0],<br>                  labels={&#39;value&#39;: &#39;log&#39;},<br>                  title=&#39;Log Returns&#39;)<br>    fig.update_layout(legend_title_text=&#39;Assets&#39;)<br>    st.plotly_chart(fig)<br>    return log_returns</pre><p>If you have everything set up correctly, you should visualize an image like this for your chosen assets:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*J_tpxPZw5hQ3KY2bOGXpjw.png" /><figcaption><strong>Image 1</strong>. Log returns for the portfolio.</figcaption></figure><p>As you can observe, the log transformation makes the time series closer to stationarity. We can verify this by applying the augmented Dickey-Fuller test. Check out how to work with time series on my new post.</p><p>Nonetheless, there may still be a few structural breakpoints for the log returns in which the prices were more volatile than their mean.</p><p>It is hard, though, to determine whether the assets showed positive or negative returns just by looking at log returns alone.</p><p>To address this, we can plot returns from the initial date by anchoring the first date and iterating through rows. Let’s see how it works:</p><pre>def return_over_time(df):<br>    return_df = pd.DataFrame()<br>    df.columns = df.columns.str.split(&#39;_&#39;).str[0]<br>    for col in df.columns:<br>        return_df[col] = df[col] / df[col].iloc[0] -1<br>        <br>    fig = px.line(return_df, x=return_df.index, y=return_df.columns[0:],<br>                  labels={&#39;value&#39;: &#39;Returns to Date&#39;},<br>                  title=&#39;returns&#39;)<br>    fig.update_layout(legend_title_text=&#39;Assets&#39;)<br>    st.plotly_chart(fig) # for streamlit plots</pre><p>The results should be something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*o1Rjh2cNkztO1bEOEVensA.png" /><figcaption><strong>Image 2</strong>. Return over time for the selected tickers.</figcaption></figure><p>As depicted in image 2, only Biogen showed a negative return for the last date considered. Banco do Brasil underwent a tumultuous period from 2020 to 2023 but made a full recovery in 2024.</p><p><strong>Return of the portfolio</strong></p><p>Calculating portfolio returns involves multiplying weights by the average log returns. While the weights are generated randomly for each simulation, the average log returns require us to assume a mean of the data points.</p><p>In this case, the steps we follow are:</p><ol><li>Resampling the dataframe for the chosen timeframe</li><li>Calculating the average of these returns.</li><li>Multiply by the number of trading days, typically 252, to obtain annualized returns.</li></ol><pre>resampler = &#39;A&#39;  # for annual<br>trading_days = 252  # usual trading year<br># Step 1. Resample keeping only the last values of each year<br>annualized_returns = df.resample(resampler).last()<br># Step 2. Calculate the log returns and take the average<br># Step 3. Multiply it by trading days<br>annualized_returns = df.pct_change().apply(lambda x: np.log(1 + x)).mean() * trading_days<br>simple_returns = np.exp(annualized_returns) - 1</pre><p>As a reminder, you can annualize multiple resampled portfolios as desired. For instance, if you want a quarterly analysis, simply change the resampling parameter to ‘3M’ and execute the snippet above. Since Mean-Variance Optimization (MVO) assumes returns are normally distributed, it is standard procedure to capture annualized returns.</p><p>A more conservative approach would be to take the average for daily log returns without resampling the original dataframe and then multiply it by the number of trading days. All you need to do is follow steps 2 and 3.</p><p>In fact, the Sharpe Ratio is indeed sensitive to how you calculate average returns, implying that the returns up to today may be replicable in the future. This assumption may simply not hold true.</p><p>Anyhow, portfolio return can be obtained by multiplying each asset return (ri) by its weight (wi):</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FfhNQzBFK1fvDxYQLLUkLvv&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2FfhNQzBFK1fvDxYQLLUkLvv&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="252" height="169" frameborder="0" scrolling="no"><a href="https://medium.com/media/4724a221323682f7dc0365d4b3126484/href">https://medium.com/media/4724a221323682f7dc0365d4b3126484/href</a></iframe><ul><li><em>n</em> is the number of assets in the portfolio.</li><li><em>ri</em>​ is the return of asset <em>i</em>.</li><li><em>wi</em>​ is the weight of asset <em>i</em> in the portfolio.</li></ul><p><strong>Portfolio risk</strong></p><p>To calculate the risk of a portfolio we need to determine weights of the assets in the portfolio, the variance of each asset alone, and the covariance between each pair of assets:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FgFVVewd2x1j64LuGeXvuut&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2FgFVVewd2x1j64LuGeXvuut&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="585" height="159" frameborder="0" scrolling="no"><a href="https://medium.com/media/fae2b75adc857e4061ed163bc483c62d/href">https://medium.com/media/fae2b75adc857e4061ed163bc483c62d/href</a></iframe><p>The term “product of the weights and covariance between assets” captures the combined influence of asset weights (e.g., w1​ and w2 ​) and their covariance (e.g., Cov(1,2)).</p><p>A positive covariance between assets 1 and 2 means that their returns tend to move in the same direction, while a negative covariance means they tend to move in opposite directions.</p><p>So, diversification is nothing more than finding assets that move upward in different ways. In other words, diversification relies on selecting assets that appreciate but not at the same pace or for the same reasons.</p><p>We can calculate the porfolio variance as it follows:</p><pre>trading_days = 252<br>var = cov_matrix.mul(weights, axis=0).mul(weights, axis=1).sum().sum()<br>sd = np.sqrt(var) # obtain the risk <br>ann_sd = sd*np.sqrt(trading_days) # to scale the risk for any timeframe</pre><p>What matters here is scaling both returns and risk to the same level. However, in part 2, we are going to take some leaps of faith by scaling returns for much shorter time frames. As the Sharpe Ratio depends on both return and risk, the timeframe matters for finding the highest Sharpe Ratio portfolio.</p><h4>Simulating the frontier</h4><p>Finally, we have all we need to simulate the Efficient Frontier. For that purpose, we will generate a thousand portfolio configurations and calculate the Sharpe Ratio for both annualized expected returns and risk.</p><pre>def efficient_frontier(df, <br>                       trading_days, <br>                       risk_free_rate,<br>                       simulations= 1000, <br>                       resampler=&#39;A&#39;):<br>    <br>    # covariance matrix of the log returns<br>    cov_matrix = df.pct_change().apply(lambda x: np.log(1+x)).cov()<br>    <br>    # lists to store the results<br>    portfolio_returns = [] <br>    portfolio_variance = [] <br>    portfolio_weights = [] <br>    <br>    num_assets = len(df.columns)<br>    for _ in range(simulations):<br>        # generating up to 1000 portfolio simulations<br>        weights = np.random.random(num_assets)<br>        weights = weights/np.sum(weights) # scaling weights to 1<br>        portfolio_weights.append(weights)<br>        # calculating the log returns<br>        returns = df.resample(resampler).last()<br>        returns = df.pct_change().apply(lambda x: np.log(1 + x)).mean() * trading_days<br>        annualized_returns = np.dot(weights, returns)<br>        portfolio_returns.append(annualized_returns)<br>        # portfolio variance<br>        var = cov_matrix.mul(weights, axis=0).mul(weights, axis=1).sum().sum()<br>        sd = np.sqrt(var) # Daily standard deviation<br>        ann_sd = sd*np.sqrt(trading_days)<br>        portfolio_variance.append(ann_sd)<br>        # storing returns and volatitly in a dataframe<br>        data = {&#39;Returns&#39;:portfolio_returns, &#39;Volatility&#39;:portfolio_variance}<br>    for counter, symbol in enumerate(df.columns.tolist()):<br>        data[symbol+&#39; weight&#39;] = [w[counter] for w in portfolio_weights]<br>    <br>    simulated_portfolios  = pd.DataFrame(data)<br>    simulated_portfolios[&#39;Sharpe_ratio&#39;] = (simulated_portfolios[&#39;Returns&#39;] - risk_free_rate) / simulated_portfolios[&#39;Volatility&#39;]<br>    <br>    return simulated_portfolios    </pre><p>Now we can plot the frontier in streamlit and do some customization by intruducing &#39;expected_sharpe&#39;, expected_return and risk taken as the initial configuration we are interested in.</p><pre>def plot_efficient_frontier(simulated_portfolios, expected_sharpe, expected_return, risk_taken):<br>    simulated_portfolios = simulated_portfolios.sort_values(by=&#39;Volatility&#39;)<br>    <br>    # concatenating weights so we can hover on them as we select data points<br>    simulated_portfolios[&#39;Weights&#39;] = simulated_portfolios.iloc[:, 2:-1].apply(<br>        lambda row: &#39;, &#39;.join([f&#39;{asset}: {weight:.4f}&#39; for asset, weight in zip(simulated_portfolios.columns[2:-1], row)]),<br>        axis=1<br>    )<br>    # creating the plot as a scatter graph<br>    frontier = px.scatter(simulated_portfolios, x=&#39;Volatility&#39;, y=&#39;Returns&#39;, width=800, height=600, <br>                          title=&quot;Markowitz&#39;s Efficient Frontier&quot;, labels={&#39;Volatility&#39;: &#39;Volatility&#39;, &#39;Returns&#39;: &#39;Return&#39;},<br>                          hover_name=&#39;Weights&#39;)<br>    <br>    # getting the index of max Sharpe Ratio and painting in green<br>    max_sharpe_ratio_portfolio = simulated_portfolios.loc[simulated_portfolios[&#39;Sharpe_ratio&#39;].idxmax()]<br>    frontier.add_trace(go.Scatter(x=[max_sharpe_ratio_portfolio[&#39;Volatility&#39;]], <br>                                  y=[max_sharpe_ratio_portfolio[&#39;Returns&#39;]],<br>                                  mode=&#39;markers&#39;,<br>                                  marker=dict(color=&#39;green&#39;, size=10),<br>                                  name=&#39;Max Sharpe Ratio&#39;,<br>                                  text=max_sharpe_ratio_portfolio[&#39;Weights&#39;]))<br>    # Getting portfolios where returns are above our expectations and below <br>    # the amount of risk we aim to take<br>    low_risk_portfolios = simulated_portfolios[<br>        (simulated_portfolios[&#39;Returns&#39;] &gt;= expected_return) &amp; <br>        (simulated_portfolios[&#39;Volatility&#39;] &lt;= risk_taken)<br>    ]<br>    <br>    frontier.add_trace(go.Scatter(x=low_risk_portfolios[&#39;Volatility&#39;], <br>                                  y=low_risk_portfolios[&#39;Returns&#39;],<br>                                  mode=&#39;markers&#39;,<br>                                  marker=dict(color=&#39;purple&#39;, size=5),<br>                                  name=&#39;Expected Return &amp; Risk Taken&#39;,<br>                                  text=low_risk_portfolios[&#39;Weights&#39;]))<br>    <br>    # Selecting portfolios with our initial Sharpe ratio expectations<br>    # and paiting it orange<br>    expected_portfolio = simulated_portfolios[<br>        (simulated_portfolios[&#39;Sharpe_ratio&#39;] &gt;= expected_sharpe - 0.001) &amp; <br>        (simulated_portfolios[&#39;Sharpe_ratio&#39;] &lt;= expected_sharpe + 0.001)<br>    ]<br>    <br>    if not expected_portfolio.empty:<br>        frontier.add_trace(go.Scatter(x=[expected_portfolio[&#39;Volatility&#39;].values[0]], <br>                                      y=[expected_portfolio[&#39;Returns&#39;].values[0]],<br>                                      mode=&#39;markers&#39;,<br>                                      marker=dict(color=&#39;orange&#39;, size=10),<br>                                      name=&#39;Expected Sharpe Ratio&#39;,<br>                                      text=expected_portfolio[&#39;Weights&#39;]))<br>    <br>    # selecting the portfolio with lowest risk and painting it red<br>    frontier.add_trace(go.Scatter(x=[simulated_portfolios.iloc[0][&#39;Volatility&#39;]], <br>                                  y=[simulated_portfolios.iloc[0][&#39;Returns&#39;]],<br>                                  mode=&#39;markers&#39;,<br>                                  marker=dict(color=&#39;red&#39;, size=10),<br>                                  name=&#39;Min Volatility&#39;, <br>                                  text=simulated_portfolios.iloc[0][&#39;Weights&#39;]))<br>    <br>    frontier.update_layout(legend=dict(<br>                           orientation=&#39;h&#39;,<br>                           yanchor=&#39;top&#39;,<br>                           y=1.1,<br>                           xanchor=&#39;center&#39;,<br>                           x=0.5))<br>    st.plotly_chart(frontier)</pre><p>If you did everything shown here, you are expected to end up with a frontier like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*zp32sZB8J_tnefKiHxaqVg.png" /><figcaption><strong>Image 3</strong>. Efficient Frontier plot</figcaption></figure><p>Note that any point on the left edge is the best configuration of Sharpe Ratio. Our initial Sharpe expectations, considering the risk we take, are marked in orange.</p><p>The maximum Sharpe Ratio is marked in green, and the lowest risk portfolio is marked in red.</p><p>Lastly, purple data points represent portfolios in which expected returns exceed our initial expectations, but we only take a defined amount of risk. For those, we should consider any portfolio also on the left edge of the plot.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FgUXfxorky_8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DgUXfxorky_8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FgUXfxorky_8%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/45c62c168e963e0c309ccb0f0f9fc26c/href">https://medium.com/media/45c62c168e963e0c309ccb0f0f9fc26c/href</a></iframe><p><strong>Final Considerations</strong></p><p>In conclusion, the analysis conducted provides valuable insights into portfolio optimization and risk management. By simulating the Efficient Frontier and exploring various portfolio configurations, we have gained a deeper understanding of how to balance risk and return in investment portfolios.</p><p>Variance Optimization (MVO) is mandatory knowledge in modern portfolio theory (MPT). However, it only suggests the weights one should have bought, as it is limited to future predictions. It relies on the premises of diversification and risk avoidance.</p><p>Having said that, MVO is one of the most used techniques for rebalancing your portfolio and defining new weights. Nonetheless, does it really work when backtesting empirical data?</p><p>In part 2, I present a script that rebalances a portfolio using the previously determined maximum Sharpe Ratio’s weights and compares the total portfolio return with randomly picked weights.</p><p>Can we actually use the Sharpe Ratio in a non-figurative way?</p><p>Thank you for reading and for your support! Your engagement and encouragement mean a lot to me. If you have any feedback or questions, please don’t hesitate to reach out.</p><h4>References</h4><p>Streamlit. (2024). Streamlit. Retrieved from <a href="https://streamlit.io/">https://streamlit.io/</a></p><p>PyTech Academy. (2023). Streamlit App Deployment: Step-by-Step Guide to Streamlit Cloud. Medium. <a href="https://pytechacademy.medium.com/streamlit-app-deployment-step-by-step-guide-to-streamlit-cloud-37c7eb2687d6">https://pytechacademy.medium.com/streamlit-app-deployment-step-by-step-guide-to-streamlit-cloud-37c7eb2687d6</a>.</p><p>DataDrivenInvestor. (2022). Easily Optimize a Stock Portfolio using PyPortfolioOpt in Python. <em>Medium</em>. Recuperado de <a href="https://medium.datadriveninvestor.com/easily-optimize-a-stock-portfolio-using-pyportfolioopt-in-python-80492b83912a">https://medium.datadriveninvestor.com/easily-optimize-a-stock-portfolio-using-pyportfolioopt-in-python-80492b83912a</a></p><p>William F. Sharpe, “The Sharpe Ratio,” Journal of Portfolio Management, Vol. 21, №1, Fall 1994, pp. 49–58. [Online]. Available: <a href="https://web.stanford.edu/~wfsharpe/art/sr/sr.htm">https://web.stanford.edu/~wfsharpe/art/sr/sr.htm</a>testando</p><p>Visit us at <a href="https://www.datadriveninvestor.com/"><em>DataDrivenInvestor.com</em></a></p><p>Subscribe to DDIntel <a href="https://www.ddintel.com/"><em>here</em></a>.</p><p>Featured Article:</p><ul><li><a href="https://www.datadriveninvestor.com/2024/03/26/singapore-unveiling-a-tapestry-of-possibilities-and-global-connections/">Singapore: Unveiling a Tapestry of Possibilities and Global Connections | DataDrivenInvestor</a></li><li><a href="https://www.datadriveninvestor.com/2024/03/20/accelerating-success-through-the-singapore-fund-asset-management-platform/">Introducing Singapore&#39;s Fund Platform | DataDrivenInvestor</a></li></ul><p>Join our creator ecosystem <a href="https://join.datadriveninvestor.com/"><em>here</em></a>.</p><p>DDI Official Telegram Channel: <a href="https://t.me/+tafUp6ecEys4YjQ1">https://t.me/+tafUp6ecEys4YjQ1</a></p><p>Follow us on <a href="https://www.linkedin.com/company/data-driven-investor"><em>LinkedIn</em></a>, <a href="https://twitter.com/@DDInvestorHQ"><em>Twitter</em></a>, <a href="https://www.youtube.com/c/datadriveninvestor"><em>YouTube</em></a>, and <a href="https://www.facebook.com/datadriveninvestor"><em>Facebook</em></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97014e8cb06d" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/coding-markowitzs-efficient-frontier-with-python-and-streamlit-97014e8cb06d">Coding Markowitz’s Efficient Frontier with Python and Streamlit</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>
    </channel>
</rss>