<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" 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" xmlns:media="http://search.yahoo.com/mrss/">
<channel>
<title><![CDATA[Math - Rafael Quintanilha]]></title>
<description><![CDATA[Essays about software engineering, web development, artificial intelligence, quantitative analysis, financial markets, books and tradition.]]></description>
<link>https://rafaelquintanilha.com/topic/math/</link>
<image><url>https://rafaelquintanilha.com/content/images/2022/12/Logo-Design--2-.png</url><title>Math - Rafael Quintanilha</title><link>https://rafaelquintanilha.com/topic/math/</link></image>
<lastBuildDate>Mon, 14 Oct 2024 15:30:25 GMT</lastBuildDate>
<atom:link href="https://rafaelquintanilha.com/topic/math/rss/" rel="self" type="application/rss+xml"/>
<ttl>60</ttl>
<item>
<title><![CDATA[Entenda o que é Valor Esperado (EV) e Sua Utilidade Para um Trader]]></title>
<description><![CDATA[Aprenda sobre o EV em diferentes contextos e como aplicar esse conceito na prática.]]></description>
<link>https://rafaelquintanilha.com/quantbrasil/entenda-o-que-e-valor-esperado-ev-e-sua-utilidade-para-um-trader/</link>
<guid isPermaLink="false">638d008e24336d003d59fdcd</guid>
<category><![CDATA[Quantitative Analysis]]></category><category><![CDATA[Math]]></category>
<dc:creator><![CDATA[Rafael Quintanilha]]></dc:creator>
<pubDate>Tue, 21 Dec 2021 03:00:00 GMT</pubDate>

