<?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 Reda Aldahan on Medium]]></title>
        <description><![CDATA[Stories by Reda Aldahan on Medium]]></description>
        <link>https://medium.com/@aldahanr1?source=rss-3c1c235461e3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Reda Aldahan on Medium</title>
            <link>https://medium.com/@aldahanr1?source=rss-3c1c235461e3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 14:50:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aldahanr1/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[Calculate Weighted Average Cost of Capital (WACC) Using Python]]></title>
            <link>https://python.plainenglish.io/calculate-weighted-average-cost-of-capital-wacc-using-python-99ddc3c396c8?source=rss-3c1c235461e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/99ddc3c396c8</guid>
            <category><![CDATA[investment]]></category>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[investing]]></category>
            <dc:creator><![CDATA[Reda Aldahan]]></dc:creator>
            <pubDate>Mon, 14 Nov 2022 14:15:49 GMT</pubDate>
            <atom:updated>2022-11-15T01:35:34.117Z</atom:updated>
            <content:encoded><![CDATA[<h4>Automatically calculate the WACC of your company with a few lines of code</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7uJqJCXDBmCvq1IT" /><figcaption>Photo by <a href="https://unsplash.com/@chrisliverani?utm_source=medium&amp;utm_medium=referral">Chris Liverani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Introduction</strong></p><p>The weighted Average Cost of Capital (WACC) is widely used in many different models. For instance, it is used in Economic Value Added and discounted Cash Flow models.</p><p>In this article, I am going to explain how easily and quickly WACC can be calculated using Python. I am using Microsoft as an example.</p><p>Below are the steps to calculate WACC:</p><ol><li><strong>Go Over the Formula</strong></li><li><strong>Import Packages</strong></li><li><strong>Calculate WACC (This is section is divided into 3 parts)</strong></li></ol><p>a.<strong> Equity Part</strong></p><p>b.<strong> Debt Part</strong></p><p>c.<strong> Tax Shield</strong></p><p>d. <strong>WACC Calculation</strong></p><ol><li><strong>Go Over the Formula</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*BHP_Q2Cs7mu599WTrrG0cA.png" /><figcaption>WACC Formula from <a href="https://www.investopedia.com/terms/w/wacc.asp">Investopedia</a></figcaption></figure><p>Some extra definitions:</p><p><strong>Cost of Equity</strong>: The required return by the shareholders given the risks they assume for investing in this company.</p><p><strong>Cost of Debt</strong>: The interest rate that a company pays on its debts less than the tax benefit being tax deductible.</p><p>2. <strong>Import Packages</strong></p><pre># Import Libraries and packages<br>import yfinance as yf<br>import pandas as pd<br>import numpy as np</pre><p>3. <strong>Calculate WACC</strong></p><p><strong>a. Equity Part</strong></p><p>Let’s start by calculating the equity part:</p><p>First, we calculate the risk free rate (we are going to use the treasury bill rate):</p><pre>treasury_yield10 = yf.Ticker(&quot;^TNX&quot;) <br>risk_free_rate = round(treasury_yield10.info[&#39;regularMarketPrice&#39;]/100,2) </pre><p>Now, we calculate the market expected return (we will assume the average return of the S&amp;P500 which is 10%):</p><pre>sp500_teturn = 0.10</pre><p>We calculate the beta of Microsoft:</p><pre>stock = yf.Ticker(&quot;MSFT&quot;)<br>beta = stock.info[&quot;beta&quot;]</pre><p>With all the information above, we can calculate the cost of equity:</p><pre>cost_of_equity = round(risk_free_rate + beta*(sp500_teturn - risk_free_rate),2)<br>cost_of_equity</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/187/1*HfX6guf37Mn0mc3szqBEfQ.png" /><figcaption>Output</figcaption></figure><p>Now, we find the weight of equity:</p><p>To do this part, we will need to import the balance sheet.</p><pre>stock_bal = stock.balance_sheet<br>stock_bal</pre><p>Since Assets = Liabilities + Equity, we divide the equity by the assets.</p><pre>weight_of_equity = stock_bal.loc[&quot;Total Stockholder Equity&quot;][0]/ stock_bal.loc[&quot;Total Assets&quot;][0]</pre><p>b.<strong> Debt Part</strong></p><p>Before we start, we need the financial statement:</p><pre># get stock financial statement<br>stock_Fin = stock.financials<br>stock_Fin </pre><p>We start with the cost of debt:</p><pre># Cost of Debt<br>cost_of_debt = round(stock_Fin.loc[&quot;Interest Expense&quot;][0] *-1 / stock_bal.loc[&quot;Total Liab&quot;][0],2)<br>cost_of_debt</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/1*6aHpd3iaehqjIZTY2J-e9g.png" /><figcaption>Output</figcaption></figure><p>Then, we do the weight of debt:</p><pre>weight_of_debt = round(stock_bal.loc[&quot;Total Liab&quot;][0]/ stock_bal.loc[&quot;Total Assets&quot;][0],2)<br>weight_of_debt</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/235/1*Ukj2khFp87SKS3yBkUsnAQ.png" /><figcaption>Output</figcaption></figure><p>c. <strong>Tax Shield</strong></p><pre># Tax Rate<br>tax_rate = round(stock_Fin.loc[&quot;Income Tax Expense&quot;][0] / stock_Fin.loc[&quot;Income Before Tax&quot;][0],2)<br>tax_rate</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/219/1*K-YaqalWq2woMluRw4po9Q.png" /><figcaption>Output</figcaption></figure><p><strong>d. WACC Calculation</strong></p><pre>WACC = round((weight_of_equity * cost_of_equity) + ((weight_of_debt * cost_of_debt ) * (1-tax_rate)),2)<br>WACC</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/1*OfolNaFRFyPMjOIJ8tpcFg.png" /><figcaption>Output</figcaption></figure><p>Here you have it.</p><p>Microsoft WACC is 0.05 or 5%. This means Microsoft must pay an average of $0.05 to raise an additional $1. WACC is used in other models such as discounted cash flow model.</p><p>Finally,</p><p>You can find the full code <a href="https://github.com/RedaAldahan/Fiancne_Models/tree/ccf271d03a36f385ea6e4b4b164bae1beb522df9/WACC"><strong>HERE</strong></a><strong>.</strong></p><p>For further reading, you can check <a href="https://www.investopedia.com/terms/w/wacc.asp">Investopedia</a> and <a href="https://corporatefinanceinstitute.com/resources/valuation/what-is-wacc-formula/">Corporate Finance Institute</a>.</p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><em>, and </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><em>. Interested in Growth Hacking? Check out </em><a href="https://circuit.ooo/"><strong><em>Circuit</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99ddc3c396c8" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/calculate-weighted-average-cost-of-capital-wacc-using-python-99ddc3c396c8">Calculate Weighted Average Cost of Capital (WACC) Using Python</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automatically and Quickly Calculate the Expected Return of your Stocks and Portfolio (CAPM) Using…]]></title>
            <link>https://blog.devgenius.io/automatically-and-quickly-calculate-the-expected-return-of-your-stocks-and-portfolio-capm-using-f9f189657584?source=rss-3c1c235461e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9f189657584</guid>
            <category><![CDATA[capm]]></category>
            <category><![CDATA[investing]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Reda Aldahan]]></dc:creator>
            <pubDate>Tue, 27 Sep 2022 10:28:28 GMT</pubDate>
            <atom:updated>2022-10-18T12:47:33.918Z</atom:updated>
            <content:encoded><![CDATA[<h3>Automatically and Quickly Calculate the Expected Return of your Stocks and Portfolio (CAPM) Using Python</h3><h4>How Much Return Should you Expect from your stocks and Portfolio Using CAPM</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*USfoEXczggdrghpnRFkY1w.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@austindistel?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Austin Distel</a> on <a href="https://unsplash.com/s/photos/capital-assets?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>The stock market has been very volatile in the last few years. Volatility can be seen as a risk to investors. “The Capital Asset Pricing Model (CAPM) describes the relationship between systematic risk, or the general risks of investing, and expected return on assets, specifically stocks. CAPM evolved as a method of measuring systematic risk. It is widely used in finance to price risky securities and generate expected returns on assets given their risk and cost of capital” (<a href="https://www.investopedia.com/terms/c/capm.asp">Investopedia</a>)</p><p>Below are the steps to Automatically and Quickly Calculate the Expected Return of your Stocks and Portfolio (CAPM):</p><ol><li>Go over the formula</li><li>Import packages</li><li>Import the portfolio</li><li>Calculate the expected return of the portfolio</li><li>Calculate the expected return of each individual stock</li><li><strong>The Formula:</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*YzqzrbWhDK-t4m3gvJ1Hfg.png" /><figcaption>CAPM Formula From Investopedia</figcaption></figure><p>Risk free rate: We will use the 10 year treasury bill.</p><p>Market return: We will use the average S&amp;P500 return which is 10 percent.</p><p>Beta indicates how volatile a stock’s price is in comparison to the overall stock market. We will extract it from yfiannce api.</p><p>2. <strong>Import packages:</strong></p><pre># Import Libraries and packages<br>import yfinance as yf<br>import pandas as pd<br>import numpy as np</pre><p>3. <strong>Import the portfolio:</strong></p><p>You can find the link to the excel file in github link at the end of this article for you to add your own portfolio:</p><pre># Import stock portfolio from excel<br>df = pd.read_excel(&quot;Stock_Portfolio.xlsx&quot;)<br>df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*kTrC1i1rkO0_iPE5KZbeAg.png" /><figcaption>Output</figcaption></figure><p>4. <strong>Calculate the expected return of the portfolio:</strong></p><p>We need to calculate the weight of each stock in the portfolio</p><pre># Calculate stock weight<br>df[&quot;stock_weight&quot;]= round((df[&#39;Purchase_Cost&#39;]/df[&quot;Purchase_Cost&quot;].sum())*100,2)<br>df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*2SLU79Wn60jJOLTUhNEfnw.png" /><figcaption>Output</figcaption></figure><p>Calculate the Beta for each stock:</p><pre># Calculate beta for each individual stock<br>for i in range(len(df)):<br>    x = df.loc[i, &quot;Stock&quot;]<br>    ticker = yf.Ticker(x)<br>    stock_beta = ticker.info[&quot;beta&quot;]<br>    df.at[i, &quot;Beta&quot;]= round(stock_beta,2)<br>df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*BsEexzBuX88wWQ7zuqgSWA.png" /><figcaption>Output</figcaption></figure><p>Find the risk free rate:</p><p>We are going to use the 10 year treasury bill.</p><pre># find the risk free rate (10 year treasury bill)<br>treasury_yield10 = yf.Ticker(&quot;^TNX&quot;) <br>risk_free_rate_prem = round(treasury_yield10.info[&#39;regularMarketPrice&#39;]/100,2)<br>risk_free_rate_prem</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/144/1*pbUkYyoO6iLYjnPHjOeqcw.png" /><figcaption>Output</figcaption></figure><p>For the market return we are going to use the 10% average of the S&amp;P500</p><pre># assume 10 percent return on the return of market ( average return of the S&amp;P 500)<br>sp500_teturn = 0.10</pre><p>Now we calculate the Beta of the portfolio by multiplying the Beta of each stock by its weight.</p><pre># Caclulate the portfolio beta<br>portfolio_beta = round(sum(df[&quot;Beta&quot;]* df[&quot;stock_weight&quot;]/100),2)<br>portfolio_beta</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/178/1*b5IzHXUJq9MgwbgMQ14s8g.png" /><figcaption>Output</figcaption></figure><p>Now we calculate the expected return of the portfolio.</p><pre># Calculate the expected return of the portfolio<br>portfolio_exp_return = round(risk_free_rate_prem + portfolio_beta *(sp500_teturn - risk_free_rate_prem),2)<br>portfolio_exp_return</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/136/1*_Zz_Ybb2lCMpeyPWJzYJyQ.png" /><figcaption>Output</figcaption></figure><p>We should expect a 9% average return in this portfolio per year.</p><p>5. Calculate the expected return of each individual stock:</p><p>Now, let’s find the expected return of each stock.</p><pre># calulate the expected return for each individual stock using CAPM forumla<br>df[&quot;exp_return&quot;]= round(risk_free_rate_prem + df[&quot;Beta&quot;]*(sp500_teturn - risk_free_rate_prem),2)<br>df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*OjPqIaWuYCNOG03kRitVZg.png" /><figcaption>Output</figcaption></figure><p>Finally, all financial models have assumptions and problems. For further readings, I would recommend reading <a href="https://www.investopedia.com/terms/c/capm.asp">the Investopedia article</a>.</p><p>For the full code and excel file, click <a href="https://github.com/RedaAldahan/Fiancne_Models/tree/3fdfc17b8b9e40dfde4fc5f9ea629b2e5fdaf42b/CAPM"><strong>HERE</strong></a><strong>.</strong></p><p><strong>Disclaimer</strong>:</p><p>There are risks associated with investing in securities. Investing in stocks, bonds, exchange-traded funds, mutual funds, and money market funds involves the risk of loss. Loss of principal is possible. A security’s or a firm’s past investment performance is not a guarantee or predictor of future investment performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9f189657584" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/automatically-and-quickly-calculate-the-expected-return-of-your-stocks-and-portfolio-capm-using-f9f189657584">Automatically and Quickly Calculate the Expected Return of your Stocks and Portfolio (CAPM) Using…</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What if You Invested Back Then in Your Favorite Stock?]]></title>
            <link>https://python.plainenglish.io/what-if-you-invested-back-then-in-your-favorite-stock-game-d0898afc8875?source=rss-3c1c235461e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0898afc8875</guid>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[investment]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Reda Aldahan]]></dc:creator>
            <pubDate>Tue, 29 Mar 2022 12:35:14 GMT</pubDate>
            <atom:updated>2022-04-06T02:40:54.071Z</atom:updated>
            <content:encoded><![CDATA[<h4>Are you lucky? How much would you make or lose?</h4><p>A few days ago, I had a discussion with one of my friends about the stock market. I told him that if he invested __$ amount of his money in time xx_xx_xxxx he would have made __$ amount of money. The discussion went on and we started playing the what-if game. This made me think of making a Python program that can calculate the profit or loss of a hypothetical investment.</p><p>First of all, we import the packages we are going to use:</p><pre>import pandas as pd<br>import yfinance as yf</pre><p>Then, get the historical data (my friend chose Microsoft. Feel free to change the stock ticket here):</p><pre># get historical market data<br>stock = yf.Ticker(&quot;MSFT&quot;)<br>hist = stock.history(period=&quot;max&quot;)</pre><p>Show the historical data:</p><pre>hist</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*Jg-5kM4pZG5QVLq9doXNjg.png" /><figcaption>Output</figcaption></figure><p>Let’s choose the amount of money we would have invested (my friend chose 1000$, choose yours):</p><pre>inv_amt = 1000</pre><p>Let’s choose the date of when we invested (my friend chose a time right after COVID was declared a pandemic)</p><p>We have an if function to warn us if the date we chose is in the data frame or not. If it is not, it might be a weekend or a holiday, so just use another day. If there is no warning, it means you picked a date the stock market was open:</p><pre>inv_date = &#39;2020-03-09&#39;<br>exists = inv_date in hist.index<br>if exists == False:<br>    print(&quot;Please enter a date that is in the dataframe&quot;)</pre><p>We want to focus on the closing price:</p><pre>choosen_price = round(hist.loc[inv_date,:][&quot;Close&quot;],2)<br>choosen_price</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/107/1*ZhKzoACndZ5PltBxLynUbA.png" /><figcaption>This is the stock closing price</figcaption></figure><p>let’s calculate how many shares we would have had (We would assume that we can buy a fraction of shares):</p><pre>num_stocks = round(float(inv_amt) / choosen_price,2)<br>num_stocks</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/113/1*v6XlxQoduGmWfMnhRIgFaQ.png" /><figcaption>number of share we would have had</figcaption></figure><p>Now, we need the current stock price:</p><pre>curr_price = round(hist[&quot;Close&quot;].iloc[-1],2)<br>curr_price</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/110/1*3dqVX0rXMoVIoaHXJYqpcQ.png" /><figcaption>Current Price</figcaption></figure><p>Let’s see how much we would have:</p><pre>stock_valu = round(num_stocks * curr_price,2)<br>print(&#39;you would have:&#39;,stock_valu)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/218/1*dxDdXrwocPy7nLeun6WDyw.png" /></figure><p>Finally, let’s whether we gained or lost money in this hypothetical investment?</p><pre>net  = round(x - inv_amt,2)<br>if x &lt; float(inv_amt):<br>    print(&#39;You would have lost: &#39;, net)<br>else:<br>   print(&#39;You would have gained: &#39;, net)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/1*WbDXRzQm0EU9f354fqnJOA.png" /></figure><p>Great Job!</p><p>My friend would have doubled his money.</p><p>I hope you can enjoy this little “game”, or use it to prove to people how the stock market can be a good investment.</p><p>You can find the full code here:</p><p><a href="https://github.com/RedaAldahan/Fiancne_Models/blob/aa1245fb8075143a9f612fb3bbc1511d25a774ff/What_if_Invested_Stock_MKT_Game/done%20what%20if.ipynb">Fiancne_Models/done what if.ipynb at aa1245fb8075143a9f612fb3bbc1511d25a774ff · RedaAldahan/Fiancne_Models</a></p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><em> and </em><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>. Join our</em><strong><em> </em></strong><a href="https://discord.gg/GtDtUAvyhW"><strong><em>community Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0898afc8875" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/what-if-you-invested-back-then-in-your-favorite-stock-game-d0898afc8875">What if You Invested Back Then in Your Favorite Stock?</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automate Emailing a Random Quote from a List of Authors]]></title>
            <link>https://blog.devgenius.io/automate-emailing-a-random-quote-from-a-list-of-authors-7cf4a31c1f3b?source=rss-3c1c235461e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/7cf4a31c1f3b</guid>
            <category><![CDATA[email]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[quotes]]></category>
            <category><![CDATA[books]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Reda Aldahan]]></dc:creator>
            <pubDate>Wed, 16 Feb 2022 12:54:14 GMT</pubDate>
            <atom:updated>2022-02-20T11:07:28.486Z</atom:updated>
            <content:encoded><![CDATA[<h4>Start Your Day with a random Quote From Your Favorite Authors</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0pFKrZzoNOuwV7BEAGCaFw.jpeg" /><figcaption>Image by <a href="https://unsplash.com/@freestocks">@freestocks</a></figcaption></figure><p>Many of us start the day with a cup of coffee, so why not add a bit of flavor — a random quote from our favorite authors. In this article, I will explain how to email yourself and your friends a random quote every day using Python.</p><p>Below are the steps:</p><ol><li>Importing packages</li><li>Define the list of the favorite authors</li><li>Generate the random quote from the list in a function</li><li>Send the email</li><li>How to automate this task</li><li><strong>Importing packages:</strong></li></ol><pre>import pandas as pd<br>import datetime<br>import smtplib<br>from email.message import EmailMessage<br>import random<br>from quote import quote</pre><p><strong>2. Define the list of the favorite authors</strong></p><pre>mylist = [&quot;leo tolstoy&quot;, &quot;simon sinek&quot;, &quot;Paulo Coelho&quot;, &quot;Stephen Covey&quot;, &quot;Tony Robbins&quot;, &quot;Mark Twain&quot;, &quot;Fyodor Dostoevsky&quot;, &quot;Lao Tzu&quot;, &quot;Sun Tzu&quot;]</pre><p>You can play around with the list here. You can remove and add your favorite authors.</p><p><strong>3. Generate the random quote from the list in a function</strong></p><pre>def quote_generate():<br>    <br>    search = random.choice(mylist)<br>    result = quote(search, limit=1)</pre><pre>df = pd.DataFrame(result)<br>    <br>    return df</pre><pre>quote_result = quote_generate()</pre><p>In this step, we created the function and saved the information in a variable.</p><p><strong>4. Send the email</strong></p><pre>def sendEmail(to, sub, msg):<br>    print(f&quot;email to {to} \nsend with subject: {sub}\n message: {msg}&quot;)<br>    email = EmailMessage()<br>    email[&#39;from&#39;] = &#39;Reda Aldahan&#39;<br>    email[&#39;to&#39;] = f&quot;{to}&quot;<br>    email[&#39;subject&#39;] = f&#39;{sub}&#39;</pre><pre>email.set_content(f&#39;{msg}&#39;)</pre><pre>with smtplib.SMTP(host=&#39;smtp.gmail.com&#39;, port=587) as smtp:<br>        smtp.ehlo()<br>        smtp.starttls()<br>        smtp.login(&#39;<a href="/service/mailto:your_Email@gmail.com">your_Email@gmail.com</a>&#39;,&#39;your password&#39;)<br>        smtp.send_message(email)<br>        print(&quot;Email send&quot;)<br>    pass<br>if __name__ == &quot;__main__&quot;:<br>    df = pd.read_excel(&quot;data.xlsx&quot;)<br>    print(df)<br>    today = datetime.datetime.now().strftime(&quot;%d-%m&quot;)<br>    #print(type(today))<br>    update = []<br>    td =  datetime.datetime.now().strftime(&quot;%d-%m&quot;)<br>    #print(yearnow)<br>    for index, item in df.iterrows():<br>        #print(index,item[&#39;birthday&#39;])<br>        #print(type(bday))<br>        if td not in str(item[&quot;Date&quot;]): <br>            sendEmail(item[&#39;Email&#39;] , &quot;Happy QUOTE &quot;+item[&quot;Name&quot;], &quot;Your Quote Today: &#39;&quot; + quote_result.iloc[0][2] + &quot;&#39; By &quot; + quote_result.iloc[0][0])<br>            update.append(index)<br>    for i in update:<br>        dt = df.loc[i, &#39;Date&#39;]<br>        #print(yr)<br>        df.loc[i,&#39;Date&#39;] = f&quot;{td}, {dt}&quot;<br>        #print((df.loc[i, &#39;Year&#39;])<br>    #print(df)<br>    df.to_excel(&quot;data.xlsx&quot;, index=False)</pre><p>In this step, we go to an excel file called “data” and bring some information for the email which are:</p><p>a. Name of the recipient</p><p>b. The date; if the person already received the quote today and want to add more people and run the code this person will not receive a quote</p><p>c. The recipient email</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*KgVnIot5Tp8q0jr1VwSghw.png" /><figcaption>This is how it should look like</figcaption></figure><p>The email will be sent if the recipient did not receive his/ her quote on that day. The date column in the excel sheet will be updated with today’s date, so you can add more people and re-run the code immediately and those who did not receive the quote will receive it.</p><p><strong>5. How to automate this task</strong></p><p>It is easy to run this code with a click of a button, but why bother if the machine can do it for you.</p><p>a. You can use Task Scheduler. Here is an article by <a href="https://medium.com/@vincentkernn?source=post_page-----661d0a40b279-----------------------------------">Vincent Tatan</a> explaining how to do it. Click <a href="https://towardsdatascience.com/automate-your-python-scripts-with-task-scheduler-661d0a40b279">Here</a> for the article.</p><p>b. Use Python Library: Schedule. Click <a href="https://pypi.org/project/schedule/">here</a> to read more about it.</p><p>The End:</p><p>The Full code and excel sheet can be found <a href="https://github.com/RedaAldahan/Python-Fun/blob/04660cf21e96b66d9d359cb4b00f7b36d9c655e3/Quote_Authors/Quote_From_Authors.py">here</a>.</p><p>Enjoy your Quote + your coffee!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7cf4a31c1f3b" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/automate-emailing-a-random-quote-from-a-list-of-authors-7cf4a31c1f3b">Automate Emailing a Random Quote from a List of Authors</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dividends Discount Model (DDM) in Python]]></title>
            <link>https://python.plainenglish.io/dividends-discount-model-in-python-13c0f141a611?source=rss-3c1c235461e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/13c0f141a611</guid>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[finance]]></category>
            <dc:creator><![CDATA[Reda Aldahan]]></dc:creator>
            <pubDate>Thu, 20 Jan 2022 04:33:02 GMT</pubDate>
            <atom:updated>2022-01-31T06:00:07.315Z</atom:updated>
            <content:encoded><![CDATA[<h4>Find the Fair Price of your Stock Using (DDM) in no time</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*JemOuXG2rA2aqi7f" /><figcaption>Photo by <a href="https://unsplash.com/@bash__profile">Nicholas Cappello</a></figcaption></figure><p><strong>Introduction</strong></p><p>The dividend discount model is a quantitative method. It tries to predict the price of a company’s stock based on the assumption that its current price is equal to the sum of all future dividend payments when discounted back to its present value.</p><p>The Formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*rqCKuQmRKIEcLpag73drQg.png" /><figcaption>Formula</figcaption></figure><p>Cost of Equity = Risk Free Rate + (Beta * Market Premium)</p><p>Market Premium = Market Return — Risk Free Rate</p><p>Risk Free Rate = 10 Years Treasury Yield</p><p>Market Return = Return of the S&amp;P 500</p><p>In this article, I am going to describe the code for calculating the fair price of a company (AT&amp;T in this article) using the dividends discount model.</p><p><strong>Steps</strong></p><p>1. Import necessary libraries</p><p>2. Get the data</p><p>3. Prepare the data by creating necessary columns</p><p>4. Calculate variables in the formula</p><p>5. Find the fair price and whether it is underpriced or overpriced</p><p><strong>Step 1: Import necessary libraries</strong></p><p>In this step, we are going to import all the libraries we need:</p><pre>import yfinance as yf # this is to get the stock data<br>import pandas as pd # this is for working on data frames<br>import numpy as np # this is to manipulate the data</pre><p><strong>Step 2: Get the data</strong></p><p>We are going to work on AT&amp;T (ticker: t). If you want to change the stock to calculate the fair price, just type the ticker inside the parenthesis.</p><pre>ticker = yf.Ticker(&quot;t&quot;) <br>stock = ticker.actions<br>stock</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*iQ6Rz_A2H1V3iHzGkrRSYg.png" /><figcaption>Output</figcaption></figure><p><strong>Step 3: Prepare the data by creating necessary columns</strong></p><p>The stock split column shows us the stock splits per quarter. We want to know the cumulative stock splits. Therefore, we are going to start by taking the values of the stock split column in a NumPy array form and assigning it to a variable.</p><pre>stock_split = stock[&quot;Stock Splits&quot;].to_numpy()<br>stock_split</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*H7bvFkjzEXgJz5RRAwjKGw.png" /><figcaption>Output</figcaption></figure><p>Now, we are going to replace all the zeros with one for the next step (just bear with me. This will make more sense in the next step).</p><pre>stock_split_replaced = np.where(stock_split == 0, 1, stock_split)<br>stock_split_replaced</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*UU9eWSOVaIWbWRM6GDv75g.png" /><figcaption>Output</figcaption></figure><p>Starting from the beginning of the array. Multiply each number by the previous one, save the value. The next “cell” is going to be multiplied by the value of the “cell” we obtained and so on.</p><p>For example, we have these numbers 2, 1,6,2,1</p><p>The calculation 2, 2*1, 2*6, 12*2, 24*1</p><p>The result will be 2,2,12,24,24</p><pre>stock_split_comp = np.cumprod(stock_split_replaced, axis=0)<br>stock_split_comp</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*1BKcpnR-4a2QLh6aewzPIA.png" /><figcaption>Output</figcaption></figure><p>Now that we have the cumulative stock split, we are going to add this array as a “stocksplit_adj” column in our original data frame</p><pre>stock[&quot;stocksplit_adj&quot;] = stock_split_comp.tolist()<br>stock</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*oHfdqxgAkVsGi3dwUne8gA.png" /><figcaption>Output</figcaption></figure><p>Now, we need to calculate the adjusted dividends by multiplying dividends by the adjusted stock split.</p><pre>stock[&quot;div_adj&quot;] = stock[&quot;Dividends&quot;] * stock[&quot;stocksplit_adj&quot;]<br>stock</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*hR0JGYThPWS7bKQVlutilA.png" /><figcaption>Output</figcaption></figure><p>Next, we need to find the total of dividends per year instead of a quarter. To do so, we will need to create a column that extracts the years in each row from the date column.</p><pre>stock[&#39;year&#39;] = stock.index.year<br>stock</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*828i8G0UAhHoK7luPVIw4Q.png" /><figcaption>Output</figcaption></figure><p>Now, we will need to sum the values by the year (group by year). Showing the last 20 rows should be enough.</p><pre>stock_grp = stock.groupby(by=[&quot;year&quot;]).sum()<br>stock_grp.tail(20)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*W-TSuWhHTyqtwDW8uYLKHw.png" /><figcaption>Output</figcaption></figure><p>Now, we need to find the median growth of the adjusted dividends. We will start by creating a column that calculates the percentage change each year. again showing 20 rows should be enough.</p><pre>stock_grp[&quot;div_PCT_Change&quot;] = stock_grp[&quot;div_adj&quot;].pct_change(fill_method =&#39;ffill&#39;)<br>stock_grp.tail(20)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*NnJJxIhS4i6EbLjNP77BIg.png" /><figcaption>Output</figcaption></figure><p><strong>Step 4: Calculate variables in the formula</strong></p><p>We will extract the median dividends growth. We can use the average but the median makes more sense here because the median is less influenced by outliers.</p><pre>median_growth = stock_grp[&quot;div_PCT_Change&quot;].median()<br>median_growth</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/177/1*tGYlyh3DUx9_3jJ21qpJ7g.png" /><figcaption>Output</figcaption></figure><p>Next, let’s extract the last dividends. We are going to get 2021 dividends because it has all four quarters.</p><pre>lst_Div = stock_grp.at[2021,&#39;Dividends&#39;]<br>lst_Div</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/105/1*YJiR66PSijOzz37HMqTNgg.png" /><figcaption>Output</figcaption></figure><p>Since we have the last dividends and the median growth, we can calculate the expected future dividends.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/77/1*bzxNKDk3xeTHWUBMN7LP0A.png" /><figcaption>Output</figcaption></figure><p>Now, we will get the Beta.</p><pre>beta = ticker.info[&quot;beta&quot;]<br>beta</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/100/1*NMwf2StL6LzGdxFWR3JX8Q.png" /><figcaption>Output</figcaption></figure><p>We can assume the risk-free rate to be equal to 3%, and the market Return equals 11%</p><pre>risk_free_rate = 0.03<br>mkt_return = .11<br>MKT_Risk_prem = mkt_return - risk_free_rate<br>MKT_Risk_prem</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/73/1*hO329FC-FNuyimzohitxPQ.png" /><figcaption>Output</figcaption></figure><p>Now, that we have the beta, risk-free rate and market return, and risk premium, we can calculate the cost of equity. We are going to round it to four decimal.</p><pre>COE = round(beta * MKT_Risk_prem + risk_free_rate,4)<br>COE</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/75/1*WaVBQRnp8FGZaFzhXAB4ww.png" /><figcaption>Output</figcaption></figure><p><strong>Step 5: Find the fair price and whether it is underpriced or overpriced</strong></p><p>We have all we need (Cost of Equity, Expected Future Dividends, and the expected growth), we can find the fair price based on this model.</p><pre>fair_sharePrice = round(exp_future_div/(COE-median_growth),2)<br>fair_sharePrice</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/85/1*NRTtMUJ1azMpVLuYffexkw.png" /><figcaption>Output</figcaption></figure><p>Let’s find the current price to compare it with the fair price of this model.</p><pre>stock_price = ticker.history(period=&quot;today&quot;)<br>stock_price_close = round(stock_price.iloc[0][&#39;Close&#39;],4)<br>stock_price_close</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/79/1*V9IWPQL411tRMUBz2YyJqw.png" /><figcaption>Output</figcaption></figure><p>The last thing we need to do is find how much we might gain/lose from buying this stock.</p><pre>expected_gain_loss = fair_sharePrice/stock_price_close-1<br>expected_gain_loss = &quot;{:.0%}&quot;.format(expected_gain_loss)<br>expected_gain_loss</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/78/1*chsE3XhZmGQFfFmWO191wQ.png" /><figcaption>Output</figcaption></figure><p>Since the value is positive, we can say that based on our dividends discount model the current price is undervalued, and we expect to gain a 58% return.</p><p><strong>Finally, some drawbacks of this model:</strong></p><p>1- A constant dividend growth rate is assumed in the dividend discount model. For a mature organization, this assumption is safe.</p><p>2- The output is extremely sensitive to the inputs.</p><p>3- When a company’s rate of return is lower than the dividend growth rate, the model fails. This might happen if a corporation continues to pay dividends despite losing money or having decreasing earnings</p><p><strong>Finally:</strong></p><p>The full code can be found <a href="https://github.com/RedaAldahan/Fiancne_Models/blob/main/Dividends_Discount_Model/Dividends_discount_Model(Final).ipynb">here</a>.</p><p>I am so passionate about data and financial models. I am planning to build financial models using Python at least once every other week. You can connect with me on <a href="https://www.linkedin.com/in/reda-aldahan-6b296910a/">LinkedIn</a> to check my last posts and work on projects together.</p><p><strong>Disclaimer</strong>:</p><p>There are risks associated with investing in securities. Investing in stocks, bonds, exchange-traded funds, mutual funds, and money market funds involves the risk of loss. Loss of principal is possible. A security’s or a firm’s past investment performance is not a guarantee or predictor of future investment performance.</p><p><strong>References</strong></p><p>J. Chen, <a href="https://www.investopedia.com/terms/d/ddm.asp">Dividend Discount Model — DDM</a> (2020), Investopedia</p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Get exclusive access to writing opportunities and advice in our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>community Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13c0f141a611" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/dividends-discount-model-in-python-13c0f141a611">Dividends Discount Model (DDM) in Python</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>