<?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 Andre Nagano on Medium]]></title>
        <description><![CDATA[Stories by Andre Nagano on Medium]]></description>
        <link>https://medium.com/@andrejin.nagano?source=rss-7d22ea87b56e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*KbAkgoY2dYkuue3N</url>
            <title>Stories by Andre Nagano on Medium</title>
            <link>https://medium.com/@andrejin.nagano?source=rss-7d22ea87b56e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 03:49:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andrejin.nagano/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[The Greeks with Python]]></title>
            <link>https://medium.com/@andrejin.nagano/the-greeks-with-python-eea94c1b85ab?source=rss-7d22ea87b56e------2</link>
            <guid isPermaLink="false">https://medium.com/p/eea94c1b85ab</guid>
            <category><![CDATA[options-trading]]></category>
            <category><![CDATA[quantitative-finance]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[options-greeks]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Andre Nagano]]></dc:creator>
            <pubDate>Wed, 15 Oct 2025 11:14:21 GMT</pubDate>
            <atom:updated>2025-10-15T11:14:21.691Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>This story is a follow-up to my Black-Scholes series. If you haven&#39;t read that yet, I recommend reading the three-part story, covering <a href="https://medium.com/@andrejin.nagano/black-scholes-option-pricing-model-assumptions-4bc60b5b78c7">the assumptions</a>, <a href="https://medium.com/@andrejin.nagano/black-scholes-option-pricing-model-formula-6438c1c22720">the math</a> and <a href="https://medium.com/@andrejin.nagano/black-scholes-option-pricing-model-python-code-293392f0755a">the code</a> behind this option pricing model.</blockquote><p>In this story, there will be <strong>an introduction to the Greeks</strong>, describing the five main measures (Delta, Gamma, Theta, Vega and Rho)and calculating their formulas by partially deriving the Black-Scholes Formula. At the end, there is also a code to automatically calculate <strong>the Greeks in Python</strong>.</p><h3>Black-Scholes Formula</h3><p>Before discussing the Greeks, let’s revise the Black-Scholes Formula.</p><p><strong>The Black-Scholes Formula is used to price European-style options</strong>. There are a number of assumptions when using the formula, that’s why I recommend reading my previous story to understand them. The formula can be written as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/0*v9ck8r6yrJuIqRcr.png" /></figure><p>where:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w35lai-dDxPqnCpU.png" /></figure><p>This formula is the original formula used in the Black-Scholes model, which assumes that the underlying asset pays no dividends. Consequently, <strong>all the formulas for the Greeks below also assume that the option analyzed has a underlying asset with no dividends</strong>.</p><p>There is an adjusted formula that includes underlying asset that pays dividends. In case you want to understand those, I recommend reading this <a href="https://quantpie.co.uk/bsm_formula/bs_summary.php">website</a>.</p><h3><strong>The Greeks</strong></h3><p>The Greeks are <strong>measures of sensitivity of an option</strong> to changes in different parameters. They help market makers understand better option, revealing certain traits that go beyond its price. Each measurement can be taken from a partial derivative of the Black-Scholes formula:</p><ul><li><strong>Delta (Δ)</strong> — measures the sensitivity of an option’s price to changes in the price of the underlying asset.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/93/1*3U-Mr0dEwXL2mFslxTiZIA.png" /></figure><ul><li><strong>Gamma (Γ)</strong> — measures the rate of change between an option’s delta and the underlying asset’s price.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/159/1*Ax1bwOwfpM0JXFcaw8LTkw.png" /></figure><ul><li><strong>Theta (Θ)</strong> — measures the rate of change of an option’s price as time passes, also known as “time decay”.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/84/1*8yxGmz3gMyCS85sIGzMRdg.png" /></figure><ul><li><strong>Vega (ν) </strong>— measures the sensitivity of an option’s price to changes in the volatility of the underlying asset.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/90/1*gm8dPuUwpYpLOROLfuaodw.png" /></figure><ul><li><strong>Rho (⍴)</strong> — measure the sensitivity of an option’s price to changes in the risk-free interest rate.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/86/1*8tcqzixwr7Wn05_ZRVsV_w.png" /></figure><h3>Delta (Δ)</h3><p><strong>The Delta measures the first-order sensitivity of an option’s price to a change in the underlying asset’s price.</strong> To obtain the formula for the Delta of an option, we can calculate the partial derivative of the Black-Scholes formula toa change in the underlying asset’s price:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*OqyqOd3duLnuwy7manp1XQ.png" /></figure><p>Let’s start by calculating the partial derivative of the first component. We can use the product rule:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*o6BAKavP85hqIzppGK180w.png" /></figure><p>Next, we calculate the second component:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*slhbwAGJX167_VDIXDCuPA.png" /></figure><p>To solve the partial derivative, we apply the chain rule:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*6oOpLwoRfc0v54B9hkldiw.png" /></figure><p>The <strong>CDF of a standard normal distribution</strong> is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/259/1*auMAUFHhb2YYym5HpvaFig.png" /></figure><p>Which means that, by the Fundamental Theorem of Calculus, its derivative is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/197/1*7ScmqaYOqn4C3yZo9VxX-Q.png" /></figure><p><strong>This is also the formula for the PDF</strong>, which makes sense, since the cumulative of the probability is equal to calculating the integral of the function from negative infinite.</p><p>Given the derivative of the CDF, and the formula for the parameter d1, we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*jEa7tUQVvZU7k6q2muxR4w.png" /></figure><p>Which means that the second component is equal to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*tdx8CeR-Eo1DMx8BPYBXUw.png" /></figure><p>Back to the derivative of the Black-Scholes formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*8lqljK8U5cWKf8FeHAczLw.png" /></figure><p>The formula for the Delta of a European-style call option that pays no dividend is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/120/1*HsefEFfWA1VT9SzSt-hJWQ.png" /></figure><p>We can do the same process for put options, which would yield the formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/155/1*abXK-csqpWWwYkm_l-S0Hg.png" /></figure><p>The Delta for a<strong> call option has a range between 0 and 1</strong>, indicating the percentage change in the option price relative to a change in the underlying asset price. While, the Delta for a <strong>put option ranges from -1 to 0</strong>.</p><h4><strong>Delta As a Proxy</strong></h4><p>The Delta is also seen as <strong>a proxy for the probability of an option expiring in-the-money</strong>. One way we can interpret the Black-Scholes formula for a call option is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*UDaLzLJRCx8DjC2_OpAFMQ.png" /></figure><p>This means that the second component is what we expect to pay. If the exponential part represents the present value of strike price, <strong>the CDF portion represents the probability of paying this amount, or the probability of exercising this option</strong>. When we exercise the option, or when the current price of the underlying asset is greater then the strike price (S&gt;K), we say that the option expires in-the-money.</p><p>The Φ(d2) probability is not exactly equal to Delta (Φ(d1)). However, depending on the value of the volatility (σ) and maturity date (T), the Delta (Φ(d1)) is close enough to be used as a proxy.</p><h4><strong>Delta Hedging</strong></h4><p>The Delta is also used for Delta hedging or creating a Delta-neutral portfolio. <strong>A Delta-neutral portfolio is one where the sum of all Deltas is zero.</strong> This means that its <strong>value won’t change if the stock price makes a small move up or down</strong>.</p><p>Let’s take for example a portfolio where we sell 1 call option contract, representing 100 shares. We’re selling a contract that gives the buyer the right but not the obligation of buying 100 stocks by a certain strike price. Let’s also assume that the shorted call option has a Delta of 0.60.</p><p>Since we’re shorting the call option, our Delta would be negative as -0.60 x 100 shares = -60. So, if the stock price rises by $1, the option’s price will increase by $0.60 per share and we lose $60.</p><p><strong>To neutralize the -60 Delta, we have to make a position with +60 Delta</strong>. The underlying stock has a Delta of 1. Therefore, we can just buy 60 shares of the underlying stock to neutralize the negative Delta position, resulting in a Delta-neutral portfolio.</p><h3><strong>Gamma (</strong>Γ<strong>)</strong></h3><p><strong>The Gamma measures the rate of change between the option’s Delta and the underlying asset’s price</strong>. In other words, the Gamma is the second-order partial derivative of the option’s value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/307/1*ZnO11Iipq4nJyXqa80ZCaQ.png" /></figure><p>Again, we can apply the chain rule:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/203/1*LHewur-7F-fIVfKhqN4nKA.png" /></figure><p>Calculating the partial derivative of d1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*XI_qedli9JmJMJKMFfRUKQ.png" /></figure><p>Which means that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*mhh0IkEGCfvI9Ly9_whONA.png" /></figure><p>Therefore, the formula for the Gamma of an European-style option with no dividends is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/159/1*qpxtFKOyjOzdk6WRou21-A.png" /></figure><p>When we calculate the second-order partial derivative of the Black-Scholes formula for a put option, we find the same results, which means that the <strong>formula above is valid for both call and put options</strong>.</p><h4><strong>Dynamic Hedging</strong></h4><p>As we’ve seen in the last topic, the Delta can be used to create Delta-neutral portfolios. However, <strong>the Delta is not constant over time</strong>, it can change as the underlying asset’s price moves. Since the Gamma measures the rate of change in Delta, <strong>we can use it to calculate how many shares we should buy or sell to maintain a Delta-neutral position</strong>.</p><p>Let’s continue with the example from the topic on Delta Hedging. The current portfolio has a Delta of 0, since we shorted the call option and bought 60 shares of the underlying stock. Assuming a Gamma of 0.40, means that an increase of $1 in the underlying stock price increases the Delta by 0.04. Therefore, the new Delta will be 0.60+0.04=0.64 per share, and the new Delta for the portfolio will be -0.64 x 100 = -64. In order to neutralize the Delta, we should buy 4 shares of the underlying stock.</p><p><strong>This constant rebalancing to maintain a Delta-neutral portfolio is called Dynamic Hedging.</strong></p><h3><strong>Theta (</strong>Θ)</h3><p><strong>The Theta measures the rate of change of an option’s price due to the passing of time.</strong> For that reason, <strong>the Theta is also commonly called the decay</strong> in price of an option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*shYF3SWEAcfpa-W2suXQJA.png" /></figure><p>The first component can be easily obtained as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/206/1*E9-7tqHkAHrGTBvoUsXJIg.png" /></figure><p>We could calculate the partial derivative of the CDF, but it will later get canceled out, so we can leave it as it is for now.</p><p>However, the second component needs a little of work:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*elxQpLxpXeli-sgRh-iPQA.png" /></figure><p>We have seen previously the formula for Φ’(d2), meaning that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*2dsQiabzPAm4KFkvFGuooQ.png" /></figure><p>Going back to the original equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*8RxW7-SfvBJ14bQsAxPiVA.png" /></figure><p>Therefore, the formula for the Vega of an European-style option that pays no dividends is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*BqAk6jREOH07j3gcYf6voQ.png" /></figure><p><strong>Notice that the value will be negative, meaning that the value will lose value as time goes by</strong>. That is why the Theta is also called decay.</p><p>When we calculate the partial derivative of the Black-Scholes formula for a put option, we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*aa8-xo_jdQyBBYEQJVWVUw.png" /></figure><p><strong>As time nears the maturity date, options decay faster, so the Theta increases</strong>. Long calls and puts usually have a negative Theta, while short ones have positive Theta. A stock has zero Theta, because it’s not eroded by time.</p><h4><strong>Profiting from Theta Decay</strong></h4><p>Again, we return to the Delta hedging portfolio. <strong>As time passes, the option you sold becomes cheaper due to Theta decay.</strong> <strong>If the stock price and volatility stay relatively stable, you can eventually buy back the same option for a lower price, and pocket the difference.</strong></p><p>So, suppose the call option was sold by $200. The Delta hedge ensures that even if the stock price moves up or down, our gains or loses from the stock position will offset the gains or loses from our short option position. After the option is eroded with time, we could buy back the same option position for a lower price, say $50. At the end, we would’ve made a profit of $150.</p><h3><strong>Vega (</strong>ν<strong>)</strong></h3><p><strong>The Vega measures the sensitivity of a option’s price to changes in the volatility of the underlying asset’s price.</strong> We will calculate it like the previous Greeks, as the partial derivative of the Black-Scholes formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*kRL5KyucI-HRagKIAza-BQ.png" /></figure><p>Again, the first component will be just:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/1*cRraLhBywi6zygubWT47GA.png" /></figure><p>Now, for the second component:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*3SEv7OVM5xILzhfsmEjLeg.png" /></figure><p>Back to the first equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*-KNx299nPQZSqQJ4QeJL2A.png" /></figure><p>Therefore, the Vega for an European-style option with no dividends is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/205/1*2VF1NwW4sNhz3B5oq-L51w.png" /></figure><p><strong>The time component means that an option’s Vega decays over time, approaching zero as the maturity date gets closer.</strong> The reason for that is <strong>the time for the volatility to have an impact decreases when time passes</strong>. The Vega for long-dated options is higher than short-dated ones.</p><p>If we do the same calculations for the put option, we would find the same results. <strong>So, the formula for the Vega is the same for both call and put options.</strong></p><h4><strong>Profiting from Vega</strong></h4><p><strong>Options become more valuable as volatility increases</strong>. Options provide the potential of unlimited profit but a strictly limited loss. So, as volatility increases, a huge upward swing could lead to massive profits. While, a huge downward swing wouldn’t make much difference, since the loss is capped.</p><p><strong>One trading strategy would be to buy options with high Vega when we expect the volatility to increase.</strong> The opposite is also viable, shorting options with high Vega when we expect the volatility to decrease.</p><p>After buying the options, we could Delta hedge it, removing the risk of losing money with price swings.</p><h3><strong>Rho (</strong>⍴<strong>)</strong></h3><p>Finally, we have <strong>the Rho, which measures the sensitivity of an option’s price to changes in the risk-free interest rate.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*BLbLMfsGKi1OdpIt2W5vIg.png" /></figure><p>One last time, the first component can be calculate as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/207/1*hUDtrQYmMSTSX5DgiuQ_Vw.png" /></figure><p>We can work the second component as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*GaHZpmqDzCprC0IDbU8r0Q.png" /></figure><p>Back to the initial equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*2vD74aTMoIeaRjvKwlD8pA.png" /></figure><p>Therefore, the Rho for an European-style option with no dividends is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/1*0vvOV0RmmE3lSLOV4lT1ig.png" /></figure><p>Whereas, for a put option we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*QBabQhzi5TzA0HZ68pDQmg.png" /></figure><p><strong>Looking at the formulas, we see that call options have a positive Rho, this means that a higher interest rate increases the value of the call option.</strong> An increase in interest rates result in the increase of the opportunity cost of holding cash to buy the stock, making the right to buy later more valuable.</p><p>For example, let’s suppose with have $10,000 and interest rates are high. Instead of spending that amount of money buying stocks, we could spend less in an option premium, say $500, and let the remaining $9,500 sit in an account earning interest. Then, later we could exercise the call option if we want in the future.</p><p>Conversely, put options have negative Rho because higher rates decrease the present value of the cash we would receive from selling the stock, making the put less valuable.</p><h3>Greeks Table Summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ECPD8HN1ottWbUc2_9oBKQ.png" /></figure><h3>Greeks in Python</h3><p>With the formulas above, we can write some Python functions to calculate the Greeks. Let’s define a class called <em>Option</em>, that takes 6 parameters when initialized: sigma (underlying asset’s volatility), K (strike price), S (underlying asset’s current price), T (time to maturity), r (risk-free interest rate) and the option_type, whether it’s a call or put option. Within this class, we’ll also define some functions:</p><ul><li><strong>_calculate_d1_d2</strong>: returns the parameters d1 and d1.</li><li><strong>price</strong>: returns the price of the option using the Black-Scholes formula.</li><li><strong>delta</strong>: returns the Greek Delta (option’s sensitivity to S).</li><li><strong>gamma</strong>: returns the Greek Gamma (delta’s sensitivity to S).</li><li><strong>theta</strong>: returns the Greek Theta (option’s sensitivity to time).</li><li><strong>vega</strong>: returns the Greek Vega (option’s sensitivity to sigma).</li><li><strong>rho</strong>: returns the Greek Rho (option’s sensitivity to the risk-free interest rate).</li></ul><p>For the CDF, we’ll use the <em>scipy.stats</em> library. Additionally, the derivative of the CDF is the PDF, so we’ll also use the <em>scipy.stats</em> for the PDF.</p><pre>import numpy as np<br>from scipy.stats import norm<br>import yfinance as yf<br>import matplotlib.pyplot as plt<br>from datetime import datetime</pre><pre>class Option:<br><br>    def __init__(self, sigma: float, K: float, S:float, T:float, r:float, option_type:str):<br><br>        if option_type not in [&#39;call&#39;, &#39;put&#39;]:<br>            raise ValueError(&quot;option_type must be either &#39;call&#39; or &#39;put&#39;&quot;)<br><br>        self.sigma = sigma<br>        self.K = K<br>        self.S = S<br>        self.T = T<br>        self.r = r<br>        self.option_type = option_type<br><br>        self._calculate_d1_d2()<br><br>    def _calculate_d1_d2(self):<br>        &quot;&quot;&quot; <br>        Calculates the d1 and d2 parameter from the Black-Scholes Formula<br>        &quot;&quot;&quot;<br><br>        self.d1 = (np.log(self.S / self.K) + self.T * (self.r + self.sigma ** 2 / 2)) / (self.sigma * np.sqrt(self.T))<br>        self.d2 = self.d1 - self.sigma * np.sqrt(self.T)<br><br>    def price(self):<br>        &quot;&quot;&quot;&quot;<br>        Applies the Black-Scholes Model to calculate the price of a option.<br>        &quot;&quot;&quot;<br><br>        # Calculates the value of the option based on its option_type, either &quot;call&quot; or &quot;put&quot;<br>        if self.option_type == &quot;call&quot;:<br><br>            V = self.S * norm.cdf(self.d1) - np.exp(-self.r * self.T) * self.K * norm.cdf(self.d2)<br><br>        elif self.option_type == &quot;put&quot;:<br><br>            V = np.exp(-self.r * self.T) * self.K * norm.cdf(-self.d2) - self.S * norm.cdf(-self.d1)<br><br>        return V<br><br>    def delta(self):<br>        &quot;&quot;&quot;<br>        Calculates the Delta measure based on the derivative of the BSF<br>        &quot;&quot;&quot;<br><br>        if self.option_type == &quot;call&quot;:<br><br>            d = norm.cdf(self.d1)<br><br>        elif self.option_type == &quot;put&quot;:<br><br>            d = norm.cdf(self.d1) - 1<br><br>        return d<br><br>    def gamma(self):<br>        &quot;&quot;&quot;<br>        Calculates the Gamma measure based on the derivative of the BSF<br>        &quot;&quot;&quot;<br><br>        g = norm.pdf(self.d1) / (self.S * self.sigma * np.sqrt(self.T))<br><br>        return g<br><br>    def theta(self):<br>        &quot;&quot;&quot;<br>        Calculates the daily Theta measure based on the derivative of the BSF<br>        &quot;&quot;&quot;<br><br>        if self.option_type == &quot;call&quot;:<br><br>            t = - self.r * self.K * np.exp(-self.r * self.T) * norm.cdf(self.d2) - (self.S * self.sigma * norm.pdf(self.d1)) / (2 * np.sqrt(self.T))<br><br>        elif self.option_type == &quot;put&quot;:<br><br>            t = self.r * self.K * np.exp(-self.r * self.T) * norm.cdf(self.d2) - (self.S * self.sigma * norm.pdf(self.d1)) / (2 * np.sqrt(self.T))<br><br>        return t/365<br><br>    def vega(self):<br>        &quot;&quot;&quot;<br>        Calculates the daily Vega measure based on the derivative of the BSF<br>        &quot;&quot;&quot;<br><br>        v = self.S * np.sqrt(self.T) * norm.pdf(self.d1)<br><br>        return v/100<br><br>    def rho(self):<br>        &quot;&quot;&quot;<br>        Calculates the Rho measure in percentage points based on the derivative of the BSF<br>        &quot;&quot;&quot;<br><br>        if self.option_type == &quot;call&quot;:<br><br>            p = self.K * self.T * np.exp(-self.r * self.T) * norm.cdf(self.d2)<br><br>        elif self.option_type == &quot;put&quot;:<br><br>            p = -self.K * self.T * np.exp(-self.r * self.T) * norm.cdf(-self.d2)<br><br>        return p/100<br>    <br>    def summary(self):<br><br>        price = self.price()<br>        D = self.delta()<br>        G = self.gamma()<br>        T = self.theta()<br>        V = self.vega()<br>        R = self.rho()<br><br>        print(&quot;-- Call Option Greeks Summary --&quot;)<br>        print(f&quot;Price: ${price: .2f}&quot;)<br>        print(f&quot;Delta: {D: .2f}&quot;)<br>        print(f&quot;Gamma: {G: .2f}&quot;)<br>        print(f&quot;Theta: {T: .2f}&quot;)<br>        print(f&quot;Vega: {V: .2f}&quot;)<br>        print(f&quot;Rho: {R: .2f}&quot;)</pre><pre># Calculates the underlying stock&#39;s volatility<br>prices = yf.Ticker(&#39;WMT&#39;).history(start=datetime(2019, 1, 1))[&#39;Close&#39;]<br>returns = np.log(prices / prices.shift())<br>sigma = returns.std() * np.sqrt(252)<br><br># Retrieves the underlying stock&#39;s current price<br>S = prices.iloc[-1]<br><br># Retrieves the risk-free interest rate<br>t_bill_3m = yf.Ticker(&quot;^IRX&quot;).history()<br>r = t_bill_3m[&quot;Close&quot;].iloc[-1] / 100<br><br># Setting parameters<br>K = 100 # The strike price of this call option is $100<br>T = 3 # It will take one 3 months to expire</pre><pre>call_option = Option(sigma, K, S, T/12, r, &#39;call&#39;)<br>call_option.summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/287/1*-mHv43k7PISo0QSaMVpPww.png" /></figure><p>The Delta reveals that a $1 dollar increase in Walmart’s stock would imply a $0.62 increase in the option’s value. Also, <strong>it suggests that the option has around 62% chance of expiring in-the-money, in other words, the strike price would be below the stock’s value at maturity.</strong></p><p><strong>The Gamma tells us that the Delta is moderately unstable.</strong> A $1 move in the stock will change the Delta by 0.03.</p><p>The Theta indicates that everyday the option loses $0.03 in value per share, which is quite standard.</p><p><strong>The Vega shows that the option is very sensitive to market sentiment.</strong> A 1 percetange point increase in implied volatility would increase the option’s price by $0.19, which is considerably high given that the current price of the option is $5.92.</p><p>Lastly, a Rho of 0.14 means that for every 1 percentage point increase in the risk-free interest rate increases the option’s price by $0.14, which is a moderate sensitivity.</p><p><strong>All of this describes a classic at-the-money option</strong>, where the strike price is close to the current underlying stock price, the outcome is highly uncertain and its value is sensitive to all market forces.</p><h3>Bibliography</h3><p>This story was written used these contents as references:</p><ul><li><a href="https://www.investopedia.com/terms/g/greeks.asp#toc-vega-gauging-volatility-sensitivity">Investopedia Greeks</a></li><li><a href="https://www.investopedia.com/terms/d/deltahedging.asp">Investopedia Delta Hedgin</a>g</li><li><a href="https://www.investopedia.com/ask/answers/042715/what-difference-between-money-and-out-money.asp">Investopedia — Between Money and Out Money</a></li><li><a href="https://www.investopedia.com/terms/a/atthemoney.asp">Investopedia — At the Money</a></li><li><a href="https://en.wikipedia.org/wiki/Greeks_(finance)">Wikipedia — Greeks</a></li><li><a href="https://www.cqf.com/blog/quant-finance-101/what-are-the-greeks">CQF — What are the Greeks?</a></li><li><a href="https://quantpie.co.uk/bsm_formula/bs_summary.php">Quantpie — BSM Formula</a></li><li><a href="https://www.columbia.edu/~mh2078/FoundationsFE/BlackScholes.pdf">Columbia — Black Scholes</a></li><li><a href="https://sites.millersville.edu/rbuchanan/book/Greeks.pdf">J. Robert Buchanan — The Greeks: Derivatives of Option Prices</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eea94c1b85ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monte Carlo Method for Evaluating Portfolios]]></title>
            <link>https://medium.com/@andrejin.nagano/monte-carlo-method-for-evaluating-portfolios-767ff7c0fae7?source=rss-7d22ea87b56e------2</link>
            <guid isPermaLink="false">https://medium.com/p/767ff7c0fae7</guid>
            <category><![CDATA[investment]]></category>
            <category><![CDATA[portfolio]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[monte-carlo]]></category>
            <category><![CDATA[finance]]></category>
            <dc:creator><![CDATA[Andre Nagano]]></dc:creator>
            <pubDate>Thu, 04 Sep 2025 19:06:33 GMT</pubDate>
            <atom:updated>2025-09-07T23:36:08.285Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>This story is a follow-up to my previous <a href="https://medium.com/@andrejin.nagano/portfolio-optimization-explained-python-code-d15cd017ff31">portfolio optimization article</a>. If you want to understand where did the portfolio used in this story came from please check that one out.</blockquote><p><strong>The process of optimizing a portfolio is essentially selecting an asset distribution in order to achieve a certain goal.</strong> We can evaluate the performance of a portfolio by estimating its risk and expected return. An alternative method is to use different techniques to simulate the portfolio&#39;s performance. In this article, we&#39;ll discuss and apply the Monte Carlo method, using randomness to forecast our portfolio&#39;s risk and return.</p><h3>Portfolio Simulation</h3><p>With our portfolio constructed, <strong>we can simulate multiple scenarios and calculate its expected returns based on the assumption that stock prices follow a </strong><a href="https://en.wikipedia.org/wiki/Geometric_Brownian_motion"><strong>Geometric Brownian motion</strong></a>. The process is to first generate normally distributed random variables to forecast stock prices using the volatility and expected return of each asset. Then, we’ll simulate a number of portfolios by calculating its expected returns with the weights and forecasted returns of each stock. Finally, we can calculate the average of the expected returns, and study the distribution of the results.</p><h3><strong>Monte Carlo Method</strong></h3><p>A <a href="https://en.wikipedia.org/wiki/Monte_Carlo_method">Monte Carlo method</a> is often to model events with significant uncertainty in inputs. <strong>The technique is to forecast multiple results from a randomly generated inputs.</strong> Once the simulation is complete, we can draw some statistics from the outputs, like average, variance and intervals of confidence.</p><h3><strong>Multi-dimensional Geometric Brownian Motion (M-GBM)</strong></h3><p>In a <a href="https://medium.com/@andrejin.nagano/black-scholes-option-pricing-model-formula-6438c1c22720">previous story</a>, I discussed the concept of Geometric Brownian Motion (GBM) and why we can use it to model the movements of stock prices. But simply put, <strong>a GBM is a stochastic process in which the change in position is given by a drift parameter and a volatility parameter multiplied by a random variable.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/217/1*wJFRqtpqSKlq2b2Hl4xtBQ.png" /></figure><p>It is often used to model the random behavior of stock prices because of its lognormal distribution.</p><p>However, the GBM model only works for a single stock’s movement. <strong>When we analyze the movement of multiple assets at once, we can’t only consider the independent variances of each stock, we also have to count for covariances between them.</strong> That’s why when we are modeling the movements of several stocks we have to use a multidimensional GBM.</p><p>The stochastic differential equation for a M-GBM is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*usrfBFRVKcNbDqkIzq_Qlg.png" /></figure><p>This formula is similar to the standard GBM, but <strong>instead of having a single volatility parameter (<em>σ</em>), now we have a volatility matrix.</strong></p><p>Each row of the volatility matrix (<em>Σ</em>) represents a stock, with its variance and <a href="https://en.wikipedia.org/wiki/Covariance">covariances</a> with the other stocks. In short, the covariance tells us the direction of the linear relationship between two variables. The more positive a covariance is, the more the two variables tend move in the same direction. The more negative a covariance is, the more the two variables tend to move in opposite directions.</p><p>The solution for this SDE is given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/355/1*RoZN5IZRMer5dF3WJW66Jw.png" /></figure><p>The <em>LW</em> is the vector of correlated random shocks. We use the <a href="https://en.wikipedia.org/wiki/Cholesky_decomposition">Cholesky decomposition</a> to obtain the lower triangular matrix L, and then we multiply it by the Wiener processes vector W.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/98/1*fQY5l7WG9ak5A9HFNT70EQ.png" /></figure><p><strong>When we multiply the Cholesky matrix L by the vector of independent Wiener processes W, we are creating a new matrix with correlated random shocks.</strong> Since the stock prices are not independent, a random shock in one price has an impact on another based on the covariance between the two. The purpose of the L matrix is to transform random numbers into correlated random numbers, like explained previously.</p><h3><strong>Code</strong></h3><h4><strong>Monte Carlo Function</strong></h4><p>Next, we define the Monte Carlo simulation function. <strong>This function simulates multiple times the returns of our portfolio in a set time horizon.</strong></p><p>First, the function creates an empty array where all the final values of each portfolio will be stored. Then, we calculate the expected daily return of each stock (<em>μ</em>) and the covariance matrix (<em>Σ</em>).</p><p>For each simulation we generate random shocks (<em>W</em>), multiplying it by the lower triangle matrix from the Cholesky decomposition (<em>L</em>). With the solution to the M-GBM SDE, we estimate the daily returns for each stock for the set time horizon.</p><p>We can accumulate the daily returns, and multiply by the weights in our portfolio, which results in the final value of the portfolio after the defined time horizon. <strong>The output of this function is an array with all the final values of each simulation.</strong></p><pre>def monte_carlo(returns, weights, initial_investment, time_horizon_years, num_simulations):<br>    &quot;&quot;&quot;<br>    Runs a correlated Monte Carlo simulation for a portfolio using M-GBM.<br>    &quot;&quot;&quot;<br><br>    # Define the time horizon for the simulation<br>    num_trading_days = 252<br>    time_horizon_days = num_trading_days * time_horizon_years<br>    num_assets = len(returns.columns)<br>    <br>    # Array to store the final portfolio values of each simulation<br>    final_portfolio_values = np.zeros(num_simulations)<br>    <br>    # Calculate the mu parameter and the volatility matrix<br>    daily_mu = returns.mean()<br>    daily_cov = returns.cov()<br>    <br>    # Calculate the L matrix with the Cholesky Decomposition<br>    L = np.linalg.cholesky(daily_cov)<br>    <br>    # Run the Simulations<br>    for i in range(num_simulations):<br><br>        # Generate vector of independent Wiener processes<br>        standard_random_shocks = np.random.normal(0, 1, (num_assets, time_horizon_days))<br>        <br>        # Calculate the matrix of correlated random shocks<br>        correlated_shocks = L @ standard_random_shocks<br>        <br>        # Calculate the drift component for the M-GBM formula<br>        drift_component = daily_mu - np.diag(daily_cov) / 2<br>        <br>        # Reshape for broadcasting<br>        drift_component = drift_component.values.reshape(num_assets, 1)<br>        <br>        # Calculate daily returns for each asset using M-GBM<br>        daily_returns = np.exp(drift_component + correlated_shocks)<br>        <br>        # Stack a row of ones to represent the starting prices (S0 = 1)<br>        price_paths = np.vstack([np.ones(num_assets), daily_returns.T])<br>        <br>        # Calculate cumulative price paths by multiplying the daily returns<br>        cumulative_price_paths = price_paths.cumprod(axis=0)<br>        <br>        # Calculate the final value of the portfolio for this simulation<br>        initial_allocations = weights * initial_investment<br>        final_asset_values = cumulative_price_paths[-1] * initial_allocations<br>        final_portfolio_values[i] = final_asset_values.sum()<br><br>    return final_portfolio_values</pre><p>We can now run the simulation defining some parameters. For this experiment, we start with $100,000.00, and run 10.000 simulations for a single year.</p><pre># Simulation Settings<br>INVESTMENT = 100000<br>YEARS = 1<br>NUM_SIMULATIONS = 10000<br><br># Run the simluation<br>final_values = monte_carlo(<br>    returns=returns, # This is from my previous story<br>    weights=optimized_results.x, # This is from my previous article<br>    initial_investment=INVESTMENT,<br>    time_horizon_years=YEARS,<br>    num_simulations=NUM_SIMULATIONS<br>)<br><br># Calculate statistics<br>mean_value = np.mean(final_values)<br>std_value = np.std(final_values)<br>percentile_5 = np.percentile(final_values, 5)<br>percentile_95 = np.percentile(final_values, 95)<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*K5PvWLFB4VUUvYOiNQ0Cpg.png" /></figure><h3><strong>Analyzing the Results</strong></h3><p>With the results from the Monte Carlo simulations, we can calculate the mean, the 5th and 95th percentile, and the standard deviation. We can also plot a histogram of all the values in the array, and see how the data is distributed.</p><pre>plt.figure(figsize=(12, 7))<br><br># Plot histogram of the distribution of final values<br>plt.hist(final_values, bins=100, density=True, alpha=0.8, label=&#39;Simulation Outcomes&#39;)<br><br># Highlight the mean, 5th and 95th percentile<br>plt.axvline(mean_value, color=&#39;red&#39;, linestyle=&#39;--&#39;, linewidth=2, label=f&#39;Mean: ${mean_value:,.2f}&#39;)<br>plt.axvline(percentile_5, color=&#39;orange&#39;, linestyle=&#39;:&#39;, linewidth=2, label=f&#39;5th Percentile (VaR): ${percentile_5:,.2f}&#39;)<br>plt.axvline(percentile_95, color=&#39;green&#39;, linestyle=&#39;:&#39;, linewidth=2, label=f&#39;95th Percentile: ${percentile_95:,.2f}&#39;)<br><br>plt.title(&#39;Distribution of Final Portfolio Values&#39;, fontsize=18)<br>plt.xlabel(&#39;Final Portfolio Value ($)&#39;, fontsize=12)<br>plt.ylabel(&#39;Probability Density&#39;, fontsize=12)<br>plt.legend(fontsize=10)<br>plt.grid(True, which=&#39;both&#39;, linestyle=&#39;--&#39;, linewidth=0.5)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*FAXlm-cF_oJ3PTYtDV5zbA.png" /></figure><h4><strong>Expected Return</strong></h4><p>The average of all final portfolio values is our expected value after the time horizon. For our Monte Carlo simulations, the expected final portfolio value is $141k. This means that in 1 year, we can expected the investment to increase by 40%.</p><h4><strong>Standard Deviation</strong></h4><p>The standard deviation of all final portfolio values is the primary measure of risk. A metric of $32,018.96 means that there is a approximately 68% change that the value of our portfolio to falls between $109k and $173k.</p><h4><strong>Value at Risk (VaR)</strong></h4><p><strong>The </strong><a href="https://en.wikipedia.org/wiki/Value_at_risk"><strong>Value at Risk</strong></a><strong> is a metric that quantifies the potential financial loss of an investment over a specified timeframe.</strong> In our Monte Carlo simulation, we see that in 5% of all experiments, the value of the portfolio decreases to lower than $97k. This would mean that there is a 5% chance of the portfolio will lose at least 3% of its value over the next year. <strong>Usually, we use this notation for VaR: the portfolio has a 5% one-year VaR of 3%.</strong></p><h4><strong>Distribution</strong></h4><p><strong>One thing to highlight is that the distribution of the portfolio’s values is </strong><a href="https://en.wikipedia.org/wiki/Log-normal_distribution"><strong>log-normally distributed</strong></a><strong>.</strong> This means that the portfolio can’t have a negative value at any time and that the distribution has a long tail to the right (positive skew). The reason for that is because the GBM model for stock prices assumes the distribution to be log-normally as well, meaning there is a cap for losses at $0 (stocks are real limited assets) and there are possible unlimited gains.</p><h3>Bibliography</h3><p>For this article, these contents were used as references:</p><ul><li><a href="https://www.investopedia.com/terms/m/montecarlosimulation.asp">Monte Carlo Simulation: What It Is, How It Works, History, 4 Key Steps by Investopedia</a></li><li><a href="https://towardsdatascience.com/how-to-simulate-financial-portfolios-with-python-d0dc4b52a278/">How to simulate financial portfolios with Python by Towards Data Science</a></li><li><a href="http://hsrm-mathematik.de/WS201516/master/option-pricing/Multi-Underlying-Black-Scholes-Model-and-Correlation.pdf">The Multi-Underlying Black-Scholes Model and Correlation</a></li><li><a href="https://arxiv.org/html/2507.09413v1">Model Reduction of Multivariate Geometric Brownian Motions and Localization in a Two-State Quantum System</a></li><li><a href="https://medium.com/@andrejin.nagano/black-scholes-option-pricing-model-formula-6438c1c22720">Black-Scholes Option Pricing Model — Formula</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=767ff7c0fae7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Portfolio Optimization Explained + Python Code]]></title>
            <link>https://medium.com/@andrejin.nagano/portfolio-optimization-explained-python-code-d15cd017ff31?source=rss-7d22ea87b56e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d15cd017ff31</guid>
            <category><![CDATA[quantitative-finance]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[portfolio]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Andre Nagano]]></dc:creator>
            <pubDate>Thu, 04 Sep 2025 01:31:32 GMT</pubDate>
            <atom:updated>2025-09-04T01:31:32.955Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>The process of optimizing a portfolio is essentially selecting an asset distribution in order to achieve a certain goal.</strong> This optimal portfolio depends on the objective, but usually is associated with maximizing your returns or minimizing the risk. In this article, we’ll try to <strong>optimize a portfolio by maximizing the sharpe ratio</strong> of our portfolio.</p><p>We’ll first discuss about some basic concepts in portfolio theory, and then we’ll write a code to optimize the portfolio.</p><h3><strong>Modern Portfolio Theory (MPT)</strong></h3><p>A portfolio is a combination of investments. These investments can have different natures, such as stocks, bonds, cash, etc. <strong>Every asset within a same class has two main attributes that differ them from each other, which are the return and the variance or risk.</strong></p><p><strong>The </strong><a href="https://en.wikipedia.org/wiki/Modern_portfolio_theory"><strong>Modern Portfolio Theory</strong></a><strong> (or mean-variance analysis) is a concept in finance which propagates the idea of building a portfolio that maximizes the expected return for a given level of risk.</strong> A key part of the theory is that <a href="https://en.wikipedia.org/wiki/Diversification_(finance)"><strong>diversification</strong></a> in investing reduces the risk of your portfolio. Investors could achieve better results by choosing an optimal combination of investments based on an assessment of their own individual tolerance to risk.</p><h4><strong>Rate of Return</strong></h4><p><strong>A portfolio’s return is the logarithmic change in value after a specified period</strong>. We can calculate the returns of each asset with:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*-F8E7MKFp0J7sc8uGq3mSQ.png" /></figure><p>For each asset, we can calculate its <a href="https://en.wikipedia.org/wiki/Rate_of_return">expected return</a>, by taking the mean of daily returns in a sample:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*CLuFxPzDeglijEOX4B3tMg.png" /></figure><p>We can think of a portfolio as a list, or vector, of weights that represent how our capital is distributed among the assets:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*hxBUjZ3D4fAWr-LTVKOrxw.png" /></figure><p>Then, <strong>the expected return of our portfolio would be the sum of weights of each asset multiplied by its expected return</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*VT6bxvzSC6JSgwRuzGukcQ.png" /></figure><h4><strong>Risk</strong></h4><p>Each asset has its own variance. <strong>We can combine the variance of each asset by just adding up each independent variance. However, we also have to account for possible covariances between different assets</strong>.</p><p>In a portfolio with two assets, the variance would be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*LSj4o-RX9i0qUflqLdQBkQ.png" /></figure><p>For a portfolio with <em>m</em> assets, we first define a covariance matrix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*VDh_JqIb_OSTpB2DXgzK3g.png" /></figure><p>Then, we can calculate the variance of our portfolio as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*953GII2mfKz4r4-tKLgrEg.png" /></figure><p>With the variance, we can also calculate the standard deviation of our portfolio.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*rLiNwtip29NfD8uhJaj8WA.png" /></figure><p><strong>Both are measures the volatility or risk in our portfolio.</strong></p><h3><strong>Example with Two Stocks</strong></h3><p>Let’s use some real data as an example.</p><pre>import yfinance as yf<br>import matplotlib.pyplot as plt<br>import numpy as np<br><br># With yfinance, we retrieve historical closing prices of WMT and AMZN stocks<br>prices = yf.download([&#39;WMT&#39;, &#39;AMZN&#39;], start=&#39;2010-01-01&#39;, auto_adjust=False)[&#39;Adj Close&#39;]<br><br># Calculate the daily returns of each stock<br>returns = np.log(prices / prices.shift())</pre><p>We will define two functions to calculate the return and the risk of our portfolio.</p><pre>def portfolio_return(returns, weights):<br>    &quot;&quot;&quot;<br>    Takes the dataframe of daily returns and multiply by the respective weight,<br>    while also annualizing by multiplying by the number of trading days.<br>    &quot;&quot;&quot;<br><br>    return np.sum(returns.mean() * weights) * 252<br><br>def portfolio_risk(returns, weights):<br>    &quot;&quot;&quot;<br>    Calculates the covariance matrix of the daily returns, adjusting for a year,<br>    and then calculates the standard deviation of the portfolio using the given<br>    weights.<br>    &quot;&quot;&quot;<br><br>    cov_matrix = returns.cov() * 252 # Calculate the covariance matrix<br><br>    risk = np.sqrt(np.dot(weights.T, np.dot(cov_matrix, weights)))<br><br>    return risk</pre><p>Then, for multiple combinations of weights, we can calculate the risk and return of those portfolios.</p><pre># Create a set of weights for the first stock<br>possible_weights = np.linspace(0, 1, 100)<br><br>portfolios = []<br><br>for w1 in possible_weights:<br><br>    # The two weights sum up to 1 or 100%<br>    w2 = 1 - w1<br>    weights = np.array([w1, w2])<br><br>    # Calculate the risk and return for a given combination of weights (portfolio)<br>    curr_risk = portfolio_risk(returns, weights)<br>    curr_return = portfolio_return(returns, weights)<br><br>    portfolios.append([curr_risk, curr_return])<br><br>portfolios = np.array(portfolios)</pre><p>Also, we’ll highlight the portfolio with the lowest volatility and use it as a divider between portfolios with returns lower and higher than it.</p><pre># Look for the portfolio with the lowest volatility<br>min_risk_idx = np.argmin(portfolios[:, 0])<br>min_risk_risk = portfolios[min_risk_idx, 0]<br>min_risk_return = portfolios[min_risk_idx, 1]<br><br># Divide the portfolios into efficient and inefficient according to the efficient frontier<br>efficient_mask = portfolios[:, 1] &gt;= min_risk_return<br>efficient_portfolios = portfolios[efficient_mask]<br>inefficient_portfolios = portfolios[~efficient_mask]</pre><p>Finally, we can plot all the portfolios in a <a href="https://en.wikipedia.org/wiki/Risk%E2%80%93return_spectrum">risk x return</a> graph.</p><pre># Create a return x volatility plot for all portfolios<br>plt.figure(figsize=(12, 7))<br>plt.plot(inefficient_portfolios[:, 0], inefficient_portfolios[:, 1], c=&#39;gray&#39;, label=&#39;Inefficient Frontier&#39;)<br>plt.plot(efficient_portfolios[:, 0], efficient_portfolios[:, 1], c=&#39;red&#39;, label=&#39;Efficient Frontier&#39;)<br><br># Highlight the portfolios with minimum risk and with 100% allocated to each stock<br>plt.scatter(min_risk_risk, min_risk_return, c=&#39;red&#39;, s=150, edgecolors=&#39;black&#39;, label=&#39;Min Volatility&#39;)<br>plt.scatter(portfolios[0, 0], portfolios[0, 1], c=&#39;green&#39;, s=150, edgecolors=&#39;black&#39;, label=&#39;100% AMZN&#39;)<br>plt.scatter(portfolios[-1, 0], portfolios[-1, 1], c=&#39;purple&#39;, s=150, edgecolors=&#39;black&#39;, label=&#39;100% WMT&#39;)<br><br>plt.title(&#39;Efficient Frontier: WMT &amp; AMZN&#39;)<br>plt.xlabel(&#39;Annualized Volatility (Risk)&#39;)<br>plt.ylabel(&#39;Annualized Return&#39;)<br>plt.legend()<br>plt.grid(True)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*VP7aJFM9kbNI61F6v7fR-Q.png" /></figure><h3><strong>Efficient Frontier</strong></h3><p>As we can see int the plot above, <strong>the portfolios corresponding to the gray line, represent sub-optimal portfolios</strong>. That’s because there are other combinations of weights which have the same risk, but with higher returns. So the optimal portfolios, which are represented by <strong>the red line or the </strong><a href="https://en.wikipedia.org/wiki/Efficient_frontier"><strong>Efficient Frontier</strong></a><strong>, are the portfolios which are worth analyzing</strong>.</p><p>The red marker is the portfolio with the lowest amount of risk. This portfolio divides the efficient frontier from the sub-optimal portfolios.</p><p><strong>We can choose any portfolio within the efficient frontier, according to the MPT, this only depends on the risk we’re willing to take, since higher risk equals higher returns. </strong>So, one way we could optimize our portfolio is by defining a level of volatility, and looking for the distributions of weights that would result in the highest expected return.</p><h3><strong>Risk-free Assets</strong></h3><p>One thing we should also consider is the existence of risk-free assets. In practice, risk-free assets can be seen as the yield of bonds issued by stable governments. Even though, there is always a risk of a government defaulting, the odds are so low compared to the volatility of other assets, that it’s acceptable to think of them as risk-free. <strong>Since you could obtain a rate of return from zero risk, any other risky investment will have to have a higher rate of return in order to induce any investors to hold it.</strong> In other words, besides finding an optimal balance of risky assets in our portfolio, we can also allocate part of our capital in a risk-free asset.</p><h3><strong>Sharpe Ratio</strong></h3><p>Another way we can measure the performance of our portfolio is by looking at its <a href="https://en.wikipedia.org/wiki/Sharpe_ratio">Sharpe Ratio</a>. The Sharpe Ratio is an indicator that combines the return (Rp) and standard deviation (σp) of our portfolio and the risk-free rate of return (Rf). <strong>In short, the Sharpe Ratio indicates how much extra return we get from every unit of risk taken.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*_WcFf57hLyyronqYiEBnWQ.png" /></figure><p>With the Sharpe Ratio, we can compare different portfolios taking both risk and return into account. The higher the Sharpe Ratio, the better our portfolio did coverting its risk into excess returns. <strong>This means that we can maximize our Sharpe Ratio to find a optimal portfolio.</strong></p><h3><strong>Capital Market Line</strong></h3><p>When we consider risk-free investments, our set of possible optimal portfolios change. <strong>The way we can visualize this is by first taking the rate of return of the risk-free asset and plotting in the volatility x return graph. Then, we trace a straight line, tangent to the efficient frontier and starting at the risk-free rate.</strong> This line is called the <a href="https://en.wikipedia.org/wiki/Capital_market_line">Capital Market Line</a> (CML).</p><pre>def sharpe_ratio(portfolio_return, portfolio_volatility, rf=0.042):<br>    &quot;&quot;&quot;<br>    Calculates the Sharpe Ratio by taking the return and volatility of<br>    the portfolio and a risk-free rate of return.<br>    &quot;&quot;&quot;<br>    return (portfolio_return - rf) / portfolio_volatility</pre><pre>max_sharpe = 0<br>max_efficient_portfolio = []<br><br># Iterate through all the portfolios, looking for the one with the highest Sharpe Ratio<br>for risk, rp in portfolios:<br>    <br>    portfolio_sharpe = sharpe_ratio(rp, risk)<br><br>    if portfolio_sharpe &gt; max_sharpe:<br>        max_sharpe = portfolio_sharpe<br>        max_efficient_portfolio = [risk, rp]</pre><pre># Create a plot with the efficient frontier + CML<br>plt.figure(figsize=(12, 7))<br><br># Plot the efficient frontier from last example<br>plt.plot(efficient_portfolios[:, 0], efficient_portfolios[:, 1], c=&#39;red&#39;, label=&#39;Efficient Frontier&#39;)<br># Plot a straight line between the risk-free rate and the optimal risky portfolio<br>plt.plot([0, max_efficient_portfolio[0]], [0.042, max_efficient_portfolio[1]], label=&#39;Capital Market Line&#39;)<br><br>plt.scatter(max_efficient_portfolio[0], max_efficient_portfolio[1], c=&#39;red&#39;, s=50, label=&#39;Tangency Portfolio&#39;)<br>plt.scatter(0, 0.042, c=&#39;black&#39;, s=50, label=&#39;Risk-free Rate of Return&#39;)<br><br>plt.title(&#39;Capital Market Line&#39;)<br>plt.xlabel(&#39;Annualized Volatility (Risk)&#39;)<br>plt.ylabel(&#39;Annualized Return&#39;)<br>plt.xlim(0, 0.4)<br>plt.legend()<br>plt.grid(True)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MVHel5JO0KzFHBSj2qoflg.png" /></figure><p>The point where the CML and the Efficient Frontier meet represents the portfolio with the highest Sharpe Ratio, which means is also the most efficient portfolio of risky assets. <strong>This portfolio is also called the tangency portfolio</strong>. The starting point of the CML represents a portfolio only invested in a risk-free asset. <strong>Every portfolio that falls on top of the CML is a mix of the most efficient portfolio and the risk-free asset.</strong> For that reason, the efficient frontier doesn’t correspond to the set of optimal portfolios anymore, since there are options of portfolios with higher returns and lower risk when we combine risky and risk-free assets. Now, the set of optimal portfolios can be seen as the portfolios in the CML.</p><p>The formula for the Capital Market Line would be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*V1uSzSjX7yT_XsMTn3aXcA.png" /></figure><p>The term (E[Rt] — Rf)/σt is simply the Sharpe Ratio of the tangency or optimal risky portfolio, which is the slope of the CML. The formula says that the expected return of any portfolio on the line is the risk-free rate plus the risk of that portfolio multiplied by the sharpe ratio of the tangency portfolio, or “price of risk”.</p><h3><strong>Optimal Portfolio with Python</strong></h3><p>With all the basic concepts in mind, we can write a code to find an optimal portfolio in python. <strong>The code will look for a distribution of weights for a set of stocks, that will maximize the Sharpe Ratio of the portfolio.</strong></p><h4><strong>Daily Returns</strong></h4><p>We will first retrieve the daily closing prices of the S&amp;P500 companies using the <em>yfinance</em> library. We’ll get a list of the companies from the S&amp;P500 wikipedia page.</p><pre>import pandas as pd<br>import requests<br><br># Scrape from the wikipedia page the list of S&amp;P500 companies<br>url = &#39;https://en.wikipedia.org/wiki/List_of_S%26P_500_companies&#39;<br><br>headers = {<br>    &#39;User-Agent&#39;: &#39;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36&#39;<br>}<br><br>r = requests.get(url, headers=headers)<br><br>table = pd.read_html(r.text)[0]<br><br># Get just the tickers<br>tickers = table[&#39;Symbol&#39;].tolist()</pre><pre># Retrieve the closing prices with yfinance<br>prices = yf.download(tickers, start=&#39;2020-01-01&#39;, auto_adjust=False)[&#39;Adj Close&#39;]<br>prices = prices.dropna(axis=1)<br>returns = np.log(prices / prices.shift())</pre><p>In our experiment, we will restrict our set to stocks from the S&amp;P500 companies since 2020. In reality this is not a good practice. It’s always good to diversify our assets, with mid or small caps and even global stocks. Also, it’s recommended to use a bigger timeframe. There are techniques to deal with the impact of the pandemic as well.</p><p>But, it would take longer to run the tests. Since this is only for educational purposes, we don’t have to go that far.</p><h4><strong>Negative Sharpe Ratio</strong></h4><p>To optimize our portfolio, we have to maximize our Sharpe Ratio. However, since we’re using the <em>minimize</em> method from <em>scipy.optimize</em> library, we’ll define a function to calculate the negative Sharpe Ratio. <strong>So, instead of maximizing the Sharpe Ratio, we’ll minimize the negative Sharpe Ratio.</strong> This is called the <a href="https://en.wikipedia.org/wiki/Loss_function">loss function</a> or cost function, which we want to minimize in order to get a better performance.</p><p>The loss function takes a array of weights (portfolio), the daily returns of stocks and the risk-free rate as inputs. First, it calculates the risk and volatility, given the weights, and then returns the negative Sharpe Ratio.</p><pre>def neg_portfolio_sharpe(weights, returns, rf=0.0):<br>    &quot;&quot;&quot;<br>    Calculates the negative Sharpe Ratio given the weight distribution,<br>    daily returns of each stock and a risk-free rate of return.<br>    &quot;&quot;&quot;<br><br>    p_returns = portfolio_return(returns, weights)<br><br>    p_risk = portfolio_risk(returns, weights)<br><br>    sharpe = (p_returns - rf) / p_risk<br><br>    return -sharpe</pre><h4><strong>Constraints and Bounds</strong></h4><p>Next, we set some constraints and bounds for the optimization. There are multiple types of limitations we can add to our portfolio. In this example, we’ll set two different limitations.</p><p><strong>The first is a constraint that the sum of all weights is equal to 1.</strong> That means that our capital will be 100% allocated.</p><p><strong>The second is a boundary that for each weight the minimum value is 0 and the maximum is 0.5.</strong> This is because we won’t allow short positions, so we won’t have negative weights. Also, we don’t want a single asset to have a weight greater than 50%, since we want a diversified portfolio.</p><pre># This constraint means that the sum of all weights minus 1 must be equal to zero<br>constraints = {&#39;type&#39;: &#39;eq&#39;, &#39;fun&#39;: lambda weights: np.sum(weights) - 1}<br><br># This creates an array of (0, 0.5) for each stock<br>bounds = [(0, 0.5) for _ in range(returns.shape[1])]</pre><h4><strong>Initial Weights</strong></h4><p>For every optimization problem, we have to start at an initial guess of what the weights would be. The optimization algorithm will work from this starting point and look for changes in the weights that would result higher Sharpe Ratio (or lower negative Sharpe Ratio). <strong>For our initial weights, we’ll just have a uniform distribution among all the stocks.</strong> A more robust approach would be to create a set of random initial weights, and use those as starting points, reducing the bias and the likelihood falling on a local minimum. However, since this is a first experiment, we’ll stick to a more basic technique.</p><pre>initial_weights = np.array([1 / returns.shape[1]] * returns.shape[1])</pre><h4><strong>Minimize</strong></h4><p>The <a href="https://en.wikipedia.org/wiki/Optimization_problem">optimization</a> is done using the <em>optimize.minimize</em> function from the <em>scipy</em> library. We’ll input the loss function, initial weights, extra arguments for the loss function (returns and risk-free rate), which type of solver, constraints and bounds.</p><p>The method <a href="https://en.wikipedia.org/wiki/Sequential_quadratic_programming"><em>SLSQP</em></a> is an iterative algorithm that is used for solving nonlinear optimization problems with constraints. <strong>It is widely used for its efficiency and robustness, being able to solve nonlinear problems with both equality and inequality constraints. </strong>Although, it can be quite sensitive to the initial guess. That’s why it’s recommended to test different starting points.</p><pre>from scipy.optimize import minimize<br><br>optimized_results = minimize(neg_portfolio_sharpe, initial_weights, args=(returns, 0.02),<br>                             method=&#39;SLSQP&#39;, constraints=constraints, bounds=bounds)</pre><pre># The weights of the minimize results is the x attribute<br>optimized_weights = optimized_results.x</pre><p>From the results of the <em>minimize</em> function, we can get the parameter <em>x</em>, which refer to the weights that leads to the lowest negative sharpe ratio found. Some of the weights from the optimized results are very small compared, less than 0.1%, so we’ll discard them.</p><p>For our optimal portfolio, we can calculate the expected annualized return, volatility and Sharpe Ratio.</p><pre>optimized_return = portfolio_return(returns, optimized_weights)<br>optimized_volatility = portfolio_risk(returns, optimized_weights)<br>optimized_sharpe = sharpe_ratio(optimized_return, optimized_volatility)<br><br>print(&#39;------ Optimal Portfolio ------&#39;)<br>print(f&quot;Annualized Returns: {optimized_return:.2f}&quot;)<br>print(f&quot;Annualized Volatility: {optimized_volatility:.2f}&quot;)<br>print(f&quot;Annualized Sharpe Ratio: {optimized_sharpe:.2f}&quot;)<br>print(f&#39;Number of Stocks in Portfolio: {len(optimized_results.x[optimized_results.x &gt; 0.0001])}&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*4t6gt_VhtI_rVCYU3qhPgA.png" /></figure><p>A annualized return of 33% is exceptionally high, way higher than the average for a S&amp;P500 index. However, a higher return is accompanied by a higher risk. <strong>Even though an annualized volatility of 20% is a moderately high risk, it’s expected from a portfolio composed only of stocks.</strong></p><p>To put it in perspective, in any given year, there’s a roughly 68% chance that the portfolio’s return will be within one standard deviation of the average. This means you can expect the annual return to fall somewhere between 12% (33% — 21%) and 54% (33% + 21%).</p><p><strong>A Sharpe Ratio of 1.39 indicates that the investment is generating more return than its associated risk, since it’s higher than 1.0.</strong> The portfolio is generating a high amount of return for every unit of risk it takes on, proving its efficience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*neWJSjC--B9fyh9He6NAiw.png" /></figure><p>The plot above shows the composition of our portfolio. <strong>The portfolio is mainly distributed among nine different stocks, with a relatively small percentage allocated to other six. </strong>Given the set of almost 500 companies, this is not necessarily a diversified portfolio. In our portfolio optimization solution, this is the weight distribution that led to the highest Sharpe Ratio. <strong>However, there could be other solutions.</strong> Depending on the minimizing method and initial guess for the weights, another local minimum or the global minimum could be found, resulting in a different distribution of stocks.</p><p>(I can make another post explaining how I made this graph, but I basically followed this post on <a href="https://python-graph-gallery.com/590-advanced-treemap/">Python Graph Gallery</a>)</p><h3>Next Steps</h3><p><strong>As discussed earlier, this is an optimal portfolio with only risky assets, under the set constraints.</strong> We could also reduce the overall percentage of stocks and add risk-free assets to reduce the volatility, but also reducing the expected return.</p><p>There are many ways we could make this optimization more robust, increase the timeframe of historical data, add stocks with different backgrounds, test different starting weights and minimization algorithms. I’m planning to write about a genetic algorithm for the portfolio optimization in the future.</p><p>In the next story, I’ll use the Monte Carlo method to stress-test the performance of this portfolio.</p><h3>Bibliography</h3><p>For this article, these contents were used as references:</p><ul><li><a href="https://www.youtube.com/watch?v=ywl3pq6yc54">MIT 18.S096 Topics in Mathematics with Applications in Finance: Lesson 14 — Portfolio Theory</a></li><li><a href="https://www.youtube.com/watch?v=wOaKzthMUQ0">The Capital Market Line by Edspira</a></li><li><a href="https://www.investopedia.com/terms/m/modernportfoliotheory.asp">Modern Portfolio Theory by Investopedia</a></li><li><a href="https://www.investopedia.com/terms/e/efficientfrontier.asp">Efficient Frontier by Investopedia</a></li><li><a href="https://www.google.com/search?client=safari&amp;rls=en&amp;q=sharpe+ratio&amp;ie=UTF-8&amp;oe=UTF-8">Sharpe Ratio by Investopedia</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d15cd017ff31" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modelo de Precificação de Opções Black-Scholes — Código no Python]]></title>
            <link>https://medium.com/@andrejin.nagano/modelo-de-precifica%C3%A7%C3%A3o-de-op%C3%A7%C3%B5es-black-scholes-c%C3%B3digo-no-python-8be8476a3a13?source=rss-7d22ea87b56e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8be8476a3a13</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[matemática]]></category>
            <category><![CDATA[finanças]]></category>
            <category><![CDATA[options-trading]]></category>
            <category><![CDATA[black-scholes-model]]></category>
            <dc:creator><![CDATA[Andre Nagano]]></dc:creator>
            <pubDate>Tue, 26 Aug 2025 20:23:55 GMT</pubDate>
            <atom:updated>2025-08-26T20:27:02.137Z</atom:updated>
            <content:encoded><![CDATA[<h3>Modelo de Precificação de Opções Black-Scholes — Código no Python</h3><blockquote>Esta é a terceira parte de uma série de três artigos sobre o modelo de precificação de opções de Black-Scholes. Na <a href="https://medium.com/@andrejin.nagano/modelo-de-precifica%C3%A7%C3%A3o-de-op%C3%A7%C3%B5es-black-scholes-pressupostos-161760c6cead">primeira parte</a>, apresentei o conceito e discuti as premissas que servem de base para o modelo. Na <a href="https://medium.com/@andrejin.nagano/modelo-de-precifica%C3%A7%C3%A3o-de-op%C3%A7%C3%B5es-black-scholes-f%C3%B3rmula-15c061c7a558">segunda parte</a>, vimos o raciocínio por trás da matemática e das fórmulas. E, finalmente, nessa terceira parte, escreveremos alguns códigos para precificar diferentes opções usando o modelo.</blockquote><p><strong>O </strong><a href="https://pt.wikipedia.org/wiki/Black-Scholes"><strong>Black-Scholes ou Black-Scholes-Merton</strong></a><strong> é um modelo matemático usado em finanças para determinar o preço teórico de uma opção do tipo europeu.</strong> O propósito principal do modelo é calcular o valor justo de mercado (<em>market fair value</em>) de uma opção levando em consideração cinco parâmetros: o preço atual e a volatilidade do ativo subjacente, o preço de exercício e o tempo até o vencimento da opção, e a taxa de juros livre de risco.</p><h3><strong>Black-Scholes no Python</strong></h3><p>Agora que conhecemos a função, <strong>vamos implementá-la no Python para precificar opções de compra e venda</strong> dado um conjunto específico de entradas.</p><h4><strong>Importando Bibliotecas</strong></h4><p>Para a matemática por trás da fórmula, vamos usar as bibliotecas <em>scipy</em> e <em>numpy</em>. Para gerar gráficos, usamos as bibliotecas <em>matplotlib</em> e <em>seaborn</em>. E para analisar dados do mundo real, usamos a biblioteca <em>yfinance</em>.</p><pre>import numpy as np<br>from scipy.stats import norm<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>import yfinance as yf</pre><h4><strong>Função</strong></h4><p>A fórmula de precificação da opção recebe 5 variáveis de entrada: <strong>volatilidade (<em>σ</em>), preço de exercício (<em>K</em>), preço atual da ação (<em>S</em>), tempo até o vencimento (<em>T</em>) e a taxa de juros livre de risco (<em>r</em>)</strong>. As fórmulas de uma opção de compra e venda são:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*idaNo_f5eSDY14AXNBvxJw.png" /></figure><p>onde:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*6dOswbdPqp6LPPDKV-Q_tw.png" /></figure><p>Para a função ɸ, que é a <a href="https://pt.wikipedia.org/wiki/Fun%C3%A7%C3%A3o_distribui%C3%A7%C3%A3o_acumulada">FDA</a> de uma <a href="https://pt.wikipedia.org/wiki/Distribui%C3%A7%C3%A3o_normal">distribuição normal</a>, vamos usar o método <em>norm.cdf()</em> da biblioteca <em>scipy.stats</em>. Além das cinco variáveis de entrada,<strong> vamos também incluir uma entrada adicional, a qual especifica se é uma opção de compra ou de venda</strong>.</p><pre>def black_scholes(type, sigma, K, S, T, r):<br>    &quot;&quot;&quot;&quot;<br>    Aplica o modelo de Black-Scholes para calcular o preço de uma opção.<br>    &quot;&quot;&quot;<br><br>    # Calcula os parâmetros d_1 e d_2 da fórmula Black-Scholes<br>    d_1 = (np.log(S / K) + T * (r + sigma ** 2 / 2)) / (sigma * np.sqrt(T))<br>    d_2 = d_1 - sigma * np.sqrt(T)<br><br>    # Calcula o valor de uma opção baseada no tipo, ou &quot;de compra&quot; ou &quot;de venda&quot;.<br>    if type == &quot;call&quot;:<br><br>        V = S * norm.cdf(d_1) - np.exp(-r * T) * K * norm.cdf(d_2)<br><br>    elif type == &quot;put&quot;:<br><br>        V = np.exp(-r * T) * K * norm.cdf(-d_2) - S * norm.cdf(-d_1)<br><br>    return V</pre><p>Vamos usar a função acima para calcular o preço de uma opção de compra e de venda para uma ação do Walmart.</p><p>Primeiramente, vamos calcular o preço de <strong>uma opção de compra com vencimento em 3 meses e um preço de exercício de $60</strong>. Já que vamos precificar uma opção de 3 meses, nós <strong>vamos usar a taxa de retorno de um título americano de 3 meses (</strong><a href="https://www.cnbc.com/quotes/US3M"><strong>3-month U.S. Treasury yield</strong></a><strong>)</strong> como a nossa taxa de juros livre de risco. <strong>A volatilidade é igual ao desvio padrão anualizado do retorno logarítmico de uma ação.</strong></p><p>O preço atual da ação, a taxa de juros e a volatilidade são obtidas por meio da biblioteca <em>yfinance</em>.</p><pre># Definindo os parâmetros<br>K = 60 # O preço de exercício da nossa opção de compra é $60<br>T = 3 # O vencimento da opção é após 3 meses<br><br># Obtém a taxa de juros isenta de risco<br>t_bill_3m = yf.Ticker(&quot;^IRX&quot;).history()<br>r = t_bill_3m[&quot;Close&quot;].iloc[-1] / 100<br><br># Calcula a volatilidade da ação subjacente<br>precos = yf.Ticker(&#39;WMT&#39;).history(start=datetime(2019, 1, 1))[&#39;Close&#39;]<br>retornos = np.log(precos / precos.shift())<br>sigma = retornos.std() * np.sqrt(252)<br><br># Obtém o preço atual da ação subjacente<br>S = precos.iloc[-1]<br><br># Chama a função<br>C = black_scholes(&quot;call&quot;, sigma, K, S, T/12, r) # Dividimos T por 12 porque r é anualizada<br><br>print(&quot;-- Modelo de Black-Scholes para a Precificação de uma Opção de Compra --&quot;)<br>print(&quot;Ação: Walmart (WMT)&quot;)<br>print(f&quot;Valor Atual: ${S: .2f}&quot;)<br>print(f&quot;Preço de Exercício: $ {K}&quot;)<br>print(f&quot;Tempo de Vencimento: {T} months&quot;)<br>print(f&quot;Taxa de Juros Livre de Risco:{r*100: .2f}%&quot;)<br>print(f&quot;Opção Avaliada em: ${C: .2f}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*PB_WpGmiusqzqvhmhOP0PQ.png" /></figure><p>Podemos usar a biblioteca <em>yfinance</em> para ter uma noção de como o mercado está precificando essa opção.</p><pre>from datetime import timedelta<br><br>wmt = yf.Ticker(&quot;WMT&quot;)<br>data_disponiveis = wmt.options<br><br>hoje = datetime.now()<br>data_alvo = hoje + timedelta(days=90) # Aproximadamente 3 meses<br><br># Calcula a diferença entre a data disponível e a data alvo<br>data_proxima = min(data_disponiveis, key=lambda d: abs(datetime.strptime(d, &quot;%Y-%m-%d&quot;) - data_alvo))<br><br>print(f&quot;Data Atual: {hoje.strftime(&#39;%Y-%m-%d&#39;)}&quot;)<br>print(f&quot;Data de vencimento disponível mais próxima de 3 meses: {data_proxima}\n&quot;)<br><br># Obtem a opção na data mais próxima<br>opcao_data_disponivel = wmt.option_chain(data_proxima)<br>calls = opcao_data_disponivel.calls<br><br># Procura uma opção de compra com preço de exercício de $60<br>opcao_compra = calls[calls[&#39;strike&#39;] == K]<br><br>print(&quot;-- Preço Atual da Opção de Compra --&quot;)<br>print(&quot;Ação: Walmart (WMT)&quot;)<br>print(f&quot;Valor Atual: ${S: .2f}&quot;)<br>print(f&quot;Preço de Exercício: $ {K}&quot;)<br>print(f&quot;Data de Vencimento: {data_proxima}&quot;)<br>print(f&quot;Taxa de Juros Livre de Risco:{r*100: .2f}%&quot;)<br>print(f&quot;Preço de Compra da Opção: ${opcao_compra[&#39;bid&#39;].values[0]: .2f}&quot;)<br>print(f&quot;Preço de Venda da Opção: ${opcao_compra[&#39;ask&#39;].values[0]: .2f}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*fYv6L9ITGJsj35anamMRfg.png" /></figure><p>O nosso modelo de Black-Scholes precifica a ação de compra em $37.15, enquanto o preço de compra atual da opção é $37.20. O <strong>preço de compra representa o maior valor que um comprado está disposto a aceitar</strong>, ou seja, é o preço que você receberia ao vender a opção imediatamente. O valor do modelo está um pouco abaixo do preço de compra atual. <strong>Isso nos diz duas coisas: o resultado do nosso modelo parece razoável e que a opção pode estar ligeiramente sobrevalorizada.</strong> Nós podemos vender (<em>short</em>) essa opção de compra a $37.20 agora e comprar posteriormente, já que acreditamos que o valor real da opção seja $37.15.</p><p>Entretanto, vale ressaltar que o retorno nessa operação é absurdamente pequeno. <strong>Essa fina discrepância muito provavelmente ocorre devido as aproximações do modelo de Black-Scholes.</strong> Esse trade não geraria nenhum lucro, considerando as taxas de transação associadas à compra e venda de opções.</p><p>Agora, vamos precificar uma opção de venda com 3 meses de vencimento e um preço de exercício de 100. Os outros parâmetros serão os mesmos.</p><pre># Definindo os parâmetros<br>K = 100 # O preço de exercício da nossa opção de venda é $100<br>T = 3 # O vencimento da opção é após 3 meses<br><br># Obtém a taxa de juros isenta de risco<br>t_bill_3m = yf.Ticker(&quot;^IRX&quot;).history()<br>r = t_bill_3m[&quot;Close&quot;].iloc[-1] / 100<br><br># Calcula a volatilidade da ação subjacente<br>precos = yf.Ticker(&#39;WMT&#39;).history(start=datetime(2019, 1, 1))[&#39;Close&#39;]<br>retornos = np.log(precos / precos.shift())<br>sigma = retornos.std() * np.sqrt(252)<br><br># Obtém o preço atual da ação subjacente<br>S = precos.iloc[-1]<br><br># Chama a função<br>P = black_scholes(&quot;put&quot;, sigma, K, S, T/12, r) # Dividimos T por 12 porque r é anualizada<br><br>print(&quot;-- Modelo de Black-Scholes para a Precificação de uma Opção de Venda --&quot;)<br>print(&quot;Ação: Walmart (WMT)&quot;)<br>print(f&quot;Valor Atual: ${S: .2f}&quot;)<br>print(f&quot;Preço de Exercício: $ {K}&quot;)<br>print(f&quot;Tempo de Vencimento: {T} months&quot;)<br>print(f&quot;Taxa de Juros Livre de Risco:{r*100: .2f}%&quot;)<br>print(f&quot;Opção Avaliada em: ${P: .2f}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*UqutOIROLnWS20ovyRn-Sg.png" /></figure><blockquote>O teste para a opção de venda foi feito em um momento diferente da opção de compra. Dessa forma, os dados de valor atual e taxa de juros livre de risco não são iguais ao teste anterior.</blockquote><pre>from datetime import timedelta<br><br>wmt = yf.Ticker(&quot;WMT&quot;)<br>data_disponiveis = wmt.options<br><br>hoje = datetime.now()<br>data_alvo = hoje + timedelta(days=90) # Aproximadamente 3 meses<br><br># Calcula a diferença entre a data disponível e a data alvo<br>data_proxima = min(data_disponiveis, key=lambda d: abs(datetime.strptime(d, &quot;%Y-%m-%d&quot;) - data_alvo))<br><br>print(f&quot;Data Atual: {hoje.strftime(&#39;%Y-%m-%d&#39;)}&quot;)<br>print(f&quot;Data de vencimento disponível mais próxima de 3 meses: {data_proxima}\n&quot;)<br><br># Obtem a opção na data mais próxima<br>opcao_data_disponivel = wmt.option_chain(data_proxima)<br>puts = opcao_data_disponivel.puts<br><br># Procura uma opção de compra com preço de exercício de $60<br>opcao_venda = puts[puts[&#39;strike&#39;] == K]<br><br>print(&quot;-- Preço Atual da Opção de Venda --&quot;)<br>print(&quot;Ação: Walmart (WMT)&quot;)<br>print(f&quot;Valor Atual: ${S: .2f}&quot;)<br>print(f&quot;Preço de Exercício: $ {K}&quot;)<br>print(f&quot;Data de Vencimento: {data_proxima}&quot;)<br>print(f&quot;Taxa de Juros Livre de Risco:{r*100: .2f}%&quot;)<br>print(f&quot;Preço de Compra da Opção: ${opcao_venda[&#39;bid&#39;].values[0]: .2f}&quot;)<br>print(f&quot;Preço de Venda da Opção: ${opcao_venda[&#39;ask&#39;].values[0]: .2f}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*mK4K57bGpWStnfz00oFkJA.png" /></figure><p>O nosso modelo de Black-Scholes precificou essa opção de venda em $5.89, enquanto o preço de compra atual é $5.70 e o preço de venda atual é $6.40. <strong>O valor do nosso modelo está entre o preço de compra e o preço de venda. </strong>Mais uma vez, isso nos indica que o resultado do nosso modelo parece razoável. <strong>Mas agora, como o valor do nosso modelo está entre o <em>spread</em> de compra e venda, não há oportunidades de arbitragem.</strong> Esse intervalo relativamente grande entre o preço de compra e venda possivelmente reflete uma alta incerteza em relação ao ativo.</p><h4>Mapa de Calor dos Preços</h4><p>Outra forma de visualizar os diferentes preços das opções é criando uma tabela com múltiplos preços de exercício e tempos de vencimento. Para cada combinação de <em>K</em> e <em>T</em>, podemos calcular o valor de uma opção de compra e de venda. <strong>Com essa matriz de valores, construímos nosso mapa de calor, assim o contraste entre preços fica mais evidente.</strong></p><pre>import pandas as pd<br><br>def matriz_precos(type, sigma, S, r):<br><br>    # Cria duas listas com preços de exercício e meses até o vencimento<br>    if type == &#39;call&#39;:<br>        precos_exercicio = np.arange(S-35, S+10, 5)<br>    elif type == &#39;put&#39;:<br>        precos_exercicio = np.arange(S-5, S+40, 5)<br>    meses = np.arange(1, 13, 1)<br><br>    # Inicializa matriz vazia<br>    matriz = []<br><br>    for K in precos_exercicio:<br><br>        linha = []<br><br>        for T in meses:<br><br>            # Calcula o valor da opção para cada K em precos_exercicio e T e meses<br>            V = black_scholes(type, sigma, K, S, T/12, r)<br><br>            linha.append(V)<br><br>        matriz.append(linha)<br><br>    preco_titulos = [f&#39;${preco}&#39; for preco in np.round(precos_exercicio).astype(int)]<br><br>    df = pd.DataFrame(matriz, index=preco_titulos, columns=meses)<br><br>    return df<br><br>call_df = matriz_precos(&#39;call&#39;, sigma, S, r)<br>put_df = matriz_precos(&#39;put&#39;, sigma, S, r)</pre><p>Agora, construímos o mapa de calor com a biblioteca seaborn.</p><pre># Defindo parâmetros do mapa de calor<br>heatmap_params = {<br>    &#39;annot&#39;: True, <br>    &#39;fmt&#39;: &#39;.2f&#39;, <br>    &#39;cmap&#39;: &quot;YlGnBu&quot;, <br>    &#39;cbar&#39;: False<br>}<br><br>dfs = {<br>    &#39;Preços das Opções de Compra&#39;: call_df,<br>    &#39;Preços das Opções de Venda&#39;: put_df<br>}<br><br># Criando gráficos<br>fig, axs = plt.subplots(1, 2, figsize=(12, 6))<br><br>for ax, (title, data) in zip(axs, dfs.items()):<br>    sns.heatmap(data, ax=ax, **heatmap_params)<br>    ax.set(title=title, <br>           xlabel=&#39;Meses até o Vencimento&#39;, <br>           ylabel=&#39;Preço de Exercício&#39;)<br>    ax.tick_params(axis=&#39;y&#39;, rotation=0)<br><br>fig.suptitle(f&#39;Modelo de Precificação de Opções de Black-Scholes com: S={round(S, 2)}, sigma={round(sigma, 2)} e r={round(r, 2)}&#39;, fontsize=14, fontweight=&#39;bold&#39;)<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wjBICFqQqU0BENnQE91_-A.png" /></figure><p>Vamos primeiro dar uma olhada nos preços das opções de compra. À medida que os preços de exercício diminuem, a opção de compra se torna mais valiosa. Isso ocorre porque os investidores gostariam de comprar as ações por um preço mais barato no futuro. Agora, olhando para o eixo x, <strong>os preços das opções aumentam à medida que os meses até o vencimento aumentam.</strong> Se esperamos que as ações continuem aumentando de valor (por causa do <em>drift</em>), o retorno da compra da opção, para um preço de exercício específico, também aumenta à medida que o tempo até o vencimento se aproxima.</p><p>A seguir, vamos analisar os preços das opções de venda. <strong>À medida que os preços de exercício aumentam, a opção de venda se torna mais valiosa.</strong> A razão para isso é que os investidores estão sempre procurando vender suas ações por um valor mais alto. Quanto ao eixo x, <strong>o preço cai à medida que o vencimento aumenta.</strong> Se esperamos que as ações continuem aumentando de valor, o retorno da venda das ações, para um preço de exercício específico, diminui à medida que o prazo de vencimento se aproxima.</p><h3>Partes I e II</h3><p>Essa é a última parte do nosso artigo sobre Black-Scholes. Se você quiser aprender mais sobre os pressupostos e a matemática por trás do modelo, peço que considere ler as partes I e II:</p><ul><li><a href="https://medium.com/@andrejin.nagano/modelo-de-precifica%C3%A7%C3%A3o-de-op%C3%A7%C3%B5es-black-scholes-pressupostos-161760c6cead">Modelo de Precificação de Opções Black-Scholes — Pressupostos</a></li><li><a href="https://medium.com/@andrejin.nagano/modelo-de-precifica%C3%A7%C3%A3o-de-op%C3%A7%C3%B5es-black-scholes-f%C3%B3rmula-15c061c7a558">Modelo de Precificação de Opções Black-Scholes — Fórmula</a></li></ul><h3>Bibliografia</h3><p>Esse artigo foi escrito usando esses conteúdos como referência:</p><ul><li><a href="https://www.columbia.edu/~mh2078/FoundationsFE/BlackScholes.pdf">The Black-Scholes Model by Martin Haugh</a></li><li><a href="https://uregina.ca/~kozdron/Teaching/Regina/441Fall14/Notes/L23-24-25-Oct29.pdf">Lecture #23, 24, 25: Deriving the Black–Scholes Partial Differential Equation by Michael Kozdron</a></li><li><a href="https://portal.if.usp.br/grenac/sites/portal.if.usp.br.ifusp/files/black_scholes_presentation.pdf">The Black-Scholes Option Pricing Model: A Comprehensive Analysis by Renoir Vieira</a></li><li><a href="https://youtu.be/pr-u4LCFYEY?si=yyWpOx441annZgO2">Introduction to the Black-Scholes formula | Finance &amp; Capital Markets | Khan Academy</a></li><li><a href="https://youtu.be/TnS8kI_KuJc?si=uUjWtbcAPIs-CjyY">19. Black-Scholes Formula, Risk-neutral Valuation by MIT OpenCourseWare</a></li><li><a href="https://www.macroption.com/black-scholes-assumptions/">https://www.macroption.com/black-scholes-assumptions/</a></li><li><a href="https://www.numberanalytics.com/blog/mastering-itos-lemma-stochastic-processes#google_vignette">https://www.numberanalytics.com/blog/mastering-itos-lemma-stochastic-processes#google_vignette</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8be8476a3a13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modelo de Precificação de Opções Black-Scholes — Fórmula]]></title>
            <link>https://medium.com/@andrejin.nagano/modelo-de-precifica%C3%A7%C3%A3o-de-op%C3%A7%C3%B5es-black-scholes-f%C3%B3rmula-15c061c7a558?source=rss-7d22ea87b56e------2</link>
            <guid isPermaLink="false">https://medium.com/p/15c061c7a558</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[black-scholes-model]]></category>
            <category><![CDATA[options-trading]]></category>
            <category><![CDATA[matemática]]></category>
            <category><![CDATA[finanças]]></category>
            <dc:creator><![CDATA[Andre Nagano]]></dc:creator>
            <pubDate>Tue, 26 Aug 2025 20:23:07 GMT</pubDate>
            <atom:updated>2025-08-26T20:26:35.400Z</atom:updated>
            <content:encoded><![CDATA[<h3>Modelo de Precificação de Opções Black-Scholes — Fórmula</h3><blockquote>Esta é a segunda parte de uma série de três artigos sobre o modelo de precificação de opções de Black-Scholes. Na <a href="https://medium.com/@andrejin.nagano/modelo-de-precifica%C3%A7%C3%A3o-de-op%C3%A7%C3%B5es-black-scholes-pressupostos-161760c6cead">primeira parte</a>, apresentei o conceito e discuti as premissas que servem de base para o modelo. Nessa segunda parte, veremos o raciocínio por trás da matemática e das fórmulas. E, finalmente, na <a href="https://medium.com/@andrejin.nagano/modelo-de-precifica%C3%A7%C3%A3o-de-op%C3%A7%C3%B5es-black-scholes-c%C3%B3digo-no-python-8be8476a3a13">terceira parte</a>, escreveremos alguns códigos para precificar diferentes opções usando o modelo.</blockquote><p><strong>O </strong><a href="https://pt.wikipedia.org/wiki/Black-Scholes"><strong>Black-Scholes ou Black-Scholes-Merton</strong></a><strong> é um modelo matemático usado em finanças para determinar o preço teórico de uma opção do tipo europeu.</strong> O propósito principal do modelo é calcular o valor justo de mercado (<em>market fair value</em>) de uma opção levando em consideração cinco parâmetros: o preço atual e a volatilidade do ativo subjacente, o preço de exercício e o tempo até o vencimento da opção, e a taxa de juros livre de risco.</p><h4>Conceitos Chaves</h4><h4><strong>Movimento Browniano Geométrico (MBG)</strong></h4><p>Como afirmado previamente, <strong>os preços dos ativos seguem um movimento aleatório</strong>. Embora esse modelo capture a essência dos movimentos imprevisíveis de um ativo, ele consiste em uma série de etapas em tempo discreto. Isso o torna insuficiente para as exigências rigorosas da precificação de derivativos, as quais requerem uma estrutura contínua.</p><p><strong>A ponto matemática que conecta a caminha aleatória discreta a um processo em tempo contínuo é o conceito do </strong><a href="https://medium.com/@andrejin.nagano/black-scholes-option-pricing-model-python-code-293392f0755a"><strong>Movimento Browniano</strong></a><strong> (<em>W</em>)</strong>. O movimento browniano padrão é um processo estocástico caracterizado por três propriedades chaves:</p><ul><li>Começa em zero.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/184/1*3jcpAm7AHHX5s3aEzqcfGw.png" /></figure><ul><li>Possui incrementos independentes, o que significa que a mudança no processo ao longo de qualquer intervalo de tempo não tem influência sobre o que ocorreu anteriormente.</li><li>Os incrementos são normalmente distribuídos, com média zero e variância igual ao intervalo de tempo.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*QRgEdJB11jaqVP-UXHLt5w.png" /></figure><p>Embora se aproxime de um modelo adequado para o preço de um ativo, ainda há um problema. <strong>Esse modelo de movimento browniano não garante uma saída positiva.</strong> Como os incrementos são normalmente distribuídos ao redor de 0, a variável pode se tornar negativa, o que é impossível para um ativo limitado, como uma ação.</p><p>Dessa forma, o modelo de Black-Scholes propõe que o movimento do preço de um ativo seja modelado por um <a href="https://pt.wikipedia.org/wiki/Movimento_browniano_geom%C3%A9trico">Movimento Browniano Geométrico</a> (<em>S</em>). Enquanto o movimento browniano padrão possui incrementos aleatórios a cada passo, <strong>o movimento browniano geométrico possui uma taxa de crescimento aleatória a cada passo</strong>. As propriedades chaves do movimento browniano geométrico são análogas às do movimento browniano padrão:</p><ul><li>Começa em um valor positivo.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/188/1*daBSzC84pEzEted6dfFWKQ.png" /></figure><ul><li>Possui fatores multiplicadores independentes.</li><li>Os fatores multiplicadores a cada passo são log-normalmente distribuídos.</li><li>Processos de movimento browniano geométrico nunca podem apresentar valores negativos.</li></ul><p>Essas propriedades se alinham com os pressupostos do modelo de Black-Scholes, tornando-o adequado para descrever os movimentos dos ativos subjacentes.</p><p>A dinâmica de um MBG é descrita por uma <a href="https://pt.wikipedia.org/wiki/Equa%C3%A7%C3%A3o_diferencial_estoc%C3%A1stica">Equação Diferencial Estocástica</a> (EDE):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*wlvVzHjD2EWpVPMQ-OqB7A.png" /></figure><p>Essa equação é composta por duas partes:</p><p>1. Um componente determinístico (<em>µStdt</em>), chamada de “drift”. Esse termo representa o retorno esperado de um ativo sobre um período de tempo infinitesimal <em>dt</em>. A constante <em>µ</em>, também chamada de percentual de drift, é a taxa de retorno esperada anualizada.</p><p>2. Um componente estocástico, <em>σStdWt</em>, chamado de “diffusão” ou “volatilidade”. Esse termo captura as flutuações aleatórias do preço do ativo. A constante <em>σ</em>, também chamada de volatilidade percentual, é o desvio padrão anualizado dos retornos do ativo.</p><h4><strong>Lema de Itô</strong></h4><p><strong>O processo de movimento browniano, observado em preços de ativos, é contínuo em todos os pontos, mas não é diferenciável em nenhum ponto. </strong>Isso se deve ao fato de que a curva é muito irregular, com uma “rugosidade” tão extrema que em nenhum ponto é possível tração uma tangente única. Essa ressalva torna impossível resolver a EDE pelos meios convencionais do cálculo. Ainda assim, por meio de uma técnica usando a expansão da série de Taylor do valor de uma opção, o matemático japonês Kiyoshi Itô conseguiu <strong>fornecer a derivada completa para uma função estocástica.</strong></p><p>Dada a função do preço de uma opção <em>V(S, t)</em>, onde <em>S</em> representa o preço do ativo subjacente (o qual é o processo estocástico) e <em>t</em> o tempo, pelo <a href="https://pt.wikipedia.org/wiki/Lema_de_It%C5%8D">lema de Itô</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nHHYtG4GV1d3mStQ1qiU_Q.png" /></figure><h3><strong>Equação Diferencial Parcial de Black-Scholes</strong></h3><p>Agora que temos todos os pressupostos e conceitos do cálculo estocástico, podemos construir a intuição por trás da equação do modelo de Black-Scholes. Primeiro, vamos começar com uma carteira protegida (“hedgeada”), com uma estratégia de autofinanciamento:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*U5fJA2_pfzqI1KYeChgZFQ.png" /></figure><p>onde, no tempo <em>t</em>:</p><ul><li><em>x</em> são as unidades de dinheiro investidas em uma conta a uma taxa de juros constante.</li><li><em>B</em> é a fórmula para uma taxa de juros composta continuamente:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/212/1*x6jZ6NQn8y-hvBY6mlDYTg.png" /></figure><ul><li><em>y</em> são as unidades do ativo subjacente.</li><li><em>S</em> é o preço do ativo subjacente.</li></ul><p>Quando derivamos a função do valor de nossa carteira, chegamos em:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*9stf3IP6kLxeVJEu9iNXMg.png" /></figure><p>Usando a EDE para descrever o movimento browniano geométrico:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*jlz8n53l3v3kachm4E75Ug.png" /></figure><p>Vamos construir uma carteira que replica o valor da opção. Isso significa que queremos ajustar as variáveis <em>x</em> e <em>y:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wCCXmDDzRcO8f9VMrjLCag.png" /></figure><p>Após igualar os termos em comum da equação acima:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*BTRJkFE4w0pdKroDUTIGZg.png" /></figure><p>Finalmente, podemos adicionar as duas variáveis na nossa fórmula para a carteira:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*KCmI3GuOS3rdNId5L1CfBQ.png" /></figure><p>A equação acima é conhecida como a <a href="https://en.wikipedia.org/wiki/Black%E2%80%93Scholes_equation">Equação Diferencial Parcial de Black-Scholes</a> (Black-Scholes EDE ou Black-Scholes PDE). <strong>Ela descreve a relação que deve existir em todos os momentos entre o preço de uma opção, o preço da ação subjacente, o tempo, a volatilidade e a taxa livre de risco para que se evite oportunidades de arbitragem.</strong></p><p>Um ponto importante que chama atenção é a ausência completa da porcentagem de drift (<em>µ</em>) na EDE final. Mesmo que pareça contra intuitivo, <strong>a taxa de retorno esperada e anualizada de um ativo não possui influência no valor justo (<em>fair value</em>) de uma opção.</strong></p><h3><strong>Fórmula de Black-Scholes</strong></h3><p>A solução da EDE de Black-Scholes é chamada de Fórmula de Black-Scholes, uma equação que fornece o valor justo de uma opção do tipo Europeu. <strong>Para resolver essa EDE, algumas condições de contorno precisam ser estabelecidas:</strong></p><p>1. Na data de vencimento, o valor de uma opção de compra é nula, caso o valor da ação caia abaixo do valor de exercício, ou o valor da ação menos o preço de exercício:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*8WFqaoX2NbTqa7-JJ_H48A.png" /></figure><p>2. Se o preço da ação cair para zero, então a opção de compra não terá valor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*gb3val6HF58UvwqfyDweRQ.png" /></figure><p>3. Quando o preço de uma ação se torna muito alta, a probabilidade da opção ser exercida aproxima-se de 100%. Neste caso, o valor da opção se aproxima do valor do valor da ação menos o valor presente do preço de exercício:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*Jwq8QSPZk8NgIa8__VI6mg.png" /></figure><p>Surprendentemente, antes de Fischer Black ou Myron Scholes ter a ideia para esse modelo de precificação de opções, a EDE de Black-Scholes já havia sido resolvida. A EDE de Black-Scholes é um tipo de EDE parabólica, a qual é matematicamente análoga a <a href="https://pt.wikipedia.org/wiki/Equa%C3%A7%C3%A3o_do_calor">equação de difusão de calor da física</a>. A volatilidade do preço da ação se comporta de forma similar à difusividade térmica e, por meio de algumas manipulações de variáveis, é possível chegar à equação de difusão de calor.</p><p>A solução da EDE de Black-Scholes nos dá o preço de uma opção de compra. Já para opção de venda, utilizamos a solução encontra em conjunto com o conceito de <a href="https://pt.wikipedia.org/wiki/Paridade_put-call">paridade put-call</a>. A paridade put-call é um princípio em finanças que afirma que o valor de uma carteira composta por uma opção de compra e um título isento de risco, o qual possui um valor igual ao valor de exercício na data de vencimento, é igual ao valor de uma carteira composta por uma opção de venda mais a ação subjacente.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*AATGGDKEDS0vxTiaEJZt-A.png" /></figure><p>Essa ideia se baseia no pressuposto de um mercado eficiente, sem oportunidades de arbitragem. <strong>Como resultado, as fórmulas de uma opção de compra e uma opção de venda, segundo o modelo de Black-Scholes, são respectivamente:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*GuUTLi8BZYUExY1IReIaUQ.png" /></figure><p>onde:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ktb7J2TyLNBf-X0rgvrdw.png" /></figure><p>O termo d2 representa a probabilidade de que a opção vencer <em>in the money</em> (S ≥ K), o que significa que <strong>ɸ(d2) fornece o valor esperado de ter que pagar o preço de exercício de uma opção de compra</strong>. O componente d1 é um pouco mais complexo. <strong>Ele calcula a probabilidade condicional do valor esperado em relação ao seu preço à vista atual, dado que o preço à vista atual é maior do que o preço de exercício no vencimento.</strong></p><p><strong>O primeiro termo da opção de compra (Sɸ(d1)) calcula a probabilidade ajustada ao risco de a opção ser exercida</strong>, o que ocorre quando o preço do ativo subjacente é maior ou igual ao preço de exercício da opção (S ≥ K).<strong> Já o segundo termo (e^(-r(T-t))Kɸ(d2)) expressa a probabilidade inversa de o investidor não exercer a opção.</strong> O componente é um preço de exercício descontado da data de vencimento até o momento presente usando a taxa livre de risco. Isso pode ser visto como o custo de oportunidade de pagar antecipadamente o prêmio, em vez de investi-lo à taxa livre de risco.</p><h4><strong>Função Distribuição Acumulada (FDA)</strong></h4><p><strong>O valor de uma </strong><a href="https://pt.wikipedia.org/wiki/Fun%C3%A7%C3%A3o_distribui%C3%A7%C3%A3o_acumulada"><strong>FDA</strong></a><strong> de uma variável <em>X</em> avaliada no ponto <em>x</em> é a probabilidade de <em>X</em> ter um valor igual ou menor a <em>x</em>.</strong> Para entender melhor este conceito, podemos mostrar graficamente no Python.</p><pre>from scipy.stats import norm<br><br># Standard Normal Distribution Parameters<br># Parâmetros de uma distribuição normal padrão<br>mu = 0  # Média<br>sigma = 1  # Desvio padrão<br><br># Ponto em que vamos calcular a FDA<br>valor_x = 1.5<br><br># Cria uma lista de valor x para o gráfico<br>x = np.linspace(mu - 4*sigma, mu + 4*sigma, 1000)<br># Calcula a Função de Densidade de Probabilidade<br>fdp = norm.pdf(x, mu, sigma)<br><br># Calcula a FDA para o valor_x<br>valor_cdf = norm.cdf(valor_x, mu, sigma)<br><br># Cria o gráfico<br>plt.figure(figsize=(10, 5))<br><br># Traça a curva do FDP<br>plt.plot(x, fdp, &#39;blue&#39;, label=&#39;Standard Normal PDF&#39;)<br><br># Preenche a área abaixo da curva FDP até o valor_x<br>fill_mask = x &lt;= valor_x<br>plt.fill_between(x[fill_mask], fdp[fill_mask], color=&#39;skyblue&#39;, alpha=0.6, label=f&#39;Área = FDA({valor_x})&#39;)<br><br>plt.axvline(valor_x, color=&#39;red&#39;, linestyle=&#39;--&#39;, label=f&#39;x = {valor_x}&#39;)<br><br># Adiociona o título, eixos e grade<br>plt.xlabel(&#39;Eixo X&#39;, fontsize=12)<br>plt.ylabel(&#39;Densidade de Probabilidade&#39;, fontsize=12)<br>plt.title(f&#39;Distribuição Normal Padrão (μ={mu}, σ={sigma})\nFDA em x={valor_x} é igual a {valor_cdf:.4f}&#39;, fontsize=14)<br>plt.grid(True)<br><br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*Rxz-tDEpf032PO_E_Xxj8Q.png" /></figure><p>O gráfico acima mostra uma curva FDP de uma distribuição normal padrão (azul) com um limite no valor <em>x=1.5</em> (vermelho). A área abaixo da curva até a reta tracejada vermelha é igual ao valor da FDA. Assim, no exemplo acima temos que <em>ɸ(1.5) = 0.9332</em>.</p><h3>Próximos Passos</h3><p>No <a href="https://medium.com/@andrejin.nagano/modelo-de-precifica%C3%A7%C3%A3o-de-op%C3%A7%C3%B5es-black-scholes-c%C3%B3digo-no-python-8be8476a3a13">próximo artigo</a>, vamos escrever um código em Python para implementar o modelo de precificação de opções de Black-Scholes.</p><h3>Bibliografia</h3><p>Esse artigo foi escrito usando esses conteúdos como referência:</p><ul><li><a href="https://www.columbia.edu/~mh2078/FoundationsFE/BlackScholes.pdf">The Black-Scholes Model by Martin Haugh</a></li><li><a href="https://uregina.ca/~kozdron/Teaching/Regina/441Fall14/Notes/L23-24-25-Oct29.pdf">Lecture #23, 24, 25: Deriving the Black–Scholes Partial Differential Equation by Michael Kozdron</a></li><li><a href="https://portal.if.usp.br/grenac/sites/portal.if.usp.br.ifusp/files/black_scholes_presentation.pdf">The Black-Scholes Option Pricing Model: A Comprehensive Analysis by Renoir Vieira</a></li><li><a href="https://youtu.be/pr-u4LCFYEY?si=yyWpOx441annZgO2">Introduction to the Black-Scholes formula | Finance &amp; Capital Markets | Khan Academy</a></li><li><a href="https://youtu.be/TnS8kI_KuJc?si=uUjWtbcAPIs-CjyY">19. Black-Scholes Formula, Risk-neutral Valuation by MIT OpenCourseWare</a></li><li><a href="https://www.macroption.com/black-scholes-assumptions/">https://www.macroption.com/black-scholes-assumptions/</a></li><li><a href="https://www.numberanalytics.com/blog/mastering-itos-lemma-stochastic-processes#google_vignette">https://www.numberanalytics.com/blog/mastering-itos-lemma-stochastic-processes#google_vignette</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15c061c7a558" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modelo de Precificação de Opções Black-Scholes— Pressupostos]]></title>
            <link>https://medium.com/@andrejin.nagano/modelo-de-precifica%C3%A7%C3%A3o-de-op%C3%A7%C3%B5es-black-scholes-pressupostos-161760c6cead?source=rss-7d22ea87b56e------2</link>
            <guid isPermaLink="false">https://medium.com/p/161760c6cead</guid>
            <category><![CDATA[options-trading]]></category>
            <category><![CDATA[black-scholes-model]]></category>
            <category><![CDATA[finanças]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[matemática]]></category>
            <dc:creator><![CDATA[Andre Nagano]]></dc:creator>
            <pubDate>Tue, 26 Aug 2025 20:22:00 GMT</pubDate>
            <atom:updated>2025-08-26T20:25:39.221Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Esta é a primeira parte de uma série de três artigos sobre o modelo de precificação de opções de Black-Scholes. Nesta primeira parte, apresentarei o conceito e discutirei as premissas que servem de base para o modelo. Na <a href="https://medium.com/@andrejin.nagano/modelo-de-precifica%C3%A7%C3%A3o-de-op%C3%A7%C3%B5es-black-scholes-f%C3%B3rmula-15c061c7a558">segunda parte</a>, veremos o raciocínio por trás da matemática e das fórmulas. E, finalmente, na <a href="https://medium.com/@andrejin.nagano/modelo-de-precifica%C3%A7%C3%A3o-de-op%C3%A7%C3%B5es-black-scholes-c%C3%B3digo-no-python-8be8476a3a13">terceira parte</a>, escreveremos alguns códigos para precificar diferentes opções usando o modelo.</blockquote><p><strong>O </strong><a href="https://pt.wikipedia.org/wiki/Black-Scholes"><strong>Black-Scholes ou Black-Scholes-Merton</strong></a><strong> é um modelo matemático usado em finanças para determinar o preço teórico de uma opção do tipo europeu.</strong> O propósito principal do modelo é calcular o valor justo de mercado (<em>market fair value</em>) de uma opção levando em consideração cinco parâmetros: o preço atual e a volatilidade do ativo subjacente, o preço de exercício e o tempo até o vencimento da opção, e a taxa de juros livre de risco.</p><h3><strong>Precificando Opções</strong></h3><p><strong>Uma opção é um tipo de ativo derivativo que permite o proprietário (titular) o direito, mas não a obrigação de comprar (<em>call option</em>) ou vender (<em>put option</em>) uma quantidade específica de um ativo subjacente a um preço de exercício combinado.</strong> Opções são utilizadas com três fins: especulação, cobertura (<em>hedge</em>) ou arbitragem.</p><p>A tarefa de prever o valor futuro de um ativo tem se demonstrado ser bem difícil. O preço de um ativo pode depender de inúmeras variáveis. <strong>Como o valor de uma opção proporcional ao valor do ativo subjacente, opções são igualmente difíceis de serem precificadas.</strong></p><p>É aí que entra o modelo de Black-Scholes-Merton. Ele provou ser um método bastante robusto para precificar esses tipos de derivativos.</p><h3><strong>Pressupostos</strong></h3><p>No entanto, há algumas ressalvas. O modelo de Black-Scholes funciona sob uma série de pressupostos. Essas suposições são relacionadas ao ativo subjacente, ao mercado em geral e à própria opção.</p><h3><strong>Pressupostos sobre o Ativo Subjacente</strong></h3><h4><strong>Caminhada Aleatória (</strong>Random Walk<strong>)</strong></h4><p>O pressuposto fundamental da teoria moderna financeira é que a direção do preço de um ativo não pode ser consistentemente prevista a partir de seu comportamento passado. O preço de um ativo segue uma “<a href="https://pt.wikipedia.org/wiki/Black-Scholes">passeio aleatória</a>” (<em>random walk</em>), <strong>o que significa que em cada momento o valor é igual ao valor prévio mais uma variável aleatória.</strong> Esse passeio aleatória é um padrão de movimento também conhecido como processo de Wiener em matemático ou movimento browniano na física.</p><h4><strong>Distribuição Log-normal do Preço de uma Ação</strong></h4><p>Devido a essa passeio aleatória, o retorno de uma ação é <a href="https://pt.wikipedia.org/wiki/Distribui%C3%A7%C3%A3o_normal">normalmente distribuída</a>. Por sua vez, significa que o preço da <strong>ação em si possui uma </strong><a href="https://pt.wikipedia.org/wiki/Distribui%C3%A7%C3%A3o_log-normal"><strong>distribuição log-normal</strong></a><strong>.</strong></p><p>Vamos usar o preço de fechamento da ação do Walmart como exemplo. Para isso vamos usar as seguintes bibliotecas do Python.</p><pre>import numpy as np<br>import yfinance as yf<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>from datetime import datetime</pre><p>A biblioteca <em>yfinance</em> nos permite obter a série temporal dos preços de fechamento do ativo nos últimos anos.</p><pre>precos = yf.Ticker(&#39;WMT&#39;).history(start=datetime(2019, 1, 1))[&#39;Close&#39;]</pre><p>Quando construímos o histograma do retorno dessa ação, encontramos um conjunto de dados normalmente distribuído. Para calcular esse retorno, assumimos um <a href="https://www.investopedia.com/terms/c/continuouscompounding.asp"><strong>retorno composto continuamente</strong></a>, o que significa:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/188/1*39IIHAGx_99LERcXFk5N7Q.png" /></figure><pre>retornos = np.log(precos / precos.shift())<br><br>sns.set_style(&quot;whitegrid&quot;)<br><br>sns.histplot(data=retornos, stat=&quot;density&quot;, bins=30)<br>sns.kdeplot(data=retornos, color=&quot;red&quot;)<br><br>plt.title(&quot;Distribuição dos Retornos Diários da Ação do Walmart&quot;)<br>plt.xlabel(&#39;Retorno da Ação&#39;)<br>plt.ylabel(&#39;Densidade&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*e8VEn2CeZQMKYpjl29w2EQ.png" /></figure><p><strong>A distribuição de uma variável aleatória, cujo logaritmo é normalmente distribuído, é log-normalmente distribuída.</strong> O gráfico acima prova que o logaritmo do preço (retorno) é normalmente distribuído. Dessa forma, o preço em si é log-normalmente distribuído.</p><pre>sns.histplot(data=precos, stat=&quot;density&quot;, bins=30)<br>sns.kdeplot(data=precos, color=&quot;red&quot;)<br><br>plt.title(&quot;Distribuição dos Preços de Fechamento da Ação do Walmart&quot;)<br>plt.xlabel(&#39;Preço&#39;)<br>plt.ylabel(&#39;Densidade&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*zwm_GPTmyhgGWCfaeifqbQ.png" /></figure><p>Distribuições log-normais possuem duas características chaves:</p><ul><li>São <strong>sempre positivas</strong>. Os preços de uma ação estão atrelados a quantidades reais, não podendo ser negativos.</li><li>Têm uma <strong>cauda longa à direita</strong>. Ações possuem uma probabilidade maior de sofrer pequenas variações e uma probabilidade menor de sofrer grandes variações.</li></ul><h4><strong>Volatilidade Constante</strong></h4><p>Outro pressuposto é que a <a href="https://pt.wikipedia.org/wiki/Volatilidade_(finan%C3%A7as)">volatilidade</a> da ação subjacente é constante no tempo. Uma <strong>volatilidade não varia ao longo do tempo</strong> significa que a amplitude dos movimentos é geralmente esperada e conhecida antecipadamente.</p><p>No mundo real, isso não é verdade. Vamos utilizar a ação do Walmart novamente. Podemos obter a probabilidade de uma ação calculando o desvio padrão dos retornos diários. Para cada instante de tempo, nós vamos calcular o desvio padrão nos últimos 60 dias, pelo método da janela móvel. Também, é uma prática comum analizar a volatilidade anualizada. Portanto, multiplicamos a volatilidade pela raiz quadrada de 252 (número de dias de negociação em um ano).</p><pre>volatilidade = retornos.rolling(60).std().dropna()<br>volatilidade_anualizada = volatilidade * np.sqrt(252)<br><br>plt.plot(volatilidade_anualizada, label=&quot;Volatilidade&quot;)<br>plt.axhline(volatilidade_anualizada.mean(), linestyle=&#39;dotted&#39;, color=&#39;black&#39;, label=&quot;Média&quot;)<br>plt.ylim(0, 1)<br><br>plt.title(&quot;Volatilidade Móvel da Ação do Walmart&quot;)<br>plt.xlabel(&#39;Volatilidade&#39;)<br>plt.ylabel(&quot;Data&quot;)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*GO_88qZyuU3YWpNsA_yCpg.png" /></figure><p>Como podemos ver, a volatilidade realmente varia com o tempo. Entretanto, parece se manter estacionária. Para tornar os cálculos da fórmula de Black-Scholes mais fáceis, aproximamos a volatilidae a um valor constante.</p><h4><strong>Sem Dividendos</strong></h4><p>Opções podem possuir diferentes tipos de ativos subjacentes. Mas, no caso de opções como derivativos de ações, o modelo original do Black-Scholes assume que <strong>a ação subjacente não paga </strong><a href="https://pt.wikipedia.org/wiki/Dividendo"><strong>dividendos</strong></a><strong> até o vencimento</strong>. Atualmente, existem fórmulas adaptadas que levam em conta o pagamento de dividendos.</p><h3><strong>Pressupostos sobre o Mercado</strong></h3><h4><strong>Sem Arbitragem</strong></h4><p>Toda a estrutura do Black-Scholes se baseia na premissa de um mercado eficiente, onde <strong>não existem oportunidades de arbitragem</strong>.</p><p>A hipótese do <a href="https://pt.wikipedia.org/wiki/Hip%C3%B3tese_do_mercado_eficiente">mercado eficiente</a> (<em>efficient-market hypothesis</em>) afirma que os preços dos ativos refletem toda as informações disponíveis. Ações sempre são negociadas pelo seu valor justo na bolsa. Portanto, a única forma que um investidor consegue obter retornos mais elevados é comprando investimentos de maior risco.</p><p><strong>A arbitragem é uma estratégia de negociação que gera lucro sem risco e sem investimento inicial.</strong> Este princípio implica que qualquer carteira que é construída para ser totalmente isenta de risco deve render exatamente a taxa de juros livre de risco.</p><p>Sabendo disso, Fischer Black e Myron Scholes perceberam que montar uma carteira consistindo de uma ação subjacente e um ativo livre de risco (como empréstimos ou financiamentos em dinheiro a uma taxa de juros) replica perfeitamente o resultado financeiro de deter a opção.</p><p>Embora existam arbitragens no mundo real, elas são extremamente difícieis de encontrar, tornando essa suposição bastante realista.</p><h4><strong>Zero Custos ou Taxas de Transação</strong></h4><p>O mercado é livre de atritos, segundo o modelo de Black-Scholes. Isso significa que <strong>não há custos de transação ou taxas associados à compra e venda de ativos</strong>. Comissões e <em>spread</em> entre oferta e demanda também não são levados em consideração.</p><h4><strong>Taxa de Juros Livre de Risco Constante</strong></h4><p>Semelhante à ideia de uma volatilidade constante, o modelo pressupões que <strong>a </strong><a href="https://en.wikipedia.org/wiki/Risk-free_rate"><strong>taxa de juros sem risco</strong></a><strong> é constante e conhecida durante toda a vida da opção</strong>.</p><p>A taxa de retorno sem risco é uma taxa teórica em finanças que representa o retorno esperado de um investimento isento de risco de perda financeira. No mundo real, não existem investimento puramente 100% isento de risco. No entanto, o mais próximo que temos é o rendimento da dívida pública de um país estável e com boa capacidade de crédito. Dependendo do país, existem diferentes práticas de padrão no setor.</p><p>Nos Estados Unidos, a aproximação mais comumente usada é a taxa de juros dos títulos do Tesouro americano (<em>U.S. Treasury Securities</em>), como T-bills, T-notes ou T-bonds. Por exemplo, se estivermos precificando uma opção de 3 meses, poderíamos usar o rendimento de um título do Tesouro americano de 3 meses (<em>3-month Treasury bill</em>).</p><p>No Brasil, o conceito de uma taxa de juros livre de risco se baseia no juros pago pelo governo, ou seja, a taxa Selic ou a Taxa DI. Para opções de curto prazo (alguns meses), geralmente se usa a taxa Selic anualizada. Já para opções de termo mais longo (um ano ou mais), a melhor pratica é utilizar o retorno de contratos futuros de DI.</p><pre>t_bill = yf.Ticker(&#39;^IRX&#39;).history(period=&quot;3mo&quot;)[&quot;Close&quot;]<br><br>plt.figure(figsize=(8, 5))<br>plt.plot(t_bill)<br><br>plt.title(&quot;Rendimento dos Títulos do Tesouro Americano a 3 Meses&quot;)<br>plt.xlabel(&#39;Data&#39;)<br>plt.ylabel(&quot;Rendimento&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*ylYc9ML_9xQhExXMmsAvhw.png" /></figure><h3><strong>Pressupostos sobre a Opção</strong></h3><h4><strong>Opção do Tipo Europeu</strong></h4><p>Existem duas tipos de opções: a americana e a europeia. Um investidor que detém uma opção do estilo americano pode exercê-la a qualquer momento antes da data de vencimento. Em contrapartida, <strong>os detentores de uma opção de estilo europeu só podem exercê-la na data de vencimento</strong>. Embora os seus nomes sugerem uma distinção regional, ambos os tipos de opções podem ser negociados em todo o mundo.</p><p>O modelo de Black-Scholes é exclusivamente adequado para opções do tipo Europeu, o que significa que a opção a qual está sendo precificada só pode ser exercida na data de vencimento, e não antes.</p><h3>Próximos Passos</h3><p>No <a href="https://medium.com/@andrejin.nagano/modelo-de-precifica%C3%A7%C3%A3o-de-op%C3%A7%C3%B5es-black-scholes-f%C3%B3rmula-15c061c7a558">próximo artigo</a>, vou introduzir a matemática por trás do modelo e apresentar a fórmula de Black-Scholes para preficifação de opções de compra e venda.</p><h3>Bibliografia</h3><p>Esse artigo foi escrito usando esses conteúdos como referência:</p><ul><li><a href="https://www.columbia.edu/~mh2078/FoundationsFE/BlackScholes.pdf">The Black-Scholes Model by Martin Haugh</a></li><li><a href="https://uregina.ca/~kozdron/Teaching/Regina/441Fall14/Notes/L23-24-25-Oct29.pdf">Lecture #23, 24, 25: Deriving the Black–Scholes Partial Differential Equation by Michael Kozdron</a></li><li><a href="https://portal.if.usp.br/grenac/sites/portal.if.usp.br.ifusp/files/black_scholes_presentation.pdf">The Black-Scholes Option Pricing Model: A Comprehensive Analysis by Renoir Vieira</a></li><li><a href="https://youtu.be/pr-u4LCFYEY?si=yyWpOx441annZgO2">Introduction to the Black-Scholes formula | Finance &amp; Capital Markets | Khan Academy</a></li><li><a href="https://youtu.be/TnS8kI_KuJc?si=uUjWtbcAPIs-CjyY">19. Black-Scholes Formula, Risk-neutral Valuation by MIT OpenCourseWare</a></li><li><a href="https://www.macroption.com/black-scholes-assumptions/">https://www.macroption.com/black-scholes-assumptions/</a></li><li><a href="https://www.numberanalytics.com/blog/mastering-itos-lemma-stochastic-processes#google_vignette">https://www.numberanalytics.com/blog/mastering-itos-lemma-stochastic-processes#google_vignette</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=161760c6cead" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Black-Scholes Option Pricing Model — Python Code]]></title>
            <link>https://medium.com/@andrejin.nagano/black-scholes-option-pricing-model-python-code-293392f0755a?source=rss-7d22ea87b56e------2</link>
            <guid isPermaLink="false">https://medium.com/p/293392f0755a</guid>
            <category><![CDATA[black-scholes-model]]></category>
            <category><![CDATA[options-trading]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Andre Nagano]]></dc:creator>
            <pubDate>Mon, 25 Aug 2025 17:13:59 GMT</pubDate>
            <atom:updated>2025-09-07T18:03:07.528Z</atom:updated>
            <content:encoded><![CDATA[<h3>Black-Scholes Option Pricing Model — Python Code</h3><blockquote>This is part three out of a three part story about the Black-Scholes option pricing model. In the <a href="https://medium.com/@andrejin.nagano/black-scholes-option-pricing-model-assumptions-4bc60b5b78c7">first part</a>, I introduced the concept and discuss the assumptions that serve as the basis of the model. In the <a href="https://medium.com/@andrejin.nagano/black-scholes-option-pricing-model-formula-6438c1c22720">second part</a>, we’ll see the thought process behind the mathematics and formulas. And finally, in this third part, we’ll write some code to actually price different options using the model.</blockquote><p><strong>The </strong><a href="https://en.wikipedia.org/wiki/Black%E2%80%93Scholes_model"><strong>Black-Scholes or Black-Scholes-Merton</strong></a><strong> is mathematical model used in finance to determine the theorical price of European-style options</strong>. The primary purpose of the model is to calculate the fair market value of an option taking into account five parameters: the current price and volatility of the underlying asset, the strike price and time until maturity of the option, and the risk-free interest rate.</p><h3><strong>Black-Scholes in Python</strong></h3><p>Now that we understand the formula, <strong>we’ll create a function in Python to price call and put options</strong> given a specific set of inputs.</p><h4><strong>Importing Libraries</strong></h4><p>For the maths behind the formula we’ll use the <em>scipy</em> and <em>numpy</em> libraries. For generating plots we’ll use the <em>matplotlib</em> and <em>seaborn</em> libraries. And we’ll also use <em>yfinance</em> library to analyze some real-world data.</p><pre>import numpy as np<br>from scipy.stats import norm<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>import yfinance as yf</pre><h4><strong>Function</strong></h4><p>The formula for a option’s price takes five variables as input: <strong>volatility (<em>σ</em>), strike price (<em>K</em>), current spot price (<em>S</em>), time until maturity (<em>T</em>) and the risk-free rate (<em>r</em>)</strong>. The formulas for a call and a put option are as follow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*idaNo_f5eSDY14AXNBvxJw.png" /></figure><p>where:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*6dOswbdPqp6LPPDKV-Q_tw.png" /></figure><p>For the function ɸ<strong>,</strong> which is a <a href="https://en.wikipedia.org/wiki/Cumulative_distribution_function">CDF</a> for a <a href="https://en.wikipedia.org/wiki/Normal_distribution">normal distribution</a>, we’ll use the <em>norm.cdf()</em> method from the <em>scipy.stats</em> library. Besides the five variables used to calculate the option’s price, <strong>we’ll also include an extra input specifying the type of option: call or put</strong>.</p><pre>def black_scholes(type, sigma, K, S, T, r):<br>    &quot;&quot;&quot;&quot;<br>    Applies the Black-Scholes Model to calculate the price of a option.<br>    &quot;&quot;&quot;<br><br>    # Calculates parameters d_1 and d_2 from the Black-Scholes formula<br>    d_1 = (np.log(S / K) + T * (r + sigma ** 2 / 2)) / (sigma * np.sqrt(T))<br>    d_2 = d_1 - sigma * np.sqrt(T)<br><br>    # Calculates the value of the option based on its type, either &quot;call&quot; or &quot;put&quot;<br>    if type == &quot;call&quot;:<br><br>        V = S * norm.cdf(d_1) - np.exp(-r * T) * K * norm.cdf(d_2)<br><br>    elif type == &quot;put&quot;:<br><br>        V = np.exp(-r * T) * K * norm.cdf(-d_2) - S * norm.cdf(-d_1)<br><br>    return V</pre><p>Let’s use the function above to calculate the price of a call and a put option for a Walmart stock.</p><p>At first, we’ll calculate the price for <strong>a call option with a 3-month maturity and a strike price of $60</strong>. Since we’re pricing a 3-month maturity call option, <strong>we’ll use a </strong><a href="https://www.cnbc.com/quotes/US3M"><strong>3-month U.S. Treasury Bill yield</strong></a> as our risk-free interest rate. <strong>The volatility is equal to the annualized standard deviation of the stock’s logarithmic returns.</strong></p><p>The current stock price, yield of the 3-month Treasury bill and volatility is retrieved using the <em>yfinance</em> library.</p><pre># Setting parameters<br>K = 60 # The strike price of this call option is $60<br>T = 3 # It will take one 3 months to expire<br><br># Retrieves the risk-free interest rate<br>t_bill_3m = yf.Ticker(&quot;^IRX&quot;).history()<br>r = t_bill_3m[&quot;Close&quot;].iloc[-1] / 100<br><br># Calculates the underlying stock&#39;s volatility<br>prices = yf.Ticker(&#39;WMT&#39;).history(start=datetime(2019, 1, 1))[&#39;Close&#39;]<br>returns = np.log(prices / prices.shift())<br>sigma = returns.std() * np.sqrt(252)<br><br># Retrieves the underlying stock&#39;s current price<br>S = prices.iloc[-1]<br><br># Calling the function<br>C = black_scholes(&quot;call&quot;, sigma, K, S, T/12, r) # We divide T by 12 because r is annualized<br><br>print(&quot;-- Black-Scholes Call Option Pricing Model --&quot;)<br>print(&quot;Stock: Walmart (WMT)&quot;)<br>print(f&quot;Current Value: ${S: .2f}&quot;)<br>print(f&quot;Strike Price: $ {K}&quot;)<br>print(f&quot;Time to Expiration: {T} months&quot;)<br>print(f&quot;Risk-free Rate:{r*100: .2f}%&quot;)<br>print(f&quot;Option Valued at: ${C: .2f}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*8TLeaACBtG5voSl5_SYsMQ.png" /></figure><p>We can also use the <em>yfinance</em> library to get some idea of what the market is pricing this call option.</p><pre>from datetime import timedelta<br><br>wmt = yf.Ticker(&quot;WMT&quot;)<br>available_dates = wmt.options<br><br>today = datetime.now()<br>target_date = today + timedelta(days=90) # Approximate 3 months<br><br># Calculate the difference between each available date and the target date<br>closest_date = min(available_dates, key=lambda d: abs(datetime.strptime(d, &quot;%Y-%m-%d&quot;) - target_date))<br><br>print(f&quot;Today&#39;s Date: {today.strftime(&#39;%Y-%m-%d&#39;)}&quot;)<br>print(f&quot;Closest available expiration date to 3 months from now: {closest_date}\n&quot;)<br><br># Get the option chain for the closest date<br>option_chain = wmt.option_chain(closest_date)<br>calls = option_chain.calls<br><br># Find the specific call option with the $60 strike price<br>call_option = calls[calls[&#39;strike&#39;] == K]<br><br>print(&quot;-- Call Option Current Price --&quot;)<br>print(&quot;Stock: Walmart (WMT)&quot;)<br>print(f&quot;Current Value: ${S: .2f}&quot;)<br>print(f&quot;Strike Price: $ {K}&quot;)<br>print(f&quot;Expiration Date: {closest_date}&quot;)<br>print(f&quot;Risk-free Rate:{r*100: .2f}%&quot;)<br>print(f&quot;Option Bid Price: ${call_option[&#39;bid&#39;].values[0]: .2f}&quot;)<br>print(f&quot;Option Ask Price: ${call_option[&#39;ask&#39;].values[0]: .2f}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_YS1kgZwc1O9Lwwjwk_-ew.png" /></figure><p>Our Black-Scholes model priced this call option at $37.15, while the current bid price is at $37.20. The <strong>bid price represents the highest price a buyer is willing to accept</strong>, which means that this is the value you would get for selling the option immediately. Our model’s value is slightly lower than the current bid price. <strong>This suggests two things: the model’s output seems reasonable and that the option might be slightly overvalued.</strong> We could short the call option for $37.20 now and buy it later, because we think it’s true value might be $37.15.</p><p>Now, we’ll try pricing a put option with a 3-month maturity and a strike price of 100. The other parameters we’ll remain the same, since they are not specific to a call option.</p><pre># Setting Parameters<br>K = 100 # The strike price of this call option is $60<br>T = 3 # It will take one 3 months to expire<br><br># Calling the function<br>P = black_scholes(&quot;put&quot;, sigma, K, S, T/12, r) # We divide T by 12 because r is annualized<br><br>print(&quot;-- Black-Scholes Put Option Pricing Model --&quot;)<br>print(&quot;Stock: Walmart (WMT)&quot;)<br>print(f&quot;Current Value: ${S: .2f}&quot;)<br>print(f&quot;Strike Price: ${K: .2f}&quot;)<br>print(f&quot;Time to Expiration: {T: .2f} months&quot;)<br>print(f&quot;Risk-free Rate: {r*100: .2f}%&quot;)<br>print(f&quot;Option Valued at: ${P: .2f}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*sZGFRSnd-3Oa9LEuGXLpNQ.png" /></figure><pre>wmt = yf.Ticker(&quot;WMT&quot;)<br>available_dates = wmt.options<br><br>today = datetime.now()<br>target_date = today + timedelta(days=90) # Approximate 3 months<br><br># Calculate the difference between each available date and the target date<br>closest_date = min(available_dates, key=lambda d: abs(datetime.strptime(d, &quot;%Y-%m-%d&quot;) - target_date))<br><br>print(f&quot;Today&#39;s Date: {today.strftime(&#39;%Y-%m-%d&#39;)}&quot;)<br>print(f&quot;Closest available expiration date to 3 months from now: {closest_date}\n&quot;)<br><br># Get the option chain for the closest date<br>option_chain = wmt.option_chain(closest_date)<br>puts = option_chain.puts<br><br># Find the specific put option with the $60 strike price<br>put_option = puts[puts[&#39;strike&#39;] == K]<br><br>print(&quot;-- Put Option Current Price --&quot;)<br>print(&quot;Stock: Walmart (WMT)&quot;)<br>print(f&quot;Current Value: ${S: .2f}&quot;)<br>print(f&quot;Strike Price: $ {K}&quot;)<br>print(f&quot;Expiration Date: {closest_date}&quot;)<br>print(f&quot;Risk-free Rate:{r*100: .2f}%&quot;)<br>print(f&quot;Option Bid Price: ${put_option[&#39;bid&#39;].values[0]: .2f}&quot;)<br>print(f&quot;Option Ask Price: ${put_option[&#39;ask&#39;].values[0]: .2f}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TmPRtdExfiE6EpY72I6IXg.png" /></figure><p>Our Black-Scholes model priced this put option at $5.63, while the ask price is at $5.60. Our model’s value is slightly higher than the current ask price. The <strong>ask price represents the lowest price a seller is willing to accept</strong>, which means that this is the price you would have to pay to buy the option immediately. Again, <strong>this suggests that the model’s output seems reasonable and that the option might be slightly undervalued.</strong> We could buy the put option for $5.60 now, because we think it’s true value might be $5.63.</p><p>Nevertheless, the return on these operations is extremely small. <strong>This slim discrepancy is most likely due to the approximations from the assumptions of the Black-Scholes model.</strong> The two possibilities of trades presented would probably not result in any profit, considering transaction fees on buying and selling options.</p><h4><strong>Prices Heatmap</strong></h4><p>Another way we can visualize different option prices is by creating a grid with multiple strike prices and times to maturity. For every combination of <em>K</em> and <em>T</em>, we can calculate a call and put option. <strong>With this matrix of values, we plot a heatmap, so the contrast between prices is more evident.</strong></p><pre>import pandas as pd<br><br>def price_matrix(type, sigma, S, r):<br><br>    # Create two arrays of strike prices and months to maturity<br>    if type == &#39;call&#39;:<br>        strike_prices = np.arange(S-35, S+10, 5)<br>    elif type == &#39;put&#39;:<br>        strike_prices = np.arange(S-5, S+40, 5)<br>    months = np.arange(1, 13, 1)<br><br>    # Initialize empty matrix<br>    matrix = []<br><br>    for K in strike_prices:<br><br>        row = []<br><br>        for T in months:<br><br>            # Calculate option value for each K in strike_prices and T in months<br>            V = black_scholes(type, sigma, K, S, T/12, r)<br><br>            row.append(V)<br><br>        matrix.append(row)<br><br>    price_labels = [f&#39;${price}&#39; for price in np.round(strike_prices).astype(int)]<br><br>    df = pd.DataFrame(matrix, index=price_labels, columns=months)<br><br>    return df<br><br>call_df = price_matrix(&#39;call&#39;, sigma, S, r)<br>put_df = price_matrix(&#39;put&#39;, sigma, S, r)</pre><p>Now, we plot the heatmap using the <em>seaborn</em> library.</p><pre># Setting heatmap parameters<br>heatmap_params = {<br>    &#39;annot&#39;: True, <br>    &#39;fmt&#39;: &#39;.2f&#39;, <br>    &#39;cmap&#39;: &quot;YlGnBu&quot;, <br>    &#39;cbar&#39;: False<br>}<br><br>dfs = {<br>    &#39;Call Option Prices&#39;: call_df,<br>    &#39;Put Option Prices&#39;: put_df<br>}<br><br># Creating the plots<br>fig, axs = plt.subplots(1, 2, figsize=(12, 6))<br><br>for ax, (title, data) in zip(axs, dfs.items()):<br>    sns.heatmap(data, ax=ax, **heatmap_params)<br>    ax.set(title=title, <br>           xlabel=&#39;Months Until Expiration&#39;, <br>           ylabel=&#39;Strike Price&#39;)<br>    ax.tick_params(axis=&#39;y&#39;, rotation=0)<br><br>fig.suptitle(f&#39;Black-Scholes Pricing Model for Option with: S={round(S, 2)}, sigma={round(sigma, 2)} and r={round(r, 2)}&#39;, fontsize=14, fontweight=&#39;bold&#39;)<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hN0q_tnbUnuH0IYE8LrjhQ.png" /></figure><p>Let’s first take a look at the call option prices. <strong>As the strike prices decrease, the call option turns more valuable.</strong> That’s because investors would like to buy the stock for cheaper in the future. Now, looking at the x-axis, <strong>the options’ prices increase as the months to maturity increase.</strong> If we’re expecting the stock to keep increasing in value (because of a drift), the return on buying the option, for a specific strike price, also increases as the time to maturity is further away.</p><p>Next, let’s analyze the put options’ prices.<strong> As the strike prices increase, the put option turns more valuable.</strong> The reason for that is investors are always looking to sell their stocks for a higher value. As for the x-axis, <strong>the price drops as the maturity increases.</strong> If we’re expecting the stock to keep increasing in value, the return on selling the stock, for a specific strike price, decreases as the time to maturity is further away.</p><h3>Parts I and II</h3><p>This was the last part on our Black-Scholes story. If you wanna learn more about the assumptions or the mathematics behind the formula, please consider reading parts I and II:</p><ul><li><a href="https://medium.com/@andrejin.nagano/black-scholes-option-pricing-model-assumptions-4bc60b5b78c7">Black-Scholes Option Pricing Model — Assumptions</a></li><li><a href="https://medium.com/@andrejin.nagano/black-scholes-option-pricing-model-formula-6438c1c22720">Black-Scholes Option Pricing Model — Formula</a></li></ul><h3>Bibliography</h3><p>This story was written used these contents as references:</p><ul><li><a href="https://www.columbia.edu/~mh2078/FoundationsFE/BlackScholes.pdf">The Black-Scholes Model by Martin Haugh</a></li><li><a href="https://uregina.ca/~kozdron/Teaching/Regina/441Fall14/Notes/L23-24-25-Oct29.pdf">Lecture #23, 24, 25: Deriving the Black–Scholes Partial Differential Equation by Michael Kozdron</a></li><li><a href="https://portal.if.usp.br/grenac/sites/portal.if.usp.br.ifusp/files/black_scholes_presentation.pdf">The Black-Scholes Option Pricing Model: A Comprehensive Analysis by Renoir Vieira</a></li><li><a href="https://youtu.be/pr-u4LCFYEY?si=yyWpOx441annZgO2">Introduction to the Black-Scholes formula | Finance &amp; Capital Markets | Khan Academy</a></li><li><a href="https://youtu.be/TnS8kI_KuJc?si=uUjWtbcAPIs-CjyY">19. Black-Scholes Formula, Risk-neutral Valuation by MIT OpenCourseWare</a></li><li><a href="https://www.macroption.com/black-scholes-assumptions/">https://www.macroption.com/black-scholes-assumptions/</a></li><li><a href="https://www.numberanalytics.com/blog/mastering-itos-lemma-stochastic-processes#google_vignette">https://www.numberanalytics.com/blog/mastering-itos-lemma-stochastic-processes#google_vignette</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=293392f0755a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Black-Scholes Option Pricing Model — Formula]]></title>
            <link>https://medium.com/@andrejin.nagano/black-scholes-option-pricing-model-formula-6438c1c22720?source=rss-7d22ea87b56e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6438c1c22720</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[options-trading]]></category>
            <category><![CDATA[black-scholes-model]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[finance]]></category>
            <dc:creator><![CDATA[Andre Nagano]]></dc:creator>
            <pubDate>Mon, 25 Aug 2025 16:35:14 GMT</pubDate>
            <atom:updated>2025-09-07T17:53:33.723Z</atom:updated>
            <content:encoded><![CDATA[<h3>Black-Scholes Option Pricing Model — Formula</h3><blockquote>This is part two out of a three part story about the Black-Scholes option pricing model. In the <a href="https://medium.com/@andrejin.nagano/black-scholes-option-pricing-model-assumptions-4bc60b5b78c7">first part</a>, I introduced the concept and discuss the assumptions that serve as the basis of the model. In this second part, we’ll see the thought process behind the mathematics and formulas. And finally, in the <a href="https://medium.com/@andrejin.nagano/black-scholes-option-pricing-model-python-code-293392f0755a">third part</a>, we’ll write some code to actually price different options using the model.</blockquote><p><strong>The </strong><a href="https://en.wikipedia.org/wiki/Black%E2%80%93Scholes_model"><strong>Black-Scholes or Black-Scholes-Merton</strong></a><strong> is mathematical model used in finance to determine the theorical price of European-style options</strong>. The primary purpose of the model is to calculate the fair market value of an option taking into account five parameters: the current price and volatility of the underlying asset, the strike price and time until maturity of the option, and the risk-free interest rate.</p><h3><strong>Basic Concepts</strong></h3><h4><strong>Geometric Brownian Motion (GBM)</strong></h4><p>As previously stated <strong>asset prices follow a random walk</strong>. Even though this model captures the essence of the unpredictable movements of an asset, this model consists of a series of steps in discrete-time. This makes it insufficient for the rigorous demands of derivative pricing, which requires a continuous framework.</p><p><strong>The mathematical bridge from a discrete random walk to a continuos-time process is the concept of </strong><a href="https://en.wikipedia.org/wiki/Brownian_motion"><strong>Brownian Motion</strong></a><strong> (<em>W</em>)</strong>. A standard brownian motion is a stochastic process characterized by three key properties:</p><ul><li>It starts at zero.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/184/1*3jcpAm7AHHX5s3aEzqcfGw.png" /></figure><ul><li>It has independent increments, which means that the change in the process over any time interval has no bearing on what happened before.</li><li>The increments are normally distributed, with a zero mean and a variance equal to the length of the time interval.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*QRgEdJB11jaqVP-UXHLt5w.png" /></figure><p>Even though, it comes close to a proper model for an asset price, there is still one issue. <strong>This brownian motion model does not guarantee a positive outcome</strong>. Since the increments are normally distributed around 0, the variable could become negative, which is impossible for a limited liability, such as a stock.</p><p>Therefore, the Black-Scholes model proposes that the movements of an asset’s price can be modeled with a <a href="https://en.wikipedia.org/wiki/Geometric_Brownian_motion">Geometric Brownian Motion</a> (<em>S</em>). While a standard brownian motion has random increments being added at each step, <strong>a geometric brownian motion has a random growth being multiplied at each step</strong>. The key properties of a geometrical brownian motion are analogous to a standard brownian motion:</p><ul><li>It starts at a positive value.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/188/1*daBSzC84pEzEted6dfFWKQ.png" /></figure><ul><li>It has independent multiplying factors.</li><li>The multiplying factors at each step are log-normally distributed.</li><li>Geometric Brownian Motion processes can never become negative.</li></ul><p>These properties align with the assumptions of a Black-Scholes model, making it suitable to describe the movement of the underlying asset.</p><p>The dynamics of a GBM are described by a <a href="https://en.wikipedia.org/wiki/Stochastic_differential_equation">Stochastic Differential Equation</a> (SDE):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*wlvVzHjD2EWpVPMQ-OqB7A.png" /></figure><p>This equation is composed by two parts:</p><p>1. A deterministic component (<em>µStdt</em>), called “drift”. This term represents the expected return of the asset over an infinitesimal time period <em>dt</em>. The constant <em>µ</em>, also called percentage drift, is the annualized expected rate of return.</p><p>2. A stochastic component (<em>σStdWt</em>) called “diffusion” or “volatility” term. This term captures the random fluctuations of the asset price. The constant <em>σ</em>, also called percentage volatility, is the annualized standard deviation of the asset’s returns.</p><h4><strong>Itô’s Lemma</strong></h4><p><strong>The Brownian Motion process, seen in asset’s prices, is continuous everywhere but nowhere differentiable</strong>. This is due to the fact the the curve is very erratic, with a “roughness” so extreme that at no point can a unique tangent line be drawn. This caveat makes it SDE impossible to be solved by calculus’ conventional means. Still, through a technique using a Taylor series expansion of an option’s value, the Japanese mathematician Kiyoshi Itô was able to <strong>provide the complete differential for a stochastic function</strong>.</p><p>Given the function for the price of an option <em>V(S, t)</em>, where <em>S</em> represents the price of the underlying asset (which is a stochastic process) and <em>t</em> the time, by <a href="https://en.wikipedia.org/wiki/It%C3%B4%27s_lemma">Itô’s lemma</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nHHYtG4GV1d3mStQ1qiU_Q.png" /></figure><h3><strong>Black-Scholes Partial Differential Equation</strong></h3><p>Now that we have all the assumptions and the concepts from stochastic calculus, we can build the intuition behind the Black-Scholes Model equation. First, let’s start with a hedged portfolio, with a self-financing strategy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*U5fJA2_pfzqI1KYeChgZFQ.png" /></figure><p>where, in time <em>t</em>:</p><ul><li><em>x</em> are the units of cash invested in a cash account at a constant interest rate.</li><li><em>B</em> is the formula for a continuously compounding interest rate:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/212/1*x6jZ6NQn8y-hvBY6mlDYTg.png" /></figure><ul><li><em>y</em> are the units of the underlying asset.</li><li><em>S</em> is the price of the underlying asset.</li></ul><p>When we derive the function for the value of our portfolio, we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*9stf3IP6kLxeVJEu9iNXMg.png" /></figure><p>Using the SDE to describe a Geometric Brownian Motion:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*jlz8n53l3v3kachm4E75Ug.png" /></figure><p>We will build a portfolio that replicates the value of the option. This means we are looking to tune the variables <em>x</em> and <em>y:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wCCXmDDzRcO8f9VMrjLCag.png" /></figure><p>After equating the common terms of the equation above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*BTRJkFE4w0pdKroDUTIGZg.png" /></figure><p>Finally, we can input the two variables into our portfolio formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*KCmI3GuOS3rdNId5L1CfBQ.png" /></figure><p>The equation above is known as the <a href="https://en.wikipedia.org/wiki/Black%E2%80%93Scholes_equation">Black-Scholes Partial Differential Equation</a> (PDE). <strong>It describes the relationship that must hold at all times between an option’s price, the underlying stock’s price, time, volatility and the risk-free rate to prevent arbitrage opportunities.</strong></p><p>One major thing to point out is the complete absence of the drift percentage (<em>µ</em>) in the final PDE. Even though it seems counter intuitive, <strong>the annualized expected rate of return on the asset has no influence on the option’s fair value</strong>.</p><h3><strong>Black-Scholes Formula</strong></h3><p>The solution to the Black-Scholes PDE is what is called the Black-Scholes Formula, a equation that provides the theoretical fair value of a European option.<strong> To solve this PDE, boundary conditions must be provided</strong>:</p><p>1. At the moment of expiration, the value of a call option is either 0, if the stock price falls lower than the strike price, or the stock price minus the strike price:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*8WFqaoX2NbTqa7-JJ_H48A.png" /></figure><p>2. If the stock price falls to zero, then the call option is worthless:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*Uk34S72xLyzwt7P3GIJ0sQ.png" /></figure><p>3. As the stock price becomes too large, the probability of the option being exercised is close to 100%. In this case, the value of the option approaches the value of holding the stock minus the present value of paying the strike price:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*RFcvXevbVtMGEoV7UJm7HQ.png" /></figure><p>Surprisingly, before Fischer Black or Myron Scholes had this idea for an option pricing model, the Black-Scholes PDE had already been solved. The Black-Scholes PDE is a type of parabolic PDE that is mathematically analogous to the <a href="https://en.wikipedia.org/wiki/Heat_equation">heat diffusion equation</a> in physics. Price volatility behaves similar to thermal diffusivity, and through some variable manipulations, it’s possible to get to the heat diffusion equation.</p><p>The solution for a the Black-Scholes PDE gives us the price for a call option. While this solution, plus the concept of a <a href="https://en.wikipedia.org/wiki/Put%E2%80%93call_parity">put-call parity</a> relationship, yields the price for a put option. The put-call parity is a principle in finance that states that the value of a portfolio consisting of a long call option and a risk-free bond, which will be worth the strike price at expiration date, is equal to the value of a portfolio containing a long put option and the underlying asset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*AATGGDKEDS0vxTiaEJZt-A.png" /></figure><p>This idea is also based on the assumption of an efficient market, with no arbitrage opportunities. <strong>As a result, the formulas for a call and a put option according to the Black-Scholes model are</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*GuUTLi8BZYUExY1IReIaUQ.png" /></figure><p>where:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rv5vXVWF_dI-xsTedngNPg.png" /></figure><p>The <em>d2</em> term represents the probability that the option will expire in the money (<em>S ≥ K</em>), which means that <strong>ɸ(<em>d2</em>) gives the expected value of having to pay out the strike price for a call</strong>. The component <em>d1</em> is a little more complex. <strong>It calculates the conditional probability of the expected value in relation to its current spot price, given that the current spot price is greater than the strike price at maturity.</strong></p><p><strong>The first term of the call option (Sɸ(<em>d1</em>)) calculates the risk adjusted probability of the option being exercised</strong>, which occurs when the price of the underlying asset is greater than or equal to the option’s strike price (<em>S ≥ K</em>). <strong>While the second term (e^(-r(T-t))Kɸ(<em>d2</em>)) expresses the inverse probability of the investor not exercising the option.</strong> The component is a discounted strike price from the expiration date to the present time using risk-free rate. This can be seen as the opportunity cost of paying upfront for the premium, instead of investing it at the risk-free rate.</p><h4><strong>Cumulative Distribution Function (CDF)</strong></h4><p><strong>The </strong><a href="https://en.wikipedia.org/wiki/Cumulative_distribution_function"><strong>CDF</strong></a><strong> of a variable <em>X </em>evaluated at <em>x</em> is the probability that <em>X</em> will take a value less than or equal to <em>x</em>.</strong> To understand it better we can plot a standard normal distribution curve using Python.</p><pre>from scipy.stats import norm<br><br># Standard normal distribution parameters<br>mu = 0  # Mean<br>sigma = 1  # Standard Deviation<br><br># Point at which to calculate the CDF<br>x_value = 1.5<br><br># Create a range of x values for the plot<br>x = np.linspace(mu - 4*sigma, mu + 4*sigma, 1000)<br># Calculate the Probability Density Function (PDF) for these x values<br>pdf = norm.pdf(x, mu, sigma)<br><br># Calculate the CDF for the x_value<br>cdf_value = norm.cdf(x_value, mu, sigma)<br><br># Create plot<br>plt.figure(figsize=(10, 5))<br><br># Plotting the PDF curve<br>plt.plot(x, pdf, &#39;blue&#39;, label=&#39;Standard Normal PDF&#39;)<br><br># Filling the area underneath the PDF curve until the x_value<br>fill_mask = x &lt;= x_value<br>plt.fill_between(x[fill_mask], pdf[fill_mask], color=&#39;skyblue&#39;, alpha=0.6, label=f&#39;Area = CDF({x_value})&#39;)<br><br>plt.axvline(x_value, color=&#39;red&#39;, linestyle=&#39;--&#39;, label=f&#39;x = {x_value}&#39;)<br><br># Adding Title, Labels and Grid<br>plt.xlabel(&#39;X-axis&#39;, fontsize=12)<br>plt.ylabel(&#39;Probability Density&#39;, fontsize=12)<br>plt.title(f&#39;Standard Normal Distribution (μ={mu}, σ={sigma})\nCDF at x={x_value} is {cdf_value:.4f}&#39;, fontsize=14)<br>plt.grid(True)<br><br># Display Plot<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*SoTHJBPZDfCjGAhHtBvkjQ.png" /></figure><p>The plot above shows the standard normal distribution PDF curve (blue) with a limit at the <em>x=1.5</em> (red). The area underneath the PDF curve until the dashed red line is equal to the value of the CDF. So, in the example above <em>ɸ(1.5) = 0.9332</em>.</p><h3>Next Steps</h3><p>In the next story, we’ll write a code in Python to implement the Black-Scholes option pricing model.</p><h3>Bibliography</h3><p>This story was written used these contents as references:</p><ul><li><a href="https://www.columbia.edu/~mh2078/FoundationsFE/BlackScholes.pdf">The Black-Scholes Model by Martin Haugh</a></li><li><a href="https://uregina.ca/~kozdron/Teaching/Regina/441Fall14/Notes/L23-24-25-Oct29.pdf">Lecture #23, 24, 25: Deriving the Black–Scholes Partial Differential Equation by Michael Kozdron</a></li><li><a href="https://portal.if.usp.br/grenac/sites/portal.if.usp.br.ifusp/files/black_scholes_presentation.pdf">The Black-Scholes Option Pricing Model: A Comprehensive Analysis by Renoir Vieira</a></li><li><a href="https://youtu.be/pr-u4LCFYEY?si=yyWpOx441annZgO2">Introduction to the Black-Scholes formula | Finance &amp; Capital Markets | Khan Academy</a></li><li><a href="https://youtu.be/TnS8kI_KuJc?si=uUjWtbcAPIs-CjyY">19. Black-Scholes Formula, Risk-neutral Valuation by MIT OpenCourseWare</a></li><li><a href="https://www.macroption.com/black-scholes-assumptions/">https://www.macroption.com/black-scholes-assumptions/</a></li><li><a href="https://www.numberanalytics.com/blog/mastering-itos-lemma-stochastic-processes#google_vignette">https://www.numberanalytics.com/blog/mastering-itos-lemma-stochastic-processes#google_vignette</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6438c1c22720" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Black-Scholes Option Pricing Model — Assumptions]]></title>
            <link>https://medium.com/@andrejin.nagano/black-scholes-option-pricing-model-assumptions-4bc60b5b78c7?source=rss-7d22ea87b56e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bc60b5b78c7</guid>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[options-trading]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[black-scholes-model]]></category>
            <category><![CDATA[finance]]></category>
            <dc:creator><![CDATA[Andre Nagano]]></dc:creator>
            <pubDate>Mon, 25 Aug 2025 15:34:41 GMT</pubDate>
            <atom:updated>2025-08-25T17:14:28.086Z</atom:updated>
            <content:encoded><![CDATA[<h3>Black-Scholes Option Pricing Model — Assumptions</h3><blockquote>This is part one out of a three part story about the Black-Scholes option pricing model. In this first part, I’ll introduce the concept and discuss the assumptions that serve as the basis of the model. In the <a href="https://medium.com/@andrejin.nagano/black-scholes-option-pricing-model-formula-6438c1c22720">second part,</a> we’ll see the thought process behind the mathematics and formulas. And finally, in the <a href="https://medium.com/@andrejin.nagano/black-scholes-option-pricing-model-python-code-293392f0755a">third part</a>, we’ll write some code to actually price different options using the model.</blockquote><p><strong>The </strong><a href="https://en.wikipedia.org/wiki/Black%E2%80%93Scholes_model"><strong>Black-Scholes or Black-Scholes-Merton</strong></a><strong> is mathematical model used in finance to determine the theorical price of European-style options. </strong>The primary purpose of the model is to calculate the fair market value of an option taking into account five parameters: the current price and volatility of the underlying asset, the strike price and time until maturity of the option, and the risk-free interest rate.</p><h3><strong>Pricing Options</strong></h3><p><strong>An option is a type of derivative asset that gives its owner (holder) the right, but not the obligation to buy (call option) or sell (put option) a specific quantity of an underlying asset at a specified strike price.</strong> Options are generally used for three main purposes: speculation, hedge or arbitrage.</p><p>The task of predicting the future value of a asset has demonstrated to be very difficult. The price of an asset can depend on a countless number of variables. <strong>Since the value of an option is tied to the future value of its underlying asset, options are equally very hard to be priced.</strong></p><p>That’s where the Black-Scholes-Merton model comes in. It has proved to be quite robust method of pricing these types of derivatives.</p><h3><strong>Assumptions</strong></h3><p>However, there are some caveats. The Black-Scholes model only works under a number of assumptions. These assumptions are related to the underlying asset, to the overall market and to the option itself.</p><h3><strong>Assumptions about the Underlying Asset</strong></h3><h4><strong>Random Walk</strong></h4><p>The foundational assumption of modern financial theory is that the direction of an asset’s price cannot be consistently predicted from its past behavior. The price of an asset follows a “<a href="https://en.wikipedia.org/wiki/Random_walk">random walk</a>”, <strong>which means that in every point of time the value is equal to the previous one plus a random variable</strong>. This random walk is a movement pattern also known as a Wiener process in mathematics or brownian motion in physics.</p><h4><strong>Log-normal Distribution of Stock Prices</strong></h4><p>Because of this random walk, the returns on the stock are <a href="https://en.wikipedia.org/wiki/Normal_distribution">normally distributed</a>. This in turn, means that <strong>the stock price itself has a </strong><a href="https://en.wikipedia.org/wiki/Log-normal_distribution"><strong>lognormal distribution</strong></a>.</p><p>Let’s take Walmart’s stock’s closing prices as an example. For this we’ll use the following Python libraries.</p><pre>import numpy as np<br>import yfinance as yf<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>from datetime import datetime</pre><p>The <em>yfinance</em> librariy allows us to retrieve the time series of the stock’s closing prices in the past few years.</p><pre>prices = yf.Ticker(&#39;WMT&#39;).history(start=datetime(2019, 1, 1))[&#39;Close&#39;]</pre><p>When we plot a histogram of the returns of this stock, we can find a normally distributed dataset. To calculate this return, we assume a <a href="https://www.investopedia.com/terms/c/continuouscompounding.asp"><strong>continuously compounded return</strong></a>, which means that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*6ziSK2-A5rIuSxze9LplKQ.png" /></figure><pre>returns = np.log(prices / prices.shift())<br><br>sns.set_style(&quot;whitegrid&quot;)<br><br>sns.histplot(data=returns, stat=&quot;density&quot;, bins=30)<br>sns.kdeplot(data=returns, color=&quot;red&quot;)<br><br>plt.title(&quot;Walmart&#39;s Stock Daily Returns Distribution&quot;)<br>plt.xlabel(&#39;Stock Return&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*70_2-CccVGfQxtwal6Z2bA.png" /></figure><p><strong>The distribution of a random variable, whose logarithm is normally distributed, is log-normally distributed.</strong> The plot above proves that the logarithm of the price (return) is normally distributed. This means that the price itself is log-normally distributed.</p><pre>sns.histplot(data=prices, stat=&quot;density&quot;, bins=30)<br>sns.kdeplot(data=prices, color=&quot;red&quot;)<br><br>plt.title(&quot;Walmart&#39;s Closing Stock Prices Distribution&quot;)<br>plt.xlabel(&#39;Price&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*br_f1_nsxILtKDS3WLbaug.png" /></figure><p>Log-normal distributions have two key characteristics:</p><ul><li>They are <strong>always positive.</strong> Stocks prices are tied to real-world quantities, which means they can’t be negative.</li><li>They have a <strong>long tail to the right</strong>. Stock prices have a higher probability of having small changes and a small probability of large changes.</li></ul><h4><strong>Constant Volatility</strong></h4><p>Another assumption is that the <a href="https://en.wikipedia.org/wiki/Volatility_(finance)">volatility</a> of the underlying stock is constant. A <strong>volatility that doesn’t change over time</strong> means that the amplitude of the moves are generally expected and known in advance.</p><p>In the real world, this is not true. Let’s use Walmart’s stock price as example again. We can calculate the volatility of a stock by taking the standard deviation of the daily returns. For each point in time we’ll take the standard deviation of the past 60 days, using a moving or rolling window method. It’s also a common practice to analyze the annualized volatility. So, we multiply it by square root of 252 (number of trading days in a year).</p><pre>volatility = returns.rolling(60).std().dropna()<br>annualized_volatlity = volatility * np.sqrt(252)<br><br>plt.plot(annualized_volatlity, label=&quot;Volatility&quot;)<br>plt.axhline(annualized_volatlity.mean(), linestyle=&#39;dotted&#39;, color=&#39;black&#39;, label=&quot;Mean&quot;)<br>plt.ylim(0, 1)<br><br>plt.title(&quot;Moving Volatility of Walmart&#39;s Stock&quot;)<br>plt.xlabel(&#39;Volatility&#39;)<br>plt.ylabel(&quot;Date&quot;)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*SsqldNtUbRxVWBwp-XcZXQ.png" /></figure><p>As we can see the volatility does change over time. However, it seems quite stationary. To make the math within the Black-Scholes formula manageable, we aproximate the volatility to a constant value.</p><h4><strong>No Dividends</strong></h4><p>Options have many different types of underlying assets. But, in the case of options as a derivative of a stock, the original Black-Scholes model assumes that <strong>the underlying stock pays no dividends until maturity</strong>. Nowadays, there are some adapted formulas to account for divindends.</p><h3><strong>Assumptions about the Market</strong></h3><h4><strong>No Arbitrage</strong></h4><p>The entire Black-Scholes framework is built upon the assumption of an <strong>efficient market where no arbitrage opportunities exist</strong>.</p><p>The <a href="https://en.wikipedia.org/wiki/Efficient-market_hypothesis">efficient-market hypothesis</a> states that asset prices reflect all available information. Stocks always trade at their fair value on exchange. Therefore, the only way an investor can obtain higher returns is by purchasing riskier investments.</p><p><strong>An arbitrage is a trading strategy that generates a risk-free profit with no initial investment.</strong> This principle implies that any portfolio that is constructed to be completely risk-free must earn exactly the risk-free rate of interest.</p><p>Knowing this, Fischer Black and Myron Scholes realized that building a portfolio consisting of the underlying stock and a risk-free asset (such as borrowing or lending cash at a interest rate) perfectly replicates the financial outcome of holding the option.</p><p>Even though that in the real-world arbitrages exist, they are extremely hard to find, turning this assumption quite realistic.</p><h4><strong>No Transaction Costs or Taxes</strong></h4><p>The market is frictionless according to the Black-Scholes model. This means that there are <strong>no transaction costs or taxes associated with buying or selling securitites</strong>. Commissions or bid-ask spread are also not taken into account.</p><h4><strong>Constant Risk-Free Interest Rate</strong></h4><p>Similar to the idea of a constant volatility, the model assumes that <strong>the </strong><a href="https://en.wikipedia.org/wiki/Risk-free_rate"><strong>risk-free interest rate</strong></a><strong> is constant and known throughout the life of the option</strong>.</p><p>The risk free rate of return is a theoretical rate in finance representing the expected return on an investment with no risk of financial loss. In the real world, no investment is truly 100% risk-free. However, the closest thing we have is the yield on government debt from a stable and creditworthy country. Depending on the country, that are different standard industry practices.</p><p>In the U.S., the most commonly used proxy is the interest rate on U.S. Treasury securities, like T-bills, T-notes, or T-bonds. For example, if we’re pricing a 3-month option, we could use the yield on a 3-month Treasury bill.</p><pre>t_bill = yf.Ticker(&#39;^IRX&#39;).history(period=&quot;3mo&quot;)[&quot;Close&quot;]<br><br>plt.plot(t_bill)<br><br>plt.title(&quot;U.S. 3-Month Treasury Bill Yield in the Past 3 Months&quot;)<br>plt.xlabel(&#39;Date&#39;)<br>plt.ylabel(&quot;Yield&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*hFLbDmjLWg4rSPo134Xlsg.png" /></figure><h3><strong>Assumptions about the Option</strong></h3><h4><strong>European-Style Option</strong></h4><p>The are two types of options: American and European. An investor holding an American-style option may exercise at any time before the maturity date. In contrast, <strong>owners of an European-style option can only exercise at the expiration date</strong>. Even though their names suggest a regional distinction, both types of options can be traded all over the world.</p><p>The Black-Scholes is suitable exclusively to European-style options, meaning that the option being priced can only be exercised at the expiration date, not before.</p><h3>Next Steps</h3><p>In the next story, I’ll introduce the maths behind the model and present the Black-Scholes formula used to price call and put options.</p><h3>Bibliography</h3><p>This story was written used these contents as references:</p><ul><li><a href="https://www.columbia.edu/~mh2078/FoundationsFE/BlackScholes.pdf">The Black-Scholes Model by Martin Haugh</a></li><li><a href="https://uregina.ca/~kozdron/Teaching/Regina/441Fall14/Notes/L23-24-25-Oct29.pdf">Lecture #23, 24, 25: Deriving the Black–Scholes Partial Differential Equation by Michael Kozdron</a></li><li><a href="https://portal.if.usp.br/grenac/sites/portal.if.usp.br.ifusp/files/black_scholes_presentation.pdf">The Black-Scholes Option Pricing Model: A Comprehensive Analysis by Renoir Vieira</a></li><li><a href="https://youtu.be/pr-u4LCFYEY?si=yyWpOx441annZgO2">Introduction to the Black-Scholes formula | Finance &amp; Capital Markets | Khan Academy</a></li><li><a href="https://youtu.be/TnS8kI_KuJc?si=uUjWtbcAPIs-CjyY">19. Black-Scholes Formula, Risk-neutral Valuation by MIT OpenCourseWare</a></li><li><a href="https://www.macroption.com/black-scholes-assumptions/">https://www.macroption.com/black-scholes-assumptions/</a></li><li><a href="https://www.numberanalytics.com/blog/mastering-itos-lemma-stochastic-processes#google_vignette">https://www.numberanalytics.com/blog/mastering-itos-lemma-stochastic-processes#google_vignette</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bc60b5b78c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Estratégia de Pairs Trading com Python]]></title>
            <link>https://medium.com/@andrejin.nagano/pairs-trading-strategy-com-python-cdb8e2cae902?source=rss-7d22ea87b56e------2</link>
            <guid isPermaLink="false">https://medium.com/p/cdb8e2cae902</guid>
            <category><![CDATA[quantitative-finance]]></category>
            <category><![CDATA[ciencia-de-dados]]></category>
            <category><![CDATA[investimento]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pair-trading]]></category>
            <dc:creator><![CDATA[Andre Nagano]]></dc:creator>
            <pubDate>Wed, 20 Aug 2025 17:03:57 GMT</pubDate>
            <atom:updated>2025-08-20T17:06:49.052Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Observação: este artigo tem fins exclusivamente educacionais e não deve ser considerado uma recomendação de estratégia de investimento.</strong></p><h3>Pair Trading</h3><p><strong>Pairs Trading é uma estratégia de trade que se aproveita do fato de que certos ativos tendem a se movimentar em sincronia</strong>, o que significa que o <em>spread</em> (diferença) entre eles tendem a reverter a um valor com o tempo.</p><p>Imagine duas empresas que operam no mesmo setor. Mesmo que o valor de suas ações sejam diferentes e únicos para cada empresa, as duas são impactadas por quedas e elevaçõs do mercado que elas pertencem. Assim, se a demanda sobe ou desce no setor, as duas empresas são afetadas. Um trader pode reconhecer esse padrão e criar uma estratégia de Pairs Trading quando o spread entre os valores das ações aumentam.</p><p>Por exemplo, se o valor de uma ação A aumenta, enquanto o valor de uma ação B permanece constante, um trader poderia ficar comprado (<em>long</em>) na ação B e vendido (<em>short</em>) na ação A. A suposição seria que o spread convergirá com o tempo, revertendo a uma média e resultando em lucro.</p><p><strong>Uma condição para esta estratégia funcionar é que o spread entre os dois ativos seja estacionário</strong>. Esse padrão pode ser encontrado em <strong>variáveis cointegradas</strong>, que demonstram uma relação estável a longo termo.</p><p>Essa estratégia é considerada <strong>neutra em relação ao mercado</strong>, já que almeja lucrar sobre a relação entre dois ativos e não sobre a direção do mercado em geral. Ao ter posições compradas e vendidas ao mesmo tempo, sua exposição ao risco geral do mercado é significativamente reduzida.</p><h3><strong>Código</strong></h3><p>Para este exercício, primeiro vamos procurar duas ações que podem ser usadas na estratégia de Pairs Trading, utilizando algumas ferramentas estatísticas, e depois testando um método de médias móveis para aplicar a estratégia.</p><h4><strong>Importando Bibliotecas</strong></h4><p>Vamos usar as bibliotecas do <em>pandas</em> e do <em>datetime</em> para manipulação de dados, <em>matplotlib</em> e <em>seaborn</em> para gerar os gráficos e <em>yfinance</em> para obter os valores das ações.</p><pre>import pandas as pd<br>import yfinance as yf<br>from datetime import datetime<br>import matplotlib.pyplot as plt<br>import seaborn as sns</pre><h4><strong>Função para Obter os Preços</strong></h4><p>Para obter o histórico dos preços de fechamento diários, nós criamos uma função para baixar os dados usando a biblioteca <em>yfinance</em>. Essa função toma como entrada uma lista de <em>tickers</em> para cada ação, além de opcionalmente, a data de início e fim da série temporal.</p><pre>def obter_precos(tickers, inicio=datetime(2020, 1, 1), fim=datetime(2025, 1, 1)):<br>    &quot;&quot;&quot;<br>    Retorna todos os valores de fechamento de cada ação no lista de<br>    tickers, desde a data de início até a data final<br>    &quot;&quot;&quot;<br><br>    dados = pd.DataFrame()<br>    <br>    # Iterates through all the tickers<br>    for ticker in tickers:<br>        try:<br>            # Request the closing prices<br>            df = yf.Ticker(ticker).history(start=inicio, end=fim)[&#39;Close&#39;]<br>            df.index = df.index.date<br>        except:<br>            pass<br>        <br>        dados = pd.concat([dados, df], axis=1)<br><br>    dados.columns = tickers<br>    <br>    return dados</pre><h4><strong>Obtendo uma Lista de Empresas do Ibovespa</strong></h4><p>Como exemplo, vamos procurar por pares de empresas do índice Bovespa. Para obter os <em>tickers</em> de cada empresa, vamos extrair a tabela da página do Wikipédia do Ibovespa. Também vamos adicionar o próprio índice nos dados.</p><pre># Lê a página do Wikipédia para obter os tickers<br>tabela = pd.read_html(&#39;https://pt.wikipedia.org/wiki/Lista_de_companhias_citadas_no_Ibovespa&#39;)[0]<br>ibov_tickers = tabela[&#39;Código&#39;].tolist()<br>ibov_tickers = [tick + &#39;.SA&#39; for tick in ibov_tickers] + [&#39;BOVA11.SA&#39;]</pre><h4><strong>Obtendo o Histórico de Preços de Fechamento de Empresas do Ibovespa</strong></h4><pre>df = obter_precos(ibov_tickers)<br>df.dropna(axis=1, inplace=True)</pre><h3><strong>Escolhendo Par de Ações</strong></h3><h4><strong>Cointegração</strong></h4><p>Estamos procurando por <a href="https://en.wikipedia.org/wiki/Cointegration">pares cointegrados</a>, <strong>o que significa que a longo prazo, as duas ações tendem a mover em conjunto</strong>. Se os preços das duas ações se movimentam junto a longo termo, o spread entre elas também possuem uma tendência de se reverter a uma média de tempos em tempos.</p><p>Para verificar a cointegração entre duas ações, vamos usar o método <em>ts.coint()</em> da biblioteca <em>statsmodels</em>. Se o valor-p<em> </em>do teste de cointegração for menor que 0,05, vamos rejeitar hipótese nula, e considerar as duas variáveis como cointegradas.</p><pre>import statsmodels.tsa.stattools as ts<br><br>pares = []<br>pares_cointegrados = []<br><br># Itera sobre todos os pares<br>for i in df.columns:<br>    for j in df.columns:<br><br>        # Pula os pares já analisados<br>        if i == j or set([i, j]) in pares:<br>            continue<br><br>        # Obtém o valor-p do teste de cointegração<br>        coint = ts.coint(df[i], df[j])[1]<br><br>        # Se o valor-p for menor que 0,05, vamos considerar o par como cointegrado<br>        if coint &lt; 0.05:<br>            pares_cointegrados.append((i, j))<br><br>        pares.append(set([i, j]))</pre><p>Um ponto de cuidado é o <a href="https://en.wikipedia.org/wiki/Multiple_comparisons_problem">Problema da Comparação Múltipla</a>. Como o teste estatístico tem um valor limite de 0,05, significa que em 5% das vezes o par será considerado cointegrado, mesmo que não sejam. Uma forma de mitigar esse problema é estudar mais profundamente as duas ações, procurando por razões pelas quais os dois ativos devem ser cointegrados.</p><p>Por exemplo, se descobrirmos que os preços das ações de duas empresas são cointegrados, uma operando no setor educativo e outra no setor de transporte, devemos suspeitar de que se trata apenas de um ruído aleatório, exigindo uma segunda verificação.</p><h4><strong>Estacionariedade</strong></h4><p><a href="https://en.wikipedia.org/wiki/Stationary_process">Variáveis estacionárias</a> são processos estocásticos, <strong>cujas médias e variâncias tendem a não variar com o tempo</strong>. Em outras palavras, elas tendem a retornar a uma média, enquanto sua variância permance a mesma. Pares cointegrados deveriam resultar em spreads estacionários, mas para ter certeza, vamos filtrar dos pares cointegrados, aqueles que não possuem um spread estacionário.</p><p>Se duas variáveis são cointegradas, a diferença entre elas não necessariamente permanecem iguais com o tempo. Isso deve ao fato de que a <strong>cointegração não leva em conta a mangnitude que cada variável move</strong>. Uma ação pode dobrar enquanto outra triplica, e elas ainda podem ser cointegradas se as subidas e descidas permanecem estáveis com o tempo.</p><p>Por esse motivo, ao invés de calcularmos apenas a diferença entre os preços das duas ações, <strong>vamos <em>fitar</em> uma regressão linear, para obter um coeficiente beta, o qual representa a proporção em que uma ação varia mais ou menos que outra.</strong></p><pre>from statsmodels.tsa.stattools import adfuller<br>import statsmodels.api as sm<br><br>cointegrados_spread_estacionario = []<br><br>for par in pares_cointegrados:<br>    acao1 = par[0]<br>    acao2 = par[1]<br><br>    # Ajustar uma regressão linear para obter o beta<br>    A1 = sm.add_constant(df[acao1])<br>    resultado = sm.OLS(df[acao2], A1).fit()<br>    beta = resultado.params[acao1]<br><br>    # Calcula o spread<br>    spread = df[acao2] - beta * df[acao1]<br><br>    # Checa se o spread e a proporção são estacionárias<br>    if adfuller(spread)[1] &lt; 0.05 and adfuller(df[acao1] / df[acao2])[1] &lt; 0.05:<br>        cointegrados_spread_estacionario.append(par)</pre><p>Podemos escolher as ações <strong>TAEE11</strong> (Taesa) e <strong>ELET3</strong> (Eletrobras), que pertecem a empresas no setor de energia elétrica. Conhecendo a relação entre as duas empresas também ajuda a minimzar o efeito do problema da comparação múltipla.</p><pre>acao1 = &#39;TAEE11.SA&#39;<br>acao2 = &#39;ELET3.SA&#39;</pre><pre>empresas_energia = [&#39;TAEE11.SA&#39;, &#39;ELET3.SA&#39;, &#39;CPFE3.SA&#39;, &#39;CMIG4.SA&#39;, &#39;EGIE3.SA&#39;, &#39;ELET6.SA&#39;, &#39;ENGI11.SA&#39;, &#39;EQTL3.SA&#39;, &#39;BOVA11.SA&#39;]<br><br>def teste_coint(acao, lista_acao, df):<br>    &quot;&quot;&quot;<br>    Retorna os valores-p para os testes de cointegração entre a ação e cada item da lista_acao.<br>    &quot;&quot;&quot;<br><br>    coint_p_values = []<br><br>    # Compare the stock chosen with all the other from stock_list<br>    for i in lista_acao:<br><br>        # If they are the same stock return 0, else get the valor-p for the cointegration test<br>        if acao != i:<br>            coint_p_values.append(round(ts.coint(df[acao], df[i])[1], 2))<br>        else:<br>            coint_p_values.append(0)<br><br>    return coint_p_values<br><br>p_values = [teste_coint(acao1, empresas_energia, df), teste_coint(acao2, empresas_energia, df)]<br><br>plt.figure(figsize=(10, 5))<br>plt.title(&#39;Teste de Cointegração entre Cada Ação Escolhida e Outras Empresas no Mesmo Setor&#39;)<br>sns.heatmap(p_values, xticklabels=empresas_energia, yticklabels=[acao1, acao2], cmap=&quot;RdYlGn_r&quot;, annot=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*ds19-XMunODr3knb0qd6PA.png" /></figure><p>Como podemos observar, o par de ações escolhidas são de fato cointegradas. As açoes escolhidas mão são apenas cointegradas entre si, como parece que nenhuma delas é cointegrada com o Ibovespa (mercado) ou com outras empresas no mesmo setor, o que significa que pode não haver nenhum ruído gerado por uma <a href="https://pt.wikipedia.org/wiki/Vari%C3%A1vel_de_confus%C3%A3o">variável de confusão</a> entre elas.</p><h3><strong>Gráficos</strong></h3><h4><strong>Histórico de Preços de Fechamento</strong></h4><p>Não é uma tarefa trivial identificar com certeza pares cointegrados apenas visualizando o gráfico de suas séries temporais. Contudo, podemos ver que a longo prazo as duas ações tendem a subir e cais simultaneamente.</p><pre>plt.figure(figsize=(16, 5))<br>plt.plot(df[acao1], label=acao1)<br>plt.plot(df[acao2], label=acao2)<br><br>plt.title(&quot;Histórico de Preços de Fechamento&quot;)<br>plt.xlabel(&quot;Data&quot;)<br>plt.ylabel(&quot;Preço (R$)&quot;)<br><br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iWR49a_auL7ky9j_zC8mkA.png" /></figure><h4><strong>Z Score (Escore Padrão)</strong></h4><p>Uma forma de ver com maior clareza o movimento em conjunto das ações é calculando o <a href="https://en.wikipedia.org/wiki/Standard_score">z-score</a> dos preços.</p><p>O z-score ou escore padrão mensura o quão longe o valor cru está de sua média, em quantidade de desvios padrão. Ou seja, se uma observação possui um z-score de +2, significa que o valor cru da observação está a 2 desvios padrão acima da média daquela amostra.</p><p>Quando calculamos o z-score de cada variável, a diferença de magnitude entre elas se torna irrelevante, já que estamos analizando o quanto os valores variam ao redor de sua média.</p><pre>def zscore(dados):<br>    &quot;&quot;&quot;<br>    Calcula os z-scores de cada série.<br>    &quot;&quot;&quot;<br><br>    media = dados.mean()<br>    desvio_padrao = dados.std()<br><br>    zscores = (dados - media) / desvio_padrao<br><br>    return zscores</pre><pre>plt.figure(figsize=(16, 5))<br>plt.plot(zscore(df[acao1]), label=f&#39;{acao1} Z-Score&#39;)<br>plt.plot(zscore(df[acao2]), label=f&#39;{acao2} Z-Score&#39;)<br><br>plt.title(&quot;Histórico de Preços de Fechamento&quot;)<br>plt.xlabel(&quot;Data&quot;)<br>plt.ylabel(&quot;Preço (Z-Score)&quot;)<br><br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6IXRra2LUdcuXUE6x2ZaUw.png" /></figure><p>Agora, fica mais aparente que as variáveis possam ser cointegradas.</p><h4><strong>Spread</strong></h4><p>Para calcular o spread, vamos utilizar o mesmo processo de antes: computar como a diferença entre o preço de uma açao e o preço de outra vezes um fator (beta).</p><pre># Fitando uma regressão linear para obter o beta<br>A1 = sm.add_constant(df[acao1])<br>resultado = sm.OLS(df[acao2], A1).fit()<br>beta = resultado.params[acao1]<br><br>spread = df[acao2] - beta * df[acao1]<br><br>plt.figure(figsize=(16, 5))<br><br>plt.plot(spread, label=&#39;Spread&#39;)<br>plt.axhline(spread.mean(), label=&#39;Média do Spread&#39;, color=&#39;black&#39;)<br><br>plt.title(&#39;Spread Entre as Duas Ações&#39;)<br>plt.xlabel(&#39;Data&#39;)<br>plt.ylabel(&#39;Spread (R$)&#39;)<br><br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FRJK77Ci3kHwxqTGsd9FEQ.png" /></figure><p>Como checamos previamente, o spread entre as duas ações resulta em um processo estacionário, o qual tende a retorna a uma média.</p><h4><strong>Spread em Z-Score</strong></h4><p>Outra forma de visualizar a estacionariedade é calculando o z-score do spread. Entretanto, ao invés de calcular o z-score usando a média e o desvio padrão sobre a amostra inteira, vamos usar uma janela móvel (moving window), já que em cada tempo nós não teríamos os dados futuros para calcular essas estatísticas.</p><p>Dessa vez, o z-score representa o quão longe da média o spread está. Então, um z-score alto significa que o spread está mais largo, um z-score baixo significa que o spread está mais apertado e um z-score perto de 0 significa que o spread está próximo a média.</p><pre># Definir o tamanho das janelas móveis<br>janela1 = 1<br>janela2 = 30<br><br># Calcula os z-scores usando o método das janelas móveis<br>zscore_spread = (spread.rolling(janela1).mean() - spread.rolling(janela2).mean()) / spread.rolling(janela2).std()<br><br>plt.figure(figsize=(16, 5))<br>plt.plot(zscore_spread, label=&#39;Spread&#39;)<br><br>plt.axhline(zscore_spread.mean(), color=&#39;black&#39;, label=&#39;Média&#39;)<br>plt.axhline(1.0, color=&#39;red&#39;, linestyle=&#39;dotted&#39;, label=&#39;+1&#39;)<br>plt.axhline(1.75, color=&#39;red&#39;, linestyle=&#39;--&#39;, label=&#39;+1,75&#39;)<br>plt.axhline(-1.0, color=&#39;green&#39;, linestyle=&#39;dotted&#39;, label=&#39;-1&#39;)<br>plt.axhline(-1.75, color=&#39;green&#39;, linestyle=&#39;--&#39;, label=&#39;-1,75&#39;)<br><br>plt.title(&#39;Spread Entre as Duas Ações em Z-Score&#39;)<br>plt.xlabel(&#39;Data&#39;)<br>plt.ylabel(&#39;Spread (Z-Score)&#39;)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_q7BPRuQV8VX4hjJvsVHIA.png" /></figure><p>O gráfico acima torna mais claro que o processo é estacionário. Sempre que o spread vai acima de +1,75 or abaixo de -1,75, ele tende a reverter a uma média.</p><p>Assim, uma estratégia que poderíamos aplicar é de ficar comprado no spread quando está abaixo de -1,75, e ficar vendido quando o spread fica acima de +1,75.</p><pre># Cria uma cópia da série de spread<br>comprado = spread.copy()<br>vendido = spread.copy()<br><br># Se o z-score estiver abaixo de -1,75, não há sinal de ficar comprado<br>comprado[zscore_spread &gt; -1.75] = None<br><br># Se o z-score estiver acima de +1,75, não há sinal de ficar vendido<br>vendido[zscore_spread &lt; 1.75] = None<br><br>plt.figure(figsize=(16, 5))<br><br>plt.plot(spread, label=&#39;Spread&#39;)<br>plt.plot(comprado, color=&#39;green&#39;, linestyle=&#39;None&#39;, marker=&#39;^&#39;, label=&#39;Sinal de Comprado&#39;)<br>plt.plot(vendido, color=&#39;red&#39;, linestyle=&#39;None&#39;, marker=&#39;^&#39;, label=&#39;Sinal de Vendido&#39;)<br><br>plt.title(&#39;Spread entre Duas Ações com Sinais para Ficar Comprado/Vendido&#39;)<br>plt.xlabel(&#39;Data&#39;)<br>plt.ylabel(&#39;Spread (R$)&#39;)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gyr_BW-HqilRM_vVgk9exQ.png" /></figure><p>O gráfico acima mostra que o spread entre as duas ações e os sinais para ficar comprado/vendido surgem sempre que o z-score do spread ultrapassa os limite de -1,75 ou +1,75. Como podemos ver os sinais para ficar comprado (verde) tendem a aparecer antes do spread subir, enquanto os sinais para ficar vendido (vermelho) tendem a aparecer antes do spread cair.</p><h4><strong>Spread com um Beta Móvel</strong></h4><p>Um grave problema com o método acima é o fato de que o coeficiente beta foi calculado regredindo sobre a amostra inteira. Isso não está correto, já que o beta está sendo usado a todo momento, e na realidade, se você está rodando a estratégia em tempo real, você não teria os valores futuros para calcular o beta.</p><p>Por esse motivo, ao invés de calcular o beta com toda a série temporal, nós vamos fazer igual fizemos com os z-scores, <strong>calculando o beta para cada observação em uma janela móvel.</strong></p><p>Além disso, <strong>vamos calcular o beta por meio da divisão entre a covariância e variância</strong> dos dois preços nessa janela. O motivo se deve ao fato de que em janela de tamanhos menores, as propriedades de cointegração (como um spread estável) não se aplicam, já que cointegração só garante que as variáveis movem em conjunto a longo prazo.</p><pre># Define o tamanho da janela móvel<br>janela = 30<br><br># Calcula a covariância, variânca e beta para cada janela<br>cov_movel = df[acao1].rolling(janela).cov(df[acao2])<br>var_movel = df[acao2].rolling(janela).var()<br>beta_movel = cov_movel / var_movel<br><br># Calcula o spread para cada observação da série temporal<br>spread_beta_movel = df[acao2] - beta_movel * df[acao1]<br><br># Calcula a média móvel para suavizar a curva<br>spread_mm1 = spread_beta_movel.rolling(1).mean()<br>spread_mm30 = spread_beta_movel.rolling(janela).mean()<br><br>plt.figure(figsize=(16, 5))<br><br>plt.plot(spread_mm1, label=&#39;Spread&#39;)<br>plt.plot(spread_mm30, label=&#39;Spread 30d Média Móvel&#39;)<br><br>plt.title(&#39;Spread com Beta Móvel&#39;)<br>plt.xlabel(&#39;Data&#39;)<br>plt.ylabel(&#39;Spread (R$)&#39;)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1bfhtRql40Q8kX1XCJdgVw.png" /></figure><p>Como pode-se observar no exemplo acima, o spread com o beta móvel permanece estacionário, apesar de parecer mais volátil que antes. Por conta do cálculo do beta estar sendo feito com uma população muito menor, há uma maior chance de erro e volatilidade.</p><h4><strong>Spread com Beta Móvel em Z-Score</strong></h4><p>Similar ao primeiro exemplo de sprea, podemos também visualizar o spread em uma métrica de z-score. Porém ao invés de utilizar a média e o desvio padrão da amostra toda, também vamos calcularmos por meio de uma janela móvel, já que não temos tais valores futuros.</p><pre># Calcula o spread com média móveis<br>zscore_30_1 = (spread_mm1 - spread_mm30) / spread_beta_movel.rolling(janela).std()<br><br>plt.figure(figsize=(16, 5))<br>plt.plot(zscore_30_1, label=&#39;Spread&#39;)<br><br>plt.axhline(zscore_30_1.mean(), color=&#39;black&#39;, label=&#39;Média&#39;)<br>plt.axhline(1.0, color=&#39;red&#39;, linestyle=&#39;dotted&#39;, label=&#39;+1&#39;)<br>plt.axhline(1.75, color=&#39;red&#39;, linestyle=&#39;--&#39;, label=&#39;+1.75&#39;)<br>plt.axhline(-1.0, color=&#39;green&#39;, linestyle=&#39;dotted&#39;, label=&#39;-1&#39;)<br>plt.axhline(-1.75, color=&#39;green&#39;, linestyle=&#39;--&#39;, label=&#39;-1.75&#39;)<br><br>plt.title(&#39;Spread com Beta Móvel em Z-Score&#39;)<br>plt.xlabel(&#39;Data&#39;)<br>plt.ylabel(&#39;Spread (Z-Score)&#39;)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t_RdcvQODzkhDoabhMIATQ.png" /></figure><p>Por fim, podemos usar os valores em z-score acima para criar uma estratégia de trade, ficando comprado no spread quando o z-score cai abaixo de -1,75 e ficando vendido quando o z-score sobe acima de +1,75.</p><pre># Cria cópias das séries de spread<br>comprado = spread_beta_movel.copy()<br>vendido = spread_beta_movel.copy()<br><br># Se o z-score estiver abaixo de -1,75, não há sinal de ficar comprado<br>comprado[zscore_30_1 &gt; -1.75] = None<br><br># Se o z-score estiver acima de +1,75, não há sinal de ficar vendido<br>vendido[zscore_30_1 &lt; 1.75] = None<br><br>plt.figure(figsize=(16, 5))<br><br>plt.plot(spread_beta_movel, label=&#39;Spread&#39;)<br>plt.plot(comprado, color=&#39;green&#39;, linestyle=&#39;None&#39;, marker=&#39;^&#39;, label=&#39;Sinal de Comprado&#39;)<br>plt.plot(vendido, color=&#39;red&#39;, linestyle=&#39;None&#39;, marker=&#39;^&#39;, label=&#39;Sinal de Vendido&#39;)<br><br>plt.title(&#39;Spread com Beta Móvel e Sinais de Comprado/Vendido&#39;)<br>plt.xlabel(&#39;Data&#39;)<br>plt.ylabel(&#39;Spread (R$)&#39;)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xBOpbVUvXKymGfl0ITuy3g.png" /></figure><h3><strong>Simulação da Estratégia</strong></h3><p>Finalmente, podemos usar os sinais gerados para simular a estratégia de Pairs Trade. Para essa implementação, <strong>ficar comprado no spread significa comprar uma unidade da ação 2 enquanto vendemos uma quantidade de unidades da ação 1 igual ao <em>beta_movel</em></strong>. Por outro lado, <strong>ficar vendido no spread significa vender uma unidade de ação 2 enquanto compramos uma quantidade de unidades de ação 1 igual ao <em>beta_movel</em>.</strong></p><p>O motivo pelo qual compramos e vendemos <em>beta_movel</em> unidades da ação, é porque essa estratégia é neutra em relação ao mercado. Como o beta mensura o quanto a ação 2 move para cada movimento unitário da ação 1, <strong>quando utilizamos o beta como métrica de proporção para o hedge, podemos construir um portfólio no qual os movimentos de cada ação são ajustados para se cancelar</strong>. Dessa forma, lucramos sobre um “preço errado” temporário, não com a direção do mercado, mas com a tendência do spread de se reverter para a média.</p><p>Como essa estratégia possui um investimento inicial nulo, não calculamos o retorno sobre o investimento inicial. Entretanto, podemos calcular o retorno sobre o capital máximo empregado, que é o valor máximo retido em nossas posições em um determinado momento. Assim, podemos entender melhor com que eficiência nossa estratégia gerou o lucro em relação à maior exposição ao risco que assumiu.</p><pre>import numpy as np<br><br>def pair_trade(A1, A2, janela1, janela2):<br>    &quot;&quot;&quot;<br>    Calcula o retorno total da estratégia de pairs trading<br>    &quot;&quot;&quot;<br>    # Garante que o tamanho da janela é válido<br>    if janela2 &lt; 2 or janela1 &lt; 1:<br>        return 0, 0, 0, []<br><br>    # 1. Cálculo do Spread<br>    cov_movel = A1.rolling(window=janela2).cov(A2)<br>    var_movel = A2.rolling(window=janela2).var()<br>    beta_movel = cov_movel / var_movel<br>    spread = A2 - beta_movel * A1<br>    spread_mm1 = spread.rolling(window=janela1).mean()<br>    spread_mm2 = spread.rolling(window=janela2).mean()<br>    spread_std = spread.rolling(window=janela2).std()<br>    zscore = (spread_mm1 - spread_mm2) / spread_std<br><br>    # 2. Simulação de Trading<br>    capital = 0<br>    A1_cont = 0<br>    A2_cont = 0<br>    saldo = []<br>    cap_max = 0  # Acompanha o capital máximo empregado<br><br>    for i in range(len(A1)):<br><br>        # Pula se o sinal não é válido<br>        if np.isnan(zscore.iloc[i]) or np.isnan(beta_movel.iloc[i]):<br>            saldo.append(capital)<br>            continue<br><br>        # Cria variável que checa se exista uma posição aberta<br>        posicao_aberta = (A2_cont != 0)<br><br>        # 2.1 Execução de Trade Baseado no Z-Score<br><br>        # Se o z-score for baixo, o spread é mais apertado, assim compramos ação2 e vendemos ação 1<br>        if zscore.iloc[i] &lt; -1.75 and not posicao_aberta:<br>            A2_cont = 1<br>            A1_cont = -beta_movel.iloc[i]<br><br>        # Se o z-score for alto, o spread é mais largo, assim vendemos ação2 e compramos ação 1<br>        elif zscore.iloc[i] &gt; 1.75 and not posicao_aberta:<br>            A2_cont = -1<br>            A1_cont = beta_movel.iloc[i]<br><br>        # Se o z-score for próximo a zero, o spread está próximo a sua média, assim fechamos nossas posições<br>        elif abs(zscore.iloc[i]) &lt; 0.75 and posicao_aberta:<br>            capital += A1.iloc[i] * A1_cont + A2.iloc[i] * A2_cont<br>            A1_cont = 0<br>            A2_cont = 0<br><br>        # 3. Acompanhamento do Capital Empregado<br><br>        # O capital empregado é o valor absoluto de mercado de todas as posições<br>        cap_atual = abs(A1.iloc[i] * A1_cont) + abs(A2.iloc[i] * A2_cont)<br>        <br>        # Atualiza o capital máximo se o capital atual for maior<br>        cap_max = max(cap_atual, cap_max)<br><br>        # Calcula o valor da carteira ao preço de mercado<br>        valor_carteira = A1.iloc[i] * A1_cont + A2.iloc[i] * A2_cont<br>        valor_total = capital + valor_carteira<br>        saldo.append(valor_total)<br><br>    # 4. Cálculo de Lucro Total<br>    lucro_total = saldo[-1] if saldo else 0<br>    <br>    # Evita divisão por zero se nenhum trade for feito<br>    if cap_max == 0:<br>        return 0, lucro_total, 0, saldo<br><br>    retorno_cap_max = lucro_total / cap_max<br>    <br>    return retorno_cap_max, lucro_total, cap_max, saldo<br><br>retorno, lucro, capital_maximo, historico_saldo = pair_trade(df[acao1], df[acao2], 1, 60)<br><br># Imprime os Resultados<br>print(&quot;--- Performance da Estratégia ---&quot;)<br>print(f&quot;Lucro Total: R${lucro:,.2f}&quot;)<br>print(f&quot;Capital Máximo Empregado: R${capital_maximo:,.2f}&quot;)<br>print(f&quot;Retorno sobre o Capital Máximo: {retorno:.2%}&quot;)<br><br>plt.figure(figsize=(16, 5))<br>plt.plot(historico_saldo)<br><br>plt.title(&#39;Histórico do Saldo do Portfólio&#39;)<br>plt.ylabel(&#39;Lucro (R$)&#39;)<br>plt.xlabel(&#39;Dias&#39;)<br>plt.grid()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LcLfjrAibsLuntSt_WkInA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*OYXh-hQBgTZCmRQSXaYQFQ.png" /></figure><p>O lucro total não parece tão alto, especialmente considerando que a estratégia foi testada em uma amostra de 5 anos. No entanto, quando levamos em conta que a simulação começou com zero dinheiro e que a estratégia compra e vende 1 unidade de ação, um retorno de 149,15% sobre o capital máximo empregado é mais do que aceitável.</p><h4>Índice de Sharpe (Sharpe Ratio)</h4><p>Embora o retorno sobre o capital máximo tenha sido bastante alto, geralmente o desempenho de uma carteira também é medido usando o Índice de Sharpe, que é uma métrica que também considera o risco associado à estratégia.</p><p>O Índice de Sharpe para minha carteira foi muito baixo, o que significa que os retornos diários dessa estratégia foram extremamente voláteis. Portanto, embora a estratégia tivesse um alto retorno, o alto risco associado a ela significava que provavelmente não valia a pena.</p><h3>Próximos passos</h3><p>Existem várias maneiras de tornar esse método mais robusto. Aqui está uma lista de possíveis próximos passos:</p><ul><li>Procurar outros pares de ações, usando métodos mais qualitativos.</li><li>Experimentar métodos diferentes para implementar essa estratégia, além da média móvel (Filtro de Kalman, RNNs, etc.).</li><li>Procurar maneiras de reduzir o risco, aumentando o Índice de Sharpe.</li></ul><h3>Bibliografia</h3><p>Este artigo foi criado usando os seguintes vídeos como referência:</p><ul><li><a href="https://youtu.be/JTucMRYMOyY?si=LNC9XJkdmFQuWpMI">Introduction to Pairs Trading by Quantopian</a></li><li><a href="https://youtu.be/JTucMRYMOyY?si=t9unWJpToEmUMffC">Quant Strategy: Pairs Trading Algorithm (Mean Reversion) by Spencer Pao</a></li><li><a href="https://www.youtube.com/watch?v=vvTKjm94Ars">Cointegration — an introduction by Ben Lambert</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cdb8e2cae902" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>