<?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 Gianluca Baglini on Medium]]></title>
        <description><![CDATA[Stories by Gianluca Baglini on Medium]]></description>
        <link>https://medium.com/@gianlucabaglini?source=rss-d82d98a49fa2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*eSBzB0406xfctywjTCCllQ.jpeg</url>
            <title>Stories by Gianluca Baglini on Medium</title>
            <link>https://medium.com/@gianlucabaglini?source=rss-d82d98a49fa2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 12:12:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gianlucabaglini/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[Trading Comps Analysis in Python]]></title>
            <link>https://medium.com/@gianlucabaglini/trading-comps-analysis-in-python-6c10651b7b35?source=rss-d82d98a49fa2------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c10651b7b35</guid>
            <category><![CDATA[peers]]></category>
            <category><![CDATA[investment-banking]]></category>
            <category><![CDATA[balance-sheet]]></category>
            <category><![CDATA[valuation]]></category>
            <category><![CDATA[trading-companies]]></category>
            <dc:creator><![CDATA[Gianluca Baglini]]></dc:creator>
            <pubDate>Sat, 16 Dec 2023 19:59:13 GMT</pubDate>
            <atom:updated>2023-12-16T20:02:01.942Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will delve into Trading Comps analysis, a fundamental aspect of financial evaluation in the realm of investments. Our focus will be on describing the characteristics and advantages of this approach and provide practical insights by showcasing a real-world application using Python.</p><h3><strong>Introduction</strong></h3><p>A Trading Comparable Analysis is a valuation method used in finance to estimate the value of a company by comparing it to the valuation multiples of similar publicly traded companies. The idea is to use the market prices and financial statement data of comparable companies as a benchmark to assess the fair market value of the company being analyzed.</p><p>Unlike the Discounted Cash Flow model described in a <a href="https://medium.com/@gianlucabaglini/automate-your-discounted-cash-flow-model-in-python-cdf98eb0924d">previous article</a>, Trading Comps is a relative valuation method that assesses a company’s value by comparing it to a group of peers. This approach assumes that comparable companies are fairly valued by the market. While DCF provides a detailed and flexible analysis, Trading Comps offers a snapshot of the current market sentiment by relying on observed market multiples. Analysts often use a combination of these methods to obtain a comprehensive understanding of a company’s valuation. Each approach has its strengths and is suited to different circumstances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*bpGd951Uldg4WOGMv3pWmg.png" /></figure><h3>An example: Tesla Inc.</h3><p>To illustrate the application of the analysis method, we first need to establish an objective company and create a list of peers for comparison. To maintain consistency with the previous article, we will continue to analyse Tesla as the chosen company. Despite the challenge of identifying direct peers for Tesla due to its unique nature, we will consider a basket of large-cap technology and automotive U.S. stocks for comparison: General Motors (GM), Google (GOOGL), Amazon (AMZN), Tencent Holdings (TCEHY), Intel Corporation (INTC), Apple (AAPL), and Ford (F).</p><p>Following the approach of previous articles, we will utilize the <a href="https://eodhd.com/">Python EOD Library </a>to retrieve fundamental data for stocks using the <em>client.get_fundamental_equity </em>function. This package provides excellent versatility and ease of use, making it an ideal choice for extracting companies’ prices and financial statement data. We begin by importing income statement data for our target firm and all companies in our comparison universe.</p><pre>stock = &quot;TSLA.US&quot; <br>peers = [&quot;GM.US&quot;, &quot;GOOGL.US&quot;, &quot;AMZN.US&quot;, &quot;TCEHY.US&quot;, &quot;INTC.US&quot;, &quot;AAPL.US&quot;, &quot;F.US&quot;]<br><br>df_fund = pd.DataFrame()<br>all_ticks = [stock] + peers<br><br>for tick in all_ticks:<br>    print(tick)<br>    inc_stat = client.get_fundamental_equity(tick, filter_=&#39;Financials::Income_Statement::yearly&#39;) <br>    df_temp = pd.DataFrame.from_dict(inc_stat, orient=&quot;index&quot;).sort_index()<br>    df_temp.index = pd.to_datetime(df_temp.index).year.astype(str)<br>    df_temp[&quot;ticker&quot;] = tick<br>    df_temp = df_temp.set_index([df_temp[&quot;ticker&quot;], df_temp.index])<br>    df_fund= pd.concat([df_fund, df_temp],axis = 0)<br><br>df_fund = df_fund.replace(to_replace={None: np.nan, type(None):  np.nan}, inplace=False)<br>df_fund.index.names = [&quot;ticker&quot;, &quot;year&quot;]</pre><p>Then we compute three key metrics for the trading comps analysis:</p><ul><li><strong>Revenue Growth</strong> measures the percentage increase in a company’s revenue over a specific period. A positive revenue growth indicates the company’s ability to increase its sales, reflecting positive market demand and potential business expansion.</li><li><strong>EBITDA Margin</strong> represents the proportion of a company’s revenue that translates into EBITDA. It is calculated by dividing EBITDA by total revenue. EBITDA margin is a valuable indicator of operational efficiency, as it shows the company’s ability to generate earnings from its core business operations, excluding certain non-operating expenses.</li><li><strong>Profit Margin</strong> measures the percentage of revenue that translates into net profit after deducting all operating expenses, interest, and taxes. It is a key indicator of a company’s profitability and cost management. A higher profit margin indicates effective cost control and operational efficiency.</li></ul><p>Also, we focus on the last three year of data and filter out information reported before 2020. Note that certain companies may operate on a fiscal year not ending on December 31st. In such cases, there might be a mismatch as we compare data from yearly reports released at different points in time. To avoid this issue, we suggest replacing <em>yearly</em> with <em>quarterly</em> in the query above.</p><pre>df_fund = df_fund[[&quot;totalRevenue&quot;, &quot;netIncome&quot;, &quot;ebitda&quot;]].astype(float)<br>df_fund[&quot;revGrowth&quot;] = df_fund.groupby(&quot;ticker&quot;)[&quot;totalRevenue&quot;].pct_change()<br>df_fund[&quot;ebitdaMargin&quot;] = df_fund[&quot;ebitda&quot;] / df_fund[&quot;totalRevenue&quot;]<br>df_fund[&quot;profitMargin&quot;] = df_fund[&quot;netIncome&quot;] / df_fund[&quot;totalRevenue&quot;]<br>df_fund = df_fund[df_fund.index.get_level_values(1) != &quot;2023&quot;] ## adjust fiscal year<br>df_last = df_fund.groupby(level=[&#39;ticker&#39;]).tail(3)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/0*PMJqlEYyo_5dWkZi.png" /><figcaption>Image by author</figcaption></figure><p>Before proceeding to the peer comparison, we need to gather additional data. Specifically, we will retrieve our target company’s market capitalization and enterprise value (EV), as these values will be used in computing the trading multiples.</p><pre>df_data = pd.DataFrame(index =all_ticks)<br>marketCap = np.zeros(len(all_ticks))<br>enterpriseValue = np.zeros(len(all_ticks))<br><br>c = 0<br>for tick in all_ticks:<br>    print(tick)<br>    marketCap[c] =  client.get_fundamental_equity(tick, filter_=&#39;Highlights::MarketCapitalization&#39;)<br>    enterpriseValue[c] = client.get_fundamental_equity(tick, filter_=&#39;Valuation::EnterpriseValue&#39;)<br>    c+=1<br>    <br>df_data[&quot;marketCap&quot;] = marketCap<br>df_data[&quot;enterpriseValue&quot;] = enterpriseValue</pre><pre>df_all = pd.merge(df_data, df_last.reset_index(level=1, drop=False), left_index=True, right_index=True)<br>df_all = df_all.set_index([b.index, &quot;year&quot;])<br>df_all.index.names = [&quot;ticker&quot;, &quot;year&quot;]</pre><h3>Trading Multiples</h3><p>Trading multiples, also known as valuation multiples or financial ratios, are metrics used in financial analysis to compare the valuation of a company’s stock relative to its financial performance or certain fundamental indicators. Although there are numerous ratios employed in equity research and financial analysis, three primary ones, as illustrated in this example, include:</p><ul><li><strong>Price-to-Earnings (P/E) </strong>compares a company’s stock price to its earnings per share (EPS). It reflects investors’ expectations of a company’s future earnings growth.</li><li><strong>Enterprise Value-to-EBITDA (EV/EBITDA) </strong>compares a company’s enterprise value (market value of equity plus debt minus cash) to its Earnings Before Interest, Taxes, Depreciation, and Amortization (EBITDA).</li><li><strong>Enterprise Value-to-Revenue</strong> assess how the market values a company’s revenue-generating capacity. A higher ratio may indicate that the market values the company’s revenue more favorably, while a lower ratio may suggest a more conservative valuation relative to revenue.</li></ul><pre>df_all[&quot;EVofRevenue&quot;] = df_all[&quot;enterpriseValue&quot;] / df_all[&quot;totalRevenue&quot;]<br>df_all[&quot;EVofEbitda&quot;] = df_all[&quot;enterpriseValue&quot;] / df_all[&quot;ebitda&quot;]<br>df_all[&quot;PofE&quot;] = df_all[&quot;marketCap&quot;] / df_all[&quot;netIncome&quot;]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rx2ZnP-GMZQpJ0fH.png" /><figcaption>Image by author</figcaption></figure><p>With our valuation metrics for each company, we can now compute statistics for the entire peers’ universe. This will assist us in visualizing where the target company falls within the distribution of its peers in relation with the group’s <em>mean, median, maximum</em> and <em>minimum </em>values. Higher P/E multiples than those of peers suggest that investors are paying more for the company’s earnings. The same logic applies to the other two ratios. This would indicate that the company may be overpriced and not represent a good investment opportunity.</p><pre>df_comp = df_all[[&quot;totalRevenue&quot;, &quot;ebitda&quot;, &quot;netIncome&quot;, &quot;revGrowth&quot;, &quot;ebitdaMargin&quot;, &quot;profitMargin&quot;, &quot;EVofRevenue&quot;, &quot;EVofEbitda&quot;, &quot;PofE&quot;]].unstack(level=&#39;year&#39;)<br>df_comp.loc[&quot;Minimum&quot;, :] = df_comp.min()<br>df_comp.loc[&quot;Mean&quot;, :] = df_comp.mean()<br>df_comp.loc[&quot; Median&quot;, :] = df_comp.median()<br>df_comp.loc[&quot;Maximum&quot;, :] = df_comp.max()<br>df_comp.loc[:, &quot;revGrowth&quot;:]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kE40n6waok5_RTOh.png" /></figure><pre>year = &quot;2022&quot;<br>df_comp.columns = df_comp.columns.map(&#39;_&#39;.join)<br>df_comp = df_comp.loc[:, df_comp.columns.str.contains(year)]<br>df_comp.columns = [i[:-5] for i in df_comp.columns]</pre><p>As the last step, we calculate the implied share prices for the target company using the group statistics and Tesla’s latest financial statement data. This can provide us with ranges for where Tesla’s price could be if its multiples were the lowest, highest, or around the mean within its peer group. To do that, we will first derive new estimates for EV <em>based on </em>Revenue and EBITDA.</p><pre>outshares = client.get_fundamental_equity(stock, filter_=&#39;SharesStats::SharesOutstanding&#39;)<br>df_price = df_comp.loc[&quot;Minimum&quot;:, &quot;EVofRevenue&quot;:]<br># Financial metric<br>df_price[stock[:-3]+&quot;_revenue&quot;] = df_comp.loc[stock, &quot;totalRevenue&quot;]<br>df_price[stock[:-3]+&quot;_ebitda&quot;] = df_comp.loc[stock, &quot;ebitda&quot;]<br>df_price[&quot;EPS&quot;] = df_comp.loc[stock, &quot;netIncome&quot;] / outshares<br># Enterprise Value<br>df_price[&quot;EV_revenue&quot;] = df_price[stock[:-3]+&quot;_revenue&quot;] *df_price[&quot;EVofRevenue&quot;]<br>df_price[&quot;EV_ebitda&quot;] = df_price[stock[:-3]+&quot;_ebitda&quot;] *df_price[&quot;EVofEbitda&quot;]</pre><p>To derive the Implied Share Price from the Enterprise Value, the first step is to compute the Equity Value, which represents the residual interest in the assets of a company after deducting liabilities. The formula is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*cziAFGRijvgZn2_xb-gl4Q.png" /></figure><p>and then divide this quantity by the number of outstanding common shares. This will give us a range of prices for Tesla based on the three metrics:<em> Revenue</em>, <em>EBITDA </em>and <em>Net Income </em>of similar public companies companies</p><pre>bs = client.get_fundamental_equity(stock, filter_=&#39;Financials::Balance_Sheet::yearly&#39;)<br>df_price[&quot;cash&quot;] = float(pd.DataFrame(bs).loc[&quot;cash&quot;].values[0])<br>df_price[&quot;debt&quot;] = float(pd.DataFrame(bs).loc[&quot;totalLiab&quot;].values[0])<br>df_price[&quot;outshares&quot;] = outshares<br>df_price[&quot;EQ_revenue&quot;] = df_price[&quot;EV_revenue&quot;] +  df_price[&quot;cash&quot;] - df_price[&quot;debt&quot;]<br><br>df_price[&quot;EQ_ebitda&quot;] = df_price[&quot;EV_ebitda&quot;] +  df_price[&quot;cash&quot;] - df_price[&quot;debt&quot;]<br>df_price[&quot;EQ_netIncome&quot;] = df_price[&quot;PofE&quot;] *  df_price[&quot;EPS&quot;] * df_price[&quot;outshares&quot;]<br><br>df_price[&quot;ISP_revenue&quot;] = df_price[&quot;EQ_revenue&quot;] / df_price[&quot;outshares&quot;]<br>df_price[&quot;ISP_ebitda&quot;] = df_price[&quot;EQ_ebitda&quot;] / df_price[&quot;outshares&quot;]<br>df_price[&quot;ISP_netIncome&quot;] = df_price[&quot;EQ_netIncome&quot;] / df_price[&quot;outshares&quot;]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/0*-o-7SdDnmaB2MGul.png" /></figure><h3>Conclusion</h3><p>In conclusion, the analysis of Tesla through trading comps provides valuable insights into the company’s relative valuation within the automotive and tech industry. By comparing key financial metrics and multiples with those of its peers, we gain a comprehensive understanding of Tesla’s market position and investor sentiment. The examination of trading multiples such as Price-to-Earnings (P/E), Enterprise Value-to-EBITDA (EV/EBITDA), and Price-to-Earnings (P/E) sheds light on Tesla’s valuation relative to its earnings, operational efficiency, and revenue generation. While the analysis underscores Tesla’s remarkable growth and market dominance, it also emphasizes the importance of considering various factors, such as industry dynamics and growth prospects, for a complete evaluation. As Tesla continues to shape the future of electric vehicles and sustainable energy, this trading comps analysis serves as a valuable tool for investors seeking to make informed decisions in the dynamic landscape.</p><p><em>References:</em><br>Full code available <a href="https://github.com/gbaglini/baglinifinance/">here</a><br>Baglini Finance <a href="https://baglinifinance.com/">website</a><br>EOD Financial Academy <a href="https://eodhd.com/financial-academy/fundamental-analysis-examples/trading-comps-analysis-in-python/">link</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c10651b7b35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time Invariant Portfolio Protection]]></title>
            <link>https://medium.com/@gianlucabaglini/time-invariant-portfolio-protection-be15e81915b6?source=rss-d82d98a49fa2------2</link>
            <guid isPermaLink="false">https://medium.com/p/be15e81915b6</guid>
            <category><![CDATA[investment-strategy]]></category>
            <category><![CDATA[portfolio-management]]></category>
            <category><![CDATA[risk-management]]></category>
            <category><![CDATA[capital-protection]]></category>
            <dc:creator><![CDATA[Gianluca Baglini]]></dc:creator>
            <pubDate>Tue, 05 Dec 2023 15:12:48 GMT</pubDate>
            <atom:updated>2023-12-05T15:12:48.188Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article we are going to present a discussion on portfolio insurance strategies. Here we will focus on an extension of the original model introduced by Estep and. Kritzman (1988), namely Time Invariant Portfolio Protection.</p><p>Constant Proportion Portfolio Insurance (CPPI) and Time-Invariant Portfolio Protection (TIPP) are two of the most famous portfolio insurance strategies that play an important role in the realm of investment management and risk mitigation. These strategies are designed to address the fundamental challenge of balancing the pursuit of financial growth with the imperative of capital protection against market downturns. Ideally, the guaranteed protection is achieved at the lowest possible premium for the investors.</p><p><strong>THE TIPP MODEL</strong></p><p>CPPI is a dynamic approach that adapts to market conditions by actively adjusting the allocation between risky and risk-free assets, striving to preserve a predefined floor value while allowing participation in market upswings. In contrast, TIPP employs a more conservative methodology, where a fixed percentage of portfolio value is guaranteed throughout the investment horizon and the risky exposure is adjusted accordingly. The main difference is that while in CPPI the floor grows at a constant rate, in TIPP it is a function of the portfolio value and thus it has a path dependent nature. These two strategies offer distinct advantages and drawbacks, making them valuable tools for investors with varying risk appetites, investment objectives, and preferences for portfolio management.</p><p>Both strategies prescribe an allocation to the risky asset that is equal to the cushion (difference between V0 and F0) multiplied by a risk-aversion coefficient <em>m</em>. The higher the coefficient, the more aggressive the strategy, and conversely. The allocation to the risk-free is determined residually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/216/1*78RmG3JIehsTW9akoOSaSA.png" /></figure><p>Let’s show an example. If we assume an initial invested capital of 100$, an initial floor of 85$, and a multiplier of 4, we obtain a risky exposure of 60 (4x(100–85)) and risk-free allocation of 40. Many finance practitioners have introduced new extensions to the plain vanilla model. For instance, setting on the maximum and minimum exposure will avoid, on one side, excessive risk taking and on the other hand, the absorption in state of 100% risk-free allocation. In our experiment, we force the exposure to lie in the range 40 to 120%.</p><p>Figure (a) and Figure (b) show examples of the two methodologies. In the first case, the protection grows over time at a fixed rate as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/0*dDLAFSY4voZtLHdx.png" /><figcaption>(a) Constant Protection Portfolio Insurance</figcaption></figure><p>In the second case, the floor adjusts upwards to maintain the same level protection with respect to the portfolio value at each point in time t:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/0*b-B1qL6S5g5js2Ky.png" /><figcaption>(b) Time Invariant Portfolio Insurance</figcaption></figure><p>Now that we have explained the difference between the two approaches we focus on the statistical properties of TIPP. To do that, we follow the methodological approach used for CPPI by Khuman et al. (2008) and implement the same analysis to this new technique. In particular, we investigate the behavior of our risk metrics obtained by applying TIPP on two simulated processes: Geometric Brownian Motion (GBM) and Jump Diffusion Process (JDP). These processes represent a proxy for our risky financial assets. Given that we set an expected negative jump size to reflect the negative skewness of financial markets, we allow for fair comparison between the two processes by introducing a positive compensator to the JDP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/0*Th17BBERO-Jtf6it.jpg" /><figcaption>( c ) Geometric Brownian Motion vs Jump Diffusion Process</figcaption></figure><p>To validate the effectiveness of the strategy under two scenarios, we consider four relevant risk metrics:</p><ul><li>Average Final Payoff</li><li>Probability of Gap i.e. a floor breach</li><li>Excess Sharpe Ratio</li><li>Maximum Drawdown</li></ul><p><strong>RESULTS</strong></p><p>The first analysis aims to understand the properties of TIPP when the multiplier (<em>m</em>) and the rebalancing frequency (<em>n</em>) are let vary. The below table shows the multidimensional structure for our measures of interest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/0*uuCSnqtEVdH-q9i-.png" /><figcaption>(d) Experiment Results</figcaption></figure><p>In general, the introduction of negative market jumps reduces by 10% on average the final payoff and increases the likelihood of a floor violation by 2–4%. For low multipliers and frequent rebalancing, the graph shows similar values of maximum drawdown. In this case, the presence of jumps does not impact the results significantly. Conversely, a 3% higher drawdown can be seen at the top of the surface when the jump is added. In terms of Sharpe ratio, the table indicates a strong preference for low exposure and daily rebalancing. In accordance with our initial intuition, higher <em>m </em>increases volatility more than what it does on performance. Considering the capital protection peculiarity of the TIPP and the impact of <em>m </em>on volatility and transaction costs, we believe that setting a multiplier in a 2 to 4 range would considerably benefit the implementation and monitoring of such an approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/0*BT6h92Okc7Ompcbt.png" /><figcaption>(e) Impact of Transaction Fees</figcaption></figure><p>Then we investigate the impact of transaction costs and turnover effect. Given the more volatile nature, the transaction fees incurred in the case of JDP will always exceed those paid in the GBM scenario. For this reason, we will conduct our analysis for the JDP case only. Management fees are not included in this case.</p><p>As the percentage fee increases, the final portfolio value falls exponentially. In particular, for the case of <em>tc </em>= 0<em>.</em>001, the net payoff is not significantly altered compared to the zero fee case. In contrast, we see a substantial impact for <em>m ≥ </em>4 and higher transaction costs. For <em>m </em>= 9, only a -10% risk asset weekly return would result in a full portfolio rebalance from maximum (120) to minimum (40) exposure.</p><p><strong>CONCLUSION</strong></p><p>The result of the study reveals that the strength of TIPP varies significantly across the two stochastic processes. The model was better able to mitigate losses in the GBM compared to the JDP case, indicating a high sensitivity to the risky asset return distribution. Moreover, we saw that high volatility and transaction costs impair the usage of multipliers above 5 and that, to increase the exposure and avoid stalling, investors in TIPP could set a lower bound of minimum level of risky asset to be hold in the portfolio instead. Conversely, increasing leverage does not have positive results on performance. Finally, we highlight how having a cost efficient trade execution represents a major constraint for TIPP fund managers, with that aspect becoming increasingly important for more aggressive funds</p><p><em>References:</em><br>SSRN: <a href="https://papers.ssrn.com/sol3/papers.cfm?abstract_id=4602283">https://papers.ssrn.com/sol3/papers.cfm?abstract_id=4602283</a><br>Quantpedia: <a href="https://quantpedia.com/time-invariant-portfolio-protection/">https://quantpedia.com/time-invariant-portfolio-protection/</a><br>Website: <a href="https://baglinifinance.com/blog/time-invariant-portfolio-protection/">https://baglinifinance.com/blog/time-invariant-portfolio-protection/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be15e81915b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automate your Discounted Cash Flow model in Python]]></title>
            <link>https://medium.com/@gianlucabaglini/automate-your-discounted-cash-flow-model-in-python-cdf98eb0924d?source=rss-d82d98a49fa2------2</link>
            <guid isPermaLink="false">https://medium.com/p/cdf98eb0924d</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[discounted-cash-flow]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[valuation]]></category>
            <category><![CDATA[investment-banking]]></category>
            <dc:creator><![CDATA[Gianluca Baglini]]></dc:creator>
            <pubDate>Wed, 22 Nov 2023 11:51:38 GMT</pubDate>
            <atom:updated>2023-11-22T11:51:38.509Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>The Discounted Cash Flow (DCF) model stands as one of the most widely employed financial models for investment evaluation. This model plays a crucial role in estimating the intrinsic value of a public company’s stock. The intrinsic share price is determined through an analysis of the company’s current and anticipated future cash flows.</p><p>In essence, the intrinsic value reflects the perceived worth of a company’s stock based on its fundamental financials. Comparing this intrinsic value with the current market valuation of a company provides valuable insights into the investment potential. This comparison aids in gauging whether a particular firm is a sound investment by indicating if its stock is currently undervalued or overvalued.</p><h3>A real case-study: Tesla</h3><p>For this case study, we will employ the <a href="https://eodhd.com/r/?ref=E1ATJB8Z">EOD Python Library</a> to seamlessly download financial statement data directly into our Jupyter notebook via the API service. In our illustrative example, we focus our analysis on Tesla stock (ticker = “TSLA.US”), a subject that sparks considerable debate on Wall Street due to its intriguing valuation. Our analysis kicks off by retrieving the most recent company data using the <em>client.get_fundamental_equity</em> function. This function can be used to obtain the three main documents that constitute an annual company report: the Balance Sheet, Income Statement, and Cash Flow Statement. Collectively, these documents offer a comprehensive overview of the company’s financial health and performance, forming the cornerstone of our analytical process.</p><pre>import eod <br>client = EodHistoricalData(api_key)</pre><pre>stock_ticker = &quot;TSLA.US&quot;<br><br>#download BS, IS, CFS from EOD historical data<br>BalanceSheet = client.get_fundamental_equity(stock_ticker, filter_=&#39;Financials::Balance_Sheet::yearly&#39;)<br>IncomeStat = client.get_fundamental_equity(stock_ticker, filter_=&#39;Financials::Income_Statement::yearly&#39;)<br>CashFlowStat = client.get_fundamental_equity(stock_ticker, filter_=&#39;Financials::Cash_Flow::yearly&#39;)<br>OutShares = client.get_fundamental_equity(stock_ticker, filter_=&#39;SharesStats::SharesOutstanding&#39;)<br><br># transpose and concatenate<br>df_bal = pd.DataFrame(BalanceSheet).T<br>df_inc = pd.DataFrame(IncomeStat).T<br>df_cfs = pd.DataFrame(CashFlowStat).T<br>df_all = pd.concat([df_bal, df_inc, df_cfs], axis=1).sort_index()<br>df_all = df_all.loc[:, ~df_all.columns.duplicated()] #remove duplicated columns</pre><p>We begin by executing some preprocessing steps to present our data in a more suitable format. This involves tasks such as converting data to float type and replacing datetime entries with the corresponding year. Given the large size of the table, we filter it taking a few sample columns and show the result below:</p><pre>#convert all None values to np.NaN datatypes<br>df = df_all.iloc[-10 :, 3:,].applymap(lambda x: float(x) if x is not None else np.NaN)<br>df.index = pd.to_datetime(df.index)<br>df.index = df.index.year<br>df = df.applymap(format_value)<br>df.head(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*RQrD_zmTlZmg0viVoWq4XA.png" /><figcaption>Image by author</figcaption></figure><p>The table serves as a snapshot for the entire dataframe, offering a glimpse into its structure ensuring that the content is displayed accurately. To facilitate visualization, the values have been converted to <em>floating-point </em>numbers and are expressed in millions of dollars ($).</p><h3>Preparing the DCF ingredients</h3><p>After retrieving the financial company data, we can now compute the value of all the variables required in a Discounted Cash Flow model:</p><ul><li>% Revenue Growth</li><li>% Ebit/Sales</li><li>% D&amp;A/Sales</li><li>% Capex/Sales</li><li>% <strong>Δ</strong> Net Working Capital/ Sales</li><li>% Tax/Ebit</li><li>Ebiat = Earning before interests after taxes</li></ul><pre># compute % of sales and % of ebit variables<br>df[&quot;rev_growth&quot;] = df[&quot;totalRevenue&quot;].pct_change()<br>df[&quot;delta_nwc&quot;] = df[&quot;netWorkingCapital&quot;].diff()<br>df[&quot;ebit_of_sales&quot;] = df[&quot;ebit&quot;]/df[&quot;totalRevenue&quot;]<br>df[&quot;dna_of_sales&quot;] = df[&quot;depreciationAndAmortization&quot;]/df[&quot;totalRevenue&quot;]<br>df[&quot;capex_of_sales&quot;] = df[&quot;capitalExpenditures&quot;]/df[&quot;totalRevenue&quot;]<br>df[&quot;nwc_of_sales&quot;] = df[&quot;delta_nwc&quot;]/df[&quot;totalRevenue&quot;]<br>df[&quot;tax_of_ebit&quot;] = df[&quot;taxProvision&quot;]/df[&quot;ebit&quot;]<br>df[&quot;ebiat&quot;] = df[&quot;ebit&quot;] - df[&quot;taxProvision&quot;]<br>last_year = df.iloc[-1, :]</pre><p>Also, we store data from the most recent financial statement in the variable <em>last_year</em>. This will be helpful to calculate our projections through linear interpolation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nNtGxtWfkQA9SpNROlYEAA.png" /><figcaption>Image by author</figcaption></figure><h3>Assumptions</h3><p>The assumptions in a Discounted Cash Flow (DCF) analysis are foundational elements that significantly influence the accuracy and reliability of the valuation. The DCF method relies on projecting future cash flows and discounting them back to their present value. Assumptions about growth rates, discount rates, terminal values, and other factors shape these projections. An example of how the sensitivity to changes in these assumptions impact the final valuation will be shown in the last chapter.</p><p>In this case study, we develop a 10-year DCF, implying that our projections extend until the year 2032. The other variables are assumed as follows:</p><ul><li>N = years of projections = 10</li><li>% Revenue Growth = 7%</li><li>% Ebit/Sales = 23%</li><li>% D&amp;A/Sales = 3%</li><li>% Capex/Sales = 5%</li><li>% <strong>Δ</strong> Net Working Capital/ Sales = 5%</li><li>% Tax/Ebit = 21%</li><li>TGR = 2.5%</li></ul><pre>n = 10<br>revenue_growth_T = 0.07<br>ebit_perc_T = 0.23<br>tax_perc_T = 0.21<br>dna_perc_T = 0.03<br>capex_perc_T = 0.05<br>nwc_perc_T = 0.05<br>TGR = 0.025</pre><h3>Creating the DCF projections</h3><p>Now that our model components are in place, it is opportune to delve into considerations regarding the company’s future values. In this scenario, the goal is to model the trajectories of the variables in accordance with our expectations of the company and the industry future developments. For the sake of simplicity, we make the assumption of a linear trend for values from time t+1 to T. Thus we assume a constant rate of change of our model variables. Despite being a stringent assumption, linear interpolation is often use to model the value at intermediate dates between the starting value and the last projection.</p><pre>def interpolate(initial_value, terminal_value, nyears):<br>    return np.linspace(initial_value, terminal_value, nyears)</pre><pre>years = range(df.index[-1]+1, df.index[-1] + n + 1)<br>df_proj = pd.DataFrame(index=years, columns=df.columns)<br># linear interpolation<br>df_proj[&quot;rev_growth&quot;] = interpolate(last_year[&quot;rev_growth&quot;], revenue_growth_T, n) <br>df_proj[&quot;ebit_of_sales&quot;] = interpolate(last_year[&quot;ebit_of_sales&quot;], ebit_perc_T, n) <br>df_proj[&quot;dna_of_sales&quot;] = interpolate(last_year[&quot;dna_of_sales&quot;], dna_perc_T, n) <br>df_proj[&quot;capex_of_sales&quot;] = interpolate(last_year[&quot;capex_of_sales&quot;], capex_perc_T, n) <br>df_proj[&quot;tax_of_ebit&quot;] = interpolate(last_year[&quot;tax_of_ebit&quot;], tax_perc_T, n) <br>df_proj[&quot;nwc_of_sales&quot;] = interpolate(last_year[&quot;nwc_of_sales&quot;], nwc_perc_T, n) <br># cumulative values<br>df_proj[&quot;totalRevenue&quot;] = last_year[&quot;totalRevenue&quot;] *(1+df_proj[&quot;rev_growth&quot;]).cumprod() <br>df_proj[&quot;ebit&quot;] = last_year[&quot;ebit&quot;] *(1+df_proj[&quot;ebit_of_sales&quot;]).cumprod() <br>df_proj[&quot;capitalExpenditures&quot;] = last_year[&quot;capitalExpenditures&quot;] *(1+df_proj[&quot;capex_of_sales&quot;]).cumprod() <br>df_proj[&quot;depreciationAndAmortization&quot;] = last_year[&quot;depreciationAndAmortization&quot;] *(1+df_proj[&quot;dna_of_sales&quot;]).cumprod() <br>df_proj[&quot;delta_nwc&quot;] = last_year[&quot;delta_nwc&quot;] *(1+df_proj[&quot;nwc_of_sales&quot;]).cumprod() <br>df_proj[&quot;taxProvision&quot;] = last_year[&quot;taxProvision&quot;] *(1+df_proj[&quot;tax_of_ebit&quot;]).cumprod() <br>df_proj[&quot;ebiat&quot;] = df_proj[&quot;ebit&quot;] - df_proj[&quot;taxProvision&quot;]</pre><p>The last step before moving to the WACC estimation is to calculate the FCF by using the equation below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*Q-FEdaal-jGE4EcbxWIprg.png" /></figure><pre>df_proj[&quot;freeCashFlow&quot;] = df_proj[&quot;ebiat&quot;] + df_proj[&quot;depreciationAndAmortization&quot;] - df_proj[&quot;capitalExpenditures&quot;] - df_proj[&quot;delta_nwc&quot;]</pre><h3>Weighted Average Cost of Capital (WACC)</h3><p>For the calculation of the WACC, we will need to retrieve more data from the <a href="https://eodhd.com/r/?ref=E1ATJB8Z">EOD database</a>:</p><ul><li>Company’s Beta</li><li>Company’s Market Capitalization</li><li>10-year US Treasury Rate, as proxy for the risk-free rate</li><li>Yield-to-Maturity of Tesla’s bonds</li><li>Equity Risk Premium, from <a href="https://pages.stern.nyu.edu/~adamodar/New_Home_Page/">Damodaran website</a></li></ul><h4>Cost of Equity</h4><p>According to the Capital Asset Pricing Model (CAPM), the cost of equity is often calculated as the expected rate of return on the company’s equity, and it is represented by the formula</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*YlNLz8TPWvrvvM7IqUL_SQ.png" /></figure><p>Thus, we first need to collect data on the company’s market capitalization and beta i.e. the sensitivity to market returns, the risk-free rate (here we use 10-y US treasury as proxy) and the equity risk premium</p><pre># company&#39;s beta and marketcap<br>beta = client.get_fundamental_equity(stock_ticker, filter_=&#39;Technicals::Beta&#39;)<br>marketcap = client.get_fundamental_equity(stock_ticker, filter_=&#39;Highlights::MarketCapitalization&#39;)<br><br># risk-free rate<br>US10Y = client.get_prices_eod(&quot;US10Y.INDX&quot;, period=&#39;d&#39;, order=&#39;a&#39;)<br>US10Y = pd.DataFrame(US10Y).set_index(&quot;date&quot;)[&quot;adjusted_close&quot;]<br>US10Y.rename(&quot;10Y&quot;, inplace=True)<br>rf_rate = US10Y.values[-1] /100<br><br># get ERP<br>excel_url = &quot;https://www.stern.nyu.edu/~adamodar/pc/datasets/histimpl.xls&quot;<br>df_ERP = pd.read_excel(excel_url, skiprows=6)<br>df_ERP = df_ERP.dropna(subset=[&quot;Year&quot;]).iloc[:-1, :].set_index(&quot;Year&quot;)<br>ERP = df_ERP[&quot;Implied ERP (FCFE)&quot;].values[-1]</pre><pre>CostOfEquity = beta*(ERP) + rf_rate</pre><p>Tesla Inc.’s cost of equity stands at 17.9%. This is attributed, on one hand, to the stock’s heightened sensitivity to market returns (beta), and on the other hand, to the elevated interest rate environment recorded in 2023.</p><h4>Cost of Debt</h4><p>We will use the yield-to-maturity (YTM) of bond issues as proxy for the Tesla’s cost of debt. Bond data can be retrieved either through the <a href="https://eodhd.com/financial-apis-blog/types-feature-for-search-api/">Search API</a> or <a href="https://eodhd.com/financial-apis/exchanges-api-list-of-tickers-and-trading-hours/">Exchange API</a> function. In the latter case, we will need to pass the code <em>BOND</em> as exchange name.</p><pre>import requests<br>url = f&#39;https://eodhd.com/api/exchange-symbol-list/BOND?api_token={apikey}&amp;fmt=json&amp;delisted=1&#39;<br>data = requests.get(url).json()<br>bond_issues = pd.DataFrame(data)<br>tsla_bond_issues = bond_issues[bond_issues[&quot;Name&quot;].str.contains(&quot;Tesla&quot;)]</pre><pre>YTM = np.zeros(len(tsla_bond_issues))<br>today = datetime.now()<br>c = 0<br><br>for i in tsla_bond_issues[&quot;Code&quot;]:<br>    bond_data = client.get_fundamentals_bonds(i, bond_only=1)<br>    YTM[c] = bond_data[&quot;YieldToMaturity&quot;]<br>    c+=1<br><br>tsla_bond_issues[&quot;YTM&quot;] = YTM<br>CostOfDebt = tsla_bond_issues[&quot;YTM&quot;].mean() /100</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*ar0OdhL8cI7eDH_5KiMAlw.png" /><figcaption>Image by author</figcaption></figure><p>Hence, we will adopt 3.885% as a proxy for the company’s cost of debt. The final step involves applying the Weighted Average Cost of Capital (WACC) formula. This is a weighted average, with the weights representing the debt and equity portions in the company’s balance sheet. The resulting equation provides us with the discount rate, which will be applied to project and anticipate future cash flow projections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*mxAXMF_EO8OM-bUOBTzgVg.png" /></figure><p>where C(D) and C(E) are the cost of debt and cost of equity, respectively, and T is the tax rate.</p><pre>Assets =  last_year[&quot;totalAssets&quot;] <br>Debt = last_year[&quot;totalLiab&quot;]<br>total = marketcap + Debt<br>AfterTaxCostOfDebt = CostOfDebt * (1-tax_perc_T)<br>WACC = (AfterTaxCostOfDebt*Debt/total) + (CostOfEquity*marketcap/total)</pre><p>In this example, we calculate a WACC of 17.2% for Tesla, a figure that stands notably higher than market standards. This elevated value can be attributed to the positive equity market performance, elevated interest rates, and Tesla’s heightened sensitivity to equity market returns.</p><h3>Calculating present value of FCF</h3><p>After estimating the company’s projections and WACC, it’s time to calculate the present value of the FCF using the WACC as the discount rate:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*JoeTGOl8sRv6VXD5F-KAow.png" /></figure><pre>def calculate_present_value(cash_flows, discount_rate):<br>    # Calculate the present value using: PV = CF / (1 + r)^t + TV/(1 + r)^T<br>    present_values_cf = [cf / (1 + discount_rate) ** t for t, cf in enumerate(cash_flows, start=1)]<br>    return present_values_cf<br>df_proj[&quot;pv_FCF&quot;] = calculate_present_value(df_proj[&quot;freeCashFlow&quot;].values, WACC)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*1o7gLaG7yc1EEbQ52Srw6A.png" /><figcaption>Image by author</figcaption></figure><p>Finally we compute the Terminal Value i.e. the present value of all future cash flows beyond the explicit forecast period; in our case, 2032. The formula for the Terminal Value is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/133/1*MUoyCFe9Fd6xer4TTgwZGw.png" /></figure><p>where TGR is the Terminal Growth Rate and represents the rate at which we expect the free cash flows of Tesla to grow beyond the explicit forecast period.</p><pre>TV = df_proj[&quot;freeCashFlow&quot;].values[-1] *(1+TGR) / (WACC - TGR)<br>pv_TV = TV/(1+WACC)**n</pre><p>As a final step, we sum up the present value of FCF and the terminal value to obtain the Enterprise Value. From here, we can derive the Equity Value by subtracting the outstanding debt and adding cash. The implied Share Price is finally obtained by dividing the Equity Value by the number of outstanding shares.</p><pre>Ent_Value = np.sum(df_proj[&quot;pv_FCF&quot;]) + pv_TV<br>Cash = last_year[&quot;cash&quot;]<br>Eq_Value = Ent_Value - Debt + Cash<br>ImpliedSharePrice = Eq_Value/OutShares</pre><p>Based on our assumptions, we obtained a Tesla share price of 42$ per shares which is very low considering that it is currently trading at 250$. This results is due to the very high cost of equity (17.9%) and extremely low level of company’s debt. As showed in the next chapter, for more moderate levels of WACC ~8% we can easily obtain valuation above 300$. Investors are invited to use assumption values in line with their own expectations and views of the market.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*B1Hzawt7LLHciwPtGAsP2g.png" /><figcaption>Image by author</figcaption></figure><h3>Sensitivity analysis</h3><p>In the context of DCF modelling, a sensitivity analysis is a technique used to understand how changes in certain key variables impact the calculated net present value (NPV) of a project or investment, and consequently, the implied share price. In this example, we vary the WACC and TGR to observe the impact of these variables on the final valuation. Intuitively, a higher WACC significantly reduces the future value of FCF and, consequently, the company’s valuation. Conversely, the TGR works in the opposite way, positively influencing the terminal value (TV) and thereby enhancing the overall valuation.</p><pre>waccs = np.linspace(0.06, 0.18, 25)  <br>tgrs = np.linspace(0.01, 0.04, 25)   <br><br># Create a meshgrid for cost of debt and growth rate<br>waccs_mesh, tgrs_mesh = np.meshgrid(waccs, tgrs)<br><br># Calculate NPV for each combination of cost of debt and growth rate<br>dcf_results = np.zeros_like(waccs_mesh)<br>for i in range(len(tgrs)):<br>    for j in range(len(waccs)):<br>         dcf_results[i, j] = Discount_Cash_Flow(df,  n=10, OutShares=OutShares, revenue_growth_T = 0.07, ebit_perc_T = 0.23,  tax_perc_T = 0.21, dna_perc_T = 0.03, capex_perc_T = 0.05, nwc_perc_T = 0.05, WACC = waccs[j],  TGR = tgrs[i])<br><br>fig = plt.figure()<br>ax = fig.add_subplot(111, projection=&#39;3d&#39;)<br>ax.plot_surface(waccs_mesh, tgrs_mesh, dcf_results, cmap=&#39;viridis&#39;)<br>ax.set_xlabel(&#39;WACC&#39;)<br>ax.set_ylabel(&#39;TGR&#39;)<br>ax.set_zlabel(&#39;Implied Share Price&#39;)<br>ax.set_title(&#39;Tesla Sensitivity Analysis&#39;)<br>plt.show()<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*kFCiInW7BKQSV_qyGba-QQ.png" /><figcaption>Image by author</figcaption></figure><p>This analytical approach allows for a more comprehensive assessment of the model’s robustness and provides insights into the sensitivity of the valuation to fluctuations in key parameters.</p><h3>Conclusion</h3><p>In conclusion, this tutorial has provided a comprehensive guide on how to perform a Discounted Cash Flow (DCF) analysis in Python, empowering users to assess the intrinsic value of a company’s stock based on its future cash flows. By leveraging the <a href="https://eodhd.com/r/?ref=E1ATJB8Z">EOD library</a>, we could download all key financial information in an efficient way and cover all the key steps to get the implicit share price, including data preprocessing, assumption setting, and the actual DCF calculation.</p><p>Our journey also delved into the fundamental concept of Free Cash Flow (FCF), providing a detailed formula and explanation of its significance in the DCF calculation. This metric serves as the cornerstone for estimating a company’s intrinsic value by accounting for its operational efficiency, capital expenditures, and overall financial health. Finally, we showed a practical approach to effectively compute the Weighted Average Cost of Capital (WACC) based on the initial data.</p><p>Full code available <a href="https://github.com/gbaglini/baglinifinance">here</a><br>Website: <a href="https://baglinifinance.com/">baglinifinance.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cdf98eb0924d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Estimate Volatility with SMA and EWMA in Python]]></title>
            <link>https://medium.com/@gianlucabaglini/estimate-volatility-with-sma-and-ewma-in-python-744094730150?source=rss-d82d98a49fa2------2</link>
            <guid isPermaLink="false">https://medium.com/p/744094730150</guid>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[volaility]]></category>
            <category><![CDATA[market-risk]]></category>
            <category><![CDATA[moving-average]]></category>
            <dc:creator><![CDATA[Gianluca Baglini]]></dc:creator>
            <pubDate>Wed, 15 Nov 2023 11:01:33 GMT</pubDate>
            <atom:updated>2023-11-15T11:01:33.828Z</atom:updated>
            <content:encoded><![CDATA[<p>Time series analysis is a critical component of understanding and predicting trends in various fields such as finance, economics, and environmental science. Two common methods used for smoothing time series data are simple, or equally weighted, Moving Averages (SMA) and Exponentially Weighted Moving Averages (EWMA). In this article, we will delve into the characteristics, advantages, and applications of both approaches.</p><p>Additionally, we will demonstrate the practical application of these techniques by deriving volatility estimates from financial time series. We will use the Euro Stoxx 50 market index as an example and highlight the main differences by comparing the two results</p><h4>An Introduction to Simple Moving Averages</h4><p>A moving average is calculated on a rolling estimation sample. In other words, we can set a window of fixed length <em>n</em>, roll it through time and then compute the mean of each sample obtained by adding a new (most recent) observation and taking off the oldest one. This window is often referred to as <em>look-back period</em>. As the name suggests, the same weight is assigned to each observation in the sample. A simple formulation is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/1*22tGvUzeijhC7zpu7_TAEQ.png" /></figure><p>where X(t) with t = (1, … , T) are the time series observations.</p><p>The advantages of this method surely lie in its simplicity and easy interpretability. By equally weighting all data points within its chosen timeframe, SMAs provide a smooth, undisturbed trend line, effectively filtering out the noise inherent in day-to-day market fluctuations and allowing the identification of long-term trends.</p><p>Despite being widely used by practitioners, SMAs also come with some pitfalls. One of the main issues is known as the <em>leverage effect</em>, indicating a phenomenon where sudden spikes or outliers in data have a long-lasting impact on the results of moving averages. Let’s consider an exceptionally high return occurring today. If tomorrow we compute the 30-day volatility based on closing prices and include the abnormal return, our volatility forecast will be very high. However, in exactly 30 days (or 22 if we consider only business days), it will suddenly drop to a much lower level on a day when absolutely nothing happened in the markets. This occurrence is simply because the extreme return dropped out of the moving estimation sample. As long as this extreme return stays within the data window, the volatility forecast remains high. We will explore this exact case in the example below.</p><h4>Exponentially Weighted Moving Averages</h4><p>Unlike the equal weighting approach, exponentially weighted moving averages (EWMA) add more weight on recent observations. This characteristic makes EWMA particularly useful in capturing short-term volatility dynamics and less prone to the <em>leverage effect </em>issues associated with SMA. By incorporating a smoothing factor 𝜆 that dictates the rate at which past data diminishes in relevance, the model can be tailored to reflect the desired responsiveness to recent market movements. The higher is 𝜆, the more weight would be attributed to past returns when computing the volatility. For constant 0&lt; 𝜆&lt; 1 , EWMAs are defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*4FJpFpNIjKXxPtaZVRIIVQ.png" /></figure><p>Following this approach, and assuming mean asset returns equal to zero, we can compute EWMA estimates of variances and covariances as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*IgoklR4HTIAgxp5k-WdTGw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*lVjk62NvFnYHAo665wRT_g.png" /></figure><p>The rightmost part of the last two equations shows a recursive closed-form formulation for variance and covariance in the EWMA case.</p><h4>An example</h4><h4>Data</h4><p>For our example, we will use time series data of one of the most known market indices, the Euro Stoxx 50, to compute risk measures for this asset and highlight the main differences obtained by comparing the results of these two techniques. The data sample spans from January 2018 to November 2023, encompassing a total of 1509 observations.</p><p>To retrieve our data through the <a href="https://eodhd.com/r/?ref=E1ATJB8Z">EOD API service</a>, we first need to download and import the <a href="https://pypi.org/project/eod/">EOD Python package</a>, and then authenticate using your personal API key. It’s recommendable to save your API keys in the environment variable.</p><pre>pip install eod</pre><pre>import os<br># load the key from the environment variables<br>api_key = os.environ[&#39;API_EOD&#39;]<br><br>import eod<br>client = EodHistoricalData(api_key)</pre><p>At this point, we are all set to run our first query. Historical prices can be downloaded using the <em>client.get_prices_eod</em> method by passing the stock ticker, data frequency, sorting criteria, and start data as arguments to the function. The query returns an object structured as list of a dictionaries containing daily price and volume information. For practicality, we apply the pandas function to convert it into a formatted table. Finally, we compute the daily logarithmic returns that will be used to calculate our volatility estimates.</p><pre>stoxx_data = client.get_prices_eod(&quot;STOXX.INDX&quot;, period=&quot;d&quot;, order=&#39;a&#39;, from_=&quot;2018-01-01&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/1*ZZu5Hv0TZStDo89w-dwI3A.png" /></figure><pre>stoxx_ts = pd.DataFrame(stoxx_data).set_index(&quot;date&quot;)[&quot;adjusted_close&quot;] <br>rets = np.log(stoxx_ts/stoxx_ts.shift(1))[1:]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*tsLbZFfhZhvjCITi5VFV3g.png" /><figcaption>Image by author</figcaption></figure><h4>SMA Volatility Estimates</h4><p>In this example we construct three different equally weighted moving average volatility estimates for the Euro Stoxx 50 index, with T = 30 days, 60 days and 90 days respectively. The pandas <em>rolling</em> function allows us to iterate through the times series keeping a fixed look-back period. As we are dealing with daily returns, volatilities are multiplied by the square root of 250 (business days in a year) to obtain an annualized measure.</p><pre>std30 = rets.rolling(30).std()*np.sqrt(250) <br>std60 = rets.rolling(60).std()*np.sqrt(250)<br>std90 = rets.rolling(90).std()*np.sqrt(250)<br>std_roll = pd.DataFrame({&#39;30-day vols&#39;: std30, &#39;60-day vols&#39;: std60, &#39;90-day vols&#39;: std90})</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*cfPsEeuBpnxjGSNs3doLDQ.png" /><figcaption>Image by author</figcaption></figure><p>As we can see, the European index reacted quite strongly to the COVID-19 news. The 30-day volatility jumped from ~15% to over 60%! The 60-day and 90-day volatility never exceed the 50%, demostrating a higher smothness due to the longer rolling window. It’s interesting to not how the these two, the peak was reached after compared to short-term volatilities, showing a lagging effect, and that all the volatilities have a sudden drop after exactly 30, 60 and 90 days, when nothing special happened in the market.</p><h4>EWMA Volatility Estimates</h4><p>The effect of using a different value of lambda in EWMA volatility forecasts can be quite substantial. The graph shows volatility estimates obtained using different lambda values, 𝜆 = (0.90, 0.97, 0.99). Note how, for high levels of 𝜆, the EWMA becomes much less reactive, while persistence improves. This is similar to what was obtained in the SMA case above by increasing the length of the rolling window.</p><pre>def EWMA_Volatility(rets, lam):<br>    sq_rets_sp500 = (rets**2).values<br>    EWMA_var = np.zeros(len(sq_rets_sp500))<br>    <br>    for r in range(1, len(sq_rets_sp500)):<br>        EWMA_var[r] = (1-lam)*sq_rets_sp500[r] + lam*EWMA_var[r-1]<br><br>    EWMA_vol = np.sqrt(EWMA_var*250)<br>    return pd.Series(EWMA_vol, index=rets.index, name =&quot;EWMA Vol {}&quot;.format(lam))[1:]<br><br>ewma99_stoxx = EWMA_Volatility(rets, 0.99)<br>ewma97_stoxx = EWMA_Volatility(rets, 0.97)<br>ewma90_stoxx = EWMA_Volatility(rets, 0.90)<br>ewma_all = pd.DataFrame({&#39;𝜆=0.99&#39;: ewma99_stoxx,&#39;𝜆=0.97&#39;: ewma97_stoxx,&#39;𝜆=0.90&#39;: ewma90_stoxx}, index=ewma90_stoxx.index)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*mFg7hH5Z1ZICTKn_7NdZjw.png" /><figcaption>Image by author</figcaption></figure><h4>A final comparison</h4><p>Let’s now compare our estimates obtained using a 60-day SMA and EWMA 𝜆=0.95. When displaying the results on the same graph, it is evident how the two methods produce different risk measures. In particular, the EWMA estimate yields higher volatility than the equally weighted estimate but returns to typical levels faster due to its immunity to the leverage effect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*31GQ2whJ8QjG0m6I_Q1iiA.png" /><figcaption>Image by author</figcaption></figure><p>Finally, note that when computing EWMA estimates for covariances, the same value of lambda should be applied to all the variables to guarantee a semi-definite positive covariance matrix. In practice, different asset classes may react differently to market shocks, and imposing the same smoothing constant to all time series may yield less precise results. This constraint represents one of the main disadvantages of EWMA.</p><h4>Conclusion</h4><p>Both Simple and Exponentially Weighted Moving Averages play essential roles in time series analysis. SMAs provide a straightforward yet potentially lagging representation of trends. On the contrary, EWMA’s adaptive nature offers a more responsive volatility estimate, particularly suited for capturing short-term fluctuations. In both cases, the choice of window length and the smoothing constant plays an important role in determining the level of persistence and responsiveness. The decision between the two methods ultimately depends on the specific needs of the analysis and the desired trade-off.</p><p>Full code available <a href="https://github.com/gbaglini/baglinifinance">here</a><br>Website: <a href="https://baglinifinance.com/">baglinifinance.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=744094730150" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>