<content:encoded><![CDATA[<p>No seu famoso livro <em>Iludidos Pelo Acaso</em> (<a href="https://amzn.to/3p9JjoO" rel="noopener noreferrer" target="_blank">Fooled by Randomness</a> no original), o autor Nassim Taleb descreve uma situação onde um colega de trabalho questiona se ele acha que o mercado vai subir ou descer. "Acho que sobe", diz Taleb. No dia seguinte, o amigo retorna furioso ao perceber que Taleb havia embolsado uma boa grana efetuando um <em>trade</em> na direção contrária, isto é, que o mercado ia <em>cair</em>. Questionado por ter dito uma coisa e feito outra, o trader responde que havia uma chance maior de ser um dia de alta, porém, caso fosse um dia de baixa, o mercado cairia com força.</p>
<p>Se você, como o colega do autor, ainda vê uma contradição na ação do trader, não se preocupe. Nesse artigo, exploraremos o conceito de <strong>Valor Esperado</strong> (também conhecido como <em>Esperança</em> ou <em>Expectativa Matemática</em>), e aprenderemos como utilizar esse importante conceito de forma prática no dia-a-dia de um trader.</p>
<h2 id="definindo-o-valor-esperado"><strong>Definindo o Valor Esperado</strong></h2>
<p>Imagine a seguinte situação: um amigo propõe uma aposta, onde vocês rolarão os dados. Se o número for par, você ganha R$10. Se for ímpar, você precisa pagá-lo R$11. Você aceitaria essa aposta?</p>
<p>Mesmo que você ainda não saiba o que é Valor Esperado (EV), a resposta provavelmente é <strong>não</strong>. Não parece justo que ele ganhe mais do que você, considerando que a <em>chance de vitória é a mesma para ambos</em>.</p>
<p>Intuitivamente fica simples perceber que essa aposta é ruim para você. Matemáticamente, como podemos ter certeza? Daí o conceito de Valor Esperado.</p>
<p>Definimos o <strong>Valor Esperado</strong> como a soma das probabilidades de um determinado evento acontecer <em>ponderadas</em> por quanto você ganha (ou perde) em cada situação. Em outras palavras:</p>
<span class="katex-display"><span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>E</mi><mi>V</mi><mo>=</mo><msub><mi>P</mi><mrow><mi>g</mi><mi>a</mi><mi>i</mi><mi>n</mi></mrow></msub><mo>×</mo><mi>p</mi><mi>a</mi><mi>y</mi><mi>o</mi><mi>f</mi><mi>f</mi><mo>+</mo><msub><mi>P</mi><mrow><mi>l</mi><mi>o</mi><mi>s</mi><mi>s</mi></mrow></msub><mo>×</mo><mi>r</mi><mi>i</mi><mi>s</mi><mi>k</mi></mrow><annotation encoding="application/x-tex">EV = P_{gain} \times payoff + P_{loss} \times risk</annotation></semantics></math></span></span></span>
<p>Onde <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi>P</mi><mrow><mi>g</mi><mi>a</mi><mi>i</mi><mi>n</mi></mrow></msub></mrow><annotation encoding="application/x-tex">P_{gain}</annotation></semantics></math></span></span> é a <em>probabilidade de acerto</em>, <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi>P</mi><mrow><mi>l</mi><mi>o</mi><mi>s</mi><mi>s</mi></mrow></msub></mrow><annotation encoding="application/x-tex">P_{loss}</annotation></semantics></math></span></span> é a <em>probabilidade de erro</em>, <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>p</mi><mi>a</mi><mi>y</mi><mi>o</mi><mi>f</mi><mi>f</mi></mrow><annotation encoding="application/x-tex">payoff</annotation></semantics></math></span></span> é <em>quanto você ganha se acertar</em> e <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>r</mi><mi>i</mi><mi>s</mi><mi>k</mi></mrow><annotation encoding="application/x-tex">risk</annotation></semantics></math></span></span> é <em>quanto você perde se errar</em>.</p>
<p>Podemos então calcular o <em>valor esperado</em> da aposta substituindo os valores na fórmula:</p>
<span class="katex-display"><span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>E</mi><mi>V</mi><mo>=</mo><mn>0.5</mn><mo>×</mo><mn>10</mn><mo>+</mo><mn>0.5</mn><mo>×</mo><mo>−</mo><mn>11</mn><mo>=</mo><mo>−</mo><mn>0.5</mn></mrow><annotation encoding="application/x-tex">EV = 0.5 \times 10 + 0.5 \times -11 = -0.5</annotation></semantics></math></span></span></span>
<p>O valor esperado <em>negativo</em> nos indica que a aposta, no longo prazo, é <em>perdedora</em>, e que é "esperado" que percamos R$0.50 cada vez que jogamos os dados. Isso é extremamente, pois significa que mesmo que haja uma sequência de eventos onde ganhemos 3x seguidas (o que tem uma probabilidade não-desprezível de 12,5%), <em>ainda assim</em> estamos fazendo um mau negócio.</p>
<h2 id="valor-esperado-na-prática"><strong>Valor Esperado na prática</strong></h2>
<p>Agora que o conceito de EV já foi definido, vamos explorá-lo em algumas situações típicas.</p>
<h3 id="apostas-esportivas"><strong>Apostas esportivas</strong></h3>
<p>Talvez o exemplo mais flagrante da utilidade do Valor Esperado se dá nas <em>apostas esportivas</em>. Apostas esportivas normalmente são eventos <em>binários</em>, ou seja, ou uma situação acontece, ou outra <em>mutuamente excludente</em>. Por exemplo:</p>
<ul>
<li>Ou o Vasco ganha, ou o Vasco não ganha (empata ou perde).</li>
<li>Ou o Charles do Bronx finaliza por guilhotina no 3º round, ou ele não finaliza por guilhotina no 3º round.</li>
</ul>
<p>Ou o Trump é eleito, ou ele não é eleito.</p>
<ul>
<li>Embora tecnicamente uma eleição não seja um evento <em>esportivo</em>, seu resultado é binário, então vamos usar a licença-poética aqui para entender "esportivas" como "<em>recreativas</em>".</li>
</ul>
<p>Como o evento é binário, se definirmos <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi>P</mi><mrow><mi>g</mi><mi>a</mi><mi>i</mi><mi>n</mi></mrow></msub><mo>=</mo><mi>p</mi></mrow><annotation encoding="application/x-tex">P_{gain} = p</annotation></semantics></math></span></span>, naturalmente segue que <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi>P</mi><mrow><mi>l</mi><mi>o</mi><mi>s</mi><mi>s</mi></mrow></msub><mo>=</mo><mn>1</mn><mo>−</mo><mi>p</mi></mrow><annotation encoding="application/x-tex">P_{loss} = 1 - p</annotation></semantics></math></span></span>, uma vez que a soma dos dois eventos precisa ser 1.</p>
<p>O que resta agora é definir quanto que recebemos em retorno por uma aposta, ou seja, o valor que estamos <em>arriscando</em> (<span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>r</mi><mi>i</mi><mi>s</mi><mi>k</mi></mrow><annotation encoding="application/x-tex">risk</annotation></semantics></math></span></span>). Essa proporção é o que chamamos de <strong>odds</strong>. Uma <em>odd</em> de 2:1 significa que, para cada real apostado, recebemos 2 de volta caso ganhemos. Usando os termos que vimos anteriormente, <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>r</mi><mi>i</mi><mi>s</mi><mi>k</mi><mo>=</mo><mn>1</mn></mrow><annotation encoding="application/x-tex">risk = 1</annotation></semantics></math></span></span> e <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>p</mi><mi>a</mi><mi>y</mi><mi>o</mi><mi>f</mi><mi>f</mi><mo>=</mo><mn>2</mn></mrow><annotation encoding="application/x-tex">payoff = 2</annotation></semantics></math></span></span>.</p>
<p>Nesse exemplo, substituindo na nossa fórmula do EV, segue que:</p>
<span class="katex-display"><span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>E</mi><mi>V</mi><mo>=</mo><mi>p</mi><mo>×</mo><mn>2</mn><mo>+</mo><mo stretchy="false">(</mo><mn>1</mn><mo>−</mo><mi>p</mi><mo stretchy="false">)</mo><mo>×</mo><mo stretchy="false">(</mo><mo>−</mo><mn>1</mn><mo stretchy="false">)</mo><mo>=</mo><mn>3</mn><mi>p</mi><mo>−</mo><mn>1</mn></mrow><annotation encoding="application/x-tex">EV = p \times 2 + (1 - p) \times (-1) = 3p - 1</annotation></semantics></math></span></span></span>
<p>Onde <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>p</mi></mrow><annotation encoding="application/x-tex">p</annotation></semantics></math></span></span> é a probabilidade de acerto.</p>
<p>Tá, mas até agora isso não quer dizer muito. Como podemos interpretar essa equação?</p>
<h4 id="descobrindo-seu-edge"><strong>Descobrindo seu edge</strong></h4>
<p>Se um EV negativo significa que você irá <em>perder</em> dinheiro no longo prazo e um EV positivo significa que você irá <em>ganhar</em> dinheiro no longo prazo, naturalmente um <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>E</mi><mi>V</mi><mo>=</mo><mn>0</mn></mrow><annotation encoding="application/x-tex">EV = 0</annotation></semantics></math></span></span> representa o seu <strong>break-even</strong>, ou seja, o limite onde sua aposta passa a ser vencedora ou perdedora.</p>
<p>Aplicando essa condição na equação anterior, temos:</p>
<span class="katex-display"><span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>E</mi><mi>V</mi><mo>=</mo><mn>3</mn><mi>p</mi><mo>−</mo><mn>1</mn><mo>=</mo><mn>0</mn></mrow><annotation encoding="application/x-tex">EV = 3p - 1 = 0</annotation></semantics></math></span></span></span>
<p>De onde segue que <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>p</mi><mo>=</mo><mstyle scriptlevel="0" displaystyle="true"><mfrac><mn>1</mn><mn>3</mn></mfrac></mstyle></mrow><annotation encoding="application/x-tex">p = \dfrac{1}{3}</annotation></semantics></math></span></span>, ou <em>33.3%</em>.</p>
<p>Isso significa que, para as odds apresentadas (2:1), o <em>break-even</em> da aposta é 33.3%. Se a chance de sucesso for maior que isso, sua aposta tem uma expectativa matemática <em>positiva</em>. Se for menor, <em>negativa</em>. À diferença entre a probabilidade de sucesso e o break-even damos o nome de <strong>edge</strong>.</p>
<p>Sendo assim, se o seu julgamento para um determinado evento é uma chance de 50% de acerto e as odds estão 2:1, você tem um <em>edge</em> sobre a casa e portanto a aposta é matematicamente aceitável. Substituindo na fórmula do EV para essas odds:</p>
<span class="katex-display"><span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>E</mi><mi>V</mi><mo>=</mo><mn>3</mn><mi>p</mi><mo>−</mo><mn>1</mn><mo>=</mo><mn>3</mn><mo>×</mo><mn>0.5</mn><mo>−</mo><mn>1</mn><mo>=</mo><mn>0.5</mn></mrow><annotation encoding="application/x-tex">EV = 3p - 1 = 3 \times 0.5 - 1  = 0.5</annotation></semantics></math></span></span></span>
<p>Em outras palavras, no longo prazo, para cada real investido você é <em>esperado</em> de obter R$0,50 de retorno.</p>
<h3 id="exemplo-final-da-libertadores"><strong>Exemplo: Final da Libertadores</strong></h3>
<p>Certo, já aprendemos o que é Valor Esperado e como podemos utilizar as <em>odds</em> para determinarmos se temos um <em>edge</em>, ou seja, uma vantagem competitiva em relação à nossa contraparte. Vou ilustrar agora como um apostador (ou trader) pode utilizar esse conceito na prática.</p>
<p>A final da Libertadores de 2021 foi entre Palmeiras e Flamengo, este último sendo considerado o <em>favorito</em>, algo que eu também acreditava. A questão então era: <strong>quão</strong> favorito? Existe um <em>edge</em> nas odds oferecidas?</p>
<p>Fui então ao site do <a href="https://sportsbet.io" rel="noopener noreferrer" target="_blank">Sportsbet</a> e descobri que eles estavam oferecendo odds de <em>10:1</em> no título do Flamengo, limitado a R$10. Essas odds obviamente são fora da realidade, já que se substituirmos na nossa fórmula do EV, descobriremos que o <em>break-even</em> da casa ficaria em <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mstyle scriptlevel="0" displaystyle="true"><mfrac><mn>1</mn><mn>11</mn></mfrac></mstyle></mrow><annotation encoding="application/x-tex">\dfrac{1}{11}</annotation></semantics></math></span></span>, ou 9%, algo incompatível com o favoritismo do rubro-negro.</p>
<p>Isso não passou de uma inteligentíssima ação de marketing da empresa, que provavelmente aumentou significativamente sua base de usuários a um risco controlado. Essas odds já seriam suficientes para que eu, que considerava o Flamengo favorito, fizesse a aposta. Porém, pensei: e se eu usar essa aposta, que tem capital limitado, como <strong>hedge</strong> (proteção, não confundir com <em>edge</em>) de uma aposta maior? Em outras palavras: consigo abater essas odds irreais de uma aposta <em>contrária</em> no Palmeiras de modo a embolsar um prêmio maior?</p>
<p>A mesma casa pagava odds de <em>2.63:1</em> no título do Palmeiras, o que correspondia a <em>27,5%</em> de probabilidade. Por si só, isso já me parecia uma odd bastante atrativa: certamente o Flamengo era favorito, mas não nessa proporção!</p>
<h4 id="o-resultado"><strong>O Resultado</strong></h4>
<p>No final, essas foram as apostas que eu fiz:</p>
<p><img alt="" loading="lazy" decoding="async" width="679" height="490" src="https://rafaelquintanilha.com/_astro/fla-pal.CNF_3nHf_Z1e6FE1.webp"></p>
<p>Vamos entender a aposta e calcular as <em>odds</em> reais que a casa de apostas estava oferecendo:</p>
<ul>
<li><em>R$10</em> no título do Flamengo, que caso se concretizasse me retornaria <em>R$100</em>;</li>
<li><em>R$200</em> no título do Palmeiras, que caso se concretizasse me retornaria <em>R$526</em>.</li>
</ul>
<p>Assim, haviam duas possibilidades:</p>
<p><strong>Possibilidade 1</strong>: Flamengo campeão, eu ganho R$100 da aposta vencedora mas perco R$200 da aposta feita no Palmeiras. Resultado: aposto R$210 e fico com R$100, um <em>prejuízo</em> de <strong>-R$110</strong>.</p>
<p><strong>Possibilidade 2</strong>: Palmeiras campeão, eu perco R$10 da aposta no Flamengo mas embolso R$526 da aposta no Palmeiras. Resultado: aposto R$210 e fico com R$526, um <em>lucro líquido</em> de <strong>R$316</strong>.</p>
<p>Resumidamente, eu estava arriscando R$110 (Flamengo campeão) para ganhar R$526 (Palmeiras campeão), <em>odds</em> de quase 5:1!</p>
<p>Vamos descobrir o <em>break-even</em> da aposta:</p>
<span class="katex-display"><span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>E</mi><mi>V</mi><mo>=</mo><mi>p</mi><mo>×</mo><mn>526</mn><mo>+</mo><mo stretchy="false">(</mo><mn>1</mn><mo>−</mo><mi>p</mi><mo stretchy="false">)</mo><mo>×</mo><mo stretchy="false">(</mo><mo>−</mo><mn>110</mn><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">EV = p \times 526 + (1 - p) \times (-110)</annotation></semantics></math></span></span></span>
<span class="katex-display"><span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>E</mi><mi>V</mi><mo>=</mo><mn>636</mn><mi>p</mi><mo>−</mo><mn>110</mn><mo>=</mo><mn>0</mn></mrow><annotation encoding="application/x-tex">EV = 636p - 110 = 0</annotation></semantics></math></span></span></span>
<span class="katex-display"><span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>p</mi><mo>=</mo><mstyle scriptlevel="0" displaystyle="true"><mfrac><mn>110</mn><mn>636</mn></mfrac></mstyle><mo>≈</mo><mn>0.173</mn></mrow><annotation encoding="application/x-tex">p = \dfrac{110}{636} \approx 0.173</annotation></semantics></math></span></span></span>
<p>Ou seja: a casa estava "precificando" o título do Palmeiras em <strong>17,3%</strong>. Se o meu julgamento inicial era um favoritismo de 60-40 para o Flamengo, eu fui praticamente obrigado a fazer a aposta no <em>underdog</em>.</p>
<h3 id="valor-esperado-no-poker"><strong>Valor Esperado no Poker</strong></h3>
<p>Outra aplicabilidade bastante comum do EV é como critério de aposta no jogo de <em>Poker</em>. Nesse jogo de cartas, os jogadores fazem apostas a cada turno, e o total apostado é acrescentado ao <em>pot</em>. O vencedor da mão leva todo o valor do <em>pot</em>.</p>
<p>Assim, à medida que os turnos avançam, o <em>pot</em> cresce e portanto o prêmio fica maior. Dessa forma, ao ser confrontado com a decisão de pagar ou não uma determinada aposta, o jogador precisa calcular qual o <em>EV</em> da jogada, isso é, se pagar a aposta é matematicamente positivo no longo prazo (<span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>E</mi><mi>V</mi><mo>></mo><mn>0</mn></mrow><annotation encoding="application/x-tex">EV > 0</annotation></semantics></math></span></span>).</p>
<p>Suponha que o <em>pot</em> contenha R$1000 no <em>flop</em> e um adversário vai <em>all-in</em> apostando R$800. Você julga possuir <em>6 outs</em>, isto é, 6 cartas que melhoram a sua mão e tornam-a vencedora. Sem entrar em muitos detalhes do jogo, isso equivale aproximadamente a uma chance de <em>24%</em> de que alguma dessas 6 cartas irá aparecer até o fim. Deve você pagar a aposta?</p>
<p>Bem, nesse caso <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>r</mi><mi>i</mi><mi>s</mi><mi>k</mi><mo>=</mo><mn>800</mn></mrow><annotation encoding="application/x-tex">risk = 800</annotation></semantics></math></span></span> e <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>p</mi><mi>a</mi><mi>y</mi><mi>o</mi><mi>f</mi><mi>f</mi><mo>=</mo><mn>1000</mn><mo>+</mo><mn>800</mn><mo>+</mo><mn>800</mn><mo>=</mo><mn>2600</mn></mrow><annotation encoding="application/x-tex">payoff = 1000 + 800 + 800 = 2600</annotation></semantics></math></span></span> (R$1000 já estavam no <em>pot</em>, R$800 apostados pelo adversário e R$800 apostados por você). Assumindo uma chance de vitória de 24%, seu EV então é:</p>
<span class="katex-display"><span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>E</mi><mi>V</mi><mo>=</mo><mn>0.24</mn><mo>×</mo><mn>2600</mn><mo>+</mo><mo stretchy="false">(</mo><mn>1</mn><mo>−</mo><mn>0.24</mn><mo stretchy="false">)</mo><mo>×</mo><mo stretchy="false">(</mo><mo>−</mo><mn>800</mn><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">EV = 0.24 \times 2600 + (1 - 0.24) \times (-800)</annotation></semantics></math></span></span></span>
<span class="katex-display"><span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>E</mi><mi>V</mi><mo>=</mo><mn>624</mn><mo>−</mo><mn>608</mn><mo>=</mo><mn>16</mn><mo>></mo><mn>0</mn></mrow><annotation encoding="application/x-tex">EV = 624 - 608 = 16 > 0</annotation></semantics></math></span></span></span>
<p>Sendo o EV positivo, o jogador está "matematicamente autorizado" a pagar a aposta.</p>
<h2 id="problemas-do-valor-esperado"><strong>Problemas do Valor Esperado</strong></h2>
<p>Sempre que calculamos o Valor Esperado devemos nos atentar a alguns problemas típicos. Alguns deles:</p>
<ul>
<li>Pressupomos um <em>longo prazo</em>. Assim, nada adianta justificar uma decisão pelo EV se é uma situação atípica ou marginalmente vencedora;</li>
<li>Nosso julgamento das probabilidades pode ser <em>enviesado</em>. Por exemplo, o fato de ter achado a probabilidade de 17,3% do Palmeiras ser campeão um escândalo pode ter sido enviesado pelo fato de eu ser vascaíno e estar fervorosamente torcendo contra;</li>
<li><strong>Não há Valor Esperado se há chance de ruína</strong>. Um exemplo clássico é a roleta russa: mesmo que você ganhe R$1 bilhão para apertar o gatilho com uma probabilidade de <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mstyle scriptlevel="0" displaystyle="true"><mfrac><mn>5</mn><mn>6</mn></mfrac></mstyle></mrow><annotation encoding="application/x-tex">\dfrac{5}{6}</annotation></semantics></math></span></span>​ de sucesso, o <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>r</mi><mi>i</mi><mi>s</mi><mi>k</mi></mrow><annotation encoding="application/x-tex">risk</annotation></semantics></math></span></span> (colocar uma bala na cabeça) inviabiliza a operação.</li>
</ul>
<p>No mundo do trading é bastante comum cometermos o primeiro erro, influenciados principalmente por situações atípicas ou um espaço amostral pequeno. Portanto, um backtest realizado com poucas operações é extremamente sensível a ruídos, o que na prática significa que aquela probabilidade não representa a realidade.</p>
<p>Já a chance de ruína é muito comum nos jogos de poker: por mais que uma jogada tenha o EV positivo, às vezes é melhor esperar uma melhor oportunidade, mais segura, do que correr o risco de ser prematuramente eliminado.</p>
<p>No mundo dos investimentos, essa é a razão pela qual nunca devemos ir <em>all-in</em> em uma única operação. Por mais certos que estejamos e por mais positivo que seja o nosso EV, o risco de ser tirado do jogo não compensa o resultado.</p>
<h2 id="valor-esperado-para-traders"><strong>Valor Esperado para Traders</strong></h2>
<p>Agora que já aprendemos a calcular e aplicar o EV e entendemos suas limitações, podemos nos aprofundar no seu uso para <em>traders</em>.</p>
<p>Na plataforma do QuantBrasil temos um <a href="https://quantbrasil.com.br/backtests" rel="noopener noreferrer" target="_blank">Simulador de Estratégias</a> onde qualquer um pode realizar o <strong>backtest</strong> de sua estratégia favorita.</p>
<p>O resultado a seguir é o resultado da estratégia do <strong>123 de Compra</strong> para <em>JBSS3</em> nos <em>120 minutos</em> quando esse ativo está no <a href="https://quantbrasil.com.br/eden-dos-traders" rel="noopener noreferrer" target="_blank">Éden dos Traders</a>:</p>
<p><img alt="" loading="lazy" decoding="async" width="1020" height="1152" src="https://rafaelquintanilha.com/_astro/backtest-123-jbs.DQnXcPwF_1VnEhY.webp"></p>
<p><strong>Quer rodar os seus próprios backtests?</strong> <a href="https://quantbrasil.com.br/cadastro" rel="noopener noreferrer" target="_blank"><strong>Crie sua conta no QuantBrasil.</strong></a> <strong>Não leva nem 1 minuto!</strong></p>
<p>O resultado é bastante positivo e o EV (Valor Esperado) é de <em>0.58%</em>. Como chegamos a esse número?</p>
<p>Bem, veja que acertamos 29/44 de operações, o que corresponde a <em>66% de assertividade</em>. Como limitamos o nosso risco a 2% do capital inicial de R$100,000, nosso <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>r</mi><mi>i</mi><mi>s</mi><mi>k</mi></mrow><annotation encoding="application/x-tex">risk</annotation></semantics></math></span></span> vai girar em torno de R$2,000 (na prática o valor sempre será diferente, pois há gaps, o lote precisa ser múltiplo de 100 ações, etc).</p>
<p>A <em>perda média</em> acabou ficando em R$1897,80 (próximo ao nosso risco máximo teórico estabelecido) e o ganho médio foi de R$1860,86. No final, é como se o "mercado" estivesse nos oferecendo odds bem próximas de 1:1 para aplicar essa estratégia.</p>
<p>Substituindo todos esses valores na fórmula do EV, segue que:</p>
<span class="katex-display"><span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>E</mi><mi>V</mi><mo>=</mo><mn>0.66</mn><mo>×</mo><mn>1860</mn><mo separator="true">,</mo><mn>86</mn><mo>+</mo><mn>0.34</mn><mo>×</mo><mo stretchy="false">(</mo><mo>−</mo><mn>1897</mn><mo separator="true">,</mo><mn>80</mn><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">EV = 0.66 \times 1860,86 + 0.34 \times (-1897,80)</annotation></semantics></math></span></span></span>
<span class="katex-display"><span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>E</mi><mi>V</mi><mo>=</mo><mn>1228</mn><mo separator="true">,</mo><mn>17</mn><mo>−</mo><mn>645</mn><mo separator="true">,</mo><mn>25</mn><mo>=</mo><mn>582</mn><mo separator="true">,</mo><mn>92</mn></mrow><annotation encoding="application/x-tex">EV = 1228,17 - 645,25 = 582,92</annotation></semantics></math></span></span></span>
<p>Isso significa que, para um capital de R$100,000 a um risco máximo de 2%, o <strong>valor esperado por trade</strong> é de R$582, ou <strong>0.58%</strong> do capital.</p>
<h3 id="o-ev-não-é-a-única-coisa-que-importa"><strong>O EV não é a única coisa que importa</strong></h3>
<p>Observadas todas as ressalvas feitas ao Valor Esperado, é inegável que esse seja uma das métricas mais importantes na tomada de decisão de um trader. Ainda assim, o EV por si só não carrega todas as informações.</p>
<p>Considere o seguinte backtest, também realizado para <em>JBSS3</em> nos <em>120 minutos</em>, mas dessa vez sem o filtro de Éden dos Traders e com um <em>risco fixo</em> de 2:1.</p>
<p><img alt="" loading="lazy" decoding="async" width="1017" height="968" src="https://rafaelquintanilha.com/_astro/backtest-123-fixed.Bq93_-rw_PWgxQ.webp"></p>
<p>Aqui, temos um EV impressionante de <strong>0.96%</strong>, o que significa que um trader executando essa estratégia durante esse período tinha uma expectativa matemática de aumentar o seu patrimônio em praticamente 1% <em>a cada trade</em>.</p>
<p>Tão bom quanto pareça, essa performance impressionante não vem de graça. Primeiro, a taxa de erro aumentou de 34% para 41%. Segundo e principal, o <a href="https://quantbrasil.com.br/entenda-o-drawdown-e-calcule-essa-medida-de-volatilidade-para-qualquer-ativo" rel="noopener noreferrer" target="_blank">drawdown</a> mais que dobrou, atingindo quase 12% (a maior sequência de <em>perdas</em> indo de 3 para 7).</p>
<p>Em outras palavras, nosso <em>retorno</em> aumentou, mas também o nosso <em>risco</em>. A combinação que melhor funciona sempre será uma função do seu apetite ao risco e força mental durante os trades. Pergunte a si mesmo: continuaria mantendo a mesma estratégia depois dela falhar 7x em sequência?</p>
<h3 id="atenção-a-dinâmica-do-mercado-muda"><strong>Atenção: a dinâmica do mercado muda</strong></h3>
<p>Você fez o dever de casa: estudou a estratégia, realizou o backtest, aferiu o EV, e agora? Deve colocar todo seu dinheiro na estratégia em questão?</p>
<p>Antes de sair fazendo isso, lembre-se que o mercado é dinâmico e <strong>backtests sempre representam o passado</strong>. Em outras palavras, não é porque uma estratégia teve <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>E</mi><mi>V</mi><mo>=</mo><mn>0.98</mn></mrow><annotation encoding="application/x-tex">EV = 0.98</annotation></semantics></math></span></span> nos últimos 2 anos que ela continuará tendo pelos próximos 2. Por exemplo, <em>JBSS3</em> foi um dos papeis mais fortes do Ibovespa em 2021, então naturalmente a maior parte das estratégias nesse ativo foi lucrativa.</p>
<p>Se o EV não é garantia de nada, por que me preocupar em calculá-lo então?</p>
<p>Essa pergunta é bastante pertinente e não nos cabe explicar com rigor matemático nesse momento. No entanto, é importante entender que um papel que teve a <em>dinâmica</em> que <em>JBSS3</em> apresentou naquele período, observados os mesmos parâmetros da estratégia, teve um EV tão alto quanto 0,98%. É possível presumir, então, que se formos capazes de identificar papeis apresentando uma <em>dinâmica</em> parecida, o resultado <em>pode</em> ser parecido.</p>
<p>No QuantBrasil, a cada semana atualizamos o <a href="https://quantbrasil.com.br/app/melhores-backtests" rel="noopener noreferrer" target="_blank">ranking</a> com os ativos que melhor performaram em uma determinada estratégia nos últimos 500 dias (<a href="https://quantbrasil.com.br/cadastro" rel="noopener noreferrer" target="_blank">crie sua conta para visualizar o ranking de backtests</a>). Essa é uma forma de estar sempre acompanhando os ativos cuja estratégia está funcionando.</p>
<p>Além disso, nosso screening de <a href="https://quantbrasil.com.br/momentum" rel="noopener noreferrer" target="_blank">momentum</a> gera sempre uma lista atualizada dos ativos que estão performando melhor nos últimos meses. Sendo a estratégia de 123 de compra majoritariamente <em>seguidora de tendência</em>, é razoável assumir que ativos com maior <em>momentum</em> apresentem um resultado melhor no backtest dessa estratégia (no momento de escrita desse artigo JBSS3 é o 3º na lista de <em>momentum</em>).</p>
<h2 id="conclusão"><strong>Conclusão</strong></h2>
<p>O <strong>Valor Esperado</strong> (ou Esperança/Expectativa Matemática) é uma métrica extremamente relevante para tomadas de decisão. Vimos que sua aplicabilidade é diversa no cotidiano, indo desde apostas esportivas, passando pelo poker e sendo crucial para <em>traders</em>.</p>
<p>No QuantBrasil é possível <a href="https://quantbrasil.com.br/backtests" rel="noopener noreferrer" target="_blank">rodar backtests</a> de diversas estratégias e saber exatamente o EV, ou quanto você é <em>esperado</em> de ganhar por trade, considerando a dinâmica do mercado no período de teste.</p>
<p>Ainda assim, o EV precisa ser observado com atenção: ele é irrelevante caso haja <strong>risco de ruína</strong> e estará sempre sujeito a alteração nas probabilidades. Ferramentas como o <a href="https://quantbrasil.com.br/app/melhores-backtests" rel="noopener noreferrer" target="_blank">ranking de backtests</a> e o <a href="https://quantbrasil.com.br/momentum" rel="noopener noreferrer" target="_blank">screening de momentum</a> são úteis para minimizar a chance de calcular um EV que já não representa a realidade.</p>
<p>Por fim e mais importante, o EV nos ajuda a entender qual é o <em>payoff</em> de uma estratégia e porquê podemos achar que um determinado evento é mais provável e ainda assim fazer uma aposta na direção contrária. Como diria Nassim Taleb no seu livro <a href="https://amzn.to/3GS7a20" rel="noopener noreferrer" target="_blank">Skin in the Game</a>:</p>
<blockquote>
<p>What matters in life isn't how frequently one is "right" about outcomes, but how much one makes when one is right.</p>
</blockquote>]]></content:encoded>
</item>
<item>
<title><![CDATA[The Drunken Sailor and The Lindy Effect]]></title>
<description><![CDATA[Understand the Lindy Effect mathematically by applying it to the well-known Drunken Sailor problem.]]></description>
<link>https://rafaelquintanilha.com/ensaios/the-drunken-sailor-and-the-lindy-effect/</link>
<guid isPermaLink="false">638bcd8f24336d003d59fc0d</guid>
<category><![CDATA[Lindy Effect]]></category><category><![CDATA[Math]]></category>
<dc:creator><![CDATA[Rafael Quintanilha]]></dc:creator>
<pubDate>Wed, 27 Mar 2019 03:00:00 GMT</pubDate>

<content:encoded><![CDATA[<p>I was scrolling through my Twitter feed on a boring Saturday afternoon when I stumbled upon this tweet:</p>
<figure class="embed embed-twitter" data-url="https://twitter.com/bilayerguy/status/1098926919402311680">
<blockquote class="twitter-tweet"><p lang="en" dir="ltr">Dear <a href="https://twitter.com/nntaleb" rel="noopener noreferrer" target="_blank">@nntaleb</a> , will you post this puzzle in memory of <a href="https://twitter.com/CutTheKnotMath" rel="noopener noreferrer" target="_blank">@CutTheKnotMath</a>? I had it in an exam 21 years ago and still do not know the solution. I am sure your followers or you will do it and I will learn something useful. Thank you! <a href="https://t.co/e9HXQZwo9K" rel="noopener noreferrer" target="_blank">pic.twitter.com/e9HXQZwo9K</a></p>— Adrian Mureșan (@bilayerguy) <a href="https://twitter.com/bilayerguy/status/1098926919402311680" rel="noopener noreferrer" target="_blank">February 22, 2019</a></blockquote>
</figure>
<p>I was immediately thrilled - finally something interesting to do!</p>
<p>Here’s the problem in full:</p>
<blockquote>
<p>A drunken sailor stands near the edge of an abyss and takes random steps either towards or away from the edge. A step towards the edge has a probability of p<em>p</em> and a step away from the edge has a probability of (1 - p)(1−<em>p</em>). If the sailor starts n<em>n</em> steps from the edge, what is his chance of survival? What is the minimum value of p<em>p</em> for which there is no chance of survival?</p>
</blockquote>
<p>Turns out the solution for this problem is not beautiful only mathematically, but also provides great insights into our daily life.</p>
<p>Let’s solve it first.</p>
<h2 id="solving-computationally"><strong>Solving Computationally</strong></h2>
<p>Before jumping into the maths, let’s try to get some intuition from code. Here’s a simple simulator for our problem:</p>
<iframe src="https://codesandbox.io/embed/angry-jerry-q3w4l9?fontsize=14&#x26;hidenavigation=1&#x26;theme=dark" style="width:100%; height:500px; border:0; border-radius: 4px; overflow:hidden;" title="drunken-sailor" allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking" sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts" loading="lazy"></iframe>
<p>The complete code is on <a href="https://codesandbox.io/s/drunken-sailor-q3w4l9" rel="noopener noreferrer" target="_blank">CodeSandbox</a> but the algorithm is pretty straightforward.</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">const</span><span style="color:#ECEBE8"> MAX_ITERATIONS </span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE"> 10000</span><span style="color:#ECEBE8">;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> updatePosition</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> (currentPosition, p) </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> randomVariable </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> Math.random</span><span style="color:#ECEBE8">();</span></span>
<span class="line"><span style="color:#A1C1E4">  if</span><span style="color:#ECEBE8"> ( randomVariable </span><span style="color:#A1C1E4">&#x3C;</span><span style="color:#ECEBE8"> p ) </span><span style="color:#A1C1E4">return</span><span style="color:#ECEBE8"> currentPosition </span><span style="color:#A1C1E4">-</span><span style="color:#97CCAE"> 1</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">  else</span><span style="color:#A1C1E4"> return</span><span style="color:#ECEBE8"> currentPosition </span><span style="color:#A1C1E4">+</span><span style="color:#97CCAE"> 1</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> simulation</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> (initialPosition, p) </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  let</span><span style="color:#ECEBE8"> iterations </span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE"> 0</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">  let</span><span style="color:#ECEBE8"> currentPosition </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> initialPosition;</span></span>
<span class="line"><span style="color:#A1C1E4">  while</span><span style="color:#ECEBE8"> ( currentPosition </span><span style="color:#A1C1E4">></span><span style="color:#97CCAE"> 0</span><span style="color:#A1C1E4"> &#x26;&#x26;</span><span style="color:#ECEBE8"> iterations </span><span style="color:#A1C1E4">&#x3C;=</span><span style="color:#ECEBE8"> MAX_ITERATIONS ) {</span></span>
<span class="line"><span style="color:#ECEBE8">    currentPosition </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> updatePosition</span><span style="color:#ECEBE8">(currentPosition, p);</span></span>
<span class="line"><span style="color:#ECEBE8">    iterations</span><span style="color:#A1C1E4">++</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#ECEBE8">  }</span></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> [currentPosition, iterations];</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span></code></pre></figure>
<p>The trick is to think of the sailor’s position as a point in the x-axis. We update the position until he dies (<code>currentPosition === 0</code>) or the maximum number of iterations is reached. In every round, we compare a random variable between 0 and 1 (yielded by <code>Math.random</code>) with p<em>p</em> and move the sailor left or right accordingly.</p>
<p>I encourage you to play a little bit with the simulator and check how’s your intuition going. In any case, here’s a table with the % of deaths for some combinations of <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>n</mi></mrow><annotation encoding="application/x-tex">n</annotation></semantics></math></span></span> and <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>p</mi></mrow><annotation encoding="application/x-tex">p</annotation></semantics></math></span></span>:</p>
<table>
<thead>
<tr>
<th>p</th>
<th>Deaths (n = 5n=5) (%)</th>
<th>Deaths (n = 15n=15) (%)</th>
<th>Deaths (n = 50n=50) (%)</th>
</tr>
</thead>
<tbody>
<tr>
<td>0.1</td>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>0.2</td>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>0.3</td>
<td>1.7</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>0.4</td>
<td>13.2</td>
<td>0.3</td>
<td>0</td>
</tr>
<tr>
<td>0.5</td>
<td>96.1</td>
<td>86.8</td>
<td>61.8</td>
</tr>
<tr>
<td>0.6</td>
<td>100</td>
<td>100</td>
<td>100</td>
</tr>
<tr>
<td>0.7</td>
<td>100</td>
<td>100</td>
<td>100</td>
</tr>
<tr>
<td>0.8</td>
<td>100</td>
<td>100</td>
<td>100</td>
</tr>
<tr>
<td>0.9</td>
<td>100</td>
<td>100</td>
<td>100</td>
</tr>
</tbody>
</table>
<p>As one could imagine, the % of deaths increases with <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>p</mi></mrow><annotation encoding="application/x-tex">p</annotation></semantics></math></span></span> and somehow decreases with <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>n</mi></mrow><annotation encoding="application/x-tex">n</annotation></semantics></math></span></span>… but only for values around <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mn>0.50</mn></mrow><annotation encoding="application/x-tex">0.50</annotation></semantics></math></span></span>. It seems that the fate of our beloved sailor is settled for <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>p</mi><mo>></mo><mn>0.5</mn></mrow><annotation encoding="application/x-tex">p > 0.5</annotation></semantics></math></span></span> and therefore this should be the answer to the second question of the problem.</p>
<p>Let us now find the exact probability of survival.</p>
<h2 id="solving-mathematically"><strong>Solving Mathematically</strong></h2>
<p>There are many solutions for this problem but the one I liked most was written in <a href="https://medium.com/i-math/the-drunkards-walk-explained-48a0205d304" rel="noopener noreferrer" target="_blank">this post by Brett Berry</a>. Here’s a summary:</p>
<p>Recall that in order to solve through code we abstracted the sailor’s position into a point in the x-axis. Let <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>P</mi><mo stretchy="false">(</mo><mi>n</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">P(n)</annotation></semantics></math></span></span> be the probability that the sailor dies when <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>n</mi></mrow><annotation encoding="application/x-tex">n</annotation></semantics></math></span></span> steps away from the edge.</p>
<figure class="image"><img alt="Credits: Brett Berry" loading="lazy" decoding="async" width="609" height="219" src="https://rafaelquintanilha.com/_astro/drunken-sailor.CNWIupFz_1ENKr0.webp"><figcaption>Credits: Brett Berry</figcaption></figure>
<p>Then:</p>
<span class="katex-display"><span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>P</mi><mo stretchy="false">(</mo><mn>1</mn><mo stretchy="false">)</mo><mo>=</mo><mi>p</mi><mo>+</mo><mo stretchy="false">(</mo><mn>1</mn><mo>−</mo><mi>p</mi><mo stretchy="false">)</mo><mi>P</mi><mo stretchy="false">(</mo><mn>2</mn><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">P(1)=p+(1−p)P(2)</annotation></semantics></math></span></span></span>
<p>The sailor surely dies if he goes to the left (with probability <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>p</mi></mrow><annotation encoding="application/x-tex">p</annotation></semantics></math></span></span>). But if he manages to move right, we now have him in <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>n</mi><mo>=</mo><mn>2</mn></mrow><annotation encoding="application/x-tex">n = 2</annotation></semantics></math></span></span> and therefore the probability that he dies is what we call <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>P</mi><mo stretchy="false">(</mo><mn>2</mn><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">P(2)</annotation></semantics></math></span></span>.</p>
<p>Well, in order to die he <strong>necessarily</strong> needs to move to the left (i.e. go from <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>n</mi><mo>=</mo><mn>2</mn></mrow><annotation encoding="application/x-tex">n = 2</annotation></semantics></math></span></span> to <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>n</mi><mo>=</mo><mn>1</mn></mrow><annotation encoding="application/x-tex">n = 1</annotation></semantics></math></span></span>). But what is <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>P</mi><mo stretchy="false">(</mo><mn>1</mn><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">P(1)</annotation></semantics></math></span></span> if not the probability that the sailor moves one unit left? Therefore, <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>P</mi><mo stretchy="false">(</mo><mn>2</mn><mo stretchy="false">)</mo><mo>=</mo><mi>P</mi><mo stretchy="false">(</mo><mn>1</mn><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">P(2) = P(1)</annotation></semantics></math></span></span> <em>times the probability of going from</em> <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>n</mi><mo>=</mo><mn>1</mn></mrow><annotation encoding="application/x-tex">n = 1</annotation></semantics></math></span></span> to <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>n</mi><mo>=</mo><mn>0</mn></mrow><annotation encoding="application/x-tex">n = 0</annotation></semantics></math></span></span>, or, <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>P</mi><mo stretchy="false">(</mo><mn>1</mn><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">P(1)</annotation></semantics></math></span></span>.</p>
<p>Hence:</p>
<span class="katex-display"><span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>P</mi><mo stretchy="false">(</mo><mn>1</mn><mo stretchy="false">)</mo><mo>=</mo><mi>p</mi><mo>+</mo><mo stretchy="false">(</mo><mn>1</mn><mo>−</mo><mi>p</mi><mo stretchy="false">)</mo><mi>P</mi><mo stretchy="false">(</mo><mn>1</mn><msup><mo stretchy="false">)</mo><mn>2</mn></msup></mrow><annotation encoding="application/x-tex">P(1) = p + (1−p)P(1)^2</annotation></semantics></math></span></span></span>
<span class="katex-display"><span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mo stretchy="false">(</mo><mn>1</mn><mo>−</mo><mi>p</mi><mo stretchy="false">)</mo><mi>P</mi><mo stretchy="false">(</mo><mn>1</mn><msup><mo stretchy="false">)</mo><mn>2</mn></msup><mo>−</mo><mi>P</mi><mo stretchy="false">(</mo><mn>1</mn><mo stretchy="false">)</mo><mo>+</mo><mi>p</mi><mo>=</mo><mn>0</mn></mrow><annotation encoding="application/x-tex">(1 - p) P(1)^2 - P(1) + p = 0</annotation></semantics></math></span></span></span>
<p>Which yields <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>P</mi><mo stretchy="false">(</mo><mn>1</mn><mo stretchy="false">)</mo><mo>=</mo><mn>1</mn></mrow><annotation encoding="application/x-tex">P(1) = 1</annotation></semantics></math></span></span> or <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>P</mi><mo stretchy="false">(</mo><mn>1</mn><mo stretchy="false">)</mo><mo>=</mo><mfrac><mi>p</mi><mrow><mn>1</mn><mo>−</mo><mi>p</mi></mrow></mfrac></mrow><annotation encoding="application/x-tex">P(1) = \frac{p}{1 - p}</annotation></semantics></math></span></span>.
Now, notice that <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>P</mi><mo stretchy="false">(</mo><mn>1</mn><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">P(1)</annotation></semantics></math></span></span> is a probability and therefore must be in the <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mo stretchy="false">[</mo><mn>0</mn><mo separator="true">,</mo><mn>1</mn><mo stretchy="false">]</mo></mrow><annotation encoding="application/x-tex">[0, 1]</annotation></semantics></math></span></span> range. Follows that <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mfrac><mi>p</mi><mrow><mn>1</mn><mo>−</mo><mi>p</mi></mrow></mfrac><mo>≤</mo><mn>1</mn></mrow><annotation encoding="application/x-tex">\frac{p}{1 - p} \leq 1</annotation></semantics></math></span></span> and then <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>p</mi><mo>≤</mo><mfrac><mn>1</mn><mn>2</mn></mfrac></mrow><annotation encoding="application/x-tex">p \leq \frac{1}{2}</annotation></semantics></math></span></span>.</p>
<p>Finally, we can write:</p>
<span class="katex-display"><span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>P</mi><mo stretchy="false">(</mo><mn>1</mn><mo stretchy="false">)</mo><mo>=</mo><mrow><mo fence="true">{</mo><mtable rowspacing="0.36em" columnalign="left left" columnspacing="1em"><mtr><mtd><mstyle scriptlevel="0" displaystyle="false"><mn>1</mn></mstyle></mtd><mtd><mstyle scriptlevel="0" displaystyle="false"><mrow><mtext>if </mtext><mi>p</mi><mo>></mo><mfrac><mn>1</mn><mn>2</mn></mfrac></mrow></mstyle></mtd></mtr><mtr><mtd><mstyle scriptlevel="0" displaystyle="false"><mfrac><mi>p</mi><mrow><mn>1</mn><mo>−</mo><mi>p</mi></mrow></mfrac></mstyle></mtd><mtd><mstyle scriptlevel="0" displaystyle="false"><mrow><mtext>if </mtext><mi>p</mi><mo>≤</mo><mfrac><mn>1</mn><mn>2</mn></mfrac></mrow></mstyle></mtd></mtr></mtable></mrow></mrow><annotation encoding="application/x-tex">P(1) = \begin{cases} 1 &#x26;\text{if } p \gt \frac{1}{2} \\ \frac{p}{1 - p} &#x26;\text{if } p \leq \frac{1}{2} \end{cases}</annotation></semantics></math></span></span></span>
<p>Once <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>P</mi><mo stretchy="false">(</mo><mn>2</mn><mo stretchy="false">)</mo><mo>=</mo><mi>P</mi><mo stretchy="false">(</mo><mn>1</mn><msup><mo stretchy="false">)</mo><mn>2</mn></msup></mrow><annotation encoding="application/x-tex">P(2) = P(1)^2</annotation></semantics></math></span></span>, it follows that:</p>
<span class="katex-display"><span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>P</mi><mo stretchy="false">(</mo><mi>n</mi><mo stretchy="false">)</mo><mo>=</mo><mrow><mo fence="true">{</mo><mtable rowspacing="0.36em" columnalign="left left" columnspacing="1em"><mtr><mtd><mstyle scriptlevel="0" displaystyle="false"><mn>1</mn></mstyle></mtd><mtd><mstyle scriptlevel="0" displaystyle="false"><mrow><mtext>if </mtext><mi>p</mi><mo>></mo><mfrac><mn>1</mn><mn>2</mn></mfrac></mrow></mstyle></mtd></mtr><mtr><mtd><mstyle scriptlevel="0" displaystyle="false"><mrow><mo stretchy="false">(</mo><mfrac><mi>p</mi><mrow><mn>1</mn><mo>−</mo><mi>p</mi></mrow></mfrac><msup><mo stretchy="false">)</mo><mi>n</mi></msup></mrow></mstyle></mtd><mtd><mstyle scriptlevel="0" displaystyle="false"><mrow><mtext>if </mtext><mi>p</mi><mo>≤</mo><mfrac><mn>1</mn><mn>2</mn></mfrac></mrow></mstyle></mtd></mtr></mtable></mrow></mrow><annotation encoding="application/x-tex">P(n) = \begin{cases} 1 &#x26;\text{if } p \gt \frac{1}{2} \\ (\frac{p}{1 - p})^n &#x26;\text{if } p \leq \frac{1}{2} \end{cases}</annotation></semantics></math></span></span></span>
<p>By the same reasoning presented above, <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>P</mi><mo stretchy="false">(</mo><mn>3</mn><mo stretchy="false">)</mo><mo>=</mo><mi>P</mi><mo stretchy="false">(</mo><mn>1</mn><msup><mo stretchy="false">)</mo><mn>3</mn></msup></mrow><annotation encoding="application/x-tex">P(3) = P(1)^3</annotation></semantics></math></span></span>. It follows that, for a given <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>n</mi></mrow><annotation encoding="application/x-tex">n</annotation></semantics></math></span></span>:</p>
<span class="katex-display"><span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>P</mi><mo stretchy="false">(</mo><mi>n</mi><mo stretchy="false">)</mo><mo>=</mo><mrow><mo fence="true">{</mo><mtable rowspacing="0.36em" columnalign="left left" columnspacing="1em"><mtr><mtd><mstyle scriptlevel="0" displaystyle="false"><mn>1</mn></mstyle></mtd><mtd><mstyle scriptlevel="0" displaystyle="false"><mrow><mtext>if </mtext><mi>p</mi><mo>></mo><mfrac><mn>1</mn><mn>2</mn></mfrac></mrow></mstyle></mtd></mtr><mtr><mtd><mstyle scriptlevel="0" displaystyle="false"><mrow><mo stretchy="false">(</mo><mfrac><mi>p</mi><mrow><mn>1</mn><mo>−</mo><mi>p</mi></mrow></mfrac><msup><mo stretchy="false">)</mo><mi>n</mi></msup></mrow></mstyle></mtd><mtd><mstyle scriptlevel="0" displaystyle="false"><mrow><mtext>if </mtext><mi>p</mi><mo>≤</mo><mfrac><mn>1</mn><mn>2</mn></mfrac></mrow></mstyle></mtd></mtr></mtable></mrow></mrow><annotation encoding="application/x-tex">P(n) = \begin{cases} 1 &#x26;\text{if } p \gt \frac{1}{2} \\ (\frac{p}{1 - p})^n &#x26;\text{if } p \leq \frac{1}{2} \end{cases}</annotation></semantics></math></span></span></span>
<p>Which completes our answer and matches the results found in the simulations.</p>
<h2 id="intepreting-the-result"><strong>Intepreting the Result</strong></h2>
<p>The answer to this problem is quite interesting because it reveals a big asymmetry: for any value <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>p</mi><mo>></mo><mfrac><mn>1</mn><mn>2</mn></mfrac></mrow><annotation encoding="application/x-tex">p > \frac{1}{2}</annotation></semantics></math></span></span>, the sailor will eventually die. Certainly, for any number sufficiently big of iterations (we are using a relatively small number of 10000 iterations per simulation), the sailor dies anyway. <em>But real life often has an upper limit</em> and therefore I'm not interested in <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>n</mi><mo>→</mo><mi mathvariant="normal">∞</mi></mrow><annotation encoding="application/x-tex">n \to \infty</annotation></semantics></math></span></span>.</p>
<p>But once life is finite and the sailor can't take random steps forever, how resilient he is? In other words, <strong>what's the probability of survival given that the sailor has been surviving for a while?</strong></p>
<h2 id="the-lindy-effect"><strong>The Lindy Effect</strong></h2>
<p>The Lindy Effect is a theory for our very intuition. From <a href="https://en.wikipedia.org/wiki/Lindy_effect" rel="noopener noreferrer" target="_blank">Wikipedia</a>:</p>
<blockquote>
<p>The Lindy effect is a theory that the future life expectancy of some non-perishable things like a technology or an idea is proportional to their current age, so that every additional period of survival implies a longer remaining life expectancy.</p>
</blockquote>
<p>In simple words, the longer <em>something</em> lives, the longer it is expected to live. We are used to perceive this as the “test of time”. If you give enough time for an idea to be tested and it survives (i.e. people keep adopting it), chances are it will survive for a while.</p>
<p>How does this apply to the Drunken Sailor problem?</p>
<p>Let us try to observe the outcome of his random walk after an arbitrary number of rounds (iterations). For example, given that the sailor survived 100 rounds, how many times does he end up alive? And for 1000? 5000?</p>
<p>Consider the following table for <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>p</mi><mo>=</mo><mn>0.5</mn></mrow><annotation encoding="application/x-tex">p = 0.5</annotation></semantics></math></span></span>, <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>n</mi><mo>=</mo><mn>10</mn></mrow><annotation encoding="application/x-tex">n = 10</annotation></semantics></math></span></span> and <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mn>10</mn><mo separator="true">,</mo><mn>000</mn></mrow><annotation encoding="application/x-tex">10,000</annotation></semantics></math></span></span> simulations, where <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>i</mi></mrow><annotation encoding="application/x-tex">i</annotation></semantics></math></span></span> is the min number of iterations for a surviving sailor:</p>
<table>
<thead>
<tr>
<th>ii</th>
<th>Survived at this point</th>
<th>Died in the end</th>
<th>Survival rate (%)</th>
</tr>
</thead>
<tbody>
<tr>
<td>10</td>
<td>10,000</td>
<td>9,230</td>
<td>7.70</td>
</tr>
<tr>
<td>100</td>
<td>6,793</td>
<td>6,023</td>
<td>11.34</td>
</tr>
<tr>
<td>1000</td>
<td>2,527</td>
<td>1,757</td>
<td>30.47</td>
</tr>
<tr>
<td>5000</td>
<td>1,129</td>
<td>359</td>
<td>68.20</td>
</tr>
</tbody>
</table>
<p>The table is very informative -- if a sailor manages to survive until the 1000th iteration (which is only <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mfrac><mn>1</mn><mn>10</mn></mfrac></mrow><annotation encoding="application/x-tex">\frac{1}{10}</annotation></semantics></math></span></span> of the number of rounds), <em>he increases his chance of survival by a factor of 4</em>. If he survives until half of the iterations, <em>his survival rate increases 800%!</em></p>
<p>The sailor is, therefore, Lindy. The longer he lives, the longer he is expected to live.</p>
<h2 id="wrapping-up"><strong>Wrapping Up</strong></h2>
<p>The Drunken Sailor Problem and the Lindy Effect help us understand the <em>test of time.</em></p>
<p>Lindy enhances <em>evolution</em>. What survives tend to have offsprings that are alike. Things that change very quickly don’t allow evolution to do its job.</p>
<p><strong>That doesn't mean that we should wait forever</strong> -- recall that even dying <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mfrac><mn>1</mn><mn>3</mn></mfrac></mrow><annotation encoding="application/x-tex">\frac{1}{3}</annotation></semantics></math></span></span> less when they hit the 5,000 mark compared to when they start to walk, <em>31% of the sailors still die</em>. But we should be respectful of things that have survived for a considerable amount of time.</p>
<p>For what is new might be fragile for events that are hard to anticipate. And drunken sailors might avoid falling off a cliff.</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Understanding the Net Present Value (NPV) with JavaScript]]></title>
<description><![CDATA[NPV and IRR with bits of math and chunks of computer science.]]></description>
<link>https://rafaelquintanilha.com/making-better-investments-with-math-and-javascript/</link>
<guid isPermaLink="false">63702f6442a473003d9dc87d</guid>
<category><![CDATA[Data Science]]></category><category><![CDATA[Quantitative Analysis]]></category><category><![CDATA[Math]]></category>
<dc:creator><![CDATA[Rafael Quintanilha]]></dc:creator>
<pubDate>Fri, 18 Jan 2019 03:00:00 GMT</pubDate>

<content:encoded><![CDATA[<p>It is often said that one of the greatest physicists of the last century, <a href="https://en.wikipedia.org/wiki/Richard_Feynman" rel="noopener noreferrer" target="_blank">Richard Feynman</a>, endorsed that the best way of learning a subject is to refine a concept to be simple enough for a 5-year-old to understand. Well, I don't expect to have any kids among my audience but I will try to explain how financial concepts NPV and IRR work using what you like (code and math).</p>
<p>This will set the foundations for building an online calculator and help us make better financial decisions in the future (<em>disclaimer: don't blame me if you go bankrupt</em>).</p>
<p>Let's start then with a simple but intriguing problem.</p>
<h2 id="the-problem">The Problem</h2>
<p>Suppose that your friend Elon asks if you are interested in backing his new endeavor. He says that if you lend him <strong>$10,000</strong> he expects to return <strong>$11,000</strong> to you after <strong>one year</strong>. Should you accept the offer?</p>
<p>In other words: <strong>should you deposit $10,000 now in order to withdraw $11,000 in one year?</strong></p>
<p>Of course, I don't intend to go into metaphysical questions about what you should do with your money nor to assess the risks of such transaction (as Elon's predictions might not be true). The real goal here is to develop a tool where one can <em>compare</em> potential investments and then decide which one fits best <em>given</em> one's condition.</p>
<h2 id="net-present-value">Net Present Value</h2>
<p>Now suppose the following: you know that you can easily allocate funds in government bonds that pay 5% per year. If your goal is to receive back the same amount your friend Elon is promising, how much should you invest?</p>
<p>Well, it's easy to see that <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mo stretchy="false">(</mo><mn>1</mn><mo>+</mo><mn>0.05</mn><mo stretchy="false">)</mo><mi>x</mi><mo>=</mo><mn>11000</mn></mrow><annotation encoding="application/x-tex">(1 + 0.05)x = 11000</annotation></semantics></math></span></span>, where <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>x</mi></mrow><annotation encoding="application/x-tex">x</annotation></semantics></math></span></span> is the initial investment in order to receive the same return Elon promised but with government bonds. This yields <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>x</mi><mo>≅</mo><mn>10476</mn></mrow><annotation encoding="application/x-tex">x \cong 10476</annotation></semantics></math></span></span>.</p>
<p>It means that, in <strong>today's money</strong>, $11,000 equates to $10,476 if you decide to go with public bonds. But according to Elon, all you need is $10,000 and hence we say that</p>
<span class="katex-display"><span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>N</mi><mi>P</mi><mi>V</mi><mo>=</mo><mn>10476</mn><mo>−</mo><mn>10000</mn><mo>=</mo><mn>476</mn></mrow><annotation encoding="application/x-tex">NPV = 10476 - 10000 = 476</annotation></semantics></math></span></span></span>
<p>This means that, in <strong>today's money</strong>, you are expected to have a <strong>net profit of $476</strong> in this transaction.</p>
<p>More generally, we can define NPV as:</p>
<span class="katex-display"><span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>N</mi><mi>P</mi><mi>V</mi><mo>=</mo><munderover><mo>∑</mo><mrow><mi>t</mi><mo>=</mo><mn>0</mn></mrow><mi>n</mi></munderover><mfrac><msub><mi>C</mi><mi>t</mi></msub><mrow><mo stretchy="false">(</mo><mn>1</mn><mo>+</mo><mi>r</mi><msup><mo stretchy="false">)</mo><mi>t</mi></msup></mrow></mfrac></mrow><annotation encoding="application/x-tex">NPV = \sum_{t=0}^n \frac{C_t}{(1 + r)^t}</annotation></semantics></math></span></span></span>
<p>Where <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi>C</mi><mi>t</mi></msub></mrow><annotation encoding="application/x-tex">C_t</annotation></semantics></math></span></span> is the <strong>cash inflow or outflow</strong> in period <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>t</mi></mrow><annotation encoding="application/x-tex">t</annotation></semantics></math></span></span> and <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>r</mi></mrow><annotation encoding="application/x-tex">r</annotation></semantics></math></span></span> is the <strong>discount rate</strong>. Check that for <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi>C</mi><mn>0</mn></msub><mo>=</mo><mo>−</mo><mn>10000</mn></mrow><annotation encoding="application/x-tex">C_0 = -10000</annotation></semantics></math></span></span>, <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi>C</mi><mn>1</mn></msub><mo>=</mo><mn>11000</mn></mrow><annotation encoding="application/x-tex">C_1 = 11000</annotation></semantics></math></span></span>, <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>n</mi><mo>=</mo><mn>1</mn></mrow><annotation encoding="application/x-tex">n = 1</annotation></semantics></math></span></span> and <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>r</mi><mo>=</mo><mn>0.05</mn></mrow><annotation encoding="application/x-tex">r = 0.05</annotation></semantics></math></span></span> we achieve the same result.</p>
<p>Remember, in plain English (and according to <a href="https://www.investopedia.com/terms/n/npv.asp" rel="noopener noreferrer" target="_blank">Investopedia</a>):</p>
<blockquote>
<p>NPV = (Today’s value of the expected cash flows) – (Today’s value of invested cash)</p>
</blockquote>
<h2 id="writing-a-function-to-evaluate-the-npv">Writing a Function to Evaluate the NPV</h2>
<p>Shall we write some code?</p>
<p>The goal here is to write a function that translates the above equation into bits. Thankfully, with JavaScript we can write it in a single-line function:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> NPV</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> (cashflow, discountRate) </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> cashflow</span></span>
<span class="line"><span style="color:#EDCC95">  .reduce</span><span style="color:#ECEBE8">((acc, val, i) </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> acc </span><span style="color:#A1C1E4">+</span><span style="color:#ECEBE8"> val </span><span style="color:#A1C1E4">/</span><span style="color:#EDCC95"> Math.pow</span><span style="color:#ECEBE8">((</span><span style="color:#97CCAE">1</span><span style="color:#A1C1E4"> +</span><span style="color:#ECEBE8"> discountRate), i), </span><span style="color:#97CCAE">0</span><span style="color:#ECEBE8">);</span></span></code></pre></figure>
<p>Beautiful, isn't it?</p>
<p>If you are not familiar with arrow functions, I suggest you take some time and read <a href="https://medium.freecodecamp.org/when-and-why-you-should-use-es6-arrow-functions-and-when-you-shouldnt-3d851d7f0b26" rel="noopener noreferrer" target="_blank">this great article about it</a>. You may also want to check <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce" rel="noopener noreferrer" target="_blank"><code>.reduce</code> reference</a> in JavaScript.</p>
<p>Let's walk through it:</p>
<p>First we assume that <code>cashflow</code> is an array of numbers, the one we want to <em>reduce</em>. The <code>.reduce</code> method takes two arguments, the first one being the <em>reducer</em> and the second one being an optional <em>initial value</em>.</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> reducer</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> (acc, val, i) </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> acc </span><span style="color:#A1C1E4">+</span><span style="color:#ECEBE8"> val </span><span style="color:#A1C1E4">/</span><span style="color:#EDCC95"> Math.pow</span><span style="color:#ECEBE8">((</span><span style="color:#97CCAE">1</span><span style="color:#A1C1E4"> +</span><span style="color:#ECEBE8"> discountRate), i);</span></span></code></pre></figure>
<p>On the other hand, <code>reducer</code> is a function that takes three args:</p>
<ul>
<li><code>acc</code> is the accumulator, the result of previous iterations.</li>
<li><code>val</code> is the current value being evaluated.</li>
<li><code>i</code> is the current index.</li>
</ul>
<p>We are then calling the <em>reducer</em> for every entry in the array (here assuming the value of <code>val</code>), and evaluating the following:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#ECEBE8">acc </span><span style="color:#A1C1E4">+</span><span style="color:#ECEBE8"> val </span><span style="color:#A1C1E4">/</span><span style="color:#EDCC95"> Math.pow</span><span style="color:#ECEBE8">((</span><span style="color:#97CCAE">1</span><span style="color:#A1C1E4"> +</span><span style="color:#ECEBE8"> discountRate), i)</span></span></code></pre></figure>
<p>Which basically is evaluating <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mfrac><msub><mi>C</mi><mi>i</mi></msub><mrow><mo stretchy="false">(</mo><mn>1</mn><mo>+</mo><mi>d</mi><mi>i</mi><mi>s</mi><mi>c</mi><mi>o</mi><mi>u</mi><mi>n</mi><mi>t</mi><mi>R</mi><mi>a</mi><mi>t</mi><mi>e</mi><msup><mo stretchy="false">)</mo><mi>i</mi></msup></mrow></mfrac></mrow><annotation encoding="application/x-tex">\frac{C_i}{(1 + discountRate)^i}</annotation></semantics></math></span></span> and adding to the previously evaluated <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>i</mi></mrow><annotation encoding="application/x-tex">i</annotation></semantics></math></span></span> (remember that we initialize <code>acc</code> as 0).</p>
<p>You are now ready to test our function:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> NPV</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> (cashflow, discountRate) </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> cashflow</span></span>
<span class="line"><span style="color:#EDCC95">  .reduce</span><span style="color:#ECEBE8">((acc, val, i) </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> acc </span><span style="color:#A1C1E4">+</span><span style="color:#ECEBE8"> val </span><span style="color:#A1C1E4">/</span><span style="color:#EDCC95"> Math.pow</span><span style="color:#ECEBE8">((</span><span style="color:#97CCAE">1</span><span style="color:#A1C1E4"> +</span><span style="color:#ECEBE8"> discountRate), i), </span><span style="color:#97CCAE">0</span><span style="color:#ECEBE8">);</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#ECEBE8"> cashflow </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> [</span><span style="color:#A1C1E4">-</span><span style="color:#97CCAE">10000</span><span style="color:#ECEBE8">, </span><span style="color:#97CCAE">11000</span><span style="color:#ECEBE8">];</span></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#ECEBE8"> discountRate </span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE"> 0.05</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#EDCC95">console.log</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">NPV</span><span style="color:#ECEBE8">(cashflow, discountRate)); </span><span style="color:#A7A49E;font-style:italic">// 476.19047619047524</span></span></code></pre></figure>
<p>Great, now you know how to define NPV in english, in mathematics and in JavaScript. Tell me about being a polyglot!</p>
<h2 id="internal-rate-of-return">Internal Rate of Return</h2>
<p>NPV is great but still an <strong>absolute</strong> number. Is <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>N</mi><mi>P</mi><mi>V</mi><mo>=</mo><mn>476</mn></mrow><annotation encoding="application/x-tex">NPV = 476</annotation></semantics></math></span></span> good or bad? Apart from the fact that this is a particular question (once risks are assessed differently by different people), it lacks information. For example, it is clear that this number is significantly better if the initial investment <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi>C</mi><mn>0</mn></msub></mrow><annotation encoding="application/x-tex">C_0</annotation></semantics></math></span></span> was $5,000, and definitely worse if <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>t</mi><mo>=</mo><mn>10</mn></mrow><annotation encoding="application/x-tex">t = 10</annotation></semantics></math></span></span>.</p>
<p>You then start looking for another metric. Instead of thinking about <em>how much money you would make</em> with such an investment, you try to figure out what the <em>discount rate</em> is. You know that the government pays you 5%, but how much is Elon paying you <em>given</em> his predictions become true?</p>
<p>Again, it's easy to see that <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mo stretchy="false">(</mo><mn>1</mn><mo>+</mo><mi>r</mi><mo stretchy="false">)</mo><mn>10000</mn><mo>=</mo><mn>11000</mn></mrow><annotation encoding="application/x-tex">(1 + r)10000 = 11000</annotation></semantics></math></span></span>, where <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>r</mi></mrow><annotation encoding="application/x-tex">r</annotation></semantics></math></span></span> is the discount rate for this investment with the projected cash inflow. This yields <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>r</mi><mo>=</mo><mn>0.1</mn></mrow><annotation encoding="application/x-tex">r = 0.1</annotation></semantics></math></span></span>, or <strong>10%</strong>.</p>
<p>And now we are talking! You have a very concrete way of <em>comparing</em> (this is the keyword) two investments: government bonds paying 5%, Elon paying 10%. Are Elon's projections real? Well, for twice the rate you find in the market, you may consider giving it a shot.</p>
<p>Meet IRR -- the <strong>internal return rate</strong> for a given initial investment and a projected cash inflow or outflow over a period of time. We can define IRR as:</p>
<span class="katex-display"><span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mn>0</mn><mo>=</mo><munderover><mo>∑</mo><mrow><mi>t</mi><mo>=</mo><mn>0</mn></mrow><mi>n</mi></munderover><mfrac><msub><mi>C</mi><mi>t</mi></msub><mrow><mo stretchy="false">(</mo><mn>1</mn><mo>+</mo><mi>r</mi><msup><mo stretchy="false">)</mo><mi>t</mi></msup></mrow></mfrac></mrow><annotation encoding="application/x-tex">0 = \sum_{t=0}^n \frac{C_t}{(1 + r)^t}</annotation></semantics></math></span></span></span>
<p>Where <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi>C</mi><mi>t</mi></msub></mrow><annotation encoding="application/x-tex">C_t</annotation></semantics></math></span></span> is the <strong>cash inflow or outflow</strong> over period <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>t</mi></mrow><annotation encoding="application/x-tex">t</annotation></semantics></math></span></span> and <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>r</mi></mrow><annotation encoding="application/x-tex">r</annotation></semantics></math></span></span> is the <strong>internal return rate</strong>. Check that for <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi>C</mi><mn>0</mn></msub><mo>=</mo><mo>−</mo><mn>10000</mn></mrow><annotation encoding="application/x-tex">C_0 = -10000</annotation></semantics></math></span></span>, <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi>C</mi><mn>1</mn></msub><mo>=</mo><mn>11000</mn></mrow><annotation encoding="application/x-tex">C_1 = 11000</annotation></semantics></math></span></span> and <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>n</mi><mo>=</mo><mn>1</mn></mrow><annotation encoding="application/x-tex">n = 1</annotation></semantics></math></span></span> the formula yields <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>r</mi><mo>=</mo><mn>0.1</mn></mrow><annotation encoding="application/x-tex">r = 0.1</annotation></semantics></math></span></span>.</p>
<blockquote>
<p>IRR is the discount rate that, for a projected cash inflow or outflow, yields <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>N</mi><mi>P</mi><mi>V</mi><mo>=</mo><mn>0</mn></mrow><annotation encoding="application/x-tex">NPV = 0</annotation></semantics></math></span></span>.</p>
</blockquote>
<p>And now things are making more sense (hopefully).</p>
<h2 id="a-more-complex-problem">A More Complex Problem</h2>
<p>Elon's example was deliberately easy to follow but -- as with many things in life -- there is not always the case.</p>
<p>You are a businessman and as such you understand that immediate returns are not usually big. Is your understanding that, in order to extract maximum value, you need to reinvest your money for at least 5 years.</p>
<p>Your friend Jeff then approaches with a different opportunity: you invest initially $10,000 and reinvest all generated cash for the next 5 years. His estimates are that this business will generate <strong>$11,000</strong> in year 1, <strong>$12,000</strong> in year 2, <strong>$13,000</strong> in year 3, <strong>$14,000</strong> in year 4 and finally <strong>$15,000</strong> in year 5.</p>
<p>That sounds good, but how good exactly? You then use the IRR formula you just learned in order to evaluate the <em>expected rate of growth</em> for this project:</p>
<p><span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mn>0</mn><mo>=</mo><mfrac><mn>10000</mn><mrow><mo stretchy="false">(</mo><mn>1</mn><mo>+</mo><mi>r</mi><msup><mo stretchy="false">)</mo><mn>0</mn></msup></mrow></mfrac><mo>+</mo><mfrac><mn>11000</mn><mrow><mo stretchy="false">(</mo><mn>1</mn><mo>+</mo><mi>r</mi><msup><mo stretchy="false">)</mo><mn>1</mn></msup></mrow></mfrac><mo>+</mo><mfrac><mn>12000</mn><mrow><mo stretchy="false">(</mo><mn>1</mn><mo>+</mo><mi>r</mi><msup><mo stretchy="false">)</mo><mn>2</mn></msup></mrow></mfrac><mo>+</mo><mfrac><mn>13000</mn><mrow><mo stretchy="false">(</mo><mn>1</mn><mo>+</mo><mi>r</mi><msup><mo stretchy="false">)</mo><mn>3</mn></msup></mrow></mfrac><mo>+</mo><mfrac><mn>14000</mn><mrow><mo stretchy="false">(</mo><mn>1</mn><mo>+</mo><mi>r</mi><msup><mo stretchy="false">)</mo><mn>4</mn></msup></mrow></mfrac><mo>+</mo><mfrac><mn>15000</mn><mrow><mo stretchy="false">(</mo><mn>1</mn><mo>+</mo><mi>r</mi><msup><mo stretchy="false">)</mo><mn>5</mn></msup></mrow></mfrac></mrow><annotation encoding="application/x-tex">0 = \frac{10000}{(1 + r)^0} + \frac{11000}{(1 + r)^1} + \frac{12000}{(1 + r)^2} + \frac{13000}{(1 + r)^3} + \frac{14000}{(1 + r)^4} + \frac{15000}{(1 + r)^5}</annotation></semantics></math></span></span></p>
<p>You quickly realize that things look more elegant if you let <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>x</mi><mo>=</mo><mfrac><mn>1</mn><mrow><mn>1</mn><mo>+</mo><mi>r</mi></mrow></mfrac></mrow><annotation encoding="application/x-tex">x = \frac{1}{1 + r}</annotation></semantics></math></span></span>:</p>
<p><span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mn>15000</mn><msup><mi>x</mi><mn>5</mn></msup><mo>+</mo><mn>14000</mn><msup><mi>x</mi><mn>4</mn></msup><mo>+</mo><mn>13000</mn><msup><mi>x</mi><mn>3</mn></msup><mo>+</mo><mn>12000</mn><msup><mi>x</mi><mn>2</mn></msup><mo>+</mo><mn>11000</mn><mi>x</mi><mo>−</mo><mn>10000</mn><mo>=</mo><mn>0</mn></mrow><annotation encoding="application/x-tex">15000x^5 + 14000x^4 + 13000x^3 + 12000x^2 + 11000x - 10000 = 0</annotation></semantics></math></span></span></p>
<p>Which is a <em>quintic polynomial</em>. Well, you definitely know how to solve quadratic polynomials (your friend Bhaskhara), cubic polynomials (<a href="https://en.wikipedia.org/wiki/Cubic_function#Cardano&#x27;s_method" rel="noopener noreferrer" target="_blank">Cardano-Tartaglia's</a> method) and quartic polynomials (<a href="https://math.stackexchange.com/questions/785/is-there-a-general-formula-for-solving-4th-degree-equations-quartic" rel="noopener noreferrer" target="_blank">which is ugly but doable</a>). But it happens that for 5th degree polynomials a fellow named <a href="https://en.wikipedia.org/wiki/%C3%89variste_Galois" rel="noopener noreferrer" target="_blank">Évariste Galois</a> explains that you simply <em>can't</em> have a nice formula (as Bhaskara is). <a href="https://en.wikipedia.org/wiki/Galois_theory" rel="noopener noreferrer" target="_blank">His ideas</a> were used to prove the <a href="https://en.wikipedia.org/wiki/Abel%E2%80%93Ruffini_theorem" rel="noopener noreferrer" target="_blank">Abel-Ruffini theorem</a> (Galois later died at age of 20 in a duel, but this is another story).</p>
<p>Anyway, we live in the computer era and therefore we shall be able to solve the above equation.</p>
<h2 id="newtons-method">Newton's Method</h2>
<p>A couple of centuries ago one guy named Isaac Newton was born and did some great stuff. That should ring a bell.</p>
<p>Among thousand other things, Newton figured out a way to find the <em>roots</em> of an equation. You can find a full reference about it in <a href="https://en.wikipedia.org/wiki/Newton%27s_method" rel="noopener noreferrer" target="_blank">Wikipedia</a> but I'll try to give some intuition here.</p>
<p>First, we are not trying to find <em>all</em> solutions. We are especially interested on the solution that is <em>semantically coherent</em>, meaning that we should be able to put our discount rate in a fair range -- I know that Jeff's operation is expected to be lucrative, therefore <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>r</mi><mo>></mo><mn>0</mn></mrow><annotation encoding="application/x-tex">r > 0</annotation></semantics></math></span></span>. On the other hand, it's certainly not multiplying my capital by a factor of 5, so <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>r</mi><mo>&#x3C;</mo><mn>4</mn></mrow><annotation encoding="application/x-tex">r &#x3C; 4</annotation></semantics></math></span></span>. Intuitively, then, <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>r</mi></mrow><annotation encoding="application/x-tex">r</annotation></semantics></math></span></span> must exist and be somewhere in the middle.</p>
<p>Now consider the above polynomial as the function:</p>
<p><span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>f</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>=</mo><mn>15000</mn><msup><mi>x</mi><mn>5</mn></msup><mo>+</mo><mn>14000</mn><msup><mi>x</mi><mn>4</mn></msup><mo>+</mo><mn>13000</mn><msup><mi>x</mi><mn>3</mn></msup><mo>+</mo><mn>12000</mn><msup><mi>x</mi><mn>2</mn></msup><mo>+</mo><mn>11000</mn><mi>x</mi><mo>−</mo><mn>10000</mn></mrow><annotation encoding="application/x-tex">f(x) = 15000x^5 + 14000x^4 + 13000x^3 + 12000x^2 + 11000x - 10000</annotation></semantics></math></span></span></p>
<p>For <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>x</mi><mo>=</mo><mn>0</mn></mrow><annotation encoding="application/x-tex">x = 0</annotation></semantics></math></span></span> we have <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>f</mi><mo stretchy="false">(</mo><mn>0</mn><mo stretchy="false">)</mo><mo>=</mo><mo>−</mo><mn>10000</mn></mrow><annotation encoding="application/x-tex">f(0) = -10000</annotation></semantics></math></span></span> and for <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>x</mi><mo>=</mo><mn>1</mn></mrow><annotation encoding="application/x-tex">x = 1</annotation></semantics></math></span></span> we have <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>f</mi><mo stretchy="false">(</mo><mn>1</mn><mo stretchy="false">)</mo><mo>=</mo><mn>55000</mn></mrow><annotation encoding="application/x-tex">f(1) = 55000</annotation></semantics></math></span></span>. What does that mean?</p>
<p>Recall that a <em>root</em> of a function is a <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>x</mi></mrow><annotation encoding="application/x-tex">x</annotation></semantics></math></span></span> in which <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>f</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>=</mo><mn>0</mn></mrow><annotation encoding="application/x-tex">f(x) = 0</annotation></semantics></math></span></span>. But also consider that, for <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>x</mi><mo>></mo><mn>0</mn></mrow><annotation encoding="application/x-tex">x > 0</annotation></semantics></math></span></span>, <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mn>15000</mn><msup><mi>x</mi><mn>5</mn></msup><mo>+</mo><mn>14000</mn><msup><mi>x</mi><mn>4</mn></msup><mo>+</mo><mn>13000</mn><msup><mi>x</mi><mn>3</mn></msup><mo>+</mo><mn>12000</mn><msup><mi>x</mi><mn>2</mn></msup><mo>+</mo><mn>11000</mn><mi>x</mi></mrow><annotation encoding="application/x-tex">15000x^5 + 14000x^4 + 13000x^3 + 12000x^2 + 11000x</annotation></semantics></math></span></span> is <strong>always</strong> positive and therefore <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>f</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">f(x)</annotation></semantics></math></span></span> is <strong>crescent</strong> in this interval.</p>
<p>So if I evaluate <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>f</mi></mrow><annotation encoding="application/x-tex">f</annotation></semantics></math></span></span> for <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>x</mi><mo>=</mo><mn>0.1</mn></mrow><annotation encoding="application/x-tex">x = 0.1</annotation></semantics></math></span></span> it must be <em>bigger</em> than <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>f</mi><mo stretchy="false">(</mo><mn>0</mn><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">f(0)</annotation></semantics></math></span></span>. I also know that <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>f</mi></mrow><annotation encoding="application/x-tex">f</annotation></semantics></math></span></span> is crescent, <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>f</mi><mo stretchy="false">(</mo><mn>0</mn><mo stretchy="false">)</mo><mo>&#x3C;</mo><mn>0</mn></mrow><annotation encoding="application/x-tex">f(0) &#x3C; 0</annotation></semantics></math></span></span>and <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>f</mi><mo stretchy="false">(</mo><mn>1</mn><mo stretchy="false">)</mo><mo>></mo><mn>0</mn></mrow><annotation encoding="application/x-tex">f(1) > 0</annotation></semantics></math></span></span>. Then if I keep increasing <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>x</mi></mrow><annotation encoding="application/x-tex">x</annotation></semantics></math></span></span> in baby steps, eventually I'm expected to get close to 0, i.e., close to the <em>root</em>.</p>
<p>In other words, knowing that <a href="https://math.stackexchange.com/questions/284184/prove-that-any-polynomial-function-is-continuous" rel="noopener noreferrer" target="_blank">all polynomials are continuous</a>, in order to go from a negative number to a positive number, I necessarily need to cross <em>zero</em>, that is, the <em>root</em>.</p>
<p>This, my friends, is the root (pun intended) of Newton's Method.</p>
<h2 id="writing-a-function-to-evaluate-the-irr">Writing a Function to Evaluate the IRR</h2>
<p>We already understand NPV and how it is needed to evaluate the IRR. But also discovered that isn't <em>that</em> simple to find the roots of big polynomials. We therefore simplified Newton's Method by adjusting it to our use case. How to turn this into code?</p>
<p>That's how:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> IRR</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> (cashflow, initialGuess </span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE"> 0.1</span><span style="color:#ECEBE8">) </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> maxTries </span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE"> 10000</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> delta </span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE"> 0.001</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">  let</span><span style="color:#ECEBE8"> guess </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> initialGuess;</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> multiplier </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> NPV</span><span style="color:#ECEBE8">(cashflow, guess) </span><span style="color:#A1C1E4">></span><span style="color:#97CCAE"> 0</span><span style="color:#A1C1E4"> ?</span><span style="color:#97CCAE"> 1</span><span style="color:#A1C1E4"> :</span><span style="color:#A1C1E4"> -</span><span style="color:#97CCAE">1</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">  let</span><span style="color:#ECEBE8"> i </span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE"> 0</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">  while</span><span style="color:#ECEBE8"> ( i </span><span style="color:#A1C1E4">&#x3C;</span><span style="color:#ECEBE8"> maxTries ) {</span></span>
<span class="line"><span style="color:#A1C1E4">    const</span><span style="color:#ECEBE8"> guessedNPV </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> NPV</span><span style="color:#ECEBE8">(cashflow, guess);</span></span>
<span class="line"><span style="color:#A1C1E4">    if</span><span style="color:#ECEBE8"> ( multiplier </span><span style="color:#A1C1E4">*</span><span style="color:#ECEBE8"> guessedNPV </span><span style="color:#A1C1E4">></span><span style="color:#ECEBE8"> delta ) {</span></span>
<span class="line"><span style="color:#ECEBE8">      guess </span><span style="color:#A1C1E4">+=</span><span style="color:#ECEBE8"> (multiplier </span><span style="color:#A1C1E4">*</span><span style="color:#ECEBE8"> delta);</span></span>
<span class="line"><span style="color:#ECEBE8">      i </span><span style="color:#A1C1E4">+=</span><span style="color:#97CCAE"> 1</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#ECEBE8">    }</span></span>
<span class="line"><span style="color:#A1C1E4">    else</span><span style="color:#A1C1E4"> break</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#ECEBE8">  }</span></span>
<span class="line"><span style="color:#EDCC95">  console.log</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">`Found IRR = ${</span><span style="color:#97CCAE">guess</span><span style="color:#97CCAE">} in ${</span><span style="color:#97CCAE">i</span><span style="color:#97CCAE">} trials`</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span></code></pre></figure>
<p>Let it sink in a bit. But don't worry, we are going to cover it all:</p>
<p>The first part basically defines the necessary variables. Here <code>cashflow</code> is the array of cash inflow or outflow and <code>initialGuess</code> our starting point for the Search of the Root™.</p>
<ul>
<li><code>maxTries</code> defines the maximum number of iterations. Eventually the algo can get stuck or our guess was too bad and we don't want this to take forever;</li>
<li><code>delta</code> is the iteration step and also how close to 0 we are satisfied to get;</li>
<li><code>guess</code> is the current guess for the root is in a particular iteration;</li>
<li><code>i</code> is the iteration counter;</li>
<li><code>multiplier</code> is <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mo>±</mo><mn>1</mn></mrow><annotation encoding="application/x-tex">±1</annotation></semantics></math></span></span>. In short, it is <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mo>+</mo><mn>1</mn></mrow><annotation encoding="application/x-tex">+1</annotation></semantics></math></span></span> when we need to <em>increase</em> <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>x</mi></mrow><annotation encoding="application/x-tex">x</annotation></semantics></math></span></span> (decrease <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>r</mi></mrow><annotation encoding="application/x-tex">r</annotation></semantics></math></span></span>) in the next step and <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mo>−</mo><mn>1</mn></mrow><annotation encoding="application/x-tex">-1</annotation></semantics></math></span></span> when our guess was too big and we need to <em>decrease</em> <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>x</mi></mrow><annotation encoding="application/x-tex">x</annotation></semantics></math></span></span> (increase <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>r</mi></mrow><annotation encoding="application/x-tex">r</annotation></semantics></math></span></span>). Recall that we made the transformation <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>x</mi><mo>=</mo><mfrac><mn>1</mn><mrow><mn>1</mn><mo>+</mo><mi>r</mi></mrow></mfrac></mrow><annotation encoding="application/x-tex">x = \frac{1}{1 + r}</annotation></semantics></math></span></span> and therefore <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>x</mi></mrow><annotation encoding="application/x-tex">x</annotation></semantics></math></span></span> is <em>inversely</em> proportional to <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>r</mi></mrow><annotation encoding="application/x-tex">r</annotation></semantics></math></span></span>.</li>
</ul>
<p>Next lines should be easy. <code>guessedNPV</code> is the NPV value for the current guess. Recall this is what we are trying to approximate to zero.</p>
<p>We then check in the following lines if our guessed value is bigger than the designated <code>delta</code>, increase the iteration and go again. If smaller -- bingo! We have found a <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>x</mi></mrow><annotation encoding="application/x-tex">x</annotation></semantics></math></span></span> that gets as close as desirable to 0 and we shall stop.</p>
<p>Go ahead and test the code:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A7A49E;font-style:italic">// Elon's proposition: IRR = 10%</span></span>
<span class="line"><span style="color:#EDCC95">IRR</span><span style="color:#ECEBE8">([</span><span style="color:#A1C1E4">-</span><span style="color:#97CCAE">10000</span><span style="color:#ECEBE8">, </span><span style="color:#97CCAE">11000</span><span style="color:#ECEBE8">], </span><span style="color:#97CCAE">0.05</span><span style="color:#ECEBE8">); </span><span style="color:#A7A49E;font-style:italic">// Found IRR = 0.10000000000000005 in 50 trials</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">// Jake's proposition: IRR = 115%</span></span>
<span class="line"><span style="color:#EDCC95">IRR</span><span style="color:#ECEBE8">([</span><span style="color:#A1C1E4">-</span><span style="color:#97CCAE">10000</span><span style="color:#ECEBE8">, </span><span style="color:#97CCAE">11000</span><span style="color:#ECEBE8">, </span><span style="color:#97CCAE">12000</span><span style="color:#ECEBE8">, </span><span style="color:#97CCAE">13000</span><span style="color:#ECEBE8">, </span><span style="color:#97CCAE">14000</span><span style="color:#ECEBE8">, </span><span style="color:#97CCAE">15000</span><span style="color:#ECEBE8">]); </span><span style="color:#A7A49E;font-style:italic">// Found IRR = 1.150999999999984 in 1051 trials</span></span></code></pre></figure>
<p>With our brand new code we are able to evaluate how much our IRR is for Jeff's project: <strong>115%</strong>. Not bad, huh?</p>
<h2 id="wrapping-up">Wrapping Up</h2>
<p>Both NPV and IRR are comparative metrics you might want to use when deciding between investments. For a given initial amount, you expect the investments with higher projected NPV and IRR to theoretically be better. In real life that's not always the case.</p>
<ol>
<li>
<p>Although IRR gives you a number to compare, it says nothing about the <em>risks</em> involved. For example, Jeff may be more reliable than Elon. His projections may be more solid. His business model is more consistent. So if investment A yields 20% and investment B yields 24% but with a <em>riskier model</em>, you may want to put your money on A.</p>
</li>
<li>
<p>Liquidity matters. IRR tells about returns, but don't forget that investments may have different durations. If investment A yields 20% <em>in 2 years</em> and investment B yields 24% <em>in 5 years</em>, you may want to go with A.</p>
</li>
<li>
<p>IRR assumes all available money at the end of each <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>t</mi></mrow><annotation encoding="application/x-tex">t</annotation></semantics></math></span></span> will be reinvested. In real life that rarely is the case.</p>
</li>
</ol>
<p>Now that our knowledge about IRR and NPV is solid, we can move forward. In this post, we have made assumptions (about convergence, for example) that won't always be true. In the next post we will cover those gaps and build together a React app that evaluates the IRR of a given investment.</p>
<p>Stay tuned!</p>]]></content:encoded>
</item>
</channel>
</rss>
