<?xml version="1.0" encoding="UTF-8"?>
<rss  xmlns:atom="http://www.w3.org/2005/Atom" 
      xmlns:media="http://search.yahoo.com/mrss/" 
      xmlns:content="http://purl.org/rss/1.0/modules/content/" 
      xmlns:dc="http://purl.org/dc/elements/1.1/" 
      version="2.0">
<channel>
<title>Sandro Silva</title>
<link>https://sandrosilva.site/</link>
<atom:link href="https://sandrosilva.site/index.xml" rel="self" type="application/rss+xml"/>
<description>Notes, tools and projects on personal finance, investing and data.</description>
<image>
<url>https://sandrosilva.site/images/headshot.jpg</url>
<title>Sandro Silva</title>
<link>https://sandrosilva.site/</link>
</image>
<generator>quarto-1.6.40</generator>
<lastBuildDate>Sat, 28 Nov 2026 00:00:00 GMT</lastBuildDate>
<item>
  <title>Do You Have Enough for Retirement?</title>
  <link>https://sandrosilva.site/writing/2026-11-28-investment-planner/</link>
  <description><![CDATA[ 




<p>Working in private banking and having started to read more about personal finance, I keep coming back to one question: am I saving enough for retirement?</p>
<p>I built this tool to picture how investing a little every month, slowly and consistently, could get me there. Plug in your own numbers and see how the plan holds up in a <strong>bear</strong> market, a <strong>typical</strong> one, and a <strong>bull</strong> run, each drawn from real S&amp;P 500 returns from 1928 through 2025.</p>
<div class="aside-note">
<p>This isn’t the final word on investing, just a starting point. Before acting on any plan, think about your ability and willingness to take risk, taxes, fees, and anything else in your own situation that a simple calculator can’t see.</p>
<p><em>This is not financial advice. It’s for educational purposes only.</em></p>
</div>
<section id="three-ways-the-market-could-go" class="level2">
<h2 class="anchored" data-anchor-id="three-ways-the-market-could-go">Three ways the market could go</h2>
<div class="scenario-guide">
<div class="guide-item guide-bear">
<p><strong>Bear market</strong><br> Usually means prices falling 20% or more from a recent high. Here, it’s a long stretch of <strong>weak returns</strong>: only 1 in 5 historical stretches did worse.</p>
</div>
<div class="guide-item guide-base">
<p><strong>Base case</strong><br> The middle of the road. It’s the <strong>typical outcome</strong>: half of all historical stretches did better and half did worse.</p>
</div>
<div class="guide-item guide-bull">
<p><strong>Bull market</strong><br> Usually means prices rising 20% or more from a recent low. Here, it’s a long stretch of <strong>strong returns</strong>: only 1 in 5 historical stretches did better.</p>
</div>
</div>
<p>All returns here are <strong>real returns</strong>: what the S&amp;P 500 earned <strong>after inflation</strong>. Since 1928 that has averaged about 7% a year, versus about 10% before inflation. Planning in real terms keeps every number in today’s money, so $1 million at the end means what $1 million buys today.</p>
<div class="planner-panel">
<div class="planner-panel-title">
<p>Your plan</p>
</div>
<div class="usd-note">
<p><strong>All amounts are in US dollars (USD).</strong> The returns come from the S&amp;P 500, which is priced in dollars. If you save in pesos, convert your numbers to dollars first.</p>
</div>
<div class="cell">
<details class="code-fold hidden">
<summary>Show code</summary>
<div class="sourceCode cell-code hidden" id="cb1" data-startfrom="51" data-source-offset="-0" style="background: #f1f3f5;"><pre class="sourceCode js code-with-copy"><code class="sourceCode javascript" style="counter-reset: source-line 50;"><span id="cb1-51">viewof initial <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">amountInput</span>({<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">label</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Starting amount"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">value</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10000</span>})</span>
<span id="cb1-52">viewof contribution <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">amountInput</span>({<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">label</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Regular contribution"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">value</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">500</span>})</span>
<span id="cb1-53">viewof frequency <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Inputs<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">select</span>(<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">new</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">Map</span>([[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Every month"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Every quarter"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Every year"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]])<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> {<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">label</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"How often"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">value</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>})</span>
<span id="cb1-54">viewof years <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Inputs<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">range</span>([<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span>]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> {<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">label</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Years until retirement"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">value</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">25</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">step</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>})</span>
<span id="cb1-55">viewof goal <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">amountInput</span>({<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">label</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Yearly income you want in retirement"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">value</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">40000</span>})</span>
<span id="cb1-56">viewof withdrawal <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Inputs<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">range</span>([<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> {<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">label</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Withdrawal rate (%)"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">value</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">step</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span>})</span>
<span id="cb1-57">viewof inflation <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Inputs<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">range</span>([<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> {<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">label</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Inflation (%)"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">value</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">step</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span>})</span>
<span id="cb1-58">viewof growContrib <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Inputs<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">toggle</span>({<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">label</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Raise contributions with inflation"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">value</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">true</span>})</span></code></pre></div>
</details>
<div class="cell-output cell-output-display">
<div>
<div id="ojs-cell-1-1" data-nodetype="declaration">

</div>
</div>
</div>
<div class="cell-output cell-output-display">
<div>
<div id="ojs-cell-1-2" data-nodetype="declaration">

</div>
</div>
</div>
<div class="cell-output cell-output-display">
<div>
<div id="ojs-cell-1-3" data-nodetype="declaration">

</div>
</div>
</div>
<div class="cell-output cell-output-display">
<div>
<div id="ojs-cell-1-4" data-nodetype="declaration">

</div>
</div>
</div>
<div class="cell-output cell-output-display">
<div>
<div id="ojs-cell-1-5" data-nodetype="declaration">

</div>
</div>
</div>
<div class="cell-output cell-output-display">
<div>
<div id="ojs-cell-1-6" data-nodetype="declaration">

</div>
</div>
</div>
<div class="cell-output cell-output-display">
<div>
<div id="ojs-cell-1-7" data-nodetype="declaration">

</div>
</div>
</div>
<div class="cell-output cell-output-display">
<div>
<div id="ojs-cell-1-8" data-nodetype="declaration">

</div>
</div>
</div>
</div>
</div>
<div class="cell">
<details class="code-fold hidden">
<summary>Show code</summary>
<div class="sourceCode cell-code hidden" id="cb2" data-startfrom="63" data-source-offset="0" style="background: #f1f3f5;"><pre class="sourceCode js code-with-copy"><code class="sourceCode javascript" style="counter-reset: source-line 62;"><span id="cb2-63">verdict <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {</span>
<span id="cb2-64">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> base <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> results<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">find</span>(r <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> r<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">===</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Base"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb2-65">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> ok <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> base<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">income</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> goal<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb2-66">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">html</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">`&lt;div class="verdict </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span>ok <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"verdict-ok"</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"verdict-short"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">"&gt;</span></span>
<span id="cb2-67"><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">    &lt;div class="verdict-kicker"&gt;In a typical market&lt;/div&gt;</span></span>
<span id="cb2-68"><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">    &lt;div class="verdict-headline"&gt;You'd retire with &lt;strong&gt;</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">money</span>(base<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">real</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">&lt;/strong&gt; in today's money, enough for &lt;strong&gt;</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">money</span>(base<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">income</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">&lt;/strong&gt; a year.&lt;/div&gt;</span></span>
<span id="cb2-69"><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">    &lt;div class="verdict-status"&gt;</span></span>
<span id="cb2-70"><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">      &lt;span class="verdict-icon"&gt;</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span>ok <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"✓"</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"✕"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">&lt;/span&gt;</span></span>
<span id="cb2-71"><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">      </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span>ok</span>
<span id="cb2-72">        <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">html</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">`That covers your </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">money</span>(goal)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;"> goal, with </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">money</span>(base<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">income</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> goal)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;"> a year to spare.`</span></span>
<span id="cb2-73">        <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">html</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">`That's </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">money</span>(goal <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> base<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">income</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;"> a year short of your </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">money</span>(goal)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;"> goal. You'd need about </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">money</span>(target)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;"> saved.`</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb2-74"><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">    &lt;/div&gt;</span></span>
<span id="cb2-75"><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">  &lt;/div&gt;`</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb2-76">}</span></code></pre></div>
</details>
<div class="cell-output cell-output-display">
<div id="ojs-cell-2" data-nodetype="declaration">

</div>
</div>
</div>
<div class="cell">
<details class="code-fold hidden">
<summary>Show code</summary>
<div class="sourceCode cell-code hidden" id="cb3" data-startfrom="81" data-source-offset="0" style="background: #f1f3f5;"><pre class="sourceCode js code-with-copy"><code class="sourceCode javascript" style="counter-reset: source-line 80;"><span id="cb3-81"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">html</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">`&lt;div class="scenario-cards"&gt;</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span>results<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">map</span>(r <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> {</span>
<span id="cb3-82">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> pct <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">Math</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(r<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">income</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> goal<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.5</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb3-83">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> ok <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> r<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">income</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> goal<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb3-84">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">html</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">`&lt;div class="scenario-card" style="--accent:</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span>r<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">color</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">"&gt;</span></span>
<span id="cb3-85"><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">    &lt;div class="scenario-name"&gt;&lt;span class="dot"&gt;&lt;/span&gt;</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span>r<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">&lt;span class="scenario-rate"&gt;</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span>(r<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">rate</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">toFixed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">% a year&lt;br&gt;&lt;span class="scenario-hist"&gt;after inflation&lt;/span&gt;&lt;/span&gt;&lt;/div&gt;</span></span>
<span id="cb3-86"><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">    &lt;div class="scenario-balance"&gt;</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">money</span>(r<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">real</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">&lt;/div&gt;</span></span>
<span id="cb3-87"><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">    &lt;div class="scenario-sub"&gt;</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">money</span>(r<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">income</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;"> a year · </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">money</span>(r<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">income</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;"> a month&lt;/div&gt;</span></span>
<span id="cb3-88"><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">    &lt;div class="goal-bar"&gt;&lt;div class="goal-fill" style="width:</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">Math</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(pct<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">%"&gt;&lt;/div&gt;&lt;/div&gt;</span></span>
<span id="cb3-89"><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">    &lt;div class="scenario-goal"&gt;</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span>ok <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"✓"</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"✕"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;"> </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">Math</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(r<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">income</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> goal <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">% of your goal&lt;/div&gt;</span></span>
<span id="cb3-90"><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">  &lt;/div&gt;`</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb3-91">})<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">&lt;/div&gt;`</span></span></code></pre></div>
</details>
<div class="cell-output cell-output-display">
<div id="ojs-cell-3" data-nodetype="expression">

</div>
</div>
</div>
</section>
<section id="how-your-money-grows" class="level2">
<h2 class="anchored" data-anchor-id="how-your-money-grows">How your money grows</h2>
<div class="cell">
<details class="code-fold hidden">
<summary>Show code</summary>
<div class="sourceCode cell-code hidden" id="cb4" data-startfrom="98" data-source-offset="0" style="background: #f1f3f5;"><pre class="sourceCode js code-with-copy"><code class="sourceCode javascript" style="counter-reset: source-line 97;"><span id="cb4-98">{</span>
<span id="cb4-99">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> key <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> realView <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"real"</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"nominal"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb4-100">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> cKey <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> realView <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"contribReal"</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"contributed"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb4-101">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> base <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> paths<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">filter</span>(d <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> d<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">scenario</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">===</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Base"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb4-102">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> band <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> base<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">map</span>((d<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> i) <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> ({<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">year</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> d<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">year</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">lo</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> bearPath[i][key]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">hi</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> bullPath[i][key]}))<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb4-103">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> last <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> paths<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">filter</span>(d <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> d<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">year</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">===</span> years)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb4-104">  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// keep end-of-line labels from overlapping</span></span>
<span id="cb4-105">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> top <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">Math</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(realView <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?</span> target <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">...</span>last<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">map</span>(d <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> d[key]))<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb4-106">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> gap <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> top <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.06</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb4-107">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> prev <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">Infinity</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb4-108">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> labels <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">...</span>last]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sort</span>((a<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> b) <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> a[key] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> b[key])<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">map</span>(d <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> {</span>
<span id="cb4-109">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">Math</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(d[key]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> prev <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> gap)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> prev <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> y<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb4-110">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> {<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">...</span>d<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">labelY</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> y}<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb4-111">  })<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb4-112">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> Plot<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">plot</span>({</span>
<span id="cb4-113">    width<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb4-114">    <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">height</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">420</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb4-115">    <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">marginLeft</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">64</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb4-116">    <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">marginRight</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">140</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb4-117">    <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">style</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> {<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">fontSize</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"13px"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">fontFamily</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Inter, system-ui, sans-serif"</span>}<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb4-118">    <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">x</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> {<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">label</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Years from now"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">tickFormat</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"d"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">ticks</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">Math</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(years<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> width <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">500</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)}<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb4-119">    <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">y</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> {<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">label</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">null</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">grid</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">true</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">tickFormat</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> d <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">shortMoney</span>(d)}<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb4-120">    <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">marks</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> [</span>
<span id="cb4-121">      Plot<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">areaY</span>(base<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> {<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">x</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"year"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">y</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> cKey<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">fill</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> ink<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">muted</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">fillOpacity</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.12</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">curve</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"monotone-x"</span>})<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb4-122">      Plot<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">areaY</span>(band<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> {<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">x</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"year"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">y1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lo"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">y2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"hi"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">fill</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> colors[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">fillOpacity</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.10</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">curve</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"monotone-x"</span>})<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb4-123">      realView <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?</span> Plot<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ruleY</span>([target]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> {<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">stroke</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> ink<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">text</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">strokeDasharray</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"5,4"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">strokeOpacity</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span>}) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">null</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb4-124">      realView <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?</span> Plot<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">text</span>([target]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> {<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">x</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> years<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">y</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> d <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> d<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">text</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> d <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> <span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">`What you need: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">shortMoney</span>(d)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">textAnchor</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"end"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">dy</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">fill</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> ink<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">text</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">fontWeight</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">600</span>}) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">null</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb4-125">      Plot<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">line</span>(paths<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> {<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">x</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"year"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">y</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> key<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">z</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"scenario"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">stroke</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> d <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> colorOf[d<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">scenario</span>]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">strokeWidth</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> d <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> d<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">scenario</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">===</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Base"</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">curve</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"monotone-x"</span>})<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb4-126">      Plot<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dot</span>(last<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> {<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">x</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"year"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">y</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> key<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">fill</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> d <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> colorOf[d<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">scenario</span>]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">r</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">stroke</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> ink<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">bg</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">strokeWidth</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>})<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb4-127">      Plot<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">text</span>(labels<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> {<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">x</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"year"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">y</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"labelY"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">text</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> d <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> <span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span>d<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">scenario</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">  </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">shortMoney</span>(d[key])<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">textAnchor</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"start"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">dx</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">fill</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> ink<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">text</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">fontWeight</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">600</span>})<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb4-128">      Plot<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">text</span>([{<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">year</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> years<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">v</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> base<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">at</span>(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)[cKey]}]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> {<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">x</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"year"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">y</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"v"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">text</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> () <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"You put in"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">textAnchor</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"start"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">dx</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">fill</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> ink<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">muted</span>})<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb4-129">      Plot<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ruleX</span>(paths<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> Plot<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pointerX</span>({<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">x</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"year"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">stroke</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> ink<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">muted</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">strokeOpacity</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>}))<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb4-130">      Plot<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dot</span>(paths<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> Plot<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pointerX</span>({<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">x</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"year"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">y</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> key<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">fill</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> d <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> colorOf[d<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">scenario</span>]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">r</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>}))<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb4-131">      Plot<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tip</span>(base<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> Plot<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pointerX</span>({<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">x</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"year"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">y</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> key<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">title</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> d <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> {</span>
<span id="cb4-132">        <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> rows <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> scenarioNames<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">map</span>(n <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> <span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span>n<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">money</span>(paths<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">find</span>(p <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> p<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">scenario</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">===</span> n <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;&amp;</span> p<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">year</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">===</span> d<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">year</span>)[key])<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb4-133">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> [<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">`Year </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span>d<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">year</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">...</span>rows<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">`You put in: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">money</span>(d[cKey])<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span>]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">join</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb4-134">      }}))</span>
<span id="cb4-135">    ]</span>
<span id="cb4-136">  })<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb4-137">}</span></code></pre></div>
</details>
<div class="cell-output cell-output-display">
<div id="ojs-cell-4" data-nodetype="expression">

</div>
</div>
</div>
<div class="cell">
<details class="code-fold hidden">
<summary>Show code</summary>
<div class="sourceCode cell-code hidden" id="cb5" data-startfrom="142" data-source-offset="0" style="background: #f1f3f5;"><pre class="sourceCode js code-with-copy"><code class="sourceCode javascript" style="counter-reset: source-line 141;"><span id="cb5-142">viewof realView <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Inputs<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">toggle</span>({<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">label</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Show in today's money (adjusted for inflation)"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">value</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">true</span>})</span></code></pre></div>
</details>
<div class="cell-output cell-output-display">
<div id="ojs-cell-5" data-nodetype="declaration">

</div>
</div>
</div>
</section>
<section id="where-the-scenarios-come-from" class="level2">
<h2 class="anchored" data-anchor-id="where-the-scenarios-come-from">Where the scenarios come from</h2>
<div class="cell">
<details class="code-fold hidden">
<summary>Show code</summary>
<div class="sourceCode cell-code hidden" id="cb6" data-startfrom="149" data-source-offset="0" style="background: #f1f3f5;"><pre class="sourceCode js code-with-copy"><code class="sourceCode javascript" style="counter-reset: source-line 148;"><span id="cb6-149">{</span>
<span id="cb6-150">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> bins <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> d3<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">bin</span>()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">thresholds</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">28</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">value</span>(d <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> d<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">cagr</span>)(windows)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb6-151">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> zone <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> x <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> byName<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">Bear</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">hist</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> byName<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">Bull</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">hist</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb6-152">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> bars <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> bins<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">map</span>(b <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> ({<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">x1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> b<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x0</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">x2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> b<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">n</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> b<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">length</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">z</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">zone</span>((b<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x0</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> b<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x1</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb6-153">    <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">starts</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> b<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">map</span>(d <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> <span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span>d<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">start</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">–</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span>d<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">start</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> years <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span>)}))<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb6-154">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> listYears <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> a <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> a<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">length</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?</span> a<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">join</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> [<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">...</span>a<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">slice</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">`+ </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span>a<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">length</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;"> more`</span>]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">join</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb6-155">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> Plot<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">plot</span>({</span>
<span id="cb6-156">    width<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb6-157">    <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">height</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">260</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb6-158">    <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">marginTop</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">44</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb6-159">    <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">marginLeft</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">40</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb6-160">    <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">marginBottom</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">48</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb6-161">    <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">style</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> {<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">fontSize</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"12px"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">fontFamily</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Inter, system-ui, sans-serif"</span>}<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb6-162">    <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">x</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> {<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">label</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> width <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">500</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?</span> <span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">`Yearly return, </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span>years<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">-year stretches`</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">`Average yearly return after inflation, every </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span>years<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">-year stretch since 1928`</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">labelAnchor</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"center"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">labelOffset</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">42</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">labelArrow</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"none"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">tickFormat</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> d <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> <span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">Math</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(d <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">%`</span>}<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb6-163">    <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">y</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> {<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">label</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Stretches"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">grid</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">true</span>}<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb6-164">    <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">marks</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> [</span>
<span id="cb6-165">      Plot<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rectY</span>(bars<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> {<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">x1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x1"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">x2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x2"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">y</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"n"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">fill</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> d <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> colors[d<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">z</span>]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">fillOpacity</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.35</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">insetLeft</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">insetRight</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">rx</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb6-166">        <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">tip</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">true</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">title</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> d <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> <span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span>(d<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">toFixed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">–</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span>(d<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">toFixed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">% a year · </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span>d<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">n</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;"> stretch</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span>d<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">n</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">===</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"es"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}\n${</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">listYears</span>(d<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">starts</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span>})<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb6-167">      Plot<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ruleY</span>([<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> {<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">stroke</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> ink<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">muted</span>})<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb6-168">      Plot<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ruleX</span>(scenarios<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> {<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">x</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"hist"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">stroke</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> d <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> d<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">color</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">strokeWidth</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.5</span>})<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb6-169">      Plot<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">text</span>(scenarios<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">filter</span>(d <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> d<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Base"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> {<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">x</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"hist"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">text</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> d <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> <span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span>d<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;"> </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span>(d<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">hist</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">toFixed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">%`</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">frameAnchor</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"top"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">dy</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">fill</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> ink<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">text</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">fontWeight</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">600</span>})<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb6-170">      Plot<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">text</span>(scenarios<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">filter</span>(d <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> d<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">===</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Base"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> {<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">x</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"hist"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">text</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> d <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> <span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span>d<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;"> </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span>(d<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">hist</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">toFixed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">%`</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">frameAnchor</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"top"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">dy</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">28</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">fill</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> ink<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">text</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">fontWeight</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">600</span>})</span>
<span id="cb6-171">    ]</span>
<span id="cb6-172">  })<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb6-173">}</span></code></pre></div>
</details>
<div class="cell-output cell-output-display">
<div id="ojs-cell-6" data-nodetype="expression">

</div>
</div>
</div>
<div class="cell">
<details class="code-fold hidden">
<summary>Show code</summary>
<div class="sourceCode cell-code hidden" id="cb7" data-startfrom="178" data-source-offset="0" style="background: #f1f3f5;"><pre class="sourceCode js code-with-copy"><code class="sourceCode javascript" style="counter-reset: source-line 177;"><span id="cb7-178"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">html</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">`&lt;p class="chart-note"&gt;&lt;strong&gt;How to read this:&lt;/strong&gt; each bar counts how many of the </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span>windows<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">length</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;"> stretches of </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span>years<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;"> years since 1928 earned that average yearly return after inflation. Hover a bar to see which years. &lt;strong&gt;Bear&lt;/strong&gt; is the 20th percentile (1 in 5 did worse), &lt;strong&gt;Base&lt;/strong&gt; the median, and &lt;strong&gt;Bull&lt;/strong&gt; the 80th percentile (1 in 5 did better). The wider the bars spread, the more your start date matters. Try a shorter horizon to see it widen, or a longer one to see it narrow.&lt;/p&gt;`</span></span></code></pre></div>
</details>
<div class="cell-output cell-output-display">
<div id="ojs-cell-7" data-nodetype="expression">

</div>
</div>
</div>
</section>
<section id="the-full-numbers" class="level2">
<h2 class="anchored" data-anchor-id="the-full-numbers">The full numbers</h2>
<div class="cell">
<details class="code-fold hidden">
<summary>Show code</summary>
<div class="sourceCode cell-code hidden" id="cb8" data-startfrom="185" data-source-offset="0" style="background: #f1f3f5;"><pre class="sourceCode js code-with-copy"><code class="sourceCode javascript" style="counter-reset: source-line 184;"><span id="cb8-185"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">html</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">`&lt;div class="table-scroll"&gt;&lt;table class="table planner-table"&gt;</span></span>
<span id="cb8-186"><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">  &lt;thead&gt;&lt;tr&gt;&lt;th&gt;Scenario&lt;/th&gt;&lt;th&gt;Return after inflation&lt;/th&gt;&lt;th&gt;Today's money&lt;/th&gt;&lt;th&gt;Future dollars&lt;/th&gt;&lt;th&gt;You put in&lt;/th&gt;&lt;th&gt;Yearly income&lt;/th&gt;&lt;th&gt;Money lasts&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;</span></span>
<span id="cb8-187"><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">  &lt;tbody&gt;</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span>results<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">map</span>(r <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">html</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">`&lt;tr&gt;</span></span>
<span id="cb8-188"><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">    &lt;td&gt;&lt;span class="dot" style="background:</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span>r<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">color</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">"&gt;&lt;/span&gt;</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span>r<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">&lt;/td&gt;</span></span>
<span id="cb8-189"><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">    &lt;td&gt;</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span>(r<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">rate</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">toFixed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">%&lt;/td&gt;</span></span>
<span id="cb8-190"><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">    &lt;td&gt;</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">money</span>(r<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">real</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">&lt;/td&gt;</span></span>
<span id="cb8-191"><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">    &lt;td&gt;</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">money</span>(r<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nominal</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">&lt;/td&gt;</span></span>
<span id="cb8-192"><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">    &lt;td&gt;</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">money</span>(r<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">contributed</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">&lt;/td&gt;</span></span>
<span id="cb8-193"><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">    &lt;td&gt;</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">money</span>(r<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">income</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">&lt;/td&gt;</span></span>
<span id="cb8-194"><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">    &lt;td&gt;</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span>r<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lasts</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">===</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">Infinity</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"60+ yrs"</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span>r<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lasts</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;"> yrs`</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">&lt;/td&gt;</span></span>
<span id="cb8-195"><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">  &lt;/tr&gt;`</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">&lt;/tbody&gt;</span></span>
<span id="cb8-196"><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">&lt;/table&gt;&lt;/div&gt;`</span></span></code></pre></div>
</details>
<div class="cell-output cell-output-display">
<div id="ojs-cell-8" data-nodetype="expression">

</div>
</div>
</div>
<p><strong>Yearly income</strong> is your withdrawal rate applied to your ending balance, in today’s money. <strong>Future dollars</strong> is the same amount in the dollars of your retirement year, using your inflation setting. <strong>Money lasts</strong> assumes you take that income every year (kept at today’s buying power) while the rest stays invested at the same scenario’s return.</p>
</section>
<section id="caveats-and-limitations" class="level2">
<h2 class="anchored" data-anchor-id="caveats-and-limitations">Caveats and limitations</h2>
<ul>
<li><strong>The past isn’t a forecast.</strong> This uses 98 years of US stocks, one of the world’s best markets. The future could be better or worse.</li>
<li><strong>Real markets are bumpy.</strong> The scenarios assume a steady return. A crash near retirement hurts far more than one decades earlier.</li>
<li><strong>It’s all stocks.</strong> Most portfolios also hold bonds or cash, which smooths the ride.</li>
<li><strong>It’s in US dollars.</strong> The returns are for the S&amp;P 500, measured in dollars. If you invest from the Philippines, moves in the peso–dollar exchange rate (FX) can add to or take away from your returns, so factor that in.</li>
<li><strong>No taxes, fees or currency.</strong> All three can cut what you keep, especially if you invest in dollars but spend in pesos.</li>
<li><strong>Retirement is simplified.</strong> It leaves out pensions, SSS, healthcare costs and changing spending.</li>
<li><strong>It assumes you stay the course.</strong> Pausing contributions or panic-selling often costs more than any fee.</li>
</ul>
</section>
<section id="everyones-journey-is-different" class="level2">
<h2 class="anchored" data-anchor-id="everyones-journey-is-different">Everyone’s journey is different</h2>
<p>Personal finance is, well, personal. What’s “enough” for you depends on your age, income, family, health, goals and comfort with risk. Start with an honest check:</p>
<ul class="task-list">
<li><label><input type="checkbox"><strong>Where am I now?</strong> What I have, what I owe, and how much I save each month.</label></li>
<li><label><input type="checkbox"><strong>Do I have emergency savings?</strong> Usually 3–6 months of expenses, kept somewhere safe and easy to get.</label></li>
<li><label><input type="checkbox"><strong>Have I paid off costly debt?</strong> Paying off a credit card at 30% is better than almost any investment.</label></li>
<li><label><input type="checkbox"><strong>Am I insured?</strong> Health insurance, and life insurance if someone depends on me.</label></li>
<li><label><input type="checkbox"><strong>How much do I spend in a year?</strong> That’s where my retirement goal starts.</label></li>
<li><label><input type="checkbox"><strong>Do I have to pay for school or other obligations?</strong> Tuition, support for parents or family, a home loan, or other big costs before I retire.</label></li>
<li><label><input type="checkbox"><strong>When do I want to retire, and how do I want to live?</strong></label></li>
<li><label><input type="checkbox"><strong>How much risk can I take?</strong> Affording a loss and staying calm through one are two different things.</label></li>
<li><label><input type="checkbox"><strong>What other income will I have?</strong> Pensions, SSS, rent, a business.</label></li>
</ul>
<p>Use this tool as a compass, not a map. Revisit your plan every year or whenever your life changes, and for decisions that matter, talk to a licensed financial professional.</p>
<div class="made-with">
<p><em>Built with Claude, as a way to get back into coding and test what AI can do. The idea and the numbers are mine; Claude helped with the code and design.</em></p>
</div>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center" data-bs-toggle="collapse" data-bs-target=".callout-1-contents" aria-controls="callout-1" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
Method and data
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-1" class="callout-1-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<ul>
<li><strong>Returns</strong> are S&amp;P 500 total returns (price plus reinvested dividends) for each calendar year, 1928–2025, adjusted for that year’s actual US inflation (CPI-U, December to December, from the St.&nbsp;Louis Fed’s FRED database).
<ul>
<li><strong>2001–2025:</strong> the actual returns of BlackRock’s <a href="https://www.ishares.com/us/products/239726/ishares-core-sp-500-etf">iShares Core S&amp;P 500 ETF (IVV)</a>, from Yahoo Finance’s dividend-adjusted prices. These are what an investor in the fund really earned, after its small fee.</li>
<li><strong>1928–2000:</strong> IVV didn’t exist yet (it launched in May 2000), so these years use the S&amp;P 500 index itself, computed from Robert Shiller’s monthly dataset. Shiller uses monthly average prices, so individual years differ slightly from the official year-end figures.</li>
</ul></li>
<li><strong>Scenario returns</strong> are the real compound annual growth rate (CAGR) of every rolling stretch of your chosen length. Bear is the 20th percentile, base the median and bull the 80th percentile.</li>
<li><strong>Your inflation setting</strong> doesn’t change the returns. It’s only used to show amounts in future dollars and, if you tick the box, to raise your contributions each year.</li>
<li><strong>Keep in mind:</strong> rolling stretches overlap heavily, and US stocks had one of the best centuries of any market, so history may still flatter what’s ahead.</li>
<li><strong>Each scenario uses one steady return every year.</strong> Real markets jump around, and the order of good and bad years matters a lot, especially once you start withdrawing.</li>
<li><strong>What you need</strong> is your yearly income goal divided by your withdrawal rate.</li>
<li>Contributions are added at the end of each period. Fees and taxes are not included.</li>
<li>This is an educational tool, not financial advice.</li>
</ul>
</div>
</div>
</div>
<div class="cell hidden">
<details class="code-fold hidden">
<summary>Show code</summary>
<div class="sourceCode cell-code hidden" id="cb9" data-startfrom="250" data-source-offset="-0" style="background: #f1f3f5;"><pre class="sourceCode js code-with-copy"><code class="sourceCode javascript" style="counter-reset: source-line 249;"><span id="cb9-250">data <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">FileAttachment</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sp500_annual.csv"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">csv</span>({<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">typed</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">true</span>})</span>
<span id="cb9-251"></span>
<span id="cb9-252">currency <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"$"</span></span>
<span id="cb9-253"></span>
<span id="cb9-254"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// Money input: shows commas as you type, plus a plain-words hint ("1.2 million")</span></span>
<span id="cb9-255"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">amountInput</span>({label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> value <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>}) {</span>
<span id="cb9-256">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> input <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">html</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">`&lt;input type="text" inputmode="numeric" autocomplete="off" spellcheck="false"&gt;`</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-257">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> hint <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">html</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">`&lt;span class="amount-hint"&gt;&lt;/span&gt;`</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-258">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> form <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">html</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">`&lt;form class="oi-amount amount-input"&gt;&lt;label&gt;</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span>label<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">&lt;/label&gt;&lt;div class="amount-row"&gt;&lt;span class="amount-field"&gt;&lt;span class="amount-prefix"&gt;US$&lt;/span&gt;</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span>input<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">&lt;/span&gt;</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span>hint<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">&lt;/div&gt;&lt;/form&gt;`</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-259">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> withCommas <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> d3<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">format</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">","</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-260">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> words <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> v <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> v <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e9</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?</span> <span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span>(v <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e9</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">toFixed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;"> billion`</span></span>
<span id="cb9-261">    <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> v <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e6</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?</span> <span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span>(v <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e6</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">toFixed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;"> million`</span></span>
<span id="cb9-262">    <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> v <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e3</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?</span> <span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span>(v <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e3</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">toFixed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;"> thousand`</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-263">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> show <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> v <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> { form<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">value</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> v<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> hint<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">textContent</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">words</span>(v)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> }<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-264">  input<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">addEventListener</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> () <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> {</span>
<span id="cb9-265">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> caret <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> input<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">selectionStart</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">??</span> input<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">value</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">length</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-266">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> digitsBefore <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> input<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">value</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">slice</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> caret)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">replace</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">/</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\D</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">/g</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">length</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-267">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> digits <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> input<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">value</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">replace</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">/</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\D</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">/g</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">replace</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">/</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">0</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+(?</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">=</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\d)</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">/</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">slice</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">13</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-268">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> v <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> digits <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span>digits <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-269">    input<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">value</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> digits <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">withCommas</span>(v) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-270">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// keep the cursor next to the same digit after commas are added or removed</span></span>
<span id="cb9-271">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> pos <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> seen <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-272">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">while</span> (pos <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> input<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">value</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">length</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;&amp;</span> seen <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> digitsBefore) { <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">/</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\d</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">/</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">test</span>(input<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">value</span>[pos])) seen<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">++;</span> pos<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">++;</span> }</span>
<span id="cb9-273">    input<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">setSelectionRange</span>(pos<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> pos)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-274">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">show</span>(v)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-275">  })<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-276">  form<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">addEventListener</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"submit"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> e <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> e<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">preventDefault</span>())<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-277">  input<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">value</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">withCommas</span>(value)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-278">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">show</span>(value)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-279">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> form<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-280">}</span>
<span id="cb9-281"></span>
<span id="cb9-282"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// Follow the site's light/dark toggle so chart colors match the theme</span></span>
<span id="cb9-283">dark <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Generators<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">observe</span>(notify <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> {</span>
<span id="cb9-284">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> check <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> () <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">notify</span>(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">document</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">body</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">classList</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">contains</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"quarto-dark"</span>))<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-285">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">check</span>()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-286">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> obs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">new</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">MutationObserver</span>(check)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-287">  obs<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">observe</span>(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">document</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">body</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> {<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">attributes</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">true</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">attributeFilter</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"class"</span>]})<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-288">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> () <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> obs<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">disconnect</span>()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-289">})</span>
<span id="cb9-290"></span>
<span id="cb9-291">colors <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> dark <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?</span> [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#d77a64"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#6f95e0"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#b88f2c"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#b5513f"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#2f5aa8"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#9a7420"</span>]</span>
<span id="cb9-292">ink <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> dark <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?</span> {<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">text</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#e8e5de"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">muted</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#a09b91"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">bg</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#18191b"</span>} <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> {<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">text</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#2a2a2a"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">muted</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#6b665d"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">bg</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#fdfcf9"</span>}</span>
<span id="cb9-293">scenarioNames <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Bear"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Base"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Bull"</span>]</span>
<span id="cb9-294">colorOf <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ({<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Bear"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> colors[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Base"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> colors[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Bull"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> colors[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]})</span>
<span id="cb9-295"></span>
<span id="cb9-296">windows <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {</span>
<span id="cb9-297">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> out <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-298">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> (<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> years <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> data<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">length</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">++</span>) {</span>
<span id="cb9-299">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> g <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-300">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> (<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> j <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> j <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> years<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> j<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">++</span>) g <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> data[j]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">real_return</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-301">    out<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">push</span>({<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">start</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> data[i]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">year</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">cagr</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">Math</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pow</span>(g<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> years) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>})<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-302">  }</span>
<span id="cb9-303">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> out<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-304">}</span>
<span id="cb9-305"></span>
<span id="cb9-306">scenarios <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {</span>
<span id="cb9-307">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> r <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> windows<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">map</span>(d <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> d<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">cagr</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-308">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> [<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.8</span>]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">map</span>((q<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> k) <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> {</span>
<span id="cb9-309">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> rate <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> d3<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">quantile</span>(r<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> q)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-310">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> {<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">name</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> scenarioNames[k]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">color</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> colors[k]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">hist</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> rate<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> rate}<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-311">  })<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-312">}</span>
<span id="cb9-313"></span>
<span id="cb9-314"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// rate is a REAL (after-inflation) return, so balances are in today's money</span></span>
<span id="cb9-315"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">simulate</span>(rate) {</span>
<span id="cb9-316">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> f <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> frequency<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> inflation <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-317">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> pr <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">Math</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pow</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> rate<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> f) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-318">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> real <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> initial<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> putReal <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> initial<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> putNom <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> initial<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-319">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> rows <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [{<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">year</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> real<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">contribReal</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> putReal<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">contributed</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> putNom}]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-320">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> (<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> years<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> y<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">++</span>) {</span>
<span id="cb9-321">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> cNom <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> growContrib <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?</span> contribution <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">Math</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pow</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> contribution<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-322">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> (<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> p <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> p <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> f<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> p<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">++</span>) {</span>
<span id="cb9-323">      <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> cReal <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cNom <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">Math</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pow</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> (p <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> f)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-324">      real <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> real <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> pr) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> cReal<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> putReal <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> cReal<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> putNom <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> cNom<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-325">    }</span>
<span id="cb9-326">    rows<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">push</span>({<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">year</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> y<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> real<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">contribReal</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> putReal<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">contributed</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> putNom})<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-327">  }</span>
<span id="cb9-328">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> rows<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">map</span>(d <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> ({<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">...</span>d<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">nominal</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> d<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">real</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">Math</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pow</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> d<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">year</span>)}))<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-329">}</span>
<span id="cb9-330"></span>
<span id="cb9-331"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// years a real balance lasts when withdrawing a fixed real amount each year</span></span>
<span id="cb9-332"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lasts</span>(start<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> rate) {</span>
<span id="cb9-333">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> bal <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> start<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-334">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> w <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> start <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> withdrawal <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-335">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> (<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">60</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> y<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">++</span>) {</span>
<span id="cb9-336">    bal <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-=</span> w<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-337">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (bal <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-338">    bal <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> rate<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-339">  }</span>
<span id="cb9-340">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">Infinity</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-341">}</span>
<span id="cb9-342"></span>
<span id="cb9-343">byName <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">Object</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fromEntries</span>(scenarios<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">map</span>(s <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> [s<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> s]))</span>
<span id="cb9-344">bearPath <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">simulate</span>(byName<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">Bear</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">rate</span>)</span>
<span id="cb9-345">bullPath <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">simulate</span>(byName<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">Bull</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">rate</span>)</span>
<span id="cb9-346">paths <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> scenarios<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">flatMap</span>(s <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">simulate</span>(s<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">rate</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">map</span>(d <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> ({<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">...</span>d<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">scenario</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> s<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name</span>})))</span>
<span id="cb9-347"></span>
<span id="cb9-348">results <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> scenarios<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">map</span>(s <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> {</span>
<span id="cb9-349">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> end <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">simulate</span>(s<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">rate</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">at</span>(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-350">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> {<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">...</span>s<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">...</span>end<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">income</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> end<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">real</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> withdrawal <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">lasts</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lasts</span>(end<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">real</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> s<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">rate</span>)}<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-351">})</span>
<span id="cb9-352"></span>
<span id="cb9-353">target <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> goal <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (withdrawal <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>)</span>
<span id="cb9-354"></span>
<span id="cb9-355">money <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> v <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> currency <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> d3<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">format</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">",.0f"</span>)(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">Math</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(v))</span>
<span id="cb9-356">shortMoney <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> v <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> currency <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> d3<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">format</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">".3~s"</span>)(v)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">replace</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"G"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"B"</span>)</span></code></pre></div>
</details>
<div class="cell-output cell-output-display hidden">
<div>
<div id="ojs-cell-9-1" data-nodetype="declaration">

</div>
</div>
</div>
<div class="cell-output cell-output-display hidden">
<div>
<div id="ojs-cell-9-2" data-nodetype="declaration">

</div>
</div>
</div>
<div class="cell-output cell-output-display hidden">
<div>
<div id="ojs-cell-9-3" data-nodetype="declaration">

</div>
</div>
</div>
<div class="cell-output cell-output-display hidden">
<div>
<div id="ojs-cell-9-4" data-nodetype="declaration">

</div>
</div>
</div>
<div class="cell-output cell-output-display hidden">
<div>
<div id="ojs-cell-9-5" data-nodetype="declaration">

</div>
</div>
</div>
<div class="cell-output cell-output-display hidden">
<div>
<div id="ojs-cell-9-6" data-nodetype="declaration">

</div>
</div>
</div>
<div class="cell-output cell-output-display hidden">
<div>
<div id="ojs-cell-9-7" data-nodetype="declaration">

</div>
</div>
</div>
<div class="cell-output cell-output-display hidden">
<div>
<div id="ojs-cell-9-8" data-nodetype="declaration">

</div>
</div>
</div>
<div class="cell-output cell-output-display hidden">
<div>
<div id="ojs-cell-9-9" data-nodetype="declaration">

</div>
</div>
</div>
<div class="cell-output cell-output-display hidden">
<div>
<div id="ojs-cell-9-10" data-nodetype="declaration">

</div>
</div>
</div>
<div class="cell-output cell-output-display hidden">
<div>
<div id="ojs-cell-9-11" data-nodetype="declaration">

</div>
</div>
</div>
<div class="cell-output cell-output-display hidden">
<div>
<div id="ojs-cell-9-12" data-nodetype="declaration">

</div>
</div>
</div>
<div class="cell-output cell-output-display hidden">
<div>
<div id="ojs-cell-9-13" data-nodetype="declaration">

</div>
</div>
</div>
<div class="cell-output cell-output-display hidden">
<div>
<div id="ojs-cell-9-14" data-nodetype="declaration">

</div>
</div>
</div>
<div class="cell-output cell-output-display hidden">
<div>
<div id="ojs-cell-9-15" data-nodetype="declaration">

</div>
</div>
</div>
<div class="cell-output cell-output-display hidden">
<div>
<div id="ojs-cell-9-16" data-nodetype="declaration">

</div>
</div>
</div>
<div class="cell-output cell-output-display hidden">
<div>
<div id="ojs-cell-9-17" data-nodetype="declaration">

</div>
</div>
</div>
<div class="cell-output cell-output-display hidden">
<div>
<div id="ojs-cell-9-18" data-nodetype="declaration">

</div>
</div>
</div>
<div class="cell-output cell-output-display hidden">
<div>
<div id="ojs-cell-9-19" data-nodetype="declaration">

</div>
</div>
</div>
<div class="cell-output cell-output-display hidden">
<div>
<div id="ojs-cell-9-20" data-nodetype="declaration">

</div>
</div>
</div>
</div>


</section>

 ]]></description>
  <category>investing</category>
  <category>retirement</category>
  <category>s&amp;p-500</category>
  <category>interactive</category>
  <guid>https://sandrosilva.site/writing/2026-11-28-investment-planner/</guid>
  <pubDate>Sat, 28 Nov 2026 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Music Through The Years</title>
  <link>https://sandrosilva.site/posts/2023-04-26-Music/</link>
  <description><![CDATA[ 




<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://sandrosilva.site/posts/2023-04-26-Music/source-files/[BDCC] Poster.gif" class="img-fluid quarto-figure quarto-figure-center figure-img" style="width:55.0%"></p>
</figure>
</div>
<div class="text-center">
Infographic on the Project Results
</div>
<section id="sec-authors" class="level2" data-number="1">
<h2 data-number="1" class="anchored" data-anchor-id="sec-authors"><span class="header-section-number">1</span> Authors</h2>
<p>This analysis was done together with my groupmate Jac Lin T. Yu</p>
<p>Original creation and submission of this report was last Dec 2019.</p>
</section>
<section id="sec-executivesummary" class="level2" data-number="2">
<h2 data-number="2" class="anchored" data-anchor-id="sec-executivesummary"><span class="header-section-number">2</span> Summary</h2>
<div class="executive-summary">
<p>Music is a ubiquitous art form that has the power to bring people together across cultures, backgrounds, and languages. As such, it is no surprise that the modern music industry has evolved into a multibillion-dollar industry that encompasses a diverse range of genres, from jazz to pop, rock to electronic, and everything in between. However, while each genre has its own unique characteristics, such as instruments used, rhythm, and tone, it is not just the content that determines whether a song becomes famous or not. There is a seasonality to the music industry, and understanding the prevailing genre per decade is crucial for artists and producers who wish to maximize profits and fame.</p>
<p>Classifying the genre of a song can be a complex and ambiguous task, as it can be based on various factors, including lyrical content, instruments used, and the overall feel of the music. However, automated genre classification using technical aspects of a song is becoming increasingly important as the volume of music produced continues to grow. Moreover, identifying the prevailing genre per decade can provide insights into the underlying sociocultural and historical context of the music, and can help artists and producers tailor their content to meet the changing tastes and preferences of their audiences.</p>
<p>This study aims to answer the question “what is the prevailing genre per decade?” by analyzing two datasets: the Echo Nest dataset, which contains music data from 1922 to 2023 and includes 1,000,000 <code>(280 GB)</code> song tracks with 54 features, and the tagtraum industries dataset, which contains 280,831 tracks with 14 unique genres. The datasets were merged using Dask and one-hot encoding was utilized to create an additional 115 features based on the classifiers. The resulting dataset was then used to train and evaluate various classification models, including Decision Trees, Random Forests, and Support Vector Machines, among others.</p>
<p>The Random Forest classifier was found to have the highest accuracy, with an accuracy improvement of over 316% compared to the baseline accuracy of <code>8.55%</code>. The model accuracy was <code>26.4%</code>, indicating that it was able to correctly classify the genre of a song more than a quarter of the time.</p>
<p>The results of the analysis showed that the prevailing genre per decade varied widely, with country being the most popular genre in the 1960s, 1970s, and 1980s, blues in the 1990s, electronica in the 2000s, and pop in the 2010s. These findings provide valuable insights into the evolution of music over the past century and can help artists and producers tailor their content to meet the changing tastes and preferences of their audiences.</p>
<p>The study also identified several areas for further research, including adding more audio features, song structure, and lyrics as features, and increasing the number of existing classifications of genres. Overall, this study provides a foundation for further research on the classification of music genres and highlights the importance of understanding the prevailing genre per decade in the music industry.</p>
</div>


</section>

 ]]></description>
  <category>python</category>
  <category>big-data</category>
  <guid>https://sandrosilva.site/posts/2023-04-26-Music/</guid>
  <pubDate>Tue, 26 Apr 2022 00:00:00 GMT</pubDate>
  <media:content url="https://sandrosilva.site/posts/2023-04-26-Music/source-files/thumbnail.jpeg" medium="image" type="image/jpeg"/>
</item>
<item>
  <title>Here Comes The Sun</title>
  <link>https://sandrosilva.site/posts/2023-04-25-Solar/</link>
  <description><![CDATA[ 




<p><img src="https://sandrosilva.site/posts/2023-04-25-Solar/source-files/thumbnail.png" class="img-fluid" style="width:100.0%"></p>
<section id="sec-authors" class="level2" data-number="1">
<h2 data-number="1" class="anchored" data-anchor-id="sec-authors"><span class="header-section-number">1</span> Authors</h2>
<p>This analysis was done together with my groupmate Jac Lin T. Yu</p>
<p>Original creation and submission of this report was last Dec 2019.</p>
</section>
<section id="sec-executivesummary" class="level2" data-number="2">
<h2 data-number="2" class="anchored" data-anchor-id="sec-executivesummary"><span class="header-section-number">2</span> Abstract</h2>
<div class="executive-summary">
<p>Due to the increasing focus towards sustainable global efforts against climate change, renewable energy generation, more specifically solar power generation, has experienced a significant growth in the past few years. However, solar power production by nature is still considered highly volatile and intermittent, due to its high dependency on various factors such as irridiation, cloud cover, temperature, and other weather parameters. As such, the inherent volatile nature of solar poses significant challenges in accurate forecasting techniques not only to solar power plant operators but also to power grid operators. This paper provides a deep learning model approach in forecasting solar power production with multiple weather variables</p>
<p>In the paper, four sites across the Philippines were considered, and four variations of the LSTM model were implemented. For two power plants, the best model had a single layer (32-nodes) LSTM, while the other two, utilized a two layer LSTM model with 64 and 32 nodes. The modifed Mean Absolute Error across all four sites reduced by at least 60% when compared to industry standard.</p>
</div>
<p><br><br></p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://sandrosilva.site/posts/2023-04-25-Solar/source-files/Poster.png" class="img-fluid quarto-figure quarto-figure-center figure-img" style="width:80.0%"></p>
</figure>
</div>
</section>
<section id="sec-introduction" class="level2" data-number="3">
<h2 data-number="3" class="anchored" data-anchor-id="sec-introduction"><span class="header-section-number">3</span> Introduction</h2>
<p>With the increasing devastating e ects of climate change, governments and industries have long been developing policies to mitigate its impact. In the COP21 or the 2015 Paris Climate Conference, all participating countries have agreed to reduce carbon emission in order to contain global warming to below 2°C. In addition, the United Nation’s 2030 Sustainable Development Goals which aims to address various societal issues, include provisions to produce affordable and clean energy (SDG 7) and provide climate action (SDG 13). Thus, the global energy industry has veered its focus away from traditional fuel sources to renewable and sustainable solutions, such as hydroelectric, solar and wind.</p>
<section id="sec-statement-of-the-problem" class="level3" data-number="3.1">
<h3 data-number="3.1" class="anchored" data-anchor-id="sec-statement-of-the-problem"><span class="header-section-number">3.1</span> Statement of the Problem</h3>
<p>The shift towards renewable energy poses new threats and challenges to existing power grids across the world due to the inherent variability and intermittency of solar power. The problem then is “Using neural networks, can solar power generation be predicted better than what industry currently uses given weather data?”</p>
</section>
<section id="sec-significance" class="level3" data-number="3.2">
<h3 data-number="3.2" class="anchored" data-anchor-id="sec-significance"><span class="header-section-number">3.2</span> Significance</h3>
<p>Accurate forecasting of solar power can help solar power plant operators reduce the risk of unnecessary market penalties. In addition, forecasting accurate solar power generation may provide power grid operators the ability to balance and schedule the distribution of generated power, for not only renewable power operators, but also conventional (and rigid) power plants, such as coal and natural gas. The overall significance of this study is to ensure a more secure and stable power grid even with high solar power penetration.</p>
</section>
<section id="sec-scope" class="level3" data-number="3.3">
<h3 data-number="3.3" class="anchored" data-anchor-id="sec-scope"><span class="header-section-number">3.3</span> Scope and Limitation</h3>
<p>The study only considers four solar power plants located in North Luzon, Greater Metro Manila, Visayas. No plants in the South Luzon and Mindanao regions were considered. Only 2 years and 8 months worth of weather data was included in the study. This data, however, does not include solar irridiance, an important indicator of solar power generation, due to the lack of availability.</p>
</section>
</section>
<section id="sec-proposed-framework" class="level2" data-number="4">
<h2 data-number="4" class="anchored" data-anchor-id="sec-proposed-framework"><span class="header-section-number">4</span> Proposed Framework</h2>
<section id="sec-lstm" class="level3" data-number="4.1">
<h3 data-number="4.1" class="anchored" data-anchor-id="sec-lstm"><span class="header-section-number">4.1</span> Long-Short Term Memory</h3>
<div id="fig-lstm" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-lstm-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://sandrosilva.site/posts/2023-04-25-Solar/source-files/LSTM_Cell.png" class="img-fluid figure-img">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-lstm-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;1: Architecture of an LSTM Cell.
</figcaption>
</figure>
</div>
<p>Long Short Term Memory, or also known as LSTM, is a deep learning method proposed in 1997 to address the vanishing or exploding gradient problem encountered in Recurrent Neural Networks when dealing with time series forecasting <span class="citation" data-cites="1">(Zhang, Chi, and Xiao 2018)</span>. It is a type of recurrent neural network (RNN) that can learn long-term dependencies between time steps of sequence data. It does this by integrating a memory cells, also known as gates, that allows the learning of complex and long-term temporal dynamics of the data <span class="citation" data-cites="2">(Qing and Niu 2018)</span>. Figure&nbsp;1 shows the gates mechanism that allows the interaction of the memory cell <span class="citation" data-cites="3">(Rassem, El-Beltagy, and Saleh 2017)</span>.</p>
<p>These “gates” determine which unimportant data should be forgotten and which important feature should be remembered. These gates are typically composed on sigmoid neural net layers and a pointwise multiplication operation. There are three gates in a typical LSTM: forget gate, input gate, and output gate.</p>
<p><span id="eq-lstm-it"><img src="https://latex.codecogs.com/png.latex?%0A%20%20%20%20%5Cvec%7Bi%7D_t=%5Csigma(%5Cvec%7BW%7D_%7Bxi%7D%5Cvec%7Bx%7D%5E%7Bt%7D+%5Cvec%7BW%7D_%7Bhi%7D%5Cvec%7Bh%7D%5E%7B(t-1)%7D+%5Cvec%7Bb%7D_i)%0A%5Ctag%7B1%7D"></span></p>
<p><span id="eq-lstm-gt"><img src="https://latex.codecogs.com/png.latex?%0A%20%20%20%20%5Cvec%7Bg%7D_t=tanh(%5Cvec%7BW%7D_%7Bxg%7D%5Cvec%7Bx%7D%5E%7Bt%7D+%5Cvec%7BW%7D_%7Bhg%7D%5Cvec%7Bh%7D%5E%7B(t-1)%7D+%5Cvec%7Bb%7D_g)%0A%5Ctag%7B2%7D"></span></p>
<p><span id="eq-lstm-ft"><img src="https://latex.codecogs.com/png.latex?%0A%20%20%20%20%5Cvec%7Bf%7D_t=%5Csigma(%5Cvec%7BW%7D_%7Bxf%7D%5Cvec%7Bx%7D%5E%7Bt%7D+%5Cvec%7BW%7D_%7Bhf%7D%5Cvec%7Bh%7D%5E%7B(t-1)%7D+%5Cvec%7Bb%7D_f)%0A%5Ctag%7B3%7D"></span></p>
<p><span id="eq-lstm-ot"><img src="https://latex.codecogs.com/png.latex?%0A%20%20%20%20%5Cvec%7Bo%7D_t=%5Csigma(%5Cvec%7BW%7D_%7Bxo%7D%5Cvec%7Bx%7D%5E%7Bt%7D+%5Cvec%7BW%7D_%7Bho%7D%5Cvec%7Bh%7D%5E%7B(t-1)%7D+%5Cvec%7Bb%7D_o)%0A%5Ctag%7B4%7D"></span></p>
<p><span id="eq-lstm-ct"><img src="https://latex.codecogs.com/png.latex?%0A%20%20%20%20%5Cvec%7BC%7D%5Et=(%5Cvec%7BC%7D%5E%7B(t-1)%7D%5Codot%5Cvec%7Bf%7D_%7Bt%7D)%5Coplus(%5Cvec%7Bi%7D_%7Bt%7D%5Codot%5Cvec%7Bg%7D_%7Bt%7D)%0A%5Ctag%7B5%7D"></span></p>
<p><span id="eq-lstm-ht"><img src="https://latex.codecogs.com/png.latex?%0A%20%20%20%20%5Cvec%7Bh%7D_t=%5Cvec%7Bo%7D_%7Bt%7D%5Codot%20tanh(%5Cvec%7BC%7D_%7Bt%7D)%0A%5Ctag%7B6%7D"></span></p>
<p>The input gate (<img src="https://latex.codecogs.com/png.latex?i_t">) seen in Equation&nbsp;1 and input modulation gate (<img src="https://latex.codecogs.com/png.latex?g_t">) seen in Equation&nbsp;2, where <img src="https://latex.codecogs.com/png.latex?%5Cvec%7BW%7D"> are the weights matrices and <img src="https://latex.codecogs.com/png.latex?%5Cvec%7Bb%7D"> are the bias terms, allows the updating of the cell.</p>
<p>Equation&nbsp;3 shows the computation of the forget gate (<img src="https://latex.codecogs.com/png.latex?f_t">) which determines if the information is suppressed or allowed to pass through and Equation&nbsp;4 shows the computation of the output gate (<img src="https://latex.codecogs.com/png.latex?o_t">) which decides how the hidden states are updated.</p>
<p>At the current time step (<img src="https://latex.codecogs.com/png.latex?t">), the cell is updated by Equation&nbsp;5 and the values of the hidden units are updated by Equation&nbsp;6</p>
</section>
<section id="sec-evaluation" class="level3" data-number="4.2">
<h3 data-number="4.2" class="anchored" data-anchor-id="sec-evaluation"><span class="header-section-number">4.2</span> Evaluation Metric</h3>
<p>Traditionally, researchers utilized classical statistical indicators used in solar power forecasting, specically the Mean Absolute Error, or also known as <img src="https://latex.codecogs.com/png.latex?MAE">, as mentioned by<span class="citation" data-cites="4">(Wang, Qi, and Liu 2019)</span> and <span class="citation" data-cites="5">(Sobri, Koohi-Kamali, and Rahim 2018)</span>. The <img src="https://latex.codecogs.com/png.latex?MAE"> refers to the average distance between the measured values and forecasting model. This analysis is appropriate to evaluate uniform prediction errors.</p>
<p><span id="eq-mae"><img src="https://latex.codecogs.com/png.latex?%0A%20%20MAE%20=%20%5Cfrac%7B1%7D%7BN%7D%20%5Csum_%7Bn=1%7D%5E%7BN%7D%20%7C%20P_%7Bpred%7D-%7BP_%7Bact%7D%20%7C%7D%0A%5Ctag%7B7%7D"></span></p>
<p>where <img src="https://latex.codecogs.com/png.latex?P_%7Bpred%7D"> defines the predicted energy generation by the model and <img src="https://latex.codecogs.com/png.latex?P_%7Bact%7D"> defines the actual energy generation</p>
<p>However, the <img src="https://latex.codecogs.com/png.latex?MAE"> fails to consider power grid elements and requirements. It is therefore important to utilize performance metrics that asses power generation forecasting by considering various forecast time-scales, and capacity restrictions. In addition, <span class="citation" data-cites="5">Sobri, Koohi-Kamali, and Rahim (2018)</span> indicated that depending on the use case, metrics assessments can be classified into four types i.e., statistical, ramp characterization, uncertainty quantification, and economic metrics. As such, <span class="citation" data-cites="6">Almeida, Perpiñán, and Narvarte (2015)</span>, implemented a modified <img src="https://latex.codecogs.com/png.latex?MAE">, defined as cvMAE, which evaluates a model by that penalize the hourly or daily energy error. The <img src="https://latex.codecogs.com/png.latex?cvMAE"> measures the goodness of the predictions for applications requiring hourly predictions during a period of a day. <span class="citation" data-cites="6">(Almeida, Perpiñán, and Narvarte 2015)</span></p>
<p><span id="eq-cvmae"><img src="https://latex.codecogs.com/png.latex?%0AcvMAE%20=%20%5Cfrac%7BMAE%7D%7BP_%7Bmean%7D%7D%0A%5Ctag%7B8%7D"></span></p>
<p>where <img src="https://latex.codecogs.com/png.latex?P_%7Bmean%7D"> defines the mean of measured power in a given time-horizon.</p>
<p>In this study, a modified version of the <img src="https://latex.codecogs.com/png.latex?MAE"> and <img src="https://latex.codecogs.com/png.latex?cvMAE"> will be utilized. The proposed metric takes into consideration not only classical statistical error measurement observed in the <img src="https://latex.codecogs.com/png.latex?MAE">, but also energy industry related considerations, such as day-ahead projected generation and rated capacity of each specific plant, labeled as <img src="https://latex.codecogs.com/png.latex?mMAE"></p>
<p><span id="eq-mmae"><img src="https://latex.codecogs.com/png.latex?%0AmMAE%20=%20%5Cfrac%7B%5Cfrac%7B1%7D%7BN%7D%20%5Csum_%7Bn=1%7D%5E%7BN%7D%20%7C%20P_%7Bpred%7D-%7BP_%7Bact%7D%20%7C%7D%7D%7BP_%7Bmax%7D%7D=%5Cfrac%7BMAE%7D%7BP_%7Bmax%7D%7D%0A%5Ctag%7B9%7D"></span></p>
<p>where <img src="https://latex.codecogs.com/png.latex?P_%7Bmax%7D"> indicates a solar power plant’s peak installed capacity, or the intended full-load sustained output of the power plant.</p>
</section>
</section>
<section id="sec-methodology" class="level2" data-number="5">
<h2 data-number="5" class="anchored" data-anchor-id="sec-methodology"><span class="header-section-number">5</span> Methodology</h2>
<section id="sec-dataset" class="level3" data-number="5.1">
<h3 data-number="5.1" class="anchored" data-anchor-id="sec-dataset"><span class="header-section-number">5.1</span> Dataset</h3>
<p>From December 26, 2016 to August 25, 2019, energy generation data in megawatts (MW) was collected from the Philippines’ Wholesale Electricity Spot Market (WESM). To limit the scope of the study, only four solar power plants located across Luzon and Visayas were chosen. One power plant was selected per location/province. Table&nbsp;1 shows these plants along with their location and rated dependable capacity, a metric that refers to the maximum amount of power that a power plant can produce over a specified period of time, while Table&nbsp;2 shows a data dictionary of the collected data.</p>
<div id="tbl-pp" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-tbl figure">
<figcaption class="quarto-float-caption-top quarto-float-caption quarto-float-tbl" id="tbl-pp-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Table&nbsp;1: Summary of selected power plants, location, and capacity
</figcaption>
<div aria-describedby="tbl-pp-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<table class="caption-top table">
<thead>
<tr class="header">
<th>Power Plant</th>
<th>Location</th>
<th>Capacity (in MW)</th>
<th></th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Clark Solar Power Plant</td>
<td>Mabalacat, Pampanga</td>
<td>22 MW</td>
<td></td>
</tr>
<tr class="even">
<td>First Toledo Solar Power Plant</td>
<td>Toledo, Cebu</td>
<td>60 MW</td>
<td></td>
</tr>
<tr class="odd">
<td>Subic Solar Power Plant</td>
<td>Olongapo, Zambales</td>
<td>100 MW</td>
<td></td>
</tr>
<tr class="even">
<td>Valenzuela Solar Power Plant</td>
<td>Valenzuela, NCR</td>
<td>8.5 MW</td>
<td></td>
</tr>
</tbody>
</table>
</div>
</figure>
</div>
<div id="tbl-pp-dict" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-tbl figure">
<figcaption class="quarto-float-caption-top quarto-float-caption quarto-float-tbl" id="tbl-pp-dict-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Table&nbsp;2: Data Dictionary of the WESM data
</figcaption>
<div aria-describedby="tbl-pp-dict-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<table class="caption-top table">
<thead>
<tr class="header">
<th>Name</th>
<th>Definition</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>DATETIME</td>
<td>Delivery datetime (ex. 12/26/2016 12:00:00 AM)</td>
</tr>
<tr class="even">
<td>YEAR</td>
<td>Datetimelike Property for the Specific Year in the Datetime</td>
</tr>
<tr class="odd">
<td>MONTH</td>
<td>Datetimelike Property for the Specific Month in the Datetime</td>
</tr>
<tr class="even">
<td>DAY</td>
<td>Datetimelike Property for the Specific Day in the Datetime</td>
</tr>
<tr class="odd">
<td>HOUR</td>
<td>Datetimelike Property for the Hour/Interval in the Datetime</td>
</tr>
<tr class="even">
<td>RESOURCE_ID</td>
<td>Each power plant and unit has a specific ID</td>
</tr>
<tr class="odd">
<td>MW</td>
<td>Registered MW generated for the spefic hour</td>
</tr>
</tbody>
</table>
</div>
</figure>
</div>
<p>Corresponding weather data, in each of these four locations, were collected separately from the Weather Underground website. The weather data contained 10 features. A data dictionary of the collected data can be seen in Table&nbsp;3.</p>
<div id="tbl-weather" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-tbl figure">
<figcaption class="quarto-float-caption-top quarto-float-caption quarto-float-tbl" id="tbl-weather-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Table&nbsp;3: Data Dictionary of the Weather data from the Weather Underground Website
</figcaption>
<div aria-describedby="tbl-weather-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<table class="caption-top table">
<thead>
<tr class="header">
<th>Name</th>
<th>Unit of Measure</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Temperature</td>
<td>degrees Fahrenheit</td>
</tr>
<tr class="even">
<td>Humidity</td>
<td>percentage</td>
</tr>
<tr class="odd">
<td>Dew Point</td>
<td>degrees Fahrenheit</td>
</tr>
<tr class="even">
<td>Pressure</td>
<td>inches</td>
</tr>
<tr class="odd">
<td>Precipitation</td>
<td>inches</td>
</tr>
<tr class="even">
<td>Cumulative Precipitation</td>
<td>inches</td>
</tr>
<tr class="odd">
<td>Wind Speed</td>
<td>mph</td>
</tr>
<tr class="even">
<td>Wind Gust</td>
<td>mph</td>
</tr>
<tr class="odd">
<td>Wind Direction</td>
<td>direction of wind</td>
</tr>
<tr class="even">
<td>Weather Condition</td>
<td>conditional</td>
</tr>
</tbody>
</table>
</div>
</figure>
</div>
<p>Granularity of the data is in 1-hr intervals, which results in a total of 23160 observations per plant. The experiment implemented a 80-10-10 training, validation and test split.</p>
</section>
<section id="sec-models" class="level3" data-number="5.2">
<h3 data-number="5.2" class="anchored" data-anchor-id="sec-models"><span class="header-section-number">5.2</span> Models</h3>
<section id="sec-industrybenchmark" class="level4" data-number="5.2.1">
<h4 data-number="5.2.1" class="anchored" data-anchor-id="sec-industrybenchmark"><span class="header-section-number">5.2.1</span> Industry Benchmark</h4>
<p>For the industry benchmark, <img src="https://latex.codecogs.com/png.latex?P_%7Bpred%7D"> is defined as each solar power plant’s day-ahead hourly projection submission to the market operator (in this case <img src="https://latex.codecogs.com/png.latex?T_%7Bt-24%7D"> hours), and <img src="https://latex.codecogs.com/png.latex?P_%7Bact%7D"> is defined as the actual scheduled dispatch by the solar plant considering the market operator’s dispatching schedule. The comparison between the <img src="https://latex.codecogs.com/png.latex?P_%7Bpred%7D"> and the <img src="https://latex.codecogs.com/png.latex?P_%7Bact%7D"> were examined.</p>
</section>
<section id="sec-proposed" class="level4" data-number="5.2.2">
<h4 data-number="5.2.2" class="anchored" data-anchor-id="sec-proposed"><span class="header-section-number">5.2.2</span> Proposed Models</h4>
<p>Four proposed models were utilized in this study all focusing on the LSTM neural network. Networks 1 and 2 considered a single LSTM layer with nodes, 64 and 32 respectively, while networks 3 and 4 considered a stacked two layer LSTM network with nodes 64-32 and 32-64 respectively.</p>
<p>An additional feed-forward hidden layer with a rectified linear unit activation function was utilized at the end of all four networks, where the number of hidden nodes corresponded to the number of hidden nodes of the last LSTM layer.</p>
<p>Network 1 and 4 utilized 32 nodes, while networks 2 and 3 utilized 64 nodes. All four networks considered the <code>optimizer=RMSProp</code>, <code>dropouts=0.2</code> and <code>recurrent dropouts=0.2</code>, <code>batch size=128</code>, and an <code>epoch setting=50</code>.</p>
</section>
</section>
</section>
<section id="sec-results" class="level2" data-number="6">
<h2 data-number="6" class="anchored" data-anchor-id="sec-results"><span class="header-section-number">6</span> Results</h2>
<div id="tbl-results" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-tbl figure">
<figcaption class="quarto-float-caption-top quarto-float-caption quarto-float-tbl" id="tbl-results-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Table&nbsp;4: Summary of Benchmark vs Model Performances
</figcaption>
<div aria-describedby="tbl-results-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<table class="caption-top table">
<colgroup>
<col style="width: 25%">
<col style="width: 25%">
<col style="width: 25%">
<col style="width: 25%">
</colgroup>
<thead>
<tr class="header">
<th>Power Plant</th>
<th>Best Model</th>
<th>Industry Benchmark Model</th>
<th>Performance Improvement</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Clark Solar Power Plant</td>
<td>LSTM+LSTM with 32 &amp; 64 nodes</td>
<td>2.86%</td>
<td>12.01%</td>
</tr>
<tr class="even">
<td>First Toledo Solar Power Plant</td>
<td>LSTM with 32 nodes</td>
<td>4.30%</td>
<td>15.34%</td>
</tr>
<tr class="odd">
<td>Subic Solar Power Plant</td>
<td>LSTM with 32 nodes</td>
<td>1.36%</td>
<td>3.64%</td>
</tr>
<tr class="even">
<td>Valenzuela Solar Power Plant</td>
<td>LSTM+LSTM with 32 &amp; 64 nodes</td>
<td>2.58%</td>
<td>12.48%</td>
</tr>
</tbody>
</table>
</div>
</figure>
</div>
<p>Table 2 shows the results of for each location. The stacked 2 layer LSTM with 32 and 64 nodes is the best performing model for the Clark Solar Power Plant and the Valenzuela Solar Power Plant, whereas the single layer LSTM model with 32 nodes best ts the First Toledo Solar Power Plant and the Subic Solar Power Plant.</p>
<p>For the Clark Solar Power Plant, the initial industry benchmark error was computed at 12.01%, and the 2 layer LSTM with 32 and 64 nodes model error is at 2.86%, which translates to a 76.19% error reduction.</p>
<p>For the First Toledo Solar Power Plant, a 15.34% industry benchmark error was computed, and the single layer LSTM with 32 nodes model produced only a 4.30% model error, which translates to a 71.97% error reduction.</p>
<p>For the Subic Solar Power Plant, the initial industry benchmark error was computed at 3.64%, and the single layer LSTM with 32 nodes model error is at 1.36%, which translates to a 62.64% error reduction.</p>
<p>For the Valenzuela Solar Power Plant, a 12.48% industry benchmark error was computed, and the two layer LSTM with 32 and 64 nodes model produced only a 2.58% model error, which translates to a 71.33% error reduction.</p>
</section>
<section id="sec-conclusions" class="level2" data-number="7">
<h2 data-number="7" class="anchored" data-anchor-id="sec-conclusions"><span class="header-section-number">7</span> Conclusions &amp; Recommendations</h2>
<p>Improvements brought upon by the utilization of deep learning models can reduce costs for both suppliers and the national grid operators, and increase the effciency of power generation.</p>
<p>Further studies can be conducted using di erent neural network architectures, varying numbers of nodes, layers, and optimizers of the LSTM layer, adding dense layers with different nodes. Including data that are main drivers of solar power generation, such as quality and angle of solar panels and the hourly irridiance, can drastically improve results.</p>
<p>A study that produces one model for all solar power plants may also be considered. Location and descriptors of the power plant can be included which is fed to a CNN network together with an LSTM model will consider both spatio-temporal features.</p>
</section>
<section id="sec-references" class="level2" data-number="8">
<h2 data-number="8" class="anchored" data-anchor-id="sec-references"><span class="header-section-number">8</span> References</h2>
<div id="refs" class="references csl-bib-body hanging-indent" data-entry-spacing="0">
<div id="ref-6" class="csl-entry">
Almeida, Marcelo Pinho, Oscar Perpiñán, and Luis Narvarte. 2015. <span>“PV Power Forecast Using a Nonparametric PV Model.”</span> <em>Solar Energy</em> 115: 354–68. https://doi.org/<a href="https://doi.org/10.1016/j.solener.2015.03.006">https://doi.org/10.1016/j.solener.2015.03.006</a>.
</div>
<div id="ref-2" class="csl-entry">
Qing, Xiangyun, and Yugang Niu. 2018. <span>“Hourly Day-Ahead Solar Irradiance Prediction Using Weather Forecasts by LSTM.”</span> <em>Energy</em> 148: 461–68. https://doi.org/<a href="https://doi.org/10.1016/j.energy.2018.01.177">https://doi.org/10.1016/j.energy.2018.01.177</a>.
</div>
<div id="ref-3" class="csl-entry">
Rassem, Aliaa, Mohammed A. El-Beltagy, and Mohamed Saleh. 2017. <span>“Cross-Country Skiing Gears Classification Using Deep Learning.”</span> <em>ArXiv</em> abs/1706.08924.
</div>
<div id="ref-5" class="csl-entry">
Sobri, Sobrina, Sam Koohi-Kamali, and Nasrudin Abd. Rahim. 2018. <span>“Solar Photovoltaic Generation Forecasting Methods: A Review.”</span> <em>Energy Conversion and Management</em> 156: 459–97. https://doi.org/<a href="https://doi.org/10.1016/j.enconman.2017.11.019">https://doi.org/10.1016/j.enconman.2017.11.019</a>.
</div>
<div id="ref-4" class="csl-entry">
Wang, Kejun, Xiaoxia Qi, and Hongda Liu. 2019. <span>“A Comparison of Day-Ahead Photovoltaic Power Forecasting Models Based on Deep Learning Neural Network.”</span> <em>Applied Energy</em> 251: 113315. https://doi.org/<a href="https://doi.org/10.1016/j.apenergy.2019.113315">https://doi.org/10.1016/j.apenergy.2019.113315</a>.
</div>
<div id="ref-1" class="csl-entry">
Zhang, Jinxia, Yuanying Chi, and Linpeng Xiao. 2018. <span>“Solar Power Generation Forecast Based on LSTM.”</span> In <em>2018 IEEE 9th International Conference on Software Engineering and Service Science (ICSESS)</em>, 869–72. <a href="https://doi.org/10.1109/ICSESS.2018.8663788">https://doi.org/10.1109/ICSESS.2018.8663788</a>.
</div>
</div>
<!-- ## Appendix {#sec-appendix} -->


</section>

 ]]></description>
  <category>python</category>
  <category>reinforced-learning</category>
  <category>time-series</category>
  <category>lstm</category>
  <guid>https://sandrosilva.site/posts/2023-04-25-Solar/</guid>
  <pubDate>Mon, 25 Apr 2022 00:00:00 GMT</pubDate>
  <media:content url="https://sandrosilva.site/posts/2023-04-25-Solar/source-files/thumbnail.png" medium="image" type="image/png" height="81" width="144"/>
</item>
<item>
  <title>UnwRappler 2</title>
  <link>https://sandrosilva.site/posts/2023-04-24-unwRappler2/</link>
  <description><![CDATA[ 




<p><img src="https://sandrosilva.site/posts/2023-04-24-unwRappler2/source/rappler-mood-meter2.png" class="img-fluid" style="width:100.0%"></p>
<section id="sec-authors" class="level2" data-number="1">
<h2 data-number="1" class="anchored" data-anchor-id="sec-authors"><span class="header-section-number">1</span> Authors</h2>
<p>This analysis was done together with my groupmates George Esleta, Carmelita Esclanda, and Elmer Robles.</p>
<p>Original creation and submission of this report was last July 2019.</p>
</section>
<section id="sec-executivesummary" class="level2" data-number="2">
<h2 data-number="2" class="anchored" data-anchor-id="sec-executivesummary"><span class="header-section-number">2</span> Executive Summary</h2>
<div class="executive-summary">
<p><a href="www.rappler.com">Rappler</a>, one of the leading online news publishers in the Philippines, obtains audience sentiment through the Mood Meter widget embedded in its articles. The Mood Meter allows a reader to select an article’s mood from a set of predefined moods (happy, inspired, amused, sad, angry, afraid, annoyed, don’t care) with varying polarities (positive mood or negative mood). Using machine learning algorithms, we created two classification models to predict a Rappler article’s dominant mood and polarity. A total of 5,735 Rappler articles with metadata such as category, author, and mood ratings were used as the training set. The resulting models can predict the article polarity with 72% accuracy and the article’s dominant mood with 51% accuracy. These models can aid Rappler and other news publishers in content personalization, article engineering, and dynamic ad placement and pricing.</p>
</div>
</section>
<section id="sec-introduction" class="level2" data-number="3">
<h2 data-number="3" class="anchored" data-anchor-id="sec-introduction"><span class="header-section-number">3</span> Introduction</h2>
<p>With the rapid growth of social networking and the internet in general, <a href="www.rappler.com">Rappler</a> has been one of the top news providers in the Philippines by developing and distributing news via the web and social media channels. It is a social news network where stories inspire community engagement and digitally fueled actions for social change.</p>
<p>Rappler deployed “Mood Meter”, similar to Facebook Reactions, and embedded it on each article. Through the widget, Rappler allows readers to share their mood towards an article by answering the question, ”How does the story make you feel?”. Readers choose from a predefined set of emotions, namely: happy, sad, angry, don’t care, inspired, afraid, amused, and annoyed. By that, each article in Rappler will have multiple labeled emotions crowd-sourced from their readers. Figure&nbsp;1 shows a sample Mood Meter report of an article.</p>
<div id="fig-rappler-mood-meter" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-rappler-mood-meter-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://sandrosilva.site/posts/2023-04-24-unwRappler2/source/rappler-mood-meter.png" class="img-fluid figure-img">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-rappler-mood-meter-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;1: The Rappler Mood Meter. The reader can select from one of eight predefined moods (Happy, Sad, Angry, Don’t Care, Inspired, Afraid, Amused, and Annoyed)
</figcaption>
</figure>
</div>
<p>This paper presents two models that implement Sentiment Analysis by predicting the mood and polarity of a given Rappler article. The paper is organized as follows: Section&nbsp;4 describes related work on emotion classification using different language resources, features, and algorithms; Section&nbsp;5 discusses the methodology; Section&nbsp;6 discusses the model performance; lastly, Section&nbsp;7 discusses the conclusions.</p>
</section>
<section id="sec-relatedworks" class="level2" data-number="4">
<h2 data-number="4" class="anchored" data-anchor-id="sec-relatedworks"><span class="header-section-number">4</span> Related Works</h2>
<p>Studies show that 80% of the way people make decisions is based on emotions, yet this fact has been disregarded by newsgroups. Given this, Rappler made its mark by implementing a ‘mood meter’ dashboard system that monitors the reader’s waves of emotion that kept them involved, thus amplified their social media presence.</p>
<p>In the advent of the knowledge economy, researchers such as <span class="citation" data-cites="11">Shivhare, Garg, and Mishra (2015)</span> utilized emotion ontology and weighting algorithm that deals with the depth of ontology and parent-child relationship to quantify emotion class. The ontology is built with the definition of schemas and aspects such as entities and attributes, the relationship between the entities, and the domain vocabulary. Their research led to an average accuracy of 79.57% from six emotion classes. The emotion detection model was tested on 135 blog posts.</p>
<p>Another research classified a document’s polarity on a multi-way scale and expanded the task of classifying a movie review as either positive or negative to predicting star ratings on either 3 or 4 star scale. <span class="citation" data-cites="2">Pang and Lee (2005)</span> checked human performance and, applied meta algorithm and metric labelling. The Meta algorithm gave the best performance over both multi-class and regression versions of SVMs when a novel similarity measure appropriate to the problem was employed.</p>
<p>Taking the study further, sentiment analysis has been applied by researchers to get insights from user-generated feedback <span class="citation" data-cites="3">(see Medhat, Hassan, and Korashy 2014)</span>. Sentiment analysis is the computational study of opinions, sentiments, and emotions in text. Although traditional sentiment analysis focuses on the sentiment or emotion in the text, this study focuses on the emotions that are being elicited by a news article from readers.</p>
<p>Several researchers,such as <span class="citation" data-cites="4">Siersdorfer et al. (2010)</span>, <span class="citation" data-cites="5">Sureka et al. (2010)</span>, <span class="citation" data-cites="6">Cheong and Cheong (2011)</span>, have performed sentiment analysis of social networks such as Twitter and YouTube. These works deal with comments, tweets and other metadata collected from the social network profiles of users or of public events that have been collected and analyzed to obtain significant and interesting insights about the usage of these social network websites by the general mass of people.</p>
<p>The work most closely related to ours is by Song et al. <span class="citation" data-cites="7">(Song et al. 2016)</span> and Taj et al. <span class="citation" data-cites="8">(Taj, Shaikh, and Meghji 2019)</span>. The former built an emotion lexicon by developing a novel joint non-negative matrix factorization model which not only incorporates crowd-annotated emotion labels of articles but also generates the lexicon using the topic-specific matrices obtained from the factorization process while the latter explored sentiment analysis of news and blogs using a dataset from BBC comprising of new articles between the year 2004 and 2005. They observed that categories of business and sports had more positive articles, whereas entertainment and tech had a majority of negative articles.</p>
</section>
<section id="sec-methodology" class="level2" data-number="5">
<h2 data-number="5" class="anchored" data-anchor-id="sec-methodology"><span class="header-section-number">5</span> Methodology</h2>
<section id="sec-datacollection" class="level3" data-number="5.1">
<h3 data-number="5.1" class="anchored" data-anchor-id="sec-datacollection"><span class="header-section-number">5.1</span> Data Collection</h3>
<p>A total of 5,735 articles were extracted from the <a href="www.rappler.com">Rappler</a> website. As shown in Figure&nbsp;2, the articles were taken from four categories: Nation (<code>1,462 articles</code>), World (<code>1,322 articles</code>), Entertainment-Movies (<code>1,452 articles</code>), and Entertainment-Music (<code>1,499 articles</code>. Apart from the full text of the article, metadata such as the article’s category, authors, and mood meter values were also extracted. The description of the Rappler data is shown in Table&nbsp;1.</p>
<div id="fig-rappler-article-count" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-rappler-article-count-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://sandrosilva.site/posts/2023-04-24-unwRappler2/source/rappler-article-count.png" class="img-fluid figure-img">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-rappler-article-count-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;2: Acticle count per category collected
</figcaption>
</figure>
</div>
<p><br></p>
<div id="tbl-datadescription" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-tbl figure">
<figcaption class="quarto-float-caption-top quarto-float-caption quarto-float-tbl" id="tbl-datadescription-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Table&nbsp;1: Data description of the articles extracted from Rappler
</figcaption>
<div aria-describedby="tbl-datadescription-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<table class="caption-top table">
<colgroup>
<col style="width: 14%">
<col style="width: 10%">
<col style="width: 74%">
</colgroup>
<thead>
<tr class="header">
<th>Feature</th>
<th>Data type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>category</td>
<td>VARCHAR</td>
<td>Article category (nation/world/entertainment)</td>
</tr>
<tr class="even">
<td>published</td>
<td>VARCHAR</td>
<td>Published date of the article</td>
</tr>
<tr class="odd">
<td>modified</td>
<td>VARCHAR</td>
<td>Modified date of the article</td>
</tr>
<tr class="even">
<td>author</td>
<td>VARCHAR</td>
<td>Author of article</td>
</tr>
<tr class="odd">
<td>title</td>
<td>VARCHAR</td>
<td>Article title</td>
</tr>
<tr class="even">
<td>happy</td>
<td>INT</td>
<td>Percentage of readers who selected “happy” as the article’s mood</td>
</tr>
<tr class="odd">
<td>sad</td>
<td>INT</td>
<td>Percentage of readers who selected “sad” as the article’s mood</td>
</tr>
<tr class="even">
<td>angry</td>
<td>INT</td>
<td>Percentage of readers who selected “angry” as the article’s mood</td>
</tr>
<tr class="odd">
<td>don’t care</td>
<td>INT</td>
<td>Percentage of readers who selected “don’t care” as the article’s mood</td>
</tr>
<tr class="even">
<td>inspired</td>
<td>INT</td>
<td>Percentage of readers who selected “inspired” as the article’s mood</td>
</tr>
<tr class="odd">
<td>afraid</td>
<td>INT</td>
<td>Percentage of readers who selected “afraid” as the article’s mood</td>
</tr>
<tr class="even">
<td>amused</td>
<td>INT</td>
<td>Percentage of readers who selected “amused” as the article’s mood</td>
</tr>
<tr class="odd">
<td>annoyed</td>
<td>INT</td>
<td>Percentage of readers who selected “annoyed” as the article’s mood</td>
</tr>
<tr class="even">
<td>text</td>
<td>VARCHAR</td>
<td>Article text</td>
</tr>
</tbody>
</table>
</div>
</figure>
</div>
</section>
<section id="sec-featureextraction" class="level3" data-number="5.2">
<h3 data-number="5.2" class="anchored" data-anchor-id="sec-featureextraction"><span class="header-section-number">5.2</span> Featue Extraction</h3>
<section id="sec-textprocessing" class="level4" data-number="5.2.1">
<h4 data-number="5.2.1" class="anchored" data-anchor-id="sec-textprocessing"><span class="header-section-number">5.2.1</span> Text Processing</h4>
<p>The article text was processed for data analysis prior to feature extraction. Common techniques like converting text to lowercase and removing leading/trailing whitespaces were applied to make text case-insensitive.</p>
<p>Advanced techniques such as stemming were also used to reduce derived words to their root form (e.g., playing, plays, and played were reduced to “play”). Stemming is a technique that reduces inflected or derived words to their base form, which can help to simplify text analysis by treating similar words as the same.</p>
<p>To further prepare the text for analysis, a bag-of-words vectorization technique was applied to the stemmed text. A Bag-of-words vectorization is a technique that represents text data as a sparse matrix of word frequencies, where each row corresponds to a document or text sample and each column corresponds to a unique word in the corpus. Table&nbsp;2 shows the hyperparameters utilized.</p>
<p>The number of features was limited to 3,730 by performing hyperparameter tuning on the bag-of-words vectorization.</p>
<div id="tbl-bagofwords" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-tbl figure">
<figcaption class="quarto-float-caption-top quarto-float-caption quarto-float-tbl" id="tbl-bagofwords-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Table&nbsp;2: Hyperparameters utilized in bag-of-words representation
</figcaption>
<div aria-describedby="tbl-bagofwords-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<table class="caption-top table">
<colgroup>
<col style="width: 50%">
<col style="width: 50%">
</colgroup>
<thead>
<tr class="header">
<th>Parameter</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>min_df</td>
<td>0.01</td>
</tr>
<tr class="even">
<td>max_df</td>
<td>0.7</td>
</tr>
<tr class="odd">
<td>ngram_range</td>
<td>(1,3)</td>
</tr>
</tbody>
</table>
</div>
</figure>
</div>
</section>
<section id="sec-variableengineering" class="level4" data-number="5.2.2">
<h4 data-number="5.2.2" class="anchored" data-anchor-id="sec-variableengineering"><span class="header-section-number">5.2.2</span> Variable Engineering</h4>
<p>The eight mood variables extracted from the Mood Meter are continuous variables and can have a value between <code>0</code> and <code>100</code>. To convert the problem to a classification problem (as opposed to regression), four additional variables were computed from the original article metadata, namely the positivity score, negativity score, polarity, and the dominant mood. Table&nbsp;3 provides a description of each computed variable. Of these four, the polarity and dominant mood were chosen as the target variables of our models.</p>
<div id="tbl-features" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-tbl figure">
<figcaption class="quarto-float-caption-top quarto-float-caption quarto-float-tbl" id="tbl-features-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Table&nbsp;3: Additional variables computed from the Rappler data
</figcaption>
<div aria-describedby="tbl-features-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<table class="caption-top table">
<colgroup>
<col style="width: 15%">
<col style="width: 8%">
<col style="width: 75%">
</colgroup>
<thead>
<tr class="header">
<th>Computed Variable</th>
<th>Data type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>positive_score</td>
<td>INT</td>
<td>Sum of positive moods (happy, inspired, amused)</td>
</tr>
<tr class="even">
<td>negative_score</td>
<td>INT</td>
<td>Sum of negative moods (angry, afraid, annoyed, sad)</td>
</tr>
<tr class="odd">
<td>polarity</td>
<td>INT</td>
<td>Article polarity, whether negative (0) or positive (1)<br>Negative polarity (polarity=0) if positive_score &lt; negative_score <br> Positive polarity (polarity=1) if positive_score &gt; negative_score</td>
</tr>
<tr class="even">
<td>dominant_mood</td>
<td>INT</td>
<td>Mood with the highest number of votes from readers<br>0: happy<br>1: sad<br>2: angry<br>3: dontcare<br>4: inspired<br>5: afraid<br>6: amused<br>7: annoyed</td>
</tr>
</tbody>
</table>
</div>
</figure>
</div>
<p>The polarity of an article was quantified by grouping the eight moods into two: the positive moods (happy, inspired, amused) and the negative moods (sad, angry, annoyed, afraid, don’t care). If the positivity score (sum of positive moods) is greater than the negativity score (sum of negative moods), the article’s polarity is tagged as positive; otherwise, the polarity is tagged as negative. The dominant mood of an article, on the other hand, was obtained by getting the mood with the highest value.</p>
</section>
</section>
<section id="sec-modelevaluation" class="level3" data-number="5.3">
<h3 data-number="5.3" class="anchored" data-anchor-id="sec-modelevaluation"><span class="header-section-number">5.3</span> Model Evaluation</h3>
<p>Two (2) classification models were developed in this study. The first model is a binary classification model that predicts article polarity (negative or positive), while the second model is a multi-class classification model that predicts an article’s dominant mood from eight predefined moods (happy, inspired, amused, sad, angry, afraid, don’t care, annoyed).</p>
<p>Several supervised machine learning algorithms were evaluated in terms of classification accuracy. For the models to be considered effective, they must achieve a classification accuracy greater than the proportional chance criteria (PCC), which is the highest possible random chance of classifying an article without an explicit mathematical model.</p>
<section id="sec-polarityclassification" class="level4" data-number="5.3.1">
<h4 data-number="5.3.1" class="anchored" data-anchor-id="sec-polarityclassification"><span class="header-section-number">5.3.1</span> Polarity Classification Model</h4>
<p>Figure&nbsp;3 shows the resulting polarity distribution of the articles. In terms of article polarity, the dataset has a proportional chance criterion (PCC) of <code>54.4%</code>, which means that there is a <code>54.4%</code> chance of randomly predicting the correct polarity without any model. For our machine learning model to be considered successful, it must achieve a minimum classification accuracy of 1.25PCC or <code>68%</code>.</p>
<div id="fig-rappler-pcc1" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-rappler-pcc1-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://sandrosilva.site/posts/2023-04-24-unwRappler2/source/rappler-pcc1.png" class="img-fluid figure-img">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-rappler-pcc1-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;3: Polarity distribution of articles. Our model must achieve a classification accuracy higher than the proportional chance criteria (PCC = 0.545) for it to be considered adequate.
</figcaption>
</figure>
</div>
</section>
<section id="sec-moodclassification" class="level4" data-number="5.3.2">
<h4 data-number="5.3.2" class="anchored" data-anchor-id="sec-moodclassification"><span class="header-section-number">5.3.2</span> Mood Classification Model</h4>
<p>The extracted Rappler dataset is highly imbalanced in terms of mood distribution as seen in Figure&nbsp;4. To address this, Synthetic Minority Oversampling Technique (SMOTE) was implemented. SMOTE is a technique for addressing class imbalance in a dataset by creating synthetic examples of the minority class through interpolation. It helps balance the class distribution and improve the performance of machine learning models. In this scenario, undersampling was utilized to equalize the class distribution among the eight multi-classes. After balancing using SMOTE, a proportional chance criteria (PCC) of <code>12.5%</code> was achieved. For our model to be considered effective, a minimum classification accuracy of 1.25PCC or <code>16%</code> must be achieved.</p>
<div id="fig-rappler-mood" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-rappler-mood-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://sandrosilva.site/posts/2023-04-24-unwRappler2/source/rappler-mood.png" class="img-fluid figure-img">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-rappler-mood-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;4: Mood distribution of articles. Synthetic Minority Oversampling Technique (SMOTE) was implemented to balance the dataset.
</figcaption>
</figure>
</div>
</section>
</section>
</section>
<section id="sec-results" class="level2" data-number="6">
<h2 data-number="6" class="anchored" data-anchor-id="sec-results"><span class="header-section-number">6</span> Results</h2>
<section id="sec-polarity-classifier" class="level3" data-number="6.1">
<h3 data-number="6.1" class="anchored" data-anchor-id="sec-polarity-classifier"><span class="header-section-number">6.1</span> Polarity Classifier</h3>
<p>Table&nbsp;4 shows the performance of the various machine learning algorithms used to predict the polarity of Rappler articles. The Random Forest classifier (with features of <code>300 trees</code>, <code>maximum depth=3</code> and, <code>maximum features=30%</code>) is the best-performing algorithm and can predict the polarity of an article with <code>72.0%</code> accuracy. This is 32% higher than the proportional chance criterion of <code>54.5%</code>, indicating that our model is successful in classifying Rappler articles based on polarity.</p>
<div id="tbl-polarityresults" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-tbl figure">
<figcaption class="quarto-float-caption-top quarto-float-caption quarto-float-tbl" id="tbl-polarityresults-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Table&nbsp;4: Performance of the various machine learning algorithms in predicting article polarity.
</figcaption>
<div aria-describedby="tbl-polarityresults-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<table class="caption-top table">
<colgroup>
<col style="width: 27%">
<col style="width: 12%">
<col style="width: 10%">
<col style="width: 15%">
<col style="width: 14%">
<col style="width: 20%">
</colgroup>
<thead>
<tr class="header">
<th>Machine Learning Method</th>
<th>Training Accuracy</th>
<th>Test Accuracy</th>
<th>Training Time (s)</th>
<th>Test Time (s)</th>
<th>Best Parameter</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>KNN (minmax scaling)</td>
<td>0.729</td>
<td>0.710</td>
<td>1.794</td>
<td>1.316</td>
<td>n_neighbors: 46</td>
</tr>
<tr class="even">
<td>Logistic Regression (l2 penalty, minmax scaling)</td>
<td>0.739</td>
<td>0.708</td>
<td>0.250</td>
<td>0.003</td>
<td>C: 0.1</td>
</tr>
<tr class="odd">
<td>Logistic Regression (l1 penalty, minmax scaling)</td>
<td>0.720</td>
<td>0.720</td>
<td>0.199</td>
<td>0.003</td>
<td>C: 0.05</td>
</tr>
<tr class="even">
<td>Linear SVM (l2 penalty, minmax scaling)</td>
<td>0.741</td>
<td>0.709</td>
<td>0.265</td>
<td>0.003</td>
<td>C: 0.02</td>
</tr>
<tr class="odd">
<td>Linear SVM (l1 penalty, minmax scaling)</td>
<td>0.720</td>
<td>0.720</td>
<td>0.173</td>
<td>0.002</td>
<td>C: 0.01</td>
</tr>
<tr class="even">
<td>Non-Linear SVM (rbf kernel, minmax scaling)</td>
<td>0.720</td>
<td>0.720</td>
<td>13.375</td>
<td>2.549</td>
<td>C: 1, gamma: auto</td>
</tr>
<tr class="odd">
<td>Non-Linear SVM (poly kernel, minmax scaling)</td>
<td>0.733</td>
<td>0.720</td>
<td>13.585</td>
<td>2.573</td>
<td>C: 0.2, degree: 2, gamma: scale</td>
</tr>
<tr class="even">
<td>Naive Bayes</td>
<td>0.684</td>
<td>0.663</td>
<td>0.047</td>
<td>0.004</td>
<td>alpha: 500</td>
</tr>
<tr class="odd">
<td>Decision Tree</td>
<td>0.722</td>
<td>0.719</td>
<td>0.179</td>
<td>0.006</td>
<td>max_depth: 3</td>
</tr>
<tr class="even">
<td>Random Forest</td>
<td>0.721</td>
<td>0.720</td>
<td>5.052</td>
<td>0.110</td>
<td>max_depth: 3, max_features: 0.3</td>
</tr>
<tr class="odd">
<td>Gradient Boosting</td>
<td>0.858</td>
<td>0.697</td>
<td>9.643</td>
<td>0.015</td>
<td>learning_rate: 0.1, max_depth: 3, max_features: 0.3</td>
</tr>
</tbody>
</table>
</div>
</figure>
</div>
<p>To further explain the output of our polarity classification model, a Shapley Additive Explanations (SHAP) summary plot of the model was created as shown in Figure&nbsp;5.</p>
<p>For context, SHAP is a framework for explaining the predictions of machine learning models. It assigns importance values to each feature in a prediction using the concept of Shapley values from cooperative game theory. SHAP values provide a measure of feature importance and can be used to understand how the model is making its predictions.</p>
<p>The horizontal axis indicates the impact of each feature on the target variable, while the color signifies the magnitude of the feature. Among the features used in the model, the article category is the top predictor of article polarity. Being categorized under Nation has a significantly negative impact on the article’s polarity. Conversely, an article that is NOT categorized under Nation (e.g., Entertainment-Music, Entertainment-Movies) is more likely to get positive reactions from readers.</p>
<div id="fig-rappler-shap" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-rappler-shap-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://sandrosilva.site/posts/2023-04-24-unwRappler2/source/rappler-shap.png" class="img-fluid figure-img">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-rappler-shap-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;5: Shapley Additive Explanations (SHAP) summary plot of the model for predicting article polarity. The horizontal axis indicates the impact of each feature on the target variable, while the color signifies the magnitude of the feature. The article category is the top predictor of polarity.
</figcaption>
</figure>
</div>
</section>
<section id="sec-mood-classifier" class="level3" data-number="6.2">
<h3 data-number="6.2" class="anchored" data-anchor-id="sec-mood-classifier"><span class="header-section-number">6.2</span> Mood Classifier</h3>
<p>Table&nbsp;5 shows the performance of the various machine algorithms used to predict article dominant mood. The Gradient Boosting classifier (<code>learning rate=0.15</code>, <code>maximum depth=3</code> and <code>maximum features=50%</code>) is the best-performing algorithm and can classify the dominant polarity of an article with <code>51.0%</code> accuracy.</p>
<div id="tbl-moodresults" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-tbl figure">
<figcaption class="quarto-float-caption-top quarto-float-caption quarto-float-tbl" id="tbl-moodresults-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Table&nbsp;5: Performance of the various machine learning algorithms in predicting the dominant mood.
</figcaption>
<div aria-describedby="tbl-moodresults-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<table class="caption-top table">
<colgroup>
<col style="width: 32%">
<col style="width: 11%">
<col style="width: 10%">
<col style="width: 10%">
<col style="width: 13%">
<col style="width: 21%">
</colgroup>
<thead>
<tr class="header">
<th>Machine Learning Method</th>
<th>Training Accuracy</th>
<th>Test Accuracy</th>
<th>Training Time (s)</th>
<th>Test Time (s)</th>
<th>Best Parameter</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>KNN (minmax scaling)</td>
<td>1.000</td>
<td>0.292</td>
<td>1.315</td>
<td>2.097</td>
<td>n_neighbors: 1</td>
</tr>
<tr class="even">
<td>Logistic Regression (l2 penalty, minmax scaling)</td>
<td>0.7333</td>
<td>0.239</td>
<td>43.838</td>
<td>0.003</td>
<td>C: 500</td>
</tr>
<tr class="odd">
<td>Logistic Regression (l1 penalty, minmax scaling)</td>
<td>0.735</td>
<td>0.239</td>
<td>223.993</td>
<td>0.004</td>
<td>C: 100</td>
</tr>
<tr class="even">
<td>Linear SVM (l2 penalty, minmax scaling)</td>
<td>0.722</td>
<td>0.219</td>
<td>76.797</td>
<td>0.003</td>
<td>C: 1000</td>
</tr>
<tr class="odd">
<td>Linear SVM (l1 penalty, minmax scaling)</td>
<td>0.722</td>
<td>0.217</td>
<td>66.984</td>
<td>0.004</td>
<td>C: 100</td>
</tr>
<tr class="even">
<td>Non-Linear SVM (rbf kernel, minmax scaling)</td>
<td>1.000</td>
<td>0.463</td>
<td>121.646</td>
<td>5.137</td>
<td>C: 500, gamma: ’auto’</td>
</tr>
<tr class="odd">
<td>Non-Linear SVM (poly kernel, minmax scaling)</td>
<td>0.999</td>
<td>0.426</td>
<td>128.128</td>
<td>5.239</td>
<td>C: 500, degree:2, gamma: ’auto’</td>
</tr>
<tr class="even">
<td>Naive Bayes</td>
<td>0.365</td>
<td>0.312</td>
<td>0.281</td>
<td>0.003</td>
<td>alpha: 5</td>
</tr>
<tr class="odd">
<td>Decision Tree</td>
<td>0.421</td>
<td>0.418</td>
<td>1.312</td>
<td>0.007</td>
<td>max_depth: 5</td>
</tr>
<tr class="even">
<td>Random Forest</td>
<td>0.608</td>
<td>0.444</td>
<td>17.425</td>
<td>0.109</td>
<td>max_depth: 5, max_features: ‘auto’</td>
</tr>
<tr class="odd">
<td>Gradient Boosting</td>
<td>1.000</td>
<td>0.510</td>
<td>1735.419</td>
<td>0.088</td>
<td>Learning_rate: 0.15, max_depth: 5, Max_features: 0.5</td>
</tr>
</tbody>
</table>
</div>
</figure>
</div>
</section>
</section>
<section id="sec-conclusions" class="level2" data-number="7">
<h2 data-number="7" class="anchored" data-anchor-id="sec-conclusions"><span class="header-section-number">7</span> Conclusions</h2>
<p>Sentiment analysis of more than 5000 Rappler articles was conducted using several machine learning models. After collecting data, extracting relevant features and evaluating the models, it is found that Gradient Boosting Method has the best accuracy of 51% in predicting the mood of an article with reference to the baseline accuracy of 16%. On the other hand, Support Vector Machine (RBF) and Random Forest are superior in predicting the polarity with 72% accuracy against the 55% proportional chance criterion. Also, it is found that category is the top indicator for predicting both mood and polarity using superior models.</p>
<p>With said findings, ML is deemed to increase the precision of recommendations and provide a personalized experience to Rappler users. Rappler is recommended to implement a Recommender System to personalize the content of its website for each visitor based on the dominant mood or polarity of the articles being viewed. In the same way, Rappler can use the study in implementing dynamic placements and pricing in their display advertising inventory. With this, advertisers in the Rappler website can acquire huge increases in conversions and sales with a lower cost of acquisition. By understanding better what drives leads, Rappler can take advantage of ML by reengineering its contents to generate moods that attract more stakeholders. Whether the objective is page views, social shares, leads, or revenue, a ranked list of words-provoking sentiments can help Rappler plan resources, priorities, and budgets more effectively.</p>
<p>For future work, we recommend exploring other Rappler article categories and predicting the authorship of Rappler articles based on sentiments.</p>
</section>
<section id="sec-references" class="level2" data-number="8">
<h2 data-number="8" class="anchored" data-anchor-id="sec-references"><span class="header-section-number">8</span> References</h2>
<div id="refs" class="references csl-bib-body hanging-indent" data-entry-spacing="0">
<div id="ref-6" class="csl-entry">
Cheong, France, and Christopher Cheong. 2011. <span>“Social Media Data Mining: A Social Network Analysis of Tweets During the 2010-2011 Australian Floods.”</span> In <em>15th Pacific Asia Conference on Information Systems (PACIS)</em>, 46.
</div>
<div id="ref-3" class="csl-entry">
Medhat, Walaa, Ahmed Hassan, and Hoda Korashy. 2014. <span>“Sentiment Analysis Algorithms and Applications: A Survey.”</span> <em>Ain Shams Engineering Journal</em> 5 (4): 1093–113. https://doi.org/<a href="https://doi.org/10.1016/j.asej.2014.04.011">https://doi.org/10.1016/j.asej.2014.04.011</a>.
</div>
<div id="ref-2" class="csl-entry">
Pang, Bo, and Lillian Lee. 2005. <span>“Seeing Stars: Exploiting Class Relationships for Sentiment Categorization with Respect to Rating Scales.”</span> In <em>Proceedings of the 43rd Annual Meeting of the Association for Computational Linguistics (<span>ACL</span><span>’</span>05)</em>, 115–24. Ann Arbor, Michigan: Association for Computational Linguistics. <a href="https://doi.org/10.3115/1219840.1219855">https://doi.org/10.3115/1219840.1219855</a>.
</div>
<div id="ref-11" class="csl-entry">
Shivhare, Shiv Naresh, Shakun Garg, and Anitesh Mishra. 2015. <span>“EmotionFinder: Detecting Emotion from Blogs and Textual Documents.”</span> In <em>International Conference on Computing, Communication &amp; Automation</em>, 52–57. <a href="https://doi.org/10.1109/CCAA.2015.7148343">https://doi.org/10.1109/CCAA.2015.7148343</a>.
</div>
<div id="ref-4" class="csl-entry">
Siersdorfer, Stefan, Sergiu Chelaru, Wolfgang Nejdl, and Jose San Pedro. 2010. <span>“How Useful Are Your Comments? Analyzing and Predicting YouTube Comments and Comment Ratings.”</span> In <em>Proceedings of the 19th International Conference on World Wide Web, WWW ’10</em>, 891–900. <a href="https://doi.org/10.1145/1772690.1772781">https://doi.org/10.1145/1772690.1772781</a>.
</div>
<div id="ref-7" class="csl-entry">
Song, Kaisong, Wei Gao, Ling Chen, Shi Feng, Daling Wang, and Chengqi Zhang. 2016. <span>“Build Emotion Lexicon from the Mood of Crowd via Topic-Assisted Joint Non-Negative Matrix Factorization.”</span> In. <a href="https://doi.org/10.1145/2911451.2914759">https://doi.org/10.1145/2911451.2914759</a>.
</div>
<div id="ref-5" class="csl-entry">
Sureka, Ashish, Ponnurangam Kumaraguru, Atul Goyal, and Sidharth Chhabra. 2010. <span>“Mining YouTube to Discover Extremist Videos, Users and Hidden Communities.”</span> In <em>Information Retrieval Technology</em>, edited by Pu-Jen Cheng, Min-Yen Kan, Wai Lam, and Preslav Nakov, 13–24. Berlin, Heidelberg: Springer Berlin Heidelberg.
</div>
<div id="ref-8" class="csl-entry">
Taj, Soonh, Baby Bakhtawer Shaikh, and Areej Fatemah Meghji. 2019. <span>“Sentiment Analysis of News Articles: A Lexicon Based Approach.”</span> <em>2019 2nd International Conference on Computing, Mathematics and Engineering Technologies (iCoMET)</em>, 1–5.
</div>
</div>


</section>

 ]]></description>
  <category>python</category>
  <category>supervised-learning</category>
  <category>sentiment-analysis</category>
  <category>nlp</category>
  <guid>https://sandrosilva.site/posts/2023-04-24-unwRappler2/</guid>
  <pubDate>Sun, 24 Apr 2022 00:00:00 GMT</pubDate>
  <media:content url="https://sandrosilva.site/posts/2023-04-24-unwRappler2/source/thumbnail.png" medium="image" type="image/png" height="81" width="144"/>
</item>
<item>
  <title>UnwRappler</title>
  <link>https://sandrosilva.site/posts/2023-04-23-UnwRappler/</link>
  <description><![CDATA[ 




<p><img src="https://sandrosilva.site/posts/2023-04-23-UnwRappler/thumbnail.png" class="img-fluid"></p>
<h2 class="anchored">
Authors and Notes
</h2>
<p>This analysis was done together with my groupmates George Esleta, Carmelita Esclanda, and Elmer Robles.</p>
<p>Original creation and submission of this report was last July 2019.</p>
<h2 class="anchored">
Executive Summary
</h2>
<div class="executive-summary">
<p>Rappler, one of the leading online news publishers in the Philippines, seeks to inspire community engagement and create action for social change through citizen journalism. However, it has recently been under scrutiny by the Philippine government for “twisted” reporting. This study aims to uncover the underlying themes of Rappler news articles via unsupervised clustering techniques and see if there is an inherent concentration of news in a specific theme. A total of 11,079 articles were extracted from Rappler’s national news section published from January 2018 to May 2019. Features were extracted from the articles using a term frequency-inverse document frequency (TF-IDF) vectorizer and dimensions were reduced by implementing Latent Semantic Analysis (LSA). Lastly, unsupervised clustering via k-means algorithm was applied to group the articles and internal validation metrics were utilized to determine the optimal number of clusters. Ten clusters were uncovered, with Philippine President Rodrigo Duterte as the dominant cluster. The remaining themes touch on different branches of government, police and weather updates, and trending national issues. The insights gained from this research can aid Rappler in balancing its reporting by lessening bias towards specific topics.</p>
</div>
<div class="column-page">
<p><img src="https://sandrosilva.site/posts/2023-04-23-UnwRappler/source/rappler_poster.png" class="img-fluid"></p>
</div>
<h2 class="anchored">
Introduction
</h2>
<p>Rappler is one of the leading online news publishers in the Philippines. It was started in 2011 by former CNN journalist Maria Ressa. However, since 2018, Rappler has been under heavy scrutiny by the Philippine government for “twisted” and “biased reporting”. Philippine President Rodrigo Duterte even went so far as calling Rappler a “fake news” outlet that publishes articles that are “pregnant with falsity.” [1] Rappler has been on the receiving end of criminal cases from the Philippine governments. BIR filed several counts of tax evasion charges against Rappler CEO Maria Ressa. Cyberlibel cases were also filed against Ressa.</p>
<p>This begs the question “Why is Rappler being targeted by the Duterte Administration?” Is <a href="https://www.rappler.com/nation/197230-duterte-rappler-ban-twisted-reporting">Rappler</a> really “twisted” and “biased” in its reporting? To answer this question, we uncovered the underlying themes of Rappler’s news articles via unsupervised clustering, to see if there is indeed an inherent concentration of news in a specific topic or theme.</p>
<h2 class="anchored">
Business Value
</h2>
<p>Extracting themes from a set of articles programmatically has a widespread application in the digital publishing industry and can be used to deliver business value to readers, journalists, advertisers, aggregators, and researchers.</p>
<ol type="1">
<li><p><strong>Readers in the digital age have no patience.</strong> They are more likely to use a search engine to retrieve a set of ranked articles from multiple news sources and it becomes a challenge for online news platforms to engage a reader continuously. Automatic theme extraction and clustering of articles provide the ability to structure a set of articles in order to make it easier for readers to navigate to related articles. If articles can be presented in a logical hierarchy driven by patterns in the data, human intervention is minimized (saving on labor costs) and the reader is kept on the news platform, increasing engagement time on the site.</p></li>
<li><p><strong>News Publishers and Journalists seeking to address topics of broad interest to their readership can benefit from a thematic clustering articles to determine the balance of news coverage. </strong> Publishing organizations are always looking for gaps in news coverage in order to offer readers some perspective and insight into topics that are not heavily covered. By examining existing themes holistically, they can better gauge what is missing and what their next article should be about.</p></li>
<li><p><strong>Advertisers that are considering online news platforms to reach specific customer segments can tailor their messages so that they are congruent with the themes that readers are interested in. </strong> For instance, themes dealing with legislative or judicial proceedings may appeal to advertisers whose clients are lawyers or law schools. Advertisers of tourism and tourist agencies may be interested in weather and specific vacation destinations, such as Boracay.</p></li>
<li><p><strong>Aggregators in the licensed publishing industry create packages of content for redistribution. </strong> Their business model, which can be subscription or advertiser-based, is to target specific customers based on their geographic, demographic, and psychographic profile. For instance, if an investor wanted to understand market conditions for a particular industry, they would subscribe to a real-time news delivery service that was able to provide the relevant articles.</p></li>
<li><p><strong>Researchers make money by selling analytical reports. </strong> By studying the themes presented on news platforms and combining the study with other metrics such as readership engagement, sentiment analysis, and political stance, they can make in-depth comparisons with other news delivery platforms to better inform advertisers and aggregators.</p></li>
</ol>
<h2 class="anchored">
Methodology
</h2>
<p>To uncover the underlying themes, a total of 11,079 news articles published from January 2018 to May 2019 were retrieved from Rappler’s Nation section (https://www.rappler.com/nation). The general workflow for clustering the Rappler articles as shown in Figure 1 involves the following steps:</p>
<ol type="1">
<li>Data Extraction</li>
<li>Data Storage</li>
<li>Data Preprocessing</li>
<li>Exploratory Data Analysis</li>
<li>Feature Extraction via TFIDF Vectorization</li>
<li>Dimensionality Reduction using Latent Semantic Analysis (LSA)</li>
<li>Unsupervised clustering using k-means algorithm</li>
</ol>
<p>Each step of the workflow will be discussed in the succeeding sections. <br><br></p>
<div class="page-columns page-full">
<div class="quarto-figure quarto-figure-center page-columns page-full">
<figure class="figure page-columns page-full">
<p class="page-columns page-full"><img src="https://sandrosilva.site/posts/2023-04-23-UnwRappler/source/rappler_methodology.png" class="img-fluid figure-img column-page"></p>
<figcaption>FIGURE 1: Workflow for clustering the Rappler Articles</figcaption>
</figure>
</div>
</div>
<!-- <iframe
    width='1200'
    height='900'
    src="source/DMW - LT01 - Tech Paper.pdf">
</iframe> -->
<h3 class="anchored">
Data Extraction
</h3>
<p>To collect data for the analysis, web scraping tools were utilized, namely the Python’s requests and BeautifulSoup modules, to extract news articles from the Nation section of Rappler website between the period of January 2018 and May 2019. The extraction process included the extraction of the article’s content and relevant metadata while excluding non-essential information such as image captions, author and photographer details, location headers, hyperlinks, social media text, and general sign-offs. To ensure data accuracy and validity, an initial cleaning process was performed to eliminate irrelevant information.</p>
<h3 class="anchored">
Data Storage
</h3>
<p>The extracted articles were stored in a local sqlite database. A total of 11,079 news articles were stored in the database. Table 1 shows the data description:</p>
<p>TABLE 1: Data Dictionary</p>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Data</th>
<th>Data type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>article_id</td>
<td>VARCHAR</td>
<td>Unique ID identifier</td>
</tr>
<tr class="even">
<td>url</td>
<td>VARCHAR</td>
<td>Relative URL</td>
</tr>
<tr class="odd">
<td>headline</td>
<td>VARCHAR</td>
<td>Headline title</td>
</tr>
<tr class="even">
<td>metadesc</td>
<td>VARCHAR</td>
<td>Quick synopsis of the article</td>
</tr>
<tr class="odd">
<td>label</td>
<td>VARCHAR</td>
<td>Absolute URL</td>
</tr>
<tr class="even">
<td>author</td>
<td>VARCHAR</td>
<td>Author name(s)</td>
</tr>
<tr class="odd">
<td>published_date</td>
<td>VARCHAR</td>
<td>Published date</td>
</tr>
<tr class="even">
<td>updated_date</td>
<td>VARCHAR</td>
<td>Date updated</td>
</tr>
<tr class="odd">
<td>article</td>
<td>VARCHAR</td>
<td>Article text</td>
</tr>
<tr class="even">
<td>metakey</td>
<td>VARCHAR</td>
<td>List of metatags associated with the article</td>
</tr>
</tbody>
</table>
<h3 class="anchored">
Data Preprocessing
</h3>
<p>Data preprocessing was implemented on the acquired article text. The text preprocessing involves:</p>
<ol type="1">
<li>Neutralizing text case-sensitivity by converting text to lowercase</li>
<li>Omitting unnecessary whitespaces by removing leading and trailing whitespace</li>
<li>Converting words to root form by performing stemming, via NLTK’s <code>PorterStemmer</code>.</li>
</ol>
<h3 class="anchored">
Exploratory Data Analysis
</h3>
<p>Exploratory data analysis was conducted on the article corpus to identify any prominent themes or topics before clustering the data. Figure 2 illustrates the word cloud and word frequency graph for the Rappler news articles published from January 2018 to May 2019. The results demonstrate that the most frequently mentioned word in the dataset is President Rodrigo Duterte, indicating that he is a significant topic in Rappler’s news articles during that period. Furthermore, notable words such as government, Philippines, police, and justice were also identified. To confirm these findings, feature extraction and cluster analysis were performed on the dataset. Consequently, it can be inferred that at least one article cluster should have Duterte as the recurring theme. <br> <br></p>
<div class="page-columns page-full">
<div class="quarto-figure quarto-figure-center page-columns page-full">
<figure class="figure page-columns page-full">
<p class="page-columns page-full"><img src="https://sandrosilva.site/posts/2023-04-23-UnwRappler/source/rappler_eda.png" class="img-fluid figure-img column-page"></p>
<figcaption>FIGURE 2: (left) Word cloud of Rappler news articles from January 2018 to May 2019, (right) Word count of the top 15 most occurring words in the Rappler article corpus. Images show Former President Duterte was the top topic during the period.</figcaption>
</figure>
</div>
</div>
<h3 class="anchored">
Feature Extraction
</h3>
<p>To vectorize the text, the term frequency-inverse document frequency (TF-IDF) vectorizer was implemented using scikit-learn’s <code>Tfidfvectorizer</code>. Unlike an equal weighting vectorizer, the TF-IDF statistic measures the significance of a word to both the document and the corpus. The implementation of the vectorizer also involved considering additional parameters, such as:</p>
<ol type="1">
<li>the removal of English stopwords</li>
<li>the inclusion of unigram, bigram, and trigram n-grams.</li>
<li>words that appeared less than 0.1% or more than 70% were discarded from the vectorization</li>
</ol>
<p>TABLE 2: Hyperparameter adjustments</p>
<table class="caption-top table">
<colgroup>
<col style="width: 18%">
<col style="width: 68%">
<col style="width: 12%">
</colgroup>
<thead>
<tr class="header">
<th>Parameter</th>
<th>Description</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><code>min_df</code></td>
<td>ignore terms that have a document frequency strictly lower than the given threshold</td>
<td>0.001</td>
</tr>
<tr class="even">
<td><code>max_df</code></td>
<td>ignore terms that have a document frequency strictly higher than the given threshold</td>
<td>0.7</td>
</tr>
<tr class="odd">
<td><code>ngram_range</code></td>
<td>The lower and upper boundary of the range of n-values for different n-grams to be extracted. All values of n such that min_n &lt;= n &lt;= max_n will be used</td>
<td>(1,3)</td>
</tr>
</tbody>
</table>
<p>The <code>TFidfVectorizer</code> performs further cleaning of the data by removing both frequent words and rare words. Stopwords, or words that appear too frequently in the English and Filipino language (e.g., the, a, an, and, or), were dropped from the corpus. Rappler-specific stopwords, or words that appear in more than 70% of the titles, were also ignored by setting the <code>max_df</code> parameter of TFidfVectorizer to <code>max_df = 0.7</code>.</p>
<p>Rare words, or words that appeared in less than 0.1% of the Rappler articles, were also excluded from the corpus. This was implemented by setting the <code>min_df</code> parameter of the TFidfVectorizer to <code>min_df = 0.001</code>.</p>
<p>Unigrams, bigrams, and trigrams were extracted as part of the vocabulary by setting the ngram_range parameter of the TFidfVectorizer to <code>ngram_range = (1,3)</code>. This range of n-grams was chosen to preserve the context of certain phrases such as “Rodrigo Duterte”, “Supreme Court” (<code>n=2</code>), and “Philippine National Police” (<code>n=3</code>)</p>
<p>After vectorization, the collection of Rappler articles has <strong>36,254</strong> unique items in its vocabulary.</p>
<h3 class="anchored">
Dimensionality Reduction
</h3>
<p>The resulting feature set was a 10,873 by 36,254 matrix, which was computationally expensive to cluster. To reduce computational power, the vectorized data underwent dimensionality reduction through latent semantic analysis (LSA) using the <code>TruncatedSVD</code> class of sklearn.</p>
<p>In general, a lower number of dimensions facilitates wider comparisons of themes in a collection of text, while a higher number of dimensions enables more specific comparisons. A dimensionality of 50 to 1000 is typically suitable depending on the document collection’s size and nature. Sensitivity analysis was conducted to determine the optimal number of components, starting with 50 components and incrementing by 50 until 1000 components. The analysis found that using 300 components (<code>n=300</code>) extracted the broader underlying themes.</p>
<h3 class="anchored">
Unsupervised Clustering
</h3>
<p>Unsupervised clustering using the k-means algorithm was utilized to extract the underlying themes present in the Rappler news articles. To determine the optimal number of clusters, sensitivity analysis was performed by testing different cluster counts ranging from <code>k=2</code> to <code>k=20</code>. Internal validation were examined to select the optimal number of clusters. These validation metrics involved:</p>
<ol type="1">
<li>minimizing the Intracluster to Intercluster distance ratio</li>
<li>maximizing the Calinski-Harabasz score</li>
<li>maximizing the Silhouette coefficient, and</li>
<li>minimizing the sum of square distance to centroids coefficient</li>
</ol>
<p>The next section will discuss the resulting article clusters and the optimal number of cluster counts.</p>
<h2 class="anchored">
Results
</h2>
<p>To determine the optimal number of clusters, k-means clustering was implemented for different values of the cluster count k from <code>k=2</code> to <code>k=20</code>. Shown in Figure 3 is the variation in the values of the different internal validation measures as the cluster count k is increased. The silhouette coefficient is monotonically increasing as the number of clusters is increased, suggesting increasing separation of the clusters. However, to keep the clustering parsimonious, the SSE elbow method was used instead to determine the optimal value of k. Plotted below are the values of the internal validation criteria for values of 𝑘 between 2 and 20. Using the elbow method, <code>k=10</code> is a good candidate for the number of clusters.</p>
<div class="page-columns page-full">
<div class="quarto-figure quarto-figure-center page-columns page-full">
<figure class="figure page-columns page-full">
<p class="page-columns page-full"><img src="https://sandrosilva.site/posts/2023-04-23-UnwRappler/source/rappler_validation.png" class="img-fluid figure-img column-page"></p>
<figcaption>FIGURE 3: Plots of the various internal validation measures for k=2 to k=20. Using elbow method at k=10</figcaption>
</figure>
</div>
</div>
<h4 class="anchored">
Cluster Themes at <code>k=10</code>
</h4>
<p>k-means clustering was performed on the Rappler articles using a cluster count of k=10. To infer the underlying theme of each article cluster, cluster word clouds were created as shown in Figure 5.</p>
<div class="page-columns page-full">
<div class="quarto-figure quarto-figure-center page-columns page-full">
<figure class="figure page-columns page-full">
<p class="page-columns page-full"><img src="https://sandrosilva.site/posts/2023-04-23-UnwRappler/source/rappler_wordcloud.png" class="img-fluid figure-img column-page"></p>
<figcaption>FIGURE 5: Rappler Wordcloud for each cluster (k=10)</figcaption>
</figure>
</div>
</div>
<p>Form these word clouds, the underlying theme of each article cluster was identified as follows:</p>
<ol type="1">
<li>Legislative</li>
<li>Foreign Affairs (PH-China Relations)</li>
<li>General News</li>
<li>Judiciary</li>
<li>Weather</li>
<li>President Rodrigo Duterte</li>
<li>2019 Philippine Midterm Elections</li>
<li>Police</li>
<li>Boracay Rehabilitation</li>
<li>Health</li>
</ol>
<p>Figure 6 displays the distribution of the number of articles across the identified clusters. The General News cluster accounts for over 25% of the articles, and the Duterte cluster is the second-largest with more than 15% of the news articles. This validates the initial findings of the exploratory data analysis, which showed that President Rodrigo Duterte is the most mentioned word in the dataset, and that Duterte is a prominent topic in Rappler’s news articles.</p>
<div class="page-columns page-full">
<div class="quarto-figure quarto-figure-center page-columns page-full">
<figure class="figure page-columns page-full">
<p class="page-columns page-full"><img src="https://sandrosilva.site/posts/2023-04-23-UnwRappler/source/rappler_themes_10.png" class="img-fluid figure-img column-page"></p>
<figcaption>FIGURE 6: Topic distibution of Rappler articles sorted descending.</figcaption>
</figure>
</div>
</div>
<h2 class="anchored">
Insights
</h2>
<p>The application of the unsupervised clustering technique on a corpus of 11, 079 news articles shows consistency of topic clusters across different resolutions that include:</p>
<h4 class="anchored">
Duterte Article Cluster
</h4>
<div class="page-columns page-full">
<div class="quarto-figure quarto-figure-center page-columns page-full">
<figure class="figure page-columns page-full">
<p class="page-columns page-full"><img src="https://sandrosilva.site/posts/2023-04-23-UnwRappler/source/rappler_duterte.png" class="img-fluid figure-img column-page"></p>
<figcaption>FIGURE 7: (left) Word cloud and top words for the Duterte article cluster, (right) Top words mentioned in the Duterte corpus - it can be inferred that the subthemes of this cluster include human rights violations, the war on illegal drugs, and Senator Antonio Trillanes</figcaption>
</figure>
</div>
</div>
<p>The dominant theme of Rappler news articles is Philippine President Rodrigo Duterte, with nearly 16% of news articles in this cluster. Subthemes in this cluster include the war on drugs, human rights, Senator Antonio Trillanes, and Duterte’s ongoing war versus Rappler. This can imply that Rappler is particular with the President’s undertakings and that while this may be reasonable, Rappler has to review its focus given their strife with the President.</p>
<h4 class="anchored">
Philippine Politics Article Cluster (Legislative and Judiciary)
</h4>
<div class="page-columns page-full">
<div class="quarto-figure quarto-figure-center page-columns page-full">
<figure class="figure page-columns page-full">
<p class="page-columns page-full"><img src="https://sandrosilva.site/posts/2023-04-23-UnwRappler/source/rappler_judiciary.png" class="img-fluid figure-img column-page"></p>
<figcaption>FIGURE 8: (left) Word cloud and top words for the Judiciary article cluster, (right) From the top words, it can be inferred that the subthemes of this cluster include the impeachment of former Chief Justice Lourdes Sereno and the drug cases against Senator Leila De Lima.</figcaption>
</figure>
</div>
</div>
<div class="page-columns page-full">
<div class="quarto-figure quarto-figure-center page-columns page-full">
<figure class="figure page-columns page-full">
<p class="page-columns page-full"><img src="https://sandrosilva.site/posts/2023-04-23-UnwRappler/source/rappler_legislative.png" class="img-fluid figure-img column-page"></p>
<figcaption>FIGURE 9: (left) Wordcloud and top words for the Legislative article cluster, (right) From the top words, it can be inferred that the subthemes of this cluster include the national budget and the proposed shift to a federal system</figcaption>
</figure>
</div>
</div>
<p>The other major themes are related to the other branches of the Philippine government, particularly the Legislative branch (House of Representatives, Senate) and the Judicial branch (Supreme Court).</p>
<p>Figure 8 shows that the Judicial cluster contains subthemes such as the impeachment of former Chief Justice Maria Lourdes Sereno and the drug charges filed against Senator Leila de Lima by the DOJ. In the case of Sereno, the impeachment was due to various issues including failure to disclose assets in her SALN and misuse of public funds. On the other hand, De Lima was charged with drug-related offenses.</p>
<p>he Legislative article cluster (Figure 9) includes subthemes such as budget and proposed changes in the constitution to shift to a federal type of government. Similar to the dominant clusters, this cluster revolves around politics. It is evident that Rappler has a strong focus on the political landscape in the Philippines, particularly on current and significant issues.</p>
<h4 class="anchored">
Police and Weather Clusters
</h4>
<div class="page-columns page-full">
<div class="quarto-figure quarto-figure-center page-columns page-full">
<figure class="figure page-columns page-full">
<p class="page-columns page-full"><img src="https://sandrosilva.site/posts/2023-04-23-UnwRappler/source/rappler_pnp.png" class="img-fluid figure-img column-page"></p>
<figcaption>FIGURE 10: (left) Wordcloud and (right) top words in the Police article cluster</figcaption>
</figure>
</div>
</div>
<div class="page-columns page-full">
<div class="quarto-figure quarto-figure-center page-columns page-full">
<figure class="figure page-columns page-full">
<p class="page-columns page-full"><img src="https://sandrosilva.site/posts/2023-04-23-UnwRappler/source/rappler_weather.png" class="img-fluid figure-img column-page"></p>
<figcaption>FIGURE 11: (left) Wordcloud and (right) top words in the Weather article cluster</figcaption>
</figure>
</div>
</div>
<p>Two recurring themes regardless of the number of clusters selected are police reports and weather reports. In line with the duterte cluster, it is sensible that the cluster about the police can be generated given the “oplan tokhang” implemented by the administration. Meanwhile, the weather cluster is sound considering the country’s geographic circumstances.</p>
<h4 class="anchored">
Time-Specific Article Clusters
</h4>
<div class="page-columns page-full">
<div class="quarto-figure quarto-figure-center page-columns page-full">
<figure class="figure page-columns page-full">
<p class="page-columns page-full"><img src="https://sandrosilva.site/posts/2023-04-23-UnwRappler/source/rappler_current.png" class="img-fluid figure-img column-page"></p>
<figcaption>FIGURE 12: (left) Wordcloud and (right) top words in the 2019 Midterm Elections article cluster</figcaption>
</figure>
</div>
</div>
<div class="page-columns page-full">
<div class="quarto-figure quarto-figure-center page-columns page-full">
<figure class="figure page-columns page-full">
<p class="page-columns page-full"><img src="https://sandrosilva.site/posts/2023-04-23-UnwRappler/source/rappler_boracay.png" class="img-fluid figure-img column-page"></p>
<figcaption>FIGURE 13: (left) Wordcloud and (right) top words in the Boracay article cluster</figcaption>
</figure>
</div>
</div>
<div class="page-columns page-full">
<div class="quarto-figure quarto-figure-center page-columns page-full">
<figure class="figure page-columns page-full">
<p class="page-columns page-full"><img src="https://sandrosilva.site/posts/2023-04-23-UnwRappler/source/rappler_health.png" class="img-fluid figure-img column-page"></p>
<figcaption>FIGURE 14: (left) Wordcloud and (right) top words in the Dengue Vaccine article cluster</figcaption>
</figure>
</div>
</div>
<p>The remaining themes are time-related and reflect major events during the timeframe selected (January 2019 to May 2019), such as the 2019 Philippine Midterm Elections, Boracay Island Rehabilitation (April 2018-October 2018), and the Dengvaxia (dengue vaccine) controversy.</p>
<h4 class="anchored">
Sensitivity Analysis
</h4>
<p>While it was concluded that 10 is the optimal number of groupings for the subject dataset, sensitivity analysis has been performed to test the robustness of the results gathered. Shown below are the resulting article clusters for <code>k=6</code> and <code>k=16</code>. It is noted that as the cluster count is increased, the most affected clusters are bigger ones, especially the Duterte cluster. As such, it can be deduced that said cluster has many subclusters which are differentiated when cluster count is increased. Nevertheless, the core clusters (e.g., General News, Duterte, 2019 Election, Police) created regardless of the number of clusters are constant.</p>
<div class="page-columns page-full">
<div class="quarto-figure quarto-figure-center page-columns page-full">
<figure class="figure page-columns page-full">
<p class="page-columns page-full"><img src="https://sandrosilva.site/posts/2023-04-23-UnwRappler/source/rappler_6.png" class="img-fluid figure-img column-page"></p>
<figcaption>FIGURE 15: Clustering and Cluster size distribution for <code>k=6</code></figcaption>
</figure>
</div>
</div>
<div class="page-columns page-full">
<div class="quarto-figure quarto-figure-center page-columns page-full">
<figure class="figure page-columns page-full">
<p class="page-columns page-full"><img src="https://sandrosilva.site/posts/2023-04-23-UnwRappler/source/rappler_16.png" class="img-fluid figure-img column-page"></p>
<figcaption>FIGURE 16: Clustering and Cluster size distribution for <code>k=16</code></figcaption>
</figure>
</div>
</div>
<h2 class="anchored">
Summary &amp; Conclusions
</h2>
<p>Grouping of articles into clusters of related topics by unsupervised clustering method has significant value to communication researchers and media practitioners in studying news output at scale and its repercussions. This study was able to unwrap 10 major themes ranging from General News, Politics, Weather, Health and relevant events. As such, the result can be used as a starting point for a generalized theme extraction project from a national corpus in order to learn the general interest and sentiments of the people.</p>
<h2 class="anchored">
Recommendations
</h2>
<p>The following points can be considered in future research related to this work:</p>
<ol type="1">
<li><p><strong>Comparative cluster analysis with other Philippine news outfits</strong> (Inquirer, ABS-CBN News, GMA News) can be explored to validate Rappler’s focus on particular topics;</p></li>
<li><p><strong>Sentiment analysis can explored to look into the subjective information or emotional states of the article.</strong> The value of combining clustering with sentiment analysis could be implemented in making better sense of Rappler’s public opinion on trending issues or the current administration; and,</p></li>
<li><p><strong>Historical analysis can be explored to compare the rappler data during previous administrations with the current to recognize difference in rappler’s focus per administration.</strong> Administration changes can affect the political landscape and prioritization of complex issues. For instance, if an issue from one administration was solved in the next administration.</p></li>
</ol>
<h2 class="anchored">
References
</h2>
<p><i> 1. <a href="https://www.rappler.com/nation/197230-duterte-rappler-ban-twisted-reporting">Duterte says he banned Rappler due to ‘twisted’ reporting</a><br> 2. <a href="https://www.rappler.com/nation/193806-duterte-fake-news-outlet">Duterte calls Rappler ’fake news outlet”</a><br> 3. <a href="https://towardsdatascience.com/all-the-news-17fa34b52b9d">All the news:Clustering 143,000 articles with KMeans</a><br> 4. <a href="https://seangtkelley.me/blog/2018/01/03/news-article-clustering">Story Discovery using K-Means Clustering on news articles</a><br> 5. <a href="https://scikit-learn.org/stable/auto_examples/text/plot_document_clustering.html#sphx-glr-auto-examples-text-plot-document-clustering-py">Clustering text documents using k-means</a><br> 6. <a href="http://www.scholarpedia.org/article/Latent_semantic_analysis">Latent semantic analysis</a> </i></p>



 ]]></description>
  <category>python</category>
  <category>unsupervised-learning</category>
  <category>clustering</category>
  <guid>https://sandrosilva.site/posts/2023-04-23-UnwRappler/</guid>
  <pubDate>Sat, 23 Apr 2022 00:00:00 GMT</pubDate>
  <media:content url="https://sandrosilva.site/posts/2023-04-23-UnwRappler/post-thumbnail.jpeg" medium="image" type="image/jpeg"/>
</item>
<item>
  <title>Unraveling Subreddits</title>
  <link>https://sandrosilva.site/posts/2023-04-20-Reddit/</link>
  <description><![CDATA[ 




<p><img src="https://sandrosilva.site/posts/2023-04-20-Reddit/thumbnail.jpeg" class="img-fluid"></p>
<h1>
Executive Summary
</h1>
<div class="executive-summary">
<p>Original creation and submission for this notebook was last June 2019.</p>
<p><a href="https://www.reddit.com/">Reddit</a> is an American discussion and aggregation website for user-generated content with more than 500 million monthly visitors. We uncovered the underlying categories or “subreddits” by performing representative-based clustering on a sample of Reddit titles. Results reveal that Reddit is a very American-centric platform and that the two main themes are (a) U.S. politics, and (b) seeking help from other Redditors on a wide range of topics including technology, food, and legal matters. For a small number of clusters (<img src="https://latex.codecogs.com/png.latex?n=10">), the high-level categories that emerged include the 2016 U.S. Presidential Elections (Donald Trump, Hillary Clinton, and Bernie Sanders), food, legal concerns, and “New year”-related subreddits. Increasing the number of clusters to <img src="https://latex.codecogs.com/png.latex?n=16"> revealed more specific subreddits such as technical support, recipes, apartment/rental concerns, and reaction compilations.</p>
</div>
<h2 class="anchored">
Acknowledgements
</h2>
<p>This analysis was done together with my Lab partner, George Esleta, and Cohortmates - Gilbert Chua, Nigel Silva and Oonre Advincula-Go.</p>
<h2 class="anchored">
A. Introduction and the Problem Statement
</h2>
<p><a href="https://www.reddit.com/">Reddit</a> is a discussion and content aggregation website. As of June 2019, it is ranked as the #5 most visited website in the United States and #15 worldwide. Registered members, also called “Redditors”, upload user-generated content (UGC) which are either voted up or voted down by other Redditors. Reddit posts are grouped into user-created boards or communities called “subreddits”, with each subreddit having a specific topic such as food, entertainment, and politics.</p>
<h2 class="anchored">
B. Methodology
</h2>
<p>Reddit titles and authors were scraped from the <a href="https://www.reddit.com/">Reddit</a> website and stored in a text file. The file is tab-delimited and has two columns: author and title. Flow of this notebook is as follows:</p>
<ol>
<li>
Pre-requisites: Load Requirement Package
</li><li>
Reading the Reddit data
</li><li>
Initial data cleaning
</li><li>
Exploratory data analysis
</li><li>
Vectorization (bag-of-words representation) using TFIDF Vectorizer
</li><li>
Dimensionality reduction using Latent Semantic Analysis (LSA)
</li><li>
Representative-based clustering using <em>k</em>-means
</li></ol>
<h3 class="anchored">
Pre-requisites: Load Requirement Package
</h3>
<p>Before anything else, let us first load all important modules for this exercise.</p>
<div class="cell" data-execution_count="1">
<details class="code-fold">
<summary>Loading required modules</summary>
<div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># These are standard imports</span></span>
<span id="cb1-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> pandas <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> pd</span>
<span id="cb1-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> matplotlib.pyplot <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> plt</span>
<span id="cb1-4"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> numpy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> np</span>
<span id="cb1-5"></span>
<span id="cb1-6"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> collections <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Counter</span>
<span id="cb1-7"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> IPython.display <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> display_html</span>
<span id="cb1-8"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> wordcloud <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> WordCloud, STOPWORDS</span>
<span id="cb1-9"></span>
<span id="cb1-10"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.preprocessing <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> StandardScaler</span>
<span id="cb1-11"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.feature_extraction.text <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> TfidfVectorizer</span>
<span id="cb1-12"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.feature_extraction <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> stop_words</span>
<span id="cb1-13"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.manifold <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> TSNE</span>
<span id="cb1-14"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.decomposition <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> TruncatedSVD</span>
<span id="cb1-15"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.metrics <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> calinski_harabaz_score, silhouette_score</span>
<span id="cb1-16"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.cluster <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> KMeans</span>
<span id="cb1-17"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.pipeline <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> make_pipeline</span>
<span id="cb1-18"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.preprocessing <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Normalizer</span>
<span id="cb1-19">    <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.metrics <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> confusion_matrix</span>
<span id="cb1-20"></span>
<span id="cb1-21"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> nltk</span>
<span id="cb1-22"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> nltk.tokenize <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> sent_tokenize, word_tokenize</span>
<span id="cb1-23"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> nltk.stem.porter <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> PorterStemmer</span>
<span id="cb1-24"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> nltk.corpus <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> stopwords</span>
<span id="cb1-25"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> nltk <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> FreqDist, RegexpTokenizer</span>
<span id="cb1-26"></span>
<span id="cb1-27"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> IPython.display <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> HTML</span>
<span id="cb1-28"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> scipy.spatial.distance <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> euclidean</span>
<span id="cb1-29"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> scipy.cluster.hierarchy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> linkage, dendrogram</span>
<span id="cb1-30"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> scipy.spatial.distance <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> euclidean, cityblock</span>
<span id="cb1-31"></span>
<span id="cb1-32"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> urllib</span>
<span id="cb1-33"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> requests</span>
<span id="cb1-34"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> pprint</span>
<span id="cb1-35"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> PIL <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Image</span>
<span id="cb1-36"></span>
<span id="cb1-37">pp <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pprint.PrettyPrinter(indent<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>)</span>
<span id="cb1-38"></span>
<span id="cb1-39">HTML(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'''&lt;script&gt;</span></span>
<span id="cb1-40"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">code_show=true; </span></span>
<span id="cb1-41"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">function code_toggle() {</span></span>
<span id="cb1-42"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;"> if (code_show){</span></span>
<span id="cb1-43"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;"> $('div.input').hide();</span></span>
<span id="cb1-44"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;"> } else {</span></span>
<span id="cb1-45"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;"> $('div.input').show();</span></span>
<span id="cb1-46"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;"> }</span></span>
<span id="cb1-47"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;"> code_show = !code_show</span></span>
<span id="cb1-48"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">} </span></span>
<span id="cb1-49"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">$( document ).ready(code_toggle);</span></span>
<span id="cb1-50"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">&lt;/script&gt;</span></span>
<span id="cb1-51"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">&lt;form action="javascript:code_toggle()"&gt;&lt;input type="submit" value="Click here to toggle on/off the raw code."&gt;&lt;/form&gt;'''</span>)</span></code></pre></div>
</details>
</div>
<h3 class="anchored">
Reading the Reddit data
</h3>
<p>The data was stored in the ACCESS lab cloud computer (JOJIE). So for this instance, the sample Reddit text file was read using the <code>read_csv</code> function of <code>pandas</code>. In reading the file, tab (<code>\t</code>) separator was used, and the first line was skipped.</p>
<div class="cell" data-execution_count="2">
<details class="code-fold">
<summary>Load Reddit data</summary>
<div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1">df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.read_csv(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'reddit-dmw-sample.txt'</span>, sep<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\t</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span>, skiprows<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, header<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>, </span>
<span id="cb2-2">                 usecols <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>], </span>
<span id="cb2-3">                 names <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'author'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'title'</span>],)</span></code></pre></div>
</details>
</div>
<p>The resulting dataframe has two columns: <code>author</code> and <code>title</code>. A sample of the Reddit topics are shown below.</p>
<table class="caption-top table">
<caption>Tale 1: Sample Reddits from the Data</caption>
<thead>
<tr class="header">
<th>author</th>
<th>title</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>PrimotechInc</td>
<td>7 Interesting Hidden Features of apple ios9</td>
</tr>
<tr class="even">
<td>xvagabondx</td>
<td>Need an advice on gaming laptop</td>
</tr>
<tr class="odd">
<td>nkindustries</td>
<td>Semi automatic ROPP Capping machine / ROPP Cap…</td>
</tr>
<tr class="even">
<td>Philo1927</td>
<td>Microsoft Plumbs Ocean’s Depths to Test Underw…</td>
</tr>
<tr class="odd">
<td>tuyetnt171</td>
<td>OPPO F1 chính hãng - Fptshop.com.vn</td>
</tr>
</tbody>
</table>
<h3 class="anchored">
Initial data cleaning
</h3>
<p>Once the Reddit data is stored in a dataframe, initial data cleaning was performed by converting all titles to lowercase, and removing leading and trailing spaces. Duplicate titles were also dropped.</p>
<p>The unique titles are then stored in a list:</p>
<div class="cell" data-execution_count="3">
<details class="code-fold">
<summary>Viewing the unique titles</summary>
<div class="sourceCode cell-code" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1">df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'title'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'title'</span>].<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>.lower()</span>
<span id="cb3-2">df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'title'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'title'</span>].<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>.strip()</span>
<span id="cb3-3">docs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>(df.title.unique())</span>
<span id="cb3-4">pp.pprint(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Number of titles: '</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(docs)))</span></code></pre></div>
</details>
</div>
<pre><code>'Number of titles: 5848'</code></pre>
<p>After removing duplicates, there are 5848 unique Reddit titles in the sample dataset.</p>
<p>Sample cleaned topics are shown below. Note that there still are punctuation marks and special characters. These will be removed during vectorization.</p>
<pre><code>[   '7 interesting hidden features of apple ios9',
    'need an advice on gaming laptop',
    'semi automatic ropp capping machine / ropp cap sealing machine',
    'microsoft plumbs ocean’s depths to test underwater data center',
    'oppo f1 chính hãng - fptshop.com.vn',
    'stewed ramps w/ fixings in helvatia, wv',
    '(california) is it a crime when a religious figure/ lecturer has '
    'relations with one of his followers',
    'being accused of public indecency, among other things. this is a '
    'misunderstanding because i had health issues. [kansas, usa]',
    '[us-ca/nv] my parents have been separated for almost 20 years, my mom '
    'found out my dad divorced her without her knowledge a few years ago when '
    'i was about 14--can she claim backdated child support?',
    'skyrim ps4?']</code></pre>
<h3 class="anchored">
Exploratory Data Analysis
</h3>
<p>Shown below are the top 15 most used words in the Reddit sample data. Note that the most common word is “TIL” (Today I Learned), followed by the names of prominent US politicians such as US President Donald Trump, 2016 presidential candidate Hillary Clinton, and Senator Bernie Sanders. All three of them figured prominently in the 2016 U.S. presidential elections, with Trump as the presidential nominee under the Republican party, while Clinton and Sanders as the Democratic party presidential candidates. Initial analysis of the data reveal that the <strong>2016 U.S. Presidential Election is one of the primary themes in the sample Reddit data</strong>.</p>
<div class="cell" data-execution_count="4">
<details class="code-fold">
<summary>Viewing the unique titles</summary>
<div class="sourceCode cell-code" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb6-1">mask <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.array(Image.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">open</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Icon-Reddit1.png'</span>))</span>
<span id="cb6-2">tokenizer <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> RegexpTokenizer(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r'\w{2,}'</span>)</span>
<span id="cb6-3">word_tokens <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tokenizer.tokenize(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">' '</span>.join(docs))</span>
<span id="cb6-4">stopword <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">set</span>(stopwords.words(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'english'</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>(stop_words.ENGLISH_STOP_WORDS))</span>
<span id="cb6-5">docs_filtered <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [w <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> w <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> word_tokens <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> w <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> stopword] </span>
<span id="cb6-6">counts <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> FreqDist(docs_filtered)</span>
<span id="cb6-7">labels, values <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">zip</span>(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>counts.items())</span>
<span id="cb6-8">indSort <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.argsort(values)[::]</span>
<span id="cb6-9">labels <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.array(labels)[indSort[<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span>:]]</span>
<span id="cb6-10">values <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.array(values)[indSort[<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span>:]]</span>
<span id="cb6-11">indexes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.arange(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(labels))</span>
<span id="cb6-12">bar_width <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.35</span></span>
<span id="cb6-13"></span>
<span id="cb6-14">fig, ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, dpi<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, figsize <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>))</span>
<span id="cb6-15">ax[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].barh(indexes, values, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'#ff4500'</span>)</span>
<span id="cb6-16">ax[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Word count'</span>)</span>
<span id="cb6-17">ax[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].set_title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Most common words in the Reddit sample data'</span>)</span>
<span id="cb6-18">ax[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].set_yticks(indexes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> bar_width)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb6-19">ax[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].set_yticklabels(labels)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb6-20"></span>
<span id="cb6-21">wordcloud <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> WordCloud(background_color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"white"</span>, max_words<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, min_font_size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>, mask<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>mask, </span>
<span id="cb6-22">                      prefer_horizontal<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span>, colormap<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'copper'</span>, relative_scaling<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">.5</span>).generate(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">' '</span>.join(docs_filtered))</span>
<span id="cb6-23"></span>
<span id="cb6-24">ax[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>].imshow(wordcloud, interpolation<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'bilinear'</span>)</span>
<span id="cb6-25">ax[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>].axis(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'off'</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div>
</details>
</div>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://sandrosilva.site/posts/2023-04-20-Reddit/image-outputs/1-TILoutput.png" class="img-fluid figure-img" style="width:100.0%"></p>
<figcaption>FIGURE 1: (1) Frequency distribution of the top 15 words in the Reddit sample data, and (b) the corresponding wordcloud. Top words include TIL (Today I learned) and the names of 2016 US Presidential Aspirants (Donald Trump, Bernie Sanders, Hillary Clinton)</figcaption>
</figure>
</div>
<h3 class="anchored">
Vectorization/Bag-of-words representation
</h3>
<p>To uncover the other underlying themes apart from the 2016 U.S. Presidential Election, unsupervised clustering via k-means is performed on the collection of Reddit titles. To do this, the topics need to be <em>vectorized</em> or be converted to their bag-of-words representation. The <code>TfidfVectorizer</code> vectorizer was used to perform the vectorization.</p>
<p>The <code>TFidfVectorizer</code> also performs further cleaning of the data by removing both frequent words and rare words. <em>Stopwords</em>, or words that appear too frequently in the English language (e.g., the, a, an, and, or), were dropped from the corpus. Reddit-specific stopwords, or words that appear in more than 70% of the titles, were also ignored by setting the <code>max_df</code> parameter of <code>TFidfVectorizer</code> to <img src="https://latex.codecogs.com/png.latex?0.7">.</p>
<p>Rare words, or words that appeared in less than 0.1% of the Reddit titles, were also excluded from the corpus. This was implemented by setting the <code>min_df</code> parameter of the <code>TFidfVectorizer</code> to <img src="https://latex.codecogs.com/png.latex?0.001">.</p>
<p><em>n</em>-grams of word lengths between <img src="https://latex.codecogs.com/png.latex?n=1"> and <img src="https://latex.codecogs.com/png.latex?n=3"> were extracted as part of the vocabulary. This range of n-grams was chosen in order to preserve the context of certain phrases such as “Hillary Clinton” (<img src="https://latex.codecogs.com/png.latex?n=2">), “Donald Trump” (<img src="https://latex.codecogs.com/png.latex?n=2">), and “Happy new year” (<img src="https://latex.codecogs.com/png.latex?n=3">)</p>
<div class="cell" data-execution_count="5">
<details class="code-fold">
<summary>Using a TFIDF Vectorizer</summary>
<div class="sourceCode cell-code" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb7-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Creating a TF-IDF Vectorizer</span></span>
<span id="cb7-2">tfidf_vectorizer <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> TfidfVectorizer(token_pattern<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r'(?u)\b\w(?:\w|\-)+\b'</span>, </span>
<span id="cb7-3">                                   stop_words<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>stopword, </span>
<span id="cb7-4">                                   ngram_range<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>), min_df<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.001</span>, max_df<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.7</span>)</span>
<span id="cb7-5"></span>
<span id="cb7-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Creating a Bag-Of-Words</span></span>
<span id="cb7-7">bow <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tfidf_vectorizer.fit_transform(docs)</span>
<span id="cb7-8"></span>
<span id="cb7-9"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Identifying the vocabulary</span></span>
<span id="cb7-10">vocabulary <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tfidf_vectorizer.get_feature_names()</span></code></pre></div>
</details>
</div>
<p>After vectorization, the sample of Reddit titles has <strong>1,655 unique items</strong> in its vocabulary:</p>
<p>Sample vocabulary items are shown below:</p>
<pre><code>[   'years old',
    'yesterday',
    'york',
    'york times',
    'young',
    'youtube',
    'zealand',
    'zelda',
    'ăn',
    'طريقة']</code></pre>
<h3 class="anchored">
Dimensionality reduction using Latent Semantics Analysis (LSA)
</h3>
<p>The resulting bag of words is a 5848 by 1655 matrix:</p>
<pre><code>print("\t Dimensions: ", bow.shape)
Dimensions:  (5848, 1655)</code></pre>
<p>It would be computationally expensive to perform clustering on a dataset this large. To minimize computational power, dimensionality reduction was performed on the vectorized data via <strong>latent semantic analysis (LSA)</strong>. This was implemented using the <code>TruncatedSVD</code> class of <code>sklearn</code>.</p>
<p>As a general rule for LSA, fewer dimensions allow for broader comparisons of the themes contained in a collection of text, while a higher number of dimensions enable more specific comparisons of themes. A dimesionality between 50 and 1,000 are suitable depending on the size and nature of the document collection, with <img src="https://latex.codecogs.com/png.latex?300%20%5Cpm%2050"> the optimum value. Unlike in other dimensionality reduction techniques such as principal component analysis (PCA), checking the proportion of variance retained to determine the optimal dimensionality is <strong>NOT</strong> applicable to LSA.</p>
<p>In this study, <img src="https://latex.codecogs.com/png.latex?n_%7Bcomponents%7D%20=%20100"> is used to extract the underlying themes.</p>
<h4 class="anchored">
Reduced dimensionality
</h4>
<p>For the purposes of this study, we reduced the dimensionality of the Reddit sample data to <strong>100 components</strong>. The transformed Reddit dataset is shown below. Numerous subclusters are revealed, confirming that there are multiple categories or themes in the dataset.</p>
<div class="cell" data-execution_count="6">
<details class="code-fold">
<summary>Using a TruncatedSVD to reduce the number of components to 100 components, then getting bag of words, the using TSNE</summary>
<div class="sourceCode cell-code" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb10-1">tsvd1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> TruncatedSVD(n_components<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>)</span>
<span id="cb10-2">normalizer <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Normalizer(copy<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>)</span>
<span id="cb10-3">lsa1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> make_pipeline(tsvd1, normalizer)</span>
<span id="cb10-4"></span>
<span id="cb10-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Getting the bag of words</span></span>
<span id="cb10-6">bow_tsvd1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> lsa1.fit_transform(bow)</span>
<span id="cb10-7"></span>
<span id="cb10-8"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Applying a TSNE model</span></span>
<span id="cb10-9">tsne <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> TSNE(n_components<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, random_state<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1704</span>, n_iter<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1500</span>, n_iter_without_progress<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">500</span>, perplexity<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span>, learning_rate<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)</span>
<span id="cb10-10">bow_tsne1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tsne.fit_transform(bow_tsvd1)</span></code></pre></div>
</details>
</div>
<p>Now, let’s make a graph on the TSNE model’s bag of words. Below you’ll see it flatted TSNE of the bag of words.</p>
<div class="cell" data-execution_count="7">
<details class="code-fold">
<summary>Creating the plot of the TSNE.</summary>
<div class="sourceCode cell-code" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb11-1">fig, ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(dpi <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>)</span>
<span id="cb11-2">ax.scatter(bow_tsne1[:,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], bow_tsne1[:,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], alpha<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>, marker<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'o'</span>, s<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>, c<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#ff4500"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div>
</details>
</div>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://sandrosilva.site/posts/2023-04-20-Reddit/image-outputs/2-TSNE.png" class="img-fluid figure-img" style="width:100.0%"></p>
<figcaption>FIGURE 2: Reddit topics visualized in two dimensions using TSNE.</figcaption>
</figure>
</div>
<h3 class="anchored">
Representative-based clustering using <em>k</em>-means
</h3>
<h4 class="anchored">
<ol type="1">
<li>Selecting the optimal number of clusters <code>k</code>
</li></ol></h4>

<p>To determine the optimal number of clusters, we perform k-means clustering for different values of the cluster count <img src="https://latex.codecogs.com/png.latex?k"> from <img src="https://latex.codecogs.com/png.latex?k=2"> to <img src="https://latex.codecogs.com/png.latex?k=20">. This range of values was chosen to keep the clustering parsimonious.</p>
<p>Several internal validation measures were computed for each value of <img src="https://latex.codecogs.com/png.latex?k">. The internal validation measures that were used are (a) intracluster to intercluster distance ratio, (b) Calinski-Harabasz score (c) Silhouette coefficient, and (d) sum of square distances to centroids coefficient.</p>
<p>The optimal value of <img src="https://latex.codecogs.com/png.latex?k"> is then chosen based on the following criteria:</p>
<ol type="1">
<li>Sum-of-square distance to centroid is minimized</li>
<li>Calinski-Harabasz index is maximized</li>
<li>Intracluster to intercluster distance ratio is minimized</li>
<li>Silhouette coefficient is maximized</li>
</ol>
<p>Plotted below are the values of the internal validation criteria for values of <img src="https://latex.codecogs.com/png.latex?k"> between 2 and 20. <strong><img src="https://latex.codecogs.com/png.latex?k%20=%2010"></strong> and <strong><img src="https://latex.codecogs.com/png.latex?k%20=%2016"></strong> are good candidates for the number of clusters because for these values, the intracluster to intercluster distance ratio has a local minima, and the silhouette coefficient has a relatively high value.</p>
<div class="cell" data-execution_count="8">
<details class="code-fold">
<summary>Function for computing intracluster to intercluster distance ratio</summary>
<div class="sourceCode cell-code" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb12-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> intra_to_inter(X, y, dist, r):</span>
<span id="cb12-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb12-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Compute intracluster to intercluster distance ratio</span></span>
<span id="cb12-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    </span></span>
<span id="cb12-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Parameters</span></span>
<span id="cb12-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    ----------</span></span>
<span id="cb12-7"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    X : array</span></span>
<span id="cb12-8"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Design matrix with each row corresponding to a point</span></span>
<span id="cb12-9"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    y : array</span></span>
<span id="cb12-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Class label of each point</span></span>
<span id="cb12-11"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    dist : callable</span></span>
<span id="cb12-12"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Distance between two points. It should accept two arrays, each </span></span>
<span id="cb12-13"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        corresponding to the coordinates of each point</span></span>
<span id="cb12-14"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    r : integer</span></span>
<span id="cb12-15"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Number of pairs to sample</span></span>
<span id="cb12-16"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        </span></span>
<span id="cb12-17"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Returns</span></span>
<span id="cb12-18"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    -------</span></span>
<span id="cb12-19"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    ratio : float</span></span>
<span id="cb12-20"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Intracluster to intercluster distance ratio</span></span>
<span id="cb12-21"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    """</span></span>
<span id="cb12-22">    P <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb12-23">    Q <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb12-24">    p<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb12-25">    q<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb12-26">    np.random.seed(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">11</span>)</span>
<span id="cb12-27">    d <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.random.choice(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>,<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(X)), (r,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>), replace<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb12-28">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> a <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>,<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(d)):</span>
<span id="cb12-29">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span>  d[a][<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> d[a][<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]:</span>
<span id="cb12-30">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">continue</span></span>
<span id="cb12-31">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">elif</span> y[d[a][<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> y[d[a][<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]]:</span>
<span id="cb12-32">            P.append(dist(X[d[a][<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]],X[d[a][<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]]))</span>
<span id="cb12-33">            p<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb12-34">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span>:</span>
<span id="cb12-35">            Q.append(dist(X[d[a][<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]],X[d[a][<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]]))</span>
<span id="cb12-36">            q<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb12-37">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(P) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">or</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(Q) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>:</span>
<span id="cb12-38">        ratio <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb12-39">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span>:</span>
<span id="cb12-40">        ratio <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>(P)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(P))<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>(np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>(Q)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(Q))</span>
<span id="cb12-41">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> ratio</span></code></pre></div>
</details>
</div>
<div class="cell" data-execution_count="9">
<details class="code-fold">
<summary>Function to create the clusters, cluster labels (and scores of internal validation values)</summary>
<div class="sourceCode cell-code" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb13-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> cluster_range(X, clusterer, k_start<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, k_stop<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16</span>, actual<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>):</span>
<span id="cb13-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb13-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Accepts the design matrix, the clustering object, the initial and final </span></span>
<span id="cb13-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    values to step through, and, optionally, actual labels. It should return a</span></span>
<span id="cb13-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    dictionary of the cluster labels, internal validation values and, if</span></span>
<span id="cb13-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    actual labels is given, external validation values, for every k.</span></span>
<span id="cb13-7"></span>
<span id="cb13-8"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Parameters</span></span>
<span id="cb13-9"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    ----------</span></span>
<span id="cb13-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    X : design matrix</span></span>
<span id="cb13-11"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    clusterer : clustering object</span></span>
<span id="cb13-12"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    k_start : initial value of clusters</span></span>
<span id="cb13-13"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    k_stop : final value of clusters</span></span>
<span id="cb13-14"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    actual : actual labels</span></span>
<span id="cb13-15"></span>
<span id="cb13-16"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Returns</span></span>
<span id="cb13-17"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    -------</span></span>
<span id="cb13-18"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    dictionary</span></span>
<span id="cb13-19"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    """</span></span>
<span id="cb13-20"></span>
<span id="cb13-21"></span>
<span id="cb13-22">    validation_dict <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"chs"</span>: [],</span>
<span id="cb13-23">                       <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"iidrs"</span>: [],</span>
<span id="cb13-24">                       <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"inertias"</span>: [],</span>
<span id="cb13-25">                       <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"scs"</span>: [],</span>
<span id="cb13-26">                       <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ys"</span>: []</span>
<span id="cb13-27">                       }</span>
<span id="cb13-28">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> actual <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>:</span>
<span id="cb13-29">        validation_dict <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"chs"</span>: [],</span>
<span id="cb13-30">                           <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"iidrs"</span>: [],</span>
<span id="cb13-31">                           <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"inertias"</span>: [],</span>
<span id="cb13-32">                           <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"scs"</span>: [],</span>
<span id="cb13-33">                           <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ys"</span>: [],</span>
<span id="cb13-34">                           <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"amis"</span>: [],</span>
<span id="cb13-35">                           <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ars"</span>: [],</span>
<span id="cb13-36">                           <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ps"</span>: []</span>
<span id="cb13-37">                           }</span>
<span id="cb13-38">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> k <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(k_start, k_stop<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>):</span>
<span id="cb13-39">        clusterer.n_clusters <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> k</span>
<span id="cb13-40">        np.random.seed(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">11</span>)</span>
<span id="cb13-41">        y_predict <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> clusterer.fit_predict(X)</span>
<span id="cb13-42">        validation_dict[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"chs"</span>].append(calinski_harabaz_score(X, y_predict))</span>
<span id="cb13-43">        validation_dict[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"iidrs"</span>].append(</span>
<span id="cb13-44">            intra_to_inter(X, y_predict, euclidean, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span>))</span>
<span id="cb13-45">        validation_dict[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"inertias"</span>].append(clusterer.inertia_)</span>
<span id="cb13-46">        validation_dict[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"scs"</span>].append(silhouette_score(X, y_predict))</span>
<span id="cb13-47">        validation_dict[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ys"</span>].append(y_predict)</span>
<span id="cb13-48">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> actual <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>:</span>
<span id="cb13-49">            validation_dict[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"amis"</span>].append(</span>
<span id="cb13-50">                adjusted_mutual_info_score(actual, y_predict))</span>
<span id="cb13-51">            validation_dict[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ars"</span>].append(</span>
<span id="cb13-52">                adjusted_rand_score(actual, y_predict))</span>
<span id="cb13-53">            validation_dict[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ps"</span>].append(purity(actual, y_predict))</span>
<span id="cb13-54">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> validation_dict</span></code></pre></div>
</details>
</div>
<pre><code>kmeans_dict1 = cluster_range(
    # bag of words results
    bow_tsvd1, 
    # using a k-means clusterer
    KMeans(random_state=1704, n_init=20, max_iter=1000, tol=1e-6), 
    2,
    20)</code></pre>
<div class="cell" data-execution_count="10">
<details class="code-fold">
<summary>Function to plot internal validation values</summary>
<div class="sourceCode cell-code" id="cb15" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb15-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> plot_internal(inertias, chs, iidrs, scs):</span>
<span id="cb15-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb15-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Plot internal validation values</span></span>
<span id="cb15-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    """</span></span>
<span id="cb15-5">    fig, ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>,dpi<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))</span>
<span id="cb15-6">    ks <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.arange(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(inertias)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb15-7">    ax[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].plot(ks, inertias, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'-o'</span>, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'SSE'</span>)</span>
<span id="cb15-8">    ax[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>].plot(ks, chs, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'-ro'</span>, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'CH'</span>)</span>
<span id="cb15-9">    ax[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'$k$'</span>)</span>
<span id="cb15-10">    ax[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>].set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'$k$'</span>)</span>
<span id="cb15-11">    ax[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].set_title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'SSE'</span>)</span>
<span id="cb15-12">    ax[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>].set_title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'CH'</span>)</span>
<span id="cb15-13">    ax[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>].plot(ks, iidrs, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'-go'</span>, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Inter-intra'</span>)</span>
<span id="cb15-14">    ax[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>].plot(ks, scs, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'-ko'</span>, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Silhouette coefficient'</span>)</span>
<span id="cb15-15">    ax[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>].set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'$k$'</span>)</span>
<span id="cb15-16">    ax[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>].set_title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Inter-intra'</span>)</span>
<span id="cb15-17">    ax[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>].set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'$k$'</span>)</span>
<span id="cb15-18">    ax[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>].set_title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Silhouette coefficient'</span>)</span>
<span id="cb15-19">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> ax</span></code></pre></div>
</details>
</div>
<p>Let’s plot the interal validation values</p>
<pre><code>plot_internal(kmeans_dict1['inertias'], kmeans_dict1['chs'], 
    kmeans_dict1['iidrs'], kmeans_dict1['scs']);</code></pre>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://sandrosilva.site/posts/2023-04-20-Reddit/image-outputs/3-internal-validation.png" class="img-fluid figure-img" style="width:100.0%"></p>
<figcaption>FIGURE 3: Plots of the various internal validation measures for <img src="https://latex.codecogs.com/png.latex?k=2"> to <img src="https://latex.codecogs.com/png.latex?k=20">. <img src="https://latex.codecogs.com/png.latex?k=10"> and <img src="https://latex.codecogs.com/png.latex?k=16"> were chosen because of the low intercluster-intracluster ration and the high silhouette coefficients for those values.</figcaption>
</figure>
</div>
<h4 class="anchored">
<ol start="2" type="1">
<li><code>k = 10</code>
</li></ol></h4>

<div class="cell" data-execution_count="11">
<details class="code-fold">
<summary>Code of setting k-means k=10</summary>
<div class="sourceCode cell-code" id="cb17" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb17-1">n1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span></span>
<span id="cb17-2">kmeans1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> KMeans(n_clusters<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>n1, random_state<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1704</span>, n_init<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>, max_iter<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span>, tol<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-6</span>)</span>
<span id="cb17-3">y_predict_kmeans1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> kmeans1.fit_predict(bow_tsvd1)</span></code></pre></div>
</details>
</div>
<p><img src="https://latex.codecogs.com/png.latex?k">-means clustering was performed on the Reddit sample titles using 10 clusters. The resulting clusters and the cluster size distribution are shown below. The clusters are relatives balanced in terms of cluster size, with the exception of one cluster (cluster 5) which contains more than 2500 Reddit titles.</p>
<div class="cell" data-execution_count="12">
<details class="code-fold">
<summary>Creating the plot and clusters</summary>
<div class="sourceCode cell-code" id="cb18" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb18-1">fig, ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, dpi <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>))</span>
<span id="cb18-2">ax[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].scatter(bow_tsne1[:,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], bow_tsne1[:,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], c<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>y_predict_kmeans1, alpha<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>, marker<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'o'</span>, s<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb18-3"></span>
<span id="cb18-4">counts <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Counter(y_predict_kmeans1)</span>
<span id="cb18-5">labels, values <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">zip</span>(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>counts.items())</span>
<span id="cb18-6">indSort <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.argsort(values)[::]</span>
<span id="cb18-7">labels <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.array(labels)[indSort]</span>
<span id="cb18-8">values <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.array(values)[indSort]</span>
<span id="cb18-9">indexes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.arange(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(labels))</span>
<span id="cb18-10">bar_width <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.35</span></span>
<span id="cb18-11">ax[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>].barh(indexes, values, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'#ff4500'</span>)</span>
<span id="cb18-12">ax[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>].set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Cluster size'</span>)</span>
<span id="cb18-13">ax[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>].set_ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Cluster labels'</span>)</span>
<span id="cb18-14">ax[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>].set_yticks(indexes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> bar_width)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb18-15">ax[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>].set_yticklabels(labels)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div>
</details>
</div>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://sandrosilva.site/posts/2023-04-20-Reddit/image-outputs/4-clusters10.png" class="img-fluid figure-img" style="width:100.0%"></p>
<figcaption>FIGURE 4: Resulting clustering for <img src="https://latex.codecogs.com/png.latex?n=10">, and the cluster size distribution per cluster. The clusters are relatives balanced in terms of cluster size, with the exception of one cluster (cluster 5) which contains more than 2500 Reddit titles.</figcaption>
</figure>
</div>
<p>To understand the theme or category of each cluster, the <strong>top words</strong> or the most frequent words for each cluster was obtained. Shown below are the top 10 most occurring words per cluster, and the corresponding wordclouds.</p>
<div class="cell" data-execution_count="13">
<details class="code-fold">
<summary>Code to see the top 10 most occuring words per cluster</summary>
<div class="sourceCode cell-code" id="cb19" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb19-1">features <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tfidf_vectorizer.get_feature_names()</span>
<span id="cb19-2">weights <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.dot(kmeans1.cluster_centers_, tsvd1.components_)</span>
<span id="cb19-3">weights <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">abs</span>(weights)</span>
<span id="cb19-4"></span>
<span id="cb19-5">fig, ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, dpi<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>))</span>
<span id="cb19-6">plt.subplots_adjust(wspace<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.1</span>, hspace<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">.8</span>)</span>
<span id="cb19-7"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(kmeans1.n_clusters):</span>
<span id="cb19-8">    indices <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.argsort(weights[i])[<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>:][::]</span>
<span id="cb19-9">    top_words <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [features[index] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> index <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> indices]</span>
<span id="cb19-10">    values <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> weights[i,indices]</span>
<span id="cb19-11">    indices <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.arange(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(top_words))</span>
<span id="cb19-12">    bar_width <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.35</span></span>
<span id="cb19-13">    ax[i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">//</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>][i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>].barh(indices, values, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'#ff4500'</span>)</span>
<span id="cb19-14">    ax[i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">//</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>][i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>].set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Weight'</span>)</span>
<span id="cb19-15">    ax[i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">//</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>][i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>].set_ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Top words'</span>)</span>
<span id="cb19-16">    ax[i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">//</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>][i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>].set_yticks(indexes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> bar_width)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb19-17">    ax[i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">//</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>][i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>].set_yticklabels(top_words)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb19-18">    ax[i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">//</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>][i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>].set_title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Cluster '</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>(i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))</span></code></pre></div>
</details>
</div>
<div class="page-columns page-full">
<div class="quarto-figure quarto-figure-center page-columns page-full">
<figure class="figure page-columns page-full">
<p class="page-columns page-full"><img src="https://sandrosilva.site/posts/2023-04-20-Reddit/image-outputs/5-topwords.png" class="img-fluid figure-img column-page" style="width:100.0%"></p>
<figcaption>FIGURE 5: Top 10 most occuring words per cluster (<img src="https://latex.codecogs.com/png.latex?k=10">)</figcaption>
</figure>
</div>
</div>
<div class="cell" data-execution_count="14">
<details class="code-fold">
<summary>Code of placing a Reddit mask wordcloud</summary>
<div class="sourceCode cell-code" id="cb20" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb20-1">mask <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.array(Image.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">open</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Icon-Reddit1.png'</span>))</span>
<span id="cb20-2">topic <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'TIL'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Apartment/Rent'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'New Year'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Iowa Caucus'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Food'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Technology'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Donald Trump'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Bernie Sanders'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Advise-seeking'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Hillary Clinton'</span>]</span>
<span id="cb20-3">fig, ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>,dpi<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>))</span>
<span id="cb20-4">plt.subplots_adjust(wspace<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">.2</span>, hspace<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb20-5"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> ctr <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(kmeans1.n_clusters):</span>
<span id="cb20-6">    indices <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [i <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i, x <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">enumerate</span>(y_predict_kmeans1) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> ctr]</span>
<span id="cb20-7">    wordcloud <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> WordCloud(background_color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"white"</span>, max_words<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, min_font_size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>, mask<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>mask, </span>
<span id="cb20-8">                          prefer_horizontal<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.7</span>, colormap<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'copper'</span>).generate(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">' '</span>.join([docs[index] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> index <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> indices]))</span>
<span id="cb20-9">    ax[ctr<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">//</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>][ctr<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>].imshow(wordcloud, interpolation<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'bilinear'</span>)</span>
<span id="cb20-10">    ax[ctr<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">//</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>][ctr<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>].axis(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'off'</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb20-11">    ax[ctr<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">//</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>][ctr<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>].set_title(topic[ctr])<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div>
</details>
</div>
<div class="page-columns page-full">
<div class="quarto-figure quarto-figure-center page-columns page-full">
<figure class="figure page-columns page-full">
<p class="page-columns page-full"><img src="https://sandrosilva.site/posts/2023-04-20-Reddit/image-outputs/6-wordclouds.png" class="img-fluid figure-img column-page" style="width:100.0%"></p>
<figcaption>FIGURE 6: Wordcloud per cluster (<img src="https://latex.codecogs.com/png.latex?k=10">)</figcaption>
</figure>
</div>
</div>
<p>Using <img src="https://latex.codecogs.com/png.latex?k%20=%2010">, the general categories listed below were revealed. Sample Reddit titles for each category are also shown.</p>
<p>The clustering results show that <strong>Reddit is a very American-centric platform</strong>. Four of the ten topics are related to the 2016 U.S. Presidential Election, specifically on the Republican nominee Donald Trump, Democrat candidates Hillary Clinton and Bernie Sanders, and the Iowa caucuses, a biennial electoral event that marks the first major contest of the United States presidential primary season.</p>
<p>Also, two of the topics are related to “advise”. This reveals that apart from discussing politics, Reddit users go to Reddit to ask help or seek advise from other Redditors, whethere it be technology-related or legal.</p>
<p>Cluster topics:</p>
<h5 class="anchored">
TIL (Today I Learned)
</h5>
<pre><code>[   'til maternal kisses are not effective in alleviating minor childhood '
    'injuries (boo-boos): a randomized, controlled and blinded study.',
    'til goldman sachs did a study in 2009 that estimated a unified korea '
    'could boast an economy larger than france, germany, and even japan by '
    '2050 with a gdp of $6 trillion.',
    "til the justice league's martian manhunter was once addicted to cookies "
    'and hulked out when deprived of them.']</code></pre>
<h5 class="anchored">
Apartment/rent-related topics
</h5>
<pre><code>[   'business telephone service',
    'illegal towing from apartment complex md.',
    'can a landlord place a security camera in a communal space']</code></pre>
<h5 class="anchored">
“Happy new year”
</h5>
<pre><code>[   'new poll shows how far hillary has fallen with democrats',
    'new zealand - new tenants wanting to take over internet account, isp is '
    'refusing.',
    'watch "best of maskedman - 2015 new year special." on youtube',
    'happy new year reddit! :) i quit retirement, spent $250k in savings and '
    '51 months (15,000 hours) to develop the new internet, owned by the '
    'people, powered by humanity - the first company in history equally owned '
    'by everybody alive! we are uniting the whole world into one!',
    'til new yorkers at nye time square wear diapers and pads for lack of '
    'porta potties']</code></pre>
<h5 class="anchored">
“Iowa caucuses”
</h5>
<pre><code>[   'the gop’s condemnation of ‘sanctuary cities’ is surprisingly awkward in '
    'iowa',
    "jesse watters questions sanders' young supporters in iowa",
    '2016 iowa democratic caucus locations - get out there and caucus!!']</code></pre>
<h5 class="anchored">
Food
</h5>
<pre><code>[   'i have access to tons and tons of green onion tops,what can i make?',
    'mexican chopped salad',
    's&amp;amp;m restaurant in beijing caters to millennial’s basic instincts by '
    'serving food &amp;amp; sex']</code></pre>
<h5 class="anchored">
Donald Trump
</h5>
<pre><code>[   "donald trump says he'll attract democrats; polls say that's unlikely",
    'inside the clintons’ plan to defeat donald trump',
    'hecklers disrupt trump rally, photographer shoved to the ground']</code></pre>
<h5 class="anchored">
Bernie Sanders
</h5>
<pre><code>[   '“it appears that mr. trump is getting nervous that working families are '
    'catching on that his policies represent the interests of the billionaire '
    'class against almost everyone else." - bernie sanders',
    'killer mike: bernie sanders is the only candidate for black voters',
    'bernie sanders: the most fascist candidate of all.']</code></pre>
<h5 class="anchored">
Food
</h5>
<pre><code>[   'i have access to tons and tons of green onion tops,what can i make?',
    'mexican chopped salad',
    's&amp;amp;m restaurant in beijing caters to millennial’s basic instincts by '
    'serving food &amp;amp; sex']</code></pre>
<h5 class="anchored">
Advise-seeking
</h5>
<pre><code>[   'need an advice on gaming laptop',
    'charged with dui 2 years and 4 months after i was involved in a single '
    'car accident.',
    "i'd like to buy the rights of a post on reddit to recreate in another "
    'medium. how do i create a legal contract for this between strangers '
    'online?',
    'significant online food ordering trend',
    'md - need advice evicting a suicidal/alcoholic tenant/roommate.']</code></pre>
<h5 class="anchored">
Hillary Clinton
</h5>
<pre><code>[   'semi automatic ropp capping machine / ropp cap sealing machine',
    'state: hundreds of old clinton emails newly classified',
    'georgia poll: clinton 70, sanders 23']</code></pre>
<h4 class="anchored">
<ol start="3" type="1">
<li><code>k = 16</code>
</li></ol></h4>

<p>Let’s try with a <code>k=16</code></p>
<div class="cell" data-execution_count="15">
<details class="code-fold">
<summary>Setting k-means to k=16</summary>
<div class="sourceCode cell-code" id="cb31" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb31-1">n2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16</span></span>
<span id="cb31-2"></span>
<span id="cb31-3">kmeans2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> KMeans(n_clusters<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>n2, random_state<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1704</span>)</span>
<span id="cb31-4">y_predict_kmeans2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> kmeans2.fit_predict(bow_tsvd1)</span>
<span id="cb31-5"></span>
<span id="cb31-6">fig, ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, dpi <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>))</span>
<span id="cb31-7">ax[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].scatter(bow_tsne1[:,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], bow_tsne1[:,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], c<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>y_predict_kmeans2, alpha<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>, marker<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'o'</span>, s<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb31-8"></span>
<span id="cb31-9">counts <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Counter(y_predict_kmeans2)</span>
<span id="cb31-10">labels, values <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">zip</span>(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>counts.items())</span>
<span id="cb31-11">indSort <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.argsort(values)[::]</span>
<span id="cb31-12">labels <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.array(labels)[indSort]</span>
<span id="cb31-13">values <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.array(values)[indSort]</span>
<span id="cb31-14">indexes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.arange(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(labels))</span>
<span id="cb31-15">bar_width <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.35</span></span>
<span id="cb31-16">ax[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>].barh(indexes, values, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'#ff4500'</span>)</span>
<span id="cb31-17">ax[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>].set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Cluster size'</span>)</span>
<span id="cb31-18">ax[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>].set_ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Cluster label'</span>)</span>
<span id="cb31-19">ax[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>].set_yticks(indexes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> bar_width)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb31-20">ax[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>].set_yticklabels(labels)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div>
</details>
</div>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://sandrosilva.site/posts/2023-04-20-Reddit/image-outputs/7-k16.png" class="img-fluid figure-img" style="width:100.0%"></p>
<figcaption>FIGURE 7. Clustering and Cluster size distribution for <img src="https://latex.codecogs.com/png.latex?k=16">)</figcaption>
</figure>
</div>
<p>To understand the theme or category of each cluster, the <strong>top words</strong> or the most frequent words for each cluster was obtained. Shown below are the top 10 most occurring words per cluster, and the corresponding wordclouds.</p>
<div class="cell" data-execution_count="16">
<details class="code-fold">
<summary>Code to see the top words per 16 clusters</summary>
<div class="sourceCode cell-code" id="cb32" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb32-1">features <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tfidf_vectorizer.get_feature_names()</span>
<span id="cb32-2">weights <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.dot(kmeans2.cluster_centers_, tsvd1.components_)</span>
<span id="cb32-3">weights <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">abs</span>(weights)</span>
<span id="cb32-4">fig, ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>, dpi<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>))</span>
<span id="cb32-5">plt.subplots_adjust(wspace<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.1</span>, hspace<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">.8</span>)</span>
<span id="cb32-6"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(kmeans2.n_clusters):</span>
<span id="cb32-7">    indices <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.argsort(weights[i])[<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>:][::]</span>
<span id="cb32-8">    top_words <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [features[index] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> index <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> indices]</span>
<span id="cb32-9">    values <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> weights[i,indices]</span>
<span id="cb32-10">    indices <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.arange(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(top_words))</span>
<span id="cb32-11">    bar_width <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.35</span></span>
<span id="cb32-12">    ax[i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">//</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>][i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>].barh(top_words, values, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'#ff4500'</span>)</span>
<span id="cb32-13">    ax[i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">//</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>][i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>].set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Weight'</span>)</span>
<span id="cb32-14">    ax[i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">//</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>][i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>].set_ylabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Top words'</span>)</span>
<span id="cb32-15"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">#    ax[i//4][i%4].set_yticks(indexes + bar_width);</span></span>
<span id="cb32-16">    ax[i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">//</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>][i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>].set_yticklabels(top_words)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb32-17">    ax[i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">//</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>][i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>].set_title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Cluster '</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>(i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))</span></code></pre></div>
</details>
</div>
<div class="page-columns page-full">
<div class="quarto-figure quarto-figure-center page-columns page-full">
<figure class="figure page-columns page-full">
<p class="page-columns page-full"><img src="https://sandrosilva.site/posts/2023-04-20-Reddit/image-outputs/8-k16-words.png" class="img-fluid figure-img column-page" style="width:100.0%"></p>
<figcaption>FIGURE 8. Top 10 most frequest words per cluster (<img src="https://latex.codecogs.com/png.latex?k=16">)</figcaption>
</figure>
</div>
</div>
<div class="cell" data-execution_count="17">
<details class="code-fold">
<summary>Code of placing a Reddit mask wordcloud for k=16</summary>
<div class="sourceCode cell-code" id="cb33" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb33-1">topics1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Tech support'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Clinton'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Trump'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Cluster 4'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Recipes'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'TIL'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Aparment/Rent'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Technology'</span></span>
<span id="cb33-2">           , <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Sanders'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Food'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Cluster 11'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Car-related queries'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'New Year'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Reaction Compilation'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Legal concerns'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Cluster 15'</span>]</span>
<span id="cb33-3"></span>
<span id="cb33-4">fig, ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>,dpi<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>))</span>
<span id="cb33-5">plt.subplots_adjust(wspace<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.2</span>, hspace<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb33-6"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> ctr <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(kmeans2.n_clusters):</span>
<span id="cb33-7">    indices <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [i <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i, x <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">enumerate</span>(y_predict_kmeans2) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> ctr]</span>
<span id="cb33-8">    wordcloud <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> WordCloud(background_color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"white"</span>, max_words<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, min_font_size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>, mask<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>mask, </span>
<span id="cb33-9">                          prefer_horizontal<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span>, colormap<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'copper'</span>).generate(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">' '</span>.join([docs[index] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> index <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> indices]))</span>
<span id="cb33-10"></span>
<span id="cb33-11">    ax[ctr<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">//</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>][ctr<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>].imshow(wordcloud, interpolation<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'bilinear'</span>)</span>
<span id="cb33-12">    ax[ctr<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">//</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>][ctr<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>].axis(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'off'</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb33-13">    ax[ctr<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">//</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>][ctr<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>].set_title(topics1[ctr])<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div>
</details>
</div>
<div class="page-columns page-full">
<div class="quarto-figure quarto-figure-center page-columns page-full">
<figure class="figure page-columns page-full">
<p class="page-columns page-full"><img src="https://sandrosilva.site/posts/2023-04-20-Reddit/image-outputs/9-k16-wordclouds.png" class="img-fluid figure-img column-page" style="width:100.0%"></p>
<figcaption>FIGURE 9. Wordcloud per cluster (<img src="https://latex.codecogs.com/png.latex?k=16">)</figcaption>
</figure>
</div>
</div>
<p>As the number of clusters was increased, the more specific themes emerge. The following themes emerged:</p>
<h5 class="anchored">
Technical Support
</h5>
<pre><code>[   'smoothly solution for the canon printer 1-877-776-4348',
    'follow these step and escan antivirus easily',
    'norton antivirus technical support phone number',
    'itech logik | uk microsoft help desk phone number',
    'til tupak shakur became the first artist to have an album at number one '
    'on the billboard 200 while serving a prison sentence.']</code></pre>
<h5 class="anchored">
Hillary Clinton Emails
</h5>
<pre><code>[   'semi automatic ropp capping machine / ropp cap sealing machine',
    'state: hundreds of old clinton emails newly classified',
    'georgia poll: clinton 70, sanders 23',
    'nsa whistleblower: clinton email server was ‘open to being hacked by '
    'anybody in the world’',
    "hillary clinton's new hampshire boosters out in full force"]</code></pre>
<h5 class="anchored">
Donald Trump
</h5>
<pre><code>[   "donald trump says he'll attract democrats; polls say that's unlikely",
    'inside the clintons’ plan to defeat donald trump',
    'hecklers disrupt trump rally, photographer shoved to the ground',
    'a photographer covering a donald trump rally in virginia said a secret '
    'service agent choked him and slammed him to the ground monday as he tried '
    'to leave a media pen at the event where a protest erupted.',
    'til that donald trump sold steaks at the sharper image']</code></pre>
<h5 class="anchored">
Recipes
</h5>
<pre><code>[   'i have access to tons and tons of green onion tops,what can i make?',
    'mexican chopped salad',
    'dublin, ireland has gone mad for spice bags from takeaways, i tried my '
    'hand at my own. potato, shredded chicken, peppers and onions, cooked in '
    'garlic, chillies and spices. apologies for photo quality!',
    'tips for starting a healthy lifestyle!',
    "arroz carreteiro - brazilian wagoners' rice gourmetcentric"]</code></pre>
<h5 class="anchored">
TIL (Today I learned) topics
</h5>
<pre><code>[   'til maternal kisses are not effective in alleviating minor childhood '
    'injuries (boo-boos): a randomized, controlled and blinded study.',
    'til goldman sachs did a study in 2009 that estimated a unified korea '
    'could boast an economy larger than france, germany, and even japan by '
    '2050 with a gdp of $6 trillion.',
    "til the justice league's martian manhunter was once addicted to cookies "
    'and hulked out when deprived of them.',
    'til that the top 25 hedge fund managers in the us earn more than all us '
    'kindergarten teachers (and pay a smaller tax rate)',
    'til leonard howell ("the first rasta") preached that ras tafari, the '
    'emperor of ethiopia in 1933, was the messiah, that black people were the '
    'chosen of god and that they would soon be restored to their native '
    'country of ethiopia.']</code></pre>
<h5 class="anchored">
Apartment and Rent Concerns
</h5>
<pre><code>[   'my dad died yesterday and my mom is now being evicted because she is not '
    'on the lease, what can she do?',
    'landlord charged my girlfriend a damage fee of $5,000 for a broken door',
    'is refusing to take a breathalyzer test an admission of guilt?',
    'does an apartment with living/housing code violations against the city '
    'equal a nullified lease?',
    'had verbal agreement with room mate for payment of back monies to be '
    'paid, to be formalized in writing, questions, etc.']</code></pre>
<h5 class="anchored">
Bernie Sanders
</h5>
<pre><code>[   '“it appears that mr. trump is getting nervous that working families are '
    'catching on that his policies represent the interests of the billionaire '
    'class against almost everyone else." - bernie sanders',
    'killer mike: bernie sanders is the only candidate for black voters',
    'hillary clinton has already forgotten about bernie sanders | vice | '
    'united states',
    'bernie sanders ‘revolution’ threatens hillary clinton in iowa.',
    "jesse watters questions sanders' young supporters in iowa"]</code></pre>
<h5 class="anchored">
Food
</h5>
<pre><code>[   'semi automatic ropp capping machine / ropp cap sealing machine',
    'state: hundreds of old clinton emails newly classified',
    'georgia poll: clinton 70, sanders 23']</code></pre>
<h5 class="anchored">
Bernie Sanders
</h5>
<pre><code>[   '“it appears that mr. trump is getting nervous that working families are '
    'catching on that his policies represent the interests of the billionaire '
    'class against almost everyone else." - bernie sanders',
    'killer mike: bernie sanders is the only candidate for black voters',
    'bernie sanders: the most fascist candidate of all.']</code></pre>
<h5 class="anchored">
Food
</h5>
<pre><code>[   'significant online food ordering trend',
    's&amp;amp;m restaurant in beijing caters to millennial’s basic instincts by '
    'serving food &amp;amp; sex',
    'food near me – jasper arkansas',
    'as i am very polish and grew up eating a lot of good food, i decided to '
    'cook it for myself tonight.',
    'food in thailand - november 2015']</code></pre>
<h5 class="anchored">
Car-related topics
</h5>
<pre><code>[   'charged with dui 2 years and 4 months after i was involved in a single '
    'car accident.',
    "[md] car impounded after repair order wasn't received in september, "
    'options?',
    'tesla unveils the model 3, its lowest-priced car',
    'lincolnshire county council hit by £1m malware demand',
    'florida adverse possession law question and others regarding married but '
    'separate couples.']</code></pre>
<h5 class="anchored">
“Happy new year” reddits
</h5>
<pre><code>[   'watch "best of maskedman - 2015 new year special." on youtube',
    'happy new year reddit! :) i quit retirement, spent $250k in savings and '
    '51 months (15,000 hours) to develop the new internet, owned by the '
    'people, powered by humanity - the first company in history equally owned '
    'by everybody alive! we are uniting the whole world into one!',
    'mobile game of the year 2015: horizon chase',
    'til that j. r. r. tolkien hand wrote and illustrated letters to his '
    'children from father christmas every year for 20 years.',
    '[bellingham, wa] wife looking at buying property in bella coola, bc; '
    'legal implications of living half the year here in bellingham and half '
    'the year in bella coola']</code></pre>
<h5 class="anchored">
Vines reaction compilation
</h5>
<pre><code>[   'happy 2016 and may all your games be mostly bug free',
    'eight issues that could shape politics in 2016',
    '2016 iowa democratic caucus locations - get out there and caucus!!',
    '♥ dragonsden vines 🔒 - february 1, 2016 🔱 dragonsden reaction compilation '
    '🎨',
    'ark: surival evolved rings in 2016 with giant, rideable kangaroos']</code></pre>
<h5 class="anchored">
Legal concerns
</h5>
<pre><code>[   '(california) is it a crime when a religious figure/ lecturer has '
    'relations with one of his followers',
    'being accused of public indecency, among other things. this is a '
    'misunderstanding because i had health issues. [kansas, usa]',
    "[philadelphia, pa] i'm concerned that something suspicious is going on at "
    "my neighbor's house. i'd like to know if there's enough probable cause "
    'for the police to investigate.',
    "refugee's treated worse than dogs!",
    'i have a great idea for a trpg.']</code></pre>
<h2 class="anchored">
Conclusions and Recommendations
</h2>
<p>The clustering results show that <strong>Reddit is a very American-centric platform</strong>. Majority of the topics are related to the 2016 U.S. Presidential Election, specifically on the Republican nominee Donald Trump, Democrat candidates Hillary Clinton, and the Iowa caucuses.</p>
<p>Also, the results show that the two primary motivations of users to post in Reddit is (a) to discuss politics, and (b) to seek advise/ask help from other Redditors, whether technological, legal, or culinary in nature.</p>
<p>Increasing the number of clusters also reveal more specific topics such as ‘technical support’ and ‘’Vines reaction compilation videos’.</p>
<p>For future studies, it is suggested to perform hierarchical clustering.</p>
<h2 class="anchored">
References
</h2>
<i>
<ul>
<li>
<a href="https://www.techspot.com/news/91081-reddit-bans-subreddit-accused-spreading-covid-19-disinformation.html">Thumbnail Image</a>
</li><li>
<a href="https://towardsdatascience.com/all-the-news-17fa34b52b9d">All the news</a>
</li><li>
<a href="https://scikit-learn.org/stable/auto_examples/text/plot_document_clustering.html#sphx-glr-auto-examples-text-plot-document-clustering-py">Clustering text documents using k-means</a>
</li><li>
<a href="http://www.scholarpedia.org/article/Latent_semantic_analysis">Latent Semantic Analysis</a>
</li></ul>
</i><p><i></i></p>



 ]]></description>
  <category>python</category>
  <category>clustering</category>
  <category>unsupervised-learning</category>
  <guid>https://sandrosilva.site/posts/2023-04-20-Reddit/</guid>
  <pubDate>Fri, 22 Apr 2022 00:00:00 GMT</pubDate>
  <media:content url="https://sandrosilva.site/posts/2023-04-20-Reddit/thumbnail.jpeg" medium="image" type="image/jpeg"/>
</item>
<item>
  <title>An analysis of the opening moves of the highest-ranked chess players</title>
  <link>https://sandrosilva.site/posts/2023-04-17-Chess/</link>
  <description><![CDATA[ 




<!-- <h4>Looks like voting in the Philippines is all about location, location, location! Literacy and religion may not be factors, but hometown pride definitely is.</h4> -->
<p><img src="https://sandrosilva.site/posts/2023-04-17-Chess/thumbnail.jpeg" class="img-fluid"></p>
<h1>
Executive Summary
</h1>
<div class="executive-summary">
<p>Original creation and submission for this notebook was last May 29, 2019.</p>
<p>This jupyter notebook was created for my Data Mining and Wrangling class for my Masters in Data Science program in the Asian Institute of Management. In particular, this was done during the 2nd semester for a class - Data Mining and Wrangling - as one of the core requirements. In this report, we shall do an analysis on opening chess moves through exploratory data analysis. In this exercise, we extracted the data from <a href="ChessGames.com">ChessGames.com</a> using the modules <code>Beautifulsoup</code>, <code>requests</code>, and <code>re</code> Python modules, then stored the data in an sqlite database. Results show that the Sicilian, Najdorf (<code>ECO = B90</code>) opening was used in nearly 2.6% of the total games won by the top players. However, looking at the individual players, there is no predominant opening move, with only 7 of the 30 players having the Sicilian, Najdorf move as their top winning opening move.</p>
</div>
<h2 class="anchored">
Acknowledgements
</h2>
<p>This analysis was done together with my Lab partner, George Esleta. I would like to thank Prof Christian Alis and the ACCeSS Laboratory for the access to the high-performance computing facility.</p>
<h2 class="anchored">
A. Introduction and the Problem Statement
</h2>
<p>Chess is a two player strategy game played on a checked 8 by 8 board. The 8 by 8 grid consists of 64 squares where each player is located at opposite ends of the checked board. At the beginning of the game, each player assigned a color of either Black or White. The color scheme indicates which player will move first, with the player with the white pieces moving first. Moves are alternating between players, with each player allowed to only move one chess piece each round.</p>
<p>Each player is given six unique types of pieces with varying numbers, with each unique piece moving differently across the board. Pieces may move to squares occupied by another chess piece. If the player moves into a square occupied by an opponent’s piece, then the opponent’s piece is captured and taken off the chessboard. The purpose of the game is to capture the opponent’s king, signaling a checkmate. Each game is then concluded with either of three scenarios: “1–0” means White won, “0–1” means Black won, and “½–½” indicates a draw (also known as a stalemate).</p>
<p>The first moves in any chess game, also known as a player’s opening move, are the most crucial as it sets the tone, foundation and area of control of the players. The rationale behind this rests on the assumption that the first few moves will influence a player’s probability of winning. The objectives of the opening moves allow each player needs to gain dominance of the grid by: (1) getting most of their pieces out of their default positions as this allows more possible moves), and (2) getting control of the centre of the board (as this allows better dominance).</p>
<p>With the assumption the player’s opening moves may play influential role to the player’s grid control and outcome, the paper will explore the top ranked players opening moves. The purpose of this paper is to determine if there is a specific opening move that each of the top-ranking players use.</p>
<h2 class="anchored">
B. Methodology
</h2>
<h3 class="anchored">
Pre-requisites: Load Requirement Package
</h3>
<p>Before anything else, let us first load all important modules for this exercise.</p>
<div class="cell" data-execution_count="1">
<details class="code-fold">
<summary>Loading required modules</summary>
<div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># These are the standard imports</span></span>
<span id="cb1-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> pandas <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> pd</span>
<span id="cb1-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> numpy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> np</span>
<span id="cb1-4"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> matplotlib.pyplot <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> plt</span>
<span id="cb1-5"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> plotly.plotly <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> py</span>
<span id="cb1-6"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> plotly.graph_objs <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> go</span>
<span id="cb1-7"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> plotly.offline <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> iplot, init_notebook_mode</span>
<span id="cb1-8"></span>
<span id="cb1-9"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Using plotly + cufflinks in offline mode</span></span>
<span id="cb1-10"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> cufflinks</span>
<span id="cb1-11">cufflinks.go_offline(connected<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb1-12">init_notebook_mode(connected<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb1-13"></span>
<span id="cb1-14"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span>matplotlib inline</span>
<span id="cb1-15"></span>
<span id="cb1-16"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># This is to allow a code fold in jupyter notebook</span></span>
<span id="cb1-17"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> IPython.display <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> HTML</span>
<span id="cb1-18">HTML(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'''&lt;script&gt;</span></span>
<span id="cb1-19"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">  function code_toggle() {</span></span>
<span id="cb1-20"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">    if (code_shown){</span></span>
<span id="cb1-21"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">      $('div.input').hide('500');</span></span>
<span id="cb1-22"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">      $('#toggleButton').val('Show Code')</span></span>
<span id="cb1-23"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">    } else {</span></span>
<span id="cb1-24"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">      $('div.input').show('500');</span></span>
<span id="cb1-25"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">      $('#toggleButton').val('Hide Code')</span></span>
<span id="cb1-26"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">    }</span></span>
<span id="cb1-27"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">    code_shown = !code_shown</span></span>
<span id="cb1-28"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">  }</span></span>
<span id="cb1-29"></span>
<span id="cb1-30"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">  $( document ).ready(function(){</span></span>
<span id="cb1-31"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">    code_shown=false;</span></span>
<span id="cb1-32"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">    $('div.input').hide()</span></span>
<span id="cb1-33"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">  });</span></span>
<span id="cb1-34"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">&lt;/script&gt;</span></span>
<span id="cb1-35"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">&lt;form action="javascript:code_toggle()"&gt;&lt;input type="submit" id="toggleButton" value="Show Code"&gt;&lt;/form&gt;'''</span>)</span></code></pre></div>
</details>
</div>
<p>Additionally, we should create a sqlite3 database for where we will store the data what we will scrape. For that, we shall use the <code>sqlite3</code> python module.</p>
<div class="cell" data-execution_count="2">
<details class="code-fold">
<summary>Import the SQLite3 moule then create an empty database called chessgames.</summary>
<div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> sqlite3</span>
<span id="cb2-2">conn <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sqlite3.<span class="ex" style="color: null;
background-color: null;
font-style: inherit;">connect</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'chessgames.db'</span>)</span></code></pre></div>
</details>
</div>
<p>Next, since we will be doing some web scraping, which may want to set our proxy and headers. A proxy server can help a scraper avoid IP address blocking, access geographically restricted content, facilitate high-volume scraping, and avoid detection. Headers in web scraping are a part of the HTTP request that provides information about the client making the request. They are important because they can affect the response received from the server. Some websites may block or restrict access to content based on the header information. To avoid being detected as a bot or being blocked by the server, it is important to ensure that the headers used in web scraping are appropriate and mimic those of a real user.</p>
<div class="cell" data-execution_count="3">
<details class="code-fold">
<summary>Edit our Proxy and Heading</summary>
<div class="sourceCode cell-code" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Setting of proxy</span></span>
<span id="cb3-2">os.environ[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'HTTP_PROXY'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'http://13.115.147.132:8080'</span></span>
<span id="cb3-3">os.environ[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'HTTPS_PROXY'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'http://13.115.147.132:8080'</span></span>
<span id="cb3-4"></span>
<span id="cb3-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Setting of header</span></span>
<span id="cb3-6">header <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'''accept: text/html,application/xhtml+xml,application/xml;q=0.9,</span></span>
<span id="cb3-7"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">            image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3</span></span>
<span id="cb3-8"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">            accept-Encoding: gzip, deflate</span></span>
<span id="cb3-9"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">            accept-Language: en-US,en;q=0.9</span></span>
<span id="cb3-10"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">            cache-Control: max-age=0</span></span>
<span id="cb3-11"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">            connection: keep-alive</span></span>
<span id="cb3-12"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">            host: www.chessgames.com</span></span>
<span id="cb3-13"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">            referer: http://www.chessgames.com/perl/chess.pl?page=16&amp;pid=14125</span></span>
<span id="cb3-14"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">            &amp;playercomp=either&amp;year=2010&amp;yearcomp=ge</span></span>
<span id="cb3-15"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">            upgrade-Insecure-Requests: 1</span></span>
<span id="cb3-16"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">            user-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 </span></span>
<span id="cb3-17"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">            (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'''</span>}</span></code></pre></div>
</details>
</div>
<h3 class="anchored">
Step 1: Understand the Data and Conduct Web Scraping Tool
</h3>
<p>To analyze the top opening moves of the highest-rated chess players, web data extraction was performed on the pages of <a href="ChessGames.com">ChessGames.com</a>. We focused on two entities, namely the chess players (<code>players</code>) and their games (<code>games</code>). Data for both entities were saved to an SQLlite database (<code>chessgames.db</code>).</p>
<p>The <code>players</code> table was obtained by scraping all web pages under the Chess Players Directory <a href="http://www.chessgames.com/directory/">http://www.chessgames.com/directory/</a>. Each page in this directory corresponds to a letter of the alphabet (e.g., <a href="http://www.chessgames.com/directory/A">http://www.chessgames.com/directory/A</a>. Each player has the following information:</p>
<center>
Table 1: <code>player</code> table fields
</center>
<table class="caption-top table">
<colgroup>
<col style="width: 13%">
<col style="width: 32%">
<col style="width: 42%">
<col style="width: 11%">
</colgroup>
<thead>
<tr class="header">
<th>Field</th>
<th>Description</th>
<th>Long Description</th>
<th>Data Type</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>pid</td>
<td>Player ID</td>
<td>indentification number</td>
<td>integer</td>
</tr>
<tr class="even">
<td>lname</td>
<td>Last Name</td>
<td>player’s last name</td>
<td>varchar</td>
</tr>
<tr class="odd">
<td>fname</td>
<td>First Name</td>
<td>player’s first name</td>
<td>varchar</td>
</tr>
<tr class="even">
<td>rating</td>
<td>Rating</td>
<td>highest rating achieved in the database</td>
<td>integer</td>
</tr>
<tr class="odd">
<td>start_year</td>
<td>Start Year</td>
<td>player’s starting year</td>
<td>integer</td>
</tr>
<tr class="even">
<td>end_year</td>
<td>End Year</td>
<td>player’s ending year</td>
<td>integer</td>
</tr>
<tr class="odd">
<td>game_count</td>
<td>Number of games</td>
<td>number of games in database</td>
<td>integer</td>
</tr>
</tbody>
</table>
<p>The <code>get_player_info</code> method was used to scrape the player information (seen below).</p>
<div class="cell" data-execution_count="4">
<details class="code-fold">
<summary>Function description for get_player_info()</summary>
<div class="sourceCode cell-code" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_player_info(url):</span>
<span id="cb4-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">'''</span></span>
<span id="cb4-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Scrapes player info from the specified URL.</span></span>
<span id="cb4-4"></span>
<span id="cb4-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Parameter</span></span>
<span id="cb4-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    ---------</span></span>
<span id="cb4-7"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    URL : URL of player page</span></span>
<span id="cb4-8"></span>
<span id="cb4-9"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Return</span></span>
<span id="cb4-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    ------</span></span>
<span id="cb4-11"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    list of tuples (pid, lname, fname, rating, start_year, end_year, </span></span>
<span id="cb4-12"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    game_count)</span></span>
<span id="cb4-13"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    '''</span></span>
<span id="cb4-14">    players_list <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb4-15">    resp <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> requests.get(url, headers<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>headers)</span>
<span id="cb4-16">    time.sleep(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb4-17">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\t</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">Status code: "</span>, resp.status_code)</span>
<span id="cb4-18">    resp_soup <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> BeautifulSoup(resp.text, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'lxml'</span>)</span>
<span id="cb4-19">    players <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> resp_soup.select(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'tr[bgcolor="#FFFFFF"],tr[bgcolor="#FFEEDD"]'</span>)</span>
<span id="cb4-20">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> player <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> players:</span>
<span id="cb4-21">        data <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> player.select(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'td'</span>)</span>
<span id="cb4-22">        rating <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> data[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].text.strip()</span>
<span id="cb4-23">        name <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> data[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>].text.split(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">','</span>)</span>
<span id="cb4-24">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(name) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>:</span>
<span id="cb4-25">            fname <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> name[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>].strip()</span>
<span id="cb4-26">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span>:</span>
<span id="cb4-27">            fname <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span></span>
<span id="cb4-28">        lname <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> name[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].strip()</span>
<span id="cb4-29">        years <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> data[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>].text.strip()</span>
<span id="cb4-30">        game_count <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> data[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>].text.strip()</span>
<span id="cb4-31">        start_year <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> re.match(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'(\d</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{4}</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">)?-?(\d</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{4}</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">)'</span>, years).group(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb4-32">        end_year <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> re.match(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'(\d</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{4}</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">)?-?(\d</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{4}</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">)'</span>, years).group(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb4-33"></span>
<span id="cb4-34">        url <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>(player.select(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'a'</span>)[<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>])</span>
<span id="cb4-35">        pid <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> re.match(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'.*?pid=(\d+)'</span>, url).group(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb4-36"></span>
<span id="cb4-37">        tup <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (pid, lname, fname, rating, start_year, end_year, game_count)</span>
<span id="cb4-38">        <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\t</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span>, tup)</span>
<span id="cb4-39">        players_list.append(tup)</span>
<span id="cb4-40">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> players_list</span></code></pre></div>
</details>
</div>
<p>For the <code>get_player_info</code> function, the <code>Requests</code> module is a Python library used for making HTTP requests. We can use basic methods such as the <code>GET</code>, <code>POST</code>, <code>PUT</code>, <code>DELETE</code>, and others. The module also provides support for handling cookies, adding custom headers, and handling redirects. We also used the <code>BeautifulSoup</code> Python library, which is a typical package in parsing HTML and XML documents. The package parses the pased HTML source code into a parsed tree, which can be easily traversed. Finally, we used the <code>re</code> Python package to utilize <code>Regular Expression</code> for easier string matching.</p>
<p><br> Next, the players data are then inserted to the <code>players</code> table using the <code>insert_players</code> method:</p>
<div class="cell" data-execution_count="5">
<details class="code-fold">
<summary>Function description for insert_players()</summary>
<div class="sourceCode cell-code" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> insert_players(conn):</span>
<span id="cb5-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">'''</span></span>
<span id="cb5-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Inserts players into the players table</span></span>
<span id="cb5-4"></span>
<span id="cb5-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Parameter</span></span>
<span id="cb5-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    ---------</span></span>
<span id="cb5-7"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    conn : sqlite connection</span></span>
<span id="cb5-8"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    '''</span></span>
<span id="cb5-9">    cur <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> conn.cursor()</span>
<span id="cb5-10">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> char <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> string.ascii_uppercase:</span>
<span id="cb5-11">        url <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"http://www.chessgames.com/directory/"</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> char <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">".html"</span></span>
<span id="cb5-12">        <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(url)</span>
<span id="cb5-13">        players <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> get_player_info(url)</span>
<span id="cb5-14">        cur.executemany(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'''INSERT INTO players </span></span>
<span id="cb5-15"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">                            VALUES (?, ?, ?, ?, ?, ?, ?);'''</span>, players)</span>
<span id="cb5-16">        conn.commit()</span></code></pre></div>
</details>
</div>
<p>Here, we access the enter the created database, then Insert the players and associated metadata into the database.</p>
<p><br> Next, this study will focus on the games of the thirty (30) highest-rated players. The ranking was based on the rating provided by the website. To extract the games of these players, we first obtained their player IDs (<code>pid</code>) by using the <code>pandas</code> method <code>read_sql</code>. Here we can pass a <code>SQL</code> statement:</p>
<div class="cell" data-execution_count="6">
<details class="code-fold">
<summary>Method to query the database</summary>
<div class="sourceCode cell-code" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb6-1">df_players <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.read_sql(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"""SELECT pid, fname || ' ' || lname, rating, </span></span>
<span id="cb6-2"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">                                    game_count </span></span>
<span id="cb6-3"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">                            FROM players</span></span>
<span id="cb6-4"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">                            WHERE rating != ''</span></span>
<span id="cb6-5"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">                            ORDER BY rating DESC"""</span>, conn)</span>
<span id="cb6-6">df_players.columns <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Player ID'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Name'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Rating'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Number of Games'</span>]</span>
<span id="cb6-7">df_players.head(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span>)</span></code></pre></div>
</details>
</div>
<table class="caption-top table">
<caption>Table 2: Top 30 chess players based on Rating</caption>
<thead>
<tr class="header">
<th style="text-align: right;">Player ID</th>
<th>Name</th>
<th style="text-align: right;">Rating</th>
<th style="text-align: right;">Number of Games</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td style="text-align: right;">52948</td>
<td>Magnus CARLSEN</td>
<td style="text-align: right;">2882</td>
<td style="text-align: right;">3,016</td>
</tr>
<tr class="even">
<td style="text-align: right;">15940</td>
<td>Garry KASPAROV</td>
<td style="text-align: right;">2851</td>
<td style="text-align: right;">2,385</td>
</tr>
<tr class="odd">
<td style="text-align: right;">76172</td>
<td>Fabiano CARUANA</td>
<td style="text-align: right;">2844</td>
<td style="text-align: right;">1,891</td>
</tr>
<tr class="even">
<td style="text-align: right;">17316</td>
<td>Levon ARONIAN</td>
<td style="text-align: right;">2830</td>
<td style="text-align: right;">2,708</td>
</tr>
<tr class="odd">
<td style="text-align: right;">95915</td>
<td>Wesley SO</td>
<td style="text-align: right;">2822</td>
<td style="text-align: right;">1,400</td>
</tr>
<tr class="even">
<td style="text-align: right;">56798</td>
<td>Maxime VACHIER-LAGRAVE</td>
<td style="text-align: right;">2819</td>
<td style="text-align: right;">2,369</td>
</tr>
<tr class="odd">
<td style="text-align: right;">12088</td>
<td>Viswanathan ANAND</td>
<td style="text-align: right;">2817</td>
<td style="text-align: right;">3,542</td>
</tr>
<tr class="even">
<td style="text-align: right;">12295</td>
<td>Vladimir KRAMNIK</td>
<td style="text-align: right;">2817</td>
<td style="text-align: right;">3,026</td>
</tr>
<tr class="odd">
<td style="text-align: right;">12089</td>
<td>Veselin TOPALOV</td>
<td style="text-align: right;">2816</td>
<td style="text-align: right;">2,278</td>
</tr>
<tr class="even">
<td style="text-align: right;">50065</td>
<td>Shakhriyar MAMEDYAROV</td>
<td style="text-align: right;">2814</td>
<td style="text-align: right;">2,254</td>
</tr>
<tr class="odd">
<td style="text-align: right;">10084</td>
<td>Hikaru NAKAMURA</td>
<td style="text-align: right;">2814</td>
<td style="text-align: right;">2,424</td>
</tr>
<tr class="even">
<td style="text-align: right;">17279</td>
<td>Alexander GRISCHUK</td>
<td style="text-align: right;">2797</td>
<td style="text-align: right;">2,586</td>
</tr>
<tr class="odd">
<td style="text-align: right;">52629</td>
<td>Ding LIREN</td>
<td style="text-align: right;">2797</td>
<td style="text-align: right;">920</td>
</tr>
<tr class="even">
<td style="text-align: right;">107252</td>
<td>Anish GIRI</td>
<td style="text-align: right;">2793</td>
<td style="text-align: right;">1,522</td>
</tr>
<tr class="odd">
<td style="text-align: right;">49796</td>
<td>Teimour RADJABOV</td>
<td style="text-align: right;">2793</td>
<td style="text-align: right;">1,746</td>
</tr>
<tr class="even">
<td style="text-align: right;">54535</td>
<td>Sergey KARJAKIN</td>
<td style="text-align: right;">2788</td>
<td style="text-align: right;">2,399</td>
</tr>
<tr class="odd">
<td style="text-align: right;">11719</td>
<td>Alexander MOROZEVICH</td>
<td style="text-align: right;">2788</td>
<td style="text-align: right;">1,847</td>
</tr>
<tr class="even">
<td style="text-align: right;">12183</td>
<td>Vassily IVANCHUK</td>
<td style="text-align: right;">2787</td>
<td style="text-align: right;">3,752</td>
</tr>
<tr class="odd">
<td style="text-align: right;">19233</td>
<td>Robert James FISCHER</td>
<td style="text-align: right;">2785</td>
<td style="text-align: right;">1,052</td>
</tr>
<tr class="even">
<td style="text-align: right;">20719</td>
<td>Anatoly KARPOV</td>
<td style="text-align: right;">2780</td>
<td style="text-align: right;">3,609</td>
</tr>
<tr class="odd">
<td style="text-align: right;">13847</td>
<td>Boris GELFAND</td>
<td style="text-align: right;">2777</td>
<td style="text-align: right;">3,014</td>
</tr>
<tr class="even">
<td style="text-align: right;">79968</td>
<td>Peter SVIDLER</td>
<td style="text-align: right;">2769</td>
<td style="text-align: right;">2,786</td>
</tr>
<tr class="odd">
<td style="text-align: right;">49080</td>
<td>Leinier Dominguez PEREZ</td>
<td style="text-align: right;">2768</td>
<td style="text-align: right;">1,342</td>
</tr>
<tr class="even">
<td style="text-align: right;">12109</td>
<td>Ruslan PONOMARIOV</td>
<td style="text-align: right;">2768</td>
<td style="text-align: right;">1,989</td>
</tr>
<tr class="odd">
<td style="text-align: right;">54683</td>
<td>Ian NEPOMNIACHTCHI</td>
<td style="text-align: right;">2767</td>
<td style="text-align: right;">1,614</td>
</tr>
<tr class="even">
<td style="text-align: right;">49246</td>
<td>Pentala HARIKRISHNA</td>
<td style="text-align: right;">2766</td>
<td style="text-align: right;">1,442</td>
</tr>
<tr class="odd">
<td style="text-align: right;">49456</td>
<td>Pavel ELJANOV</td>
<td style="text-align: right;">2765</td>
<td style="text-align: right;">1,409</td>
</tr>
<tr class="even">
<td style="text-align: right;">15874</td>
<td>Gata KAMSKY</td>
<td style="text-align: right;">2763</td>
<td style="text-align: right;">1,889</td>
</tr>
<tr class="odd">
<td style="text-align: right;">12290</td>
<td>Peter LEKO</td>
<td style="text-align: right;">2763</td>
<td style="text-align: right;">2,364</td>
</tr>
<tr class="even">
<td style="text-align: right;">112240</td>
<td>Yu YANGYI</td>
<td style="text-align: right;">2762</td>
<td style="text-align: right;">991</td>
</tr>
</tbody>
</table>
<p>The <code>games</code> table was then populated by web scraping <small><code>http://www.chessgames.com/perl/chessplayer?pid=&lt;pid&gt;</code></small> and iterating over the top 30 player IDs. The following fields were extracted for each game:</p>
<table class="caption-top table">
<caption>Table 3: <code>games</code> table fields</caption>
<thead>
<tr class="header">
<th>Field</th>
<th>Description</th>
<th>Data Type</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>gid</td>
<td>Game ID</td>
<td>integer</td>
</tr>
<tr class="even">
<td>white_pid</td>
<td>White Player ID</td>
<td>int</td>
</tr>
<tr class="odd">
<td>black_pid</td>
<td>Black Player ID</td>
<td>int</td>
</tr>
<tr class="even">
<td>result</td>
<td>Result</td>
<td>varchar</td>
</tr>
<tr class="odd">
<td>moves</td>
<td>Number of moves</td>
<td>integer</td>
</tr>
<tr class="even">
<td>year</td>
<td>Year</td>
<td>integer</td>
</tr>
<tr class="odd">
<td>tournament</td>
<td>Tournament Name</td>
<td>varchar</td>
</tr>
<tr class="even">
<td>eco</td>
<td>Encyclopaedia of Chess Openings</td>
<td>varchar</td>
</tr>
<tr class="odd">
<td>opening_move</td>
<td>Opening move</td>
<td>varchar</td>
</tr>
</tbody>
</table>
<p>The <code>get_players_games</code> function was implemented to scrape the game data for a given Player ID <code>pid</code> and page number <code>page_start</code>. This writes the games data of the player to a CSV file (<code>&lt;pid&gt;.csv</code>):</p>
<div class="cell" data-execution_count="7">
<details class="code-fold">
<summary>Function description for the get_players_games()</summary>
<div class="sourceCode cell-code" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb7-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_player_games(pid, page_start):</span>
<span id="cb7-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb7-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Web scrapes the games list for a player and writes it to a CSV </span></span>
<span id="cb7-4"></span>
<span id="cb7-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Parameters:</span></span>
<span id="cb7-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    -----------</span></span>
<span id="cb7-7"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    pid : player ID</span></span>
<span id="cb7-8"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    page_start : starting page</span></span>
<span id="cb7-9"></span>
<span id="cb7-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Returns:</span></span>
<span id="cb7-11"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    --------</span></span>
<span id="cb7-12"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    None</span></span>
<span id="cb7-13"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    """</span></span>
<span id="cb7-14">    url <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'http://www.chessgames.com/perl/chessplayer?pid='</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>(pid)</span>
<span id="cb7-15">    resp <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> requests.get(url, headers<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>headers)</span>
<span id="cb7-16">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'pid = '</span>, pid, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\t</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">url = '</span>, url, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\t</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">code = '</span>, resp.status_code)</span>
<span id="cb7-17">    time.sleep(np.random.randint(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))</span>
<span id="cb7-18">    soup <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> BeautifulSoup(resp.text, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'lxml'</span>)</span>
<span id="cb7-19">    div_page_count <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> soup.select(</span>
<span id="cb7-20">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'td[background$="/chessimages/table_stripes.gif"]'</span>)</span>
<span id="cb7-21">    page_count <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>(re.findall(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'of (\d+)\;'</span>, div_page_count[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].text)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>])</span>
<span id="cb7-22"></span>
<span id="cb7-23">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">open</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>pid<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">.csv'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'a'</span>) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">file</span>:</span>
<span id="cb7-24">        csv_writer <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> csv.writer(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">file</span>, delimiter<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">','</span>, quotechar<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'"'</span>)</span>
<span id="cb7-25">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> page <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(page_start, page_count<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>):</span>
<span id="cb7-26">            page_url <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'http://www.chessgames.com/perl/chess.pl?page='</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\</span></span>
<span id="cb7-27">                <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>(page) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'&amp;pid='</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>(pid)</span>
<span id="cb7-28">            page_resp <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> requests.get(page_url, headers<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>headers)</span>
<span id="cb7-29">            <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\t</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">page = '</span>, page, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\t</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">url = '</span>, page_url,</span>
<span id="cb7-30">                  <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\t</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">code = '</span>, page_resp.status_code)</span>
<span id="cb7-31">            time.sleep(np.random.randint(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))</span>
<span id="cb7-32">            page_soup <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> BeautifulSoup(page_resp.text, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'lxml'</span>)</span>
<span id="cb7-33">            games <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> page_soup.select(</span>
<span id="cb7-34">                <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'tr[bgcolor="#FFFFFF"],tr[bgcolor="#EEDDCC"]'</span>)</span>
<span id="cb7-35"></span>
<span id="cb7-36">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> game <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> games:</span>
<span id="cb7-37">                data <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> game.select(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'td'</span>)</span>
<span id="cb7-38">                game_url <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> data[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].find(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"a"</span>)[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'href'</span>]</span>
<span id="cb7-39">                game_id <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> re.findall(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'(\d+)'</span>, game_url)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb7-40">                result <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> data[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>].text.strip()</span>
<span id="cb7-41">                moves <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> data[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>].text.strip()</span>
<span id="cb7-42">                year <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> data[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>].text.strip()</span>
<span id="cb7-43">                tournament <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> data[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>].text.strip()</span>
<span id="cb7-44">                eco <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> data[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>].select(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'a'</span>)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].text.strip()</span>
<span id="cb7-45">                opening_move <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> re.findall(</span>
<span id="cb7-46">                    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'^[A-E0-9][0-9]</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{2}</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;"> (.*)'</span>, data[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>].text.strip())[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb7-47"></span>
<span id="cb7-48">                game_resp <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> requests.get(</span>
<span id="cb7-49">                    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'http://www.chessgames.com'</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> game_url, headers<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>headers)</span>
<span id="cb7-50">                time.sleep(np.random.randint(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))</span>
<span id="cb7-51">                game_soup <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> BeautifulSoup(game_resp.text, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'lxml'</span>)</span>
<span id="cb7-52">                players <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> game_soup.select(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'center'</span>)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].select(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'a'</span>)</span>
<span id="cb7-53">                <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">try</span>:</span>
<span id="cb7-54">                    white_id <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> re.findall(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'(\d+)'</span>, players[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>][<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'href'</span>])[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb7-55">                <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">except</span>:</span>
<span id="cb7-56">                    white_id <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span></span>
<span id="cb7-57">                <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">try</span>:</span>
<span id="cb7-58">                    black_id <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> re.findall(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'(\d+)'</span>, players[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>][<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'href'</span>])[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb7-59">                <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">except</span>:</span>
<span id="cb7-60">                    black_id <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span></span>
<span id="cb7-61">                tup <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (game_id, white_id, black_id, result,</span>
<span id="cb7-62">                       moves, year, tournament, eco, opening_move)</span>
<span id="cb7-63"></span>
<span id="cb7-64">                <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">try</span>:</span>
<span id="cb7-65">                    csv_writer.writerow(tup)</span>
<span id="cb7-66">                <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">except</span>:</span>
<span id="cb7-67">                    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\t\t</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">gameID: '</span>, game_id, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\t</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">Write to CSV failed'</span>)</span></code></pre></div>
</details>
</div>
<p>All player csv files were then inserted to the <code>games</code> table of the <code>chessgames.db</code> database using the <code>read_csvs</code> function:</p>
<div class="cell" data-execution_count="8">
<details class="code-fold">
<summary>Function description for read_csvs()</summary>
<div class="sourceCode cell-code" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb8-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> read_csvs(conn):</span>
<span id="cb8-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb8-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Read all player csvs and save them to the games table</span></span>
<span id="cb8-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    """</span></span>
<span id="cb8-5">    gid_failed <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb8-6">    cur <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> conn.cursor()</span>
<span id="cb8-7">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> file_name <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> glob.glob(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'./games/*.csv'</span>):</span>
<span id="cb8-8">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">open</span>(file_name) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">file</span>:</span>
<span id="cb8-9">            <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(file_name)</span>
<span id="cb8-10">            reader <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> csv.reader(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">file</span>, delimiter <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">','</span>)</span>
<span id="cb8-11">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> line <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> reader:</span>
<span id="cb8-12">                <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">try</span>:</span>
<span id="cb8-13">                    cur.execute(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'''INSERT INTO games VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);'''</span>, line)</span>
<span id="cb8-14">                    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\t\t</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">gameID: '</span>, line[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\t</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">Insert success!'</span>)</span>
<span id="cb8-15">                <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">except</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">Exception</span> <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> e:</span>
<span id="cb8-16">                    gid_failed.append(line[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>])</span>
<span id="cb8-17">                    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\t\t</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">gameID: '</span>, line[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\t</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">Insert Failed!</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\t</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span>, e)</span>
<span id="cb8-18">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> gid_failed</span></code></pre></div>
</details>
</div>
<p>Now, let us examine the games dataframe by calling it with the <code>read_sql</code> Pandas module.</p>
<div class="cell" data-execution_count="9">
<details class="code-fold">
<summary>Accessing the database.</summary>
<div class="sourceCode cell-code" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb9-1">df_games <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.read_sql(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"""SELECT * FROM games"""</span>, conn)</span>
<span id="cb9-2">df_games.columns <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ([<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Game ID'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'White Player ID'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Black Player ID'</span>,</span>
<span id="cb9-3">                     <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Result'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Number of Moves'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Year'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Tournament'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'ECO'</span>,</span>
<span id="cb9-4">                     <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Opening Move'</span>])</span></code></pre></div>
</details>
</div>
<p>Below you can see that <strong>Table 4</strong> and <strong>Table 5</strong> shows the summary statistics for the <code>players</code> and <code>games</code> table. <strong>8,574 players</strong> and <strong>50,087</strong> games were inserted into the chessgames database.</p>
<table class="caption-top table">
<caption>Table 4: <code>players</code> table summary statistics</caption>
<thead>
<tr class="header">
<th>Statistic</th>
<th>Rating</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>count</td>
<td>8574.000000</td>
</tr>
<tr class="even">
<td>mean</td>
<td>2361.279566</td>
</tr>
<tr class="odd">
<td>std</td>
<td>184.344627</td>
</tr>
<tr class="even">
<td>min</td>
<td>1379.000000</td>
</tr>
<tr class="odd">
<td>25%</td>
<td>2268.000000</td>
</tr>
<tr class="even">
<td>50%</td>
<td>2389.000000</td>
</tr>
<tr class="odd">
<td>75%</td>
<td>2479.000000</td>
</tr>
<tr class="even">
<td>max</td>
<td>2882.000000</td>
</tr>
</tbody>
</table>
<table class="caption-top table">
<caption>Table 5: <code>games</code> table summary statistics</caption>
<thead>
<tr class="header">
<th>Statistic</th>
<th>Number of Moves</th>
<th>Year</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>count</td>
<td>50087.000000</td>
<td>50087.000000</td>
</tr>
<tr class="even">
<td>mean</td>
<td>42.893485</td>
<td>2005.074950</td>
</tr>
<tr class="odd">
<td>std</td>
<td>17.288031</td>
<td>11.643902</td>
</tr>
<tr class="even">
<td>min</td>
<td>0.000000</td>
<td>1953.000000</td>
</tr>
<tr class="odd">
<td>25%</td>
<td>31.000000</td>
<td>2000.000000</td>
</tr>
<tr class="even">
<td>50%</td>
<td>41.000000</td>
<td>2008.000000</td>
</tr>
<tr class="odd">
<td>75%</td>
<td>52.000000</td>
<td>2014.000000</td>
</tr>
<tr class="even">
<td>max</td>
<td>255.000000</td>
<td>2019.000000</td>
</tr>
</tbody>
</table>
<h2 class="anchored">
Results
</h2>
<p><strong>Figure 1</strong> below shows the top 10 opening moves used by the thirty highest-ranked chess players. 356 games, or nearly 2.6% of the games won by the top players, were opened using the Sicilian, Najdorf (ECO = B90) move.</p>
<p>However, looking at the top opening moves per player as seen in <strong>Figure 3</strong>, the Sicilian, Najdorf (ECO = B90) move does not appear as the top move for most of the players. For instance, Magnus Carlsen, the highest-ranked player, has the Ruy Lopez, Berlin Defense as his top opening move. As shown in <strong>Table 7</strong>, Only 7 of the top 30 players have the Sicilian, Najdorf move as their top winning opening move. Also, if we look at the top 5 highest-rated players, 3 of 5 of them have the Ruy Lopez, Berlin Defense move as the top winning move.</p>
<div class="cell" data-execution_count="10">
<details class="code-fold">
<summary>Function to see top 10 opening moves and % won.</summary>
<div class="sourceCode cell-code" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb10-1">df_top_moves <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.read_sql(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"""SELECT g.white_pid, p.fname || ' ' || </span></span>
<span id="cb10-2"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">                            p.lname, p.rating, g.eco, g.opening_move, count(*) </span></span>
<span id="cb10-3"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">                            FROM games g</span></span>
<span id="cb10-4"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">                          INNER JOIN players p on g.white_pid = p.pid</span></span>
<span id="cb10-5"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">                          WHERE g.white_pid IN (SELECT pid FROM players </span></span>
<span id="cb10-6"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">                                              WHERE rating != ''</span></span>
<span id="cb10-7"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">                                              ORDER BY rating DESC limit 30)</span></span>
<span id="cb10-8"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">                          AND g.result = '1-0'</span></span>
<span id="cb10-9"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">                          GROUP BY g.white_pid, g.eco, g.opening_move</span></span>
<span id="cb10-10"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">                          ORDER BY p.rating DESC, count(*) DESC"""</span>, conn)</span>
<span id="cb10-11">df_top_moves.columns <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'PID'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Name'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Rating'</span>,</span>
<span id="cb10-12">                        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'ECO'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Top Opening Move'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Number of Games Won'</span>]</span>
<span id="cb10-13">df_top_moves <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df_top_moves.groupby([<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'ECO'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Top Opening Move'</span>])[</span>
<span id="cb10-14">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Number of Games Won'</span>].<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>().to_frame()</span>
<span id="cb10-15">df_top_moves <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df_top_moves.sort_values(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Number of Games Won'</span>, ascending<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>)</span>
<span id="cb10-16">df_top_moves.reset_index(inplace<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb10-17">df_top_moves[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">% o</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">f Games Won'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (</span>
<span id="cb10-18">    df_top_moves[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Number of Games Won'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> df_top_moves[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Number of Games Won'</span>].<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>)</span>
<span id="cb10-19">df_top_moves.head(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)</span></code></pre></div>
</details>
</div>
<table class="caption-top table">
<caption>Table 6: Top Opening Moves of the 30 highest-rated players</caption>
<colgroup>
<col style="width: 9%">
<col style="width: 37%">
<col style="width: 29%">
<col style="width: 24%">
</colgroup>
<thead>
<tr class="header">
<th>ECO</th>
<th>Top Opening Move</th>
<th>Number of Games Won</th>
<th>% of Games Won</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>B90</td>
<td>Sicilian, Najdorf</td>
<td>356</td>
<td>2.566321</td>
</tr>
<tr class="even">
<td>A07</td>
<td>King’s Indian Attack</td>
<td>250</td>
<td>1.802191</td>
</tr>
<tr class="odd">
<td>B12</td>
<td>Caro-Kann Defense</td>
<td>227</td>
<td>1.63639</td>
</tr>
<tr class="even">
<td>C78</td>
<td>Ruy Lopez</td>
<td>206</td>
<td>1.485006</td>
</tr>
<tr class="odd">
<td>C42</td>
<td>Petrov Defense</td>
<td>205</td>
<td>1.477797</td>
</tr>
<tr class="even">
<td>C11</td>
<td>French</td>
<td>204</td>
<td>1.470588</td>
</tr>
<tr class="odd">
<td>E15</td>
<td>Queen’s Indian</td>
<td>203</td>
<td>1.463379</td>
</tr>
<tr class="even">
<td>A04</td>
<td>Reti Opening</td>
<td>192</td>
<td>1.384083</td>
</tr>
<tr class="odd">
<td>D37</td>
<td>Queen’s Gambit Declined</td>
<td>186</td>
<td>1.34083</td>
</tr>
<tr class="even">
<td>C65</td>
<td>Ruy Lopez, Berlin Defense</td>
<td>176</td>
<td>1.268743</td>
</tr>
</tbody>
</table>
<div class="cell" data-execution_count="11">
<details class="code-fold">
<summary>Code to generate the Top Opening Moves.</summary>
<div class="sourceCode cell-code" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb11-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> matplotlib.pyplot <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> plt</span>
<span id="cb11-2">fig, ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(dpi<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">150</span>)</span>
<span id="cb11-3">df_top_moves[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>::<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>].plot.barh(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Top Opening Move'</span>,</span>
<span id="cb11-4">                               <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">% o</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">f Games Won'</span>, ax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>ax, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'#BF5209'</span>,</span>
<span id="cb11-5">                               legend<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>)</span>
<span id="cb11-6">ax.set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">% o</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">f Games Won'</span>)</span></code></pre></div>
</details>
</div>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://sandrosilva.site/posts/2023-04-17-Chess/image-outputs/image1-topmoves.png" class="img-fluid figure-img"></p>
<figcaption>FIGURE 1:Top Opening Moves of the 30 highest-rated chess players</figcaption>
</figure>
</div>
<p>Now, let us view the top opening moves per top player (top 10 players)</p>
<div class="cell" data-execution_count="12">
<details class="code-fold">
<summary>Code to generate the Top Opening Moves for top players</summary>
<div class="sourceCode cell-code" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb12-1">df_top_moves <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.read_sql(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"""SELECT g.white_pid, p.fname || ' ' || </span></span>
<span id="cb12-2"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">                            p.lname, p.rating, g.eco, g.opening_move, count(*) </span></span>
<span id="cb12-3"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">                            FROM games g</span></span>
<span id="cb12-4"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">                          INNER JOIN players p on g.white_pid = p.pid</span></span>
<span id="cb12-5"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">                          WHERE g.white_pid IN (SELECT pid FROM players </span></span>
<span id="cb12-6"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">                                              WHERE rating != ''</span></span>
<span id="cb12-7"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">                                              ORDER BY rating DESC limit 30)</span></span>
<span id="cb12-8"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">                          AND g.result = '1-0'</span></span>
<span id="cb12-9"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">                          GROUP BY g.white_pid, g.eco</span></span>
<span id="cb12-10"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">                          ORDER BY p.rating DESC, count(*) DESC"""</span>, conn)</span>
<span id="cb12-11">df_top_moves.columns <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'PID'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Name'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Rating'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'ECO'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Top Opening Move'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Number of Games Won'</span>]</span>
<span id="cb12-12">df_top_moves <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (df_top_moves</span>
<span id="cb12-13">                .groupby([<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Rating'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'PID'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Name'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'ECO'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Top Opening Move'</span>])</span>
<span id="cb12-14">                [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Number of Games Won'</span>].<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>().to_frame())</span>
<span id="cb12-15">df_top_moves <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (df_top_moves.reset_index()</span>
<span id="cb12-16">                .sort_values([<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Rating'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Number of Games Won'</span>],</span>
<span id="cb12-17">                             ascending<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>])</span>
<span id="cb12-18">                .set_index([<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'PID'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Rating'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Name'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'ECO'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Top Opening Move'</span>]))</span>
<span id="cb12-19">df_top_moves <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df_top_moves.groupby(level<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>).head(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)</span>
<span id="cb12-20">df_top_moves.reset_index(inplace<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb12-21">df_top_moves</span>
<span id="cb12-22"></span>
<span id="cb12-23">names <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df_top_moves[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Name'</span>].unique()</span>
<span id="cb12-24"></span>
<span id="cb12-25"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> name <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> names:</span>
<span id="cb12-26">    fig, ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots()</span>
<span id="cb12-27">    df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df_top_moves[df_top_moves[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Name'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> name]</span>
<span id="cb12-28">    df[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>::<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>].plot.barh(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Top Opening Move'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Number of Games Won'</span>,</span>
<span id="cb12-29">                         ax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>ax, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'#BF5209'</span>, legend<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>)</span>
<span id="cb12-30">    ax.set_title(name)</span>
<span id="cb12-31">    ax.set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Number of Games Won'</span>)</span></code></pre></div>
</details>
</div>
<div id="fig-top" class="quarto-layout-panel">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-top-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<div class="quarto-layout-row">
<div class="quarto-layout-cell" style="flex-basis: 100.0%;justify-content: flex-start;">
<p><img src="https://sandrosilva.site/posts/2023-04-17-Chess/image-outputs/1-carlsen.png" class="img-fluid figure-img" style="width:100.0%"> <img src="https://sandrosilva.site/posts/2023-04-17-Chess/image-outputs/2-kasparov.png" class="img-fluid figure-img" style="width:100.0%"></p>
</div>
</div>
<div class="quarto-layout-row">
<div class="quarto-layout-cell" style="flex-basis: 100.0%;justify-content: flex-start;">
<p><img src="https://sandrosilva.site/posts/2023-04-17-Chess/image-outputs/3-caruana.png" class="img-fluid figure-img" style="width:100.0%"> <img src="https://sandrosilva.site/posts/2023-04-17-Chess/image-outputs/4-aronian.png" class="img-fluid figure-img" style="width:100.0%"></p>
</div>
</div>
<div class="quarto-layout-row">
<div class="quarto-layout-cell" style="flex-basis: 100.0%;justify-content: flex-start;">
<p><img src="https://sandrosilva.site/posts/2023-04-17-Chess/image-outputs/5-so.png" class="img-fluid figure-img" style="width:100.0%"> <img src="https://sandrosilva.site/posts/2023-04-17-Chess/image-outputs/6-lagrave.png" class="img-fluid figure-img" style="width:100.0%"></p>
</div>
</div>
<div class="quarto-layout-row">
<div class="quarto-layout-cell" style="flex-basis: 100.0%;justify-content: flex-start;">
<p><img src="https://sandrosilva.site/posts/2023-04-17-Chess/image-outputs/7-anand.png" class="img-fluid figure-img" style="width:100.0%"> <img src="https://sandrosilva.site/posts/2023-04-17-Chess/image-outputs/8-kramnik.png" class="img-fluid figure-img" style="width:100.0%"></p>
</div>
</div>
<div class="quarto-layout-row">
<div class="quarto-layout-cell" style="flex-basis: 100.0%;justify-content: flex-start;">
<p><img src="https://sandrosilva.site/posts/2023-04-17-Chess/image-outputs/9-topalov.png" class="img-fluid figure-img" style="width:100.0%"> <img src="https://sandrosilva.site/posts/2023-04-17-Chess/image-outputs/10-nakamura.png" class="img-fluid figure-img" style="width:100.0%"></p>
</div>
</div>
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-top-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;1: Top Winning Moves Per Top Player
</figcaption>
</figure>
</div>
<h2 class="anchored">
Conclusions and Recommendations
</h2>
<p>The results indicate that the Sicilian, Najdorf is the most used opening move by the thirty top-ranked players, with 356 games or nearly 2.6% of the games were won using this move. However, looking at the individual opening moves of each top-ranked players, there is no predominant opening move, with only 7 of the 30 players have the Sicilian, Najdorf move as their top winning opening move. Additionally, looking at the top five players, the Ruy Lopez, Berlin Defense was the most frequent opening move.</p>
<p>The methodology of the study does not take into account the total number of games each player competed in. Certain top ranked players have higher number of competition appearances. This may affect the number of instances the Sicilian, Najdorf may appear due to playing style bias. Further research may be conducted to explore normalizing the data by the number of games each top-player appeared in and won. Also, we can explore why the top-ranked players have a preference towards the Ruy Lopez, Berlin Defense.</p>
<h2 class="anchored">
References
</h2>
<i>
<ul>
<li>
<a href="ChessGames.com">ChessGames.com</a>
</li><li>
<a href="https://www.chesscentral.com/pages/learn-chess-play-better/chess-strategy-for-chess-openings-and-chess-principles.html">Chess Strategy for Chess Openings and Chess Principles</a>
</li><li>
<a href="https://www.chessbazaar.com/blog/chess-tournament-rules-regulations-fide-approved/">Chess Tournament Rules Regulations Fide Approved</a>
</li><li>
<a href="https://exeterchessclub.org.uk/content/ten-rules-opening">Ten Rules Openings</a>
</li></ul>
</i><p><i></i></p>



 ]]></description>
  <category>python</category>
  <category>EDA</category>
  <category>SQL</category>
  <guid>https://sandrosilva.site/posts/2023-04-17-Chess/</guid>
  <pubDate>Wed, 20 Apr 2022 00:00:00 GMT</pubDate>
  <media:content url="https://sandrosilva.site/posts/2023-04-17-Chess/thumbnail.jpeg" medium="image" type="image/jpeg"/>
</item>
<item>
  <title>Regional Voting Preferences in the 2019 Philippine Senatorial Elections</title>
  <link>https://sandrosilva.site/posts/2023-04-14-Elections/</link>
  <description><![CDATA[ 




<!-- <h4>Looks like voting in the Philippines is all about location, location, location! Literacy and religion may not be factors, but hometown pride definitely is.</h4> -->
<p><img src="https://sandrosilva.site/posts/2023-04-14-Elections/thumbnail.jpeg" class="img-fluid"></p>
<h1>
Overview
</h1>
<p>Original creation and submission for this notebook was last May 29, 2019.</p>
<p>This jupyter notebook was created for my Data Mining and Wrangling class for my Masters in Data Science program in the Asian Institute of Management. In particular, this was done during the 2nd semester for a class - Data Mining and Wrangling - as one of the core requirements. In this report, we shall explore and understand the results of the 2019 elections through descriptive statistics. We shall show some exploratory data analysis on the following questions: <br></p>
<ol>
<li>
How did the various administrative regions of the Philippines voted for their senators?
</li><li>
Is the voter preference homogeneous across the country, or is there a preferred candidate or party per region? More specifically, how does (1) religious affiliation, (2) educational attainment, and (2) sex play a major role on how the voters select their candidates.
</li></ol>
<h1>
Acknowledgements
</h1>
This analysis was done together with my Lab partner, George Esleta. I would like to thank Prof Christian Alis and the ACCeSS Laboratory for the access to the high-performance computing facility.
<h2 class="anchored">
Methodology
</h2>
<h3 class="anchored">
Pre-requisites: Load Requirement Package
</h3>
<p>Before anything else, let us first load all important modules for this exercise.</p>
<div class="cell" data-execution_count="1">
<details class="code-fold">
<summary>Loading required modules</summary>
<div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> os</span>
<span id="cb1-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> io</span>
<span id="cb1-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> re</span>
<span id="cb1-4"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> time</span>
<span id="cb1-5"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> glob</span>
<span id="cb1-6"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> requests</span>
<span id="cb1-7"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> urllib.request</span>
<span id="cb1-8"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> numpy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> np</span>
<span id="cb1-9"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> pandas <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> pd</span>
<span id="cb1-10"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> geopandas <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> gpd</span>
<span id="cb1-11"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> matplotlib.pyplot <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> plt</span>
<span id="cb1-12"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> matplotlib.colors <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> LinearSegmentedColormap</span>
<span id="cb1-13"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> seaborn <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> sns</span></code></pre></div>
</details>
</div>
<p>It is important to identify the datasets we are going to use for this exercise. The two identified datasets the group intends to use are: the 2019 National Data and the 2015-2016 Census data.</p>
<p>With regards to 2019 National data, the team used a web scapper provided Prof.&nbsp;Alis. The web scapper downloaded the election results from the Commission of Elections’ 2019 National and Local Elections website. The results were then stored in a local repository which is then easily accesible for the team. The 2019 elections results are broken down into two main directories: results and contest. In this exercise, the team will explore both directories to map out a comprehensive summary of the 2019 senatorial and party elections.</p>
<p>Secondly, the 2015-2016 Census data has already been stored in a local repository for easier access. One of the main reasons why the team decided to use the 2015-2016 Census data is because of the lack of availability of recent data. The Philippine Statistics Authority only releases a comprehensive census survey ever six years. However for the purpose of this exercise, the team has agreed that the 2015-2016 census data can act as an appproximate for today’s population.</p>
<h3 class="anchored">
Step 1: Extract and collect the 2019 Elections (Results) data
</h3>
<p>The first directory to explore is the 2019 Election <code>results</code>. The <code>results</code> directory contains all electoral results from a regional level down to the barangay level. For each level, a specific <code>coc.json</code> file is stored. This file contains all electoral results data and metadata for both national and local elections. However for the purposes of this analysis, we will only look at the aggregated elections data at the regional level. The files that we are interested are the coc.json files associated to each province, as these files contain the metadata and data on the election results.</p>
<p>The main structure of each coc.json file contains the following main keys: <code>vbc</code>, <code>rs</code>, <code>sts</code>, <code>obs</code>, and <code>cos</code>. For the purpose of this exercise, the important key the group needs to extract is the <code>rs</code> key as this provides the each candidate’s total votes per area. Under the <code>rs</code> key, the following keys can be found: <code>cc</code>, <code>bo</code>, <code>v</code>, <code>tot</code>, <code>per</code>, and <code>ser</code>. Cross referencing these keys with official statements and comelec documentations suggests that important keys are as follows: <code>cc</code> pertaining to contest_type, <code>bo</code> pertaining to the candidate_id, and <code>v</code> pertaining to votes_per_province.</p>
<table class="caption-top table">
<thead>
<tr class="header">
<th style="text-align: left;">Paremeter</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td style="text-align: left;">cc</td>
<td>Contestant Code</td>
</tr>
<tr class="even">
<td style="text-align: left;">bo</td>
<td>Contestant ID</td>
</tr>
<tr class="odd">
<td style="text-align: left;">v</td>
<td>Total Votes Per Contestant</td>
</tr>
<tr class="even">
<td style="text-align: left;">tot</td>
<td>Total Votes Per Province</td>
</tr>
</tbody>
</table>
<p>However, it must be pointed out that the available data only goes as high as provincial data. If we want to process the provincial level, the team will have to aggregate the data up.</p>
<p>The group created utility functions for easier retrieval of the provincial elections datasets. The purpose for the utility functions (and future utility functions) are for initial cleaning and manipulations. This is to ensure each dataset is ready for aggregation.</p>
<p>The <code>get_province_coc</code> method unpacks each key and value from the <code>coc.json</code> dictionary into a cleaned up dataframe. In addition, the method identifies which region and province the file originated from by examining the filepath that was passed.</p>
<p>The <code>get_all_province_coc</code> method is a walker that goes through each of the results directory. The walker checks if the filename has an equal value to <code>coc.json</code>. If a <code>coc.json</code>was located, the <code>get_province_coc</code> method is applied with the filepath as the parameter. The resulting dataframe is then appended to a master dataframe for further extraction and analysis. For this exercise, the group only had to extract data up to the regional and provincial levels so only three wildcard were use for the <code>glob</code> walker.</p>
<p>Special methods (<code>get_ncr_coc</code> and <code>get_all_ncr_coc</code>) were established to get the cities’ <code>coc.json</code>. For the case of the NCR cities, theire associated <code>coc.json</code> files were one directory lower.</p>
<h4 class="anchored">
</h4>
<div class="cell" data-execution_count="2">
<details class="code-fold">
<summary>Function for get_province_coc()</summary>
<div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_province_coc(filepath):</span>
<span id="cb2-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb2-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Loads a single coc file. </span></span>
<span id="cb2-4"></span>
<span id="cb2-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Adds additional columns `region` and `province to the DataFrame,</span></span>
<span id="cb2-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    depending on filepath.</span></span>
<span id="cb2-7"></span>
<span id="cb2-8"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Parameters</span></span>
<span id="cb2-9"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    ----------</span></span>
<span id="cb2-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    filepath    : filepath</span></span>
<span id="cb2-11"></span>
<span id="cb2-12"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Return</span></span>
<span id="cb2-13"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    ------</span></span>
<span id="cb2-14"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    df          : a dataframe</span></span>
<span id="cb2-15"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    """</span></span>
<span id="cb2-16">    output <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb2-17">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">open</span>(filepath, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'r'</span>) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> f:</span>
<span id="cb2-18">        dirpath, filepath <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> os.path.split(filepath)</span>
<span id="cb2-19">        region <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> dirpath.split(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'/'</span>)[<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]</span>
<span id="cb2-20">        province <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> dirpath.split(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'/'</span>)[<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb2-21">        data <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> json.load(f)</span>
<span id="cb2-22">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> each <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> data[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'rs'</span>]:</span>
<span id="cb2-23">            row <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>(element) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> element <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>(each.values())]</span>
<span id="cb2-24">            output.append([data[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'vbc'</span>]] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> row <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> [region] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> [province])</span>
<span id="cb2-25">    df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.DataFrame(output,</span>
<span id="cb2-26">                      columns<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'vbc'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'cc'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'bo'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'v'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'tot'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'per'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'ser'</span>,</span>
<span id="cb2-27">                               <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'province'</span>])</span>
<span id="cb2-28">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> df</span></code></pre></div>
</details>
</div>
<div class="cell" data-execution_count="3">
<details class="code-fold">
<summary>Function for get_all_province_coc()</summary>
<div class="sourceCode cell-code" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_all_province_coc(tree):</span>
<span id="cb3-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb3-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Loads all province COC files and saves them to a dataframe</span></span>
<span id="cb3-4"></span>
<span id="cb3-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Checks the filepath if filename is 'coc.json'</span></span>
<span id="cb3-6"></span>
<span id="cb3-7"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Created a new column to deal with the reclassification of</span></span>
<span id="cb3-8"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        "NEGROS ORIENTAL" and "NEGROS OCCIDENTAL" to "NIR" </span></span>
<span id="cb3-9"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">            to match the PSA 2016 dataset.</span></span>
<span id="cb3-10"></span>
<span id="cb3-11"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Parameters</span></span>
<span id="cb3-12"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    ----------</span></span>
<span id="cb3-13"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    filepath    : filepath</span></span>
<span id="cb3-14"></span>
<span id="cb3-15"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Return</span></span>
<span id="cb3-16"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    ------</span></span>
<span id="cb3-17"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    df          : a dataframe</span></span>
<span id="cb3-18"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    """</span></span>
<span id="cb3-19">    total <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.DataFrame()</span>
<span id="cb3-20">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">file</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> glob.glob(tree):</span>
<span id="cb3-21">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> os.path.basename(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">file</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'coc.json'</span>:</span>
<span id="cb3-22">            df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> get_province_coc(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">file</span>)</span>
<span id="cb3-23">            total <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> total.append(df)</span>
<span id="cb3-24">    total.rename(columns<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>{<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region'</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region_raw'</span>}, inplace<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb3-25">    total[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> total[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region_raw'</span>].copy()</span>
<span id="cb3-26">    total.loc[(total[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'province'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"NEGROS ORIENTAL"</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span></span>
<span id="cb3-27">              (total[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'province'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"NEGROS OCCIDENTAL"</span>), <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'NIR'</span></span>
<span id="cb3-28">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> total</span></code></pre></div>
</details>
</div>
<div class="cell" data-execution_count="4">
<details class="code-fold">
<summary>Function for get_ncr_coc()</summary>
<div class="sourceCode cell-code" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_ncr_coc(filepath):</span>
<span id="cb4-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb4-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Loads a single coc file. </span></span>
<span id="cb4-4"></span>
<span id="cb4-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Adds additional columns `region` and `province to the DataFrame,</span></span>
<span id="cb4-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    depending on filepath.</span></span>
<span id="cb4-7"></span>
<span id="cb4-8"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Parameters</span></span>
<span id="cb4-9"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    ----------</span></span>
<span id="cb4-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    filepath    : filepath</span></span>
<span id="cb4-11"></span>
<span id="cb4-12"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Return</span></span>
<span id="cb4-13"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    ------</span></span>
<span id="cb4-14"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    df          : a dataframe    </span></span>
<span id="cb4-15"></span>
<span id="cb4-16"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    """</span></span>
<span id="cb4-17">    output <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb4-18">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">open</span>(filepath, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'r'</span>) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> f:</span>
<span id="cb4-19">        dirpath, filepath <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> os.path.split(filepath)</span>
<span id="cb4-20">        region <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> dirpath.split(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'/'</span>)[<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>]</span>
<span id="cb4-21">        province <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> dirpath.split(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'/'</span>)[<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]</span>
<span id="cb4-22">        data <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> json.load(f)</span>
<span id="cb4-23">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> each <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> data[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'rs'</span>]:</span>
<span id="cb4-24">            row <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>(element) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> element <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>(each.values())]</span>
<span id="cb4-25">            output.append([data[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'vbc'</span>]] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> row <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> [region] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> [province])</span>
<span id="cb4-26">    df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.DataFrame(output,</span>
<span id="cb4-27">                      columns<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'vbc'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'cc'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'bo'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'v'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'tot'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'per'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'ser'</span>,</span>
<span id="cb4-28">                               <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'province'</span>])</span>
<span id="cb4-29">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> df</span></code></pre></div>
</details>
</div>
<div class="cell" data-execution_count="5">
<details class="code-fold">
<summary>Function for get_all_ncr_coc()</summary>
<div class="sourceCode cell-code" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_all_ncr_coc(tree):</span>
<span id="cb5-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb5-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Loads all province COC files and saves them to a dataframe</span></span>
<span id="cb5-4"></span>
<span id="cb5-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Checks the filepath if filename is 'coc.json'</span></span>
<span id="cb5-6"></span>
<span id="cb5-7"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Parameters</span></span>
<span id="cb5-8"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    ----------</span></span>
<span id="cb5-9"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    filepath    : filepath</span></span>
<span id="cb5-10"></span>
<span id="cb5-11"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Return</span></span>
<span id="cb5-12"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    ------</span></span>
<span id="cb5-13"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    df          : a dataframe</span></span>
<span id="cb5-14"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    """</span></span>
<span id="cb5-15">    total <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.DataFrame()</span>
<span id="cb5-16">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">file</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> glob.glob(tree):</span>
<span id="cb5-17">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">file</span>.split(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'/'</span>)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">7</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'NCR'</span>:</span>
<span id="cb5-18">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> os.path.basename(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">file</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'coc.json'</span>:</span>
<span id="cb5-19">                df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> get_ncr_coc(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">file</span>)</span>
<span id="cb5-20">                total <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> total.append(df)</span>
<span id="cb5-21">    total.rename(columns<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>{<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region'</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region_raw'</span>}, inplace<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb5-22">    total[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> total[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region_raw'</span>].copy()</span>
<span id="cb5-23">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> total</span></code></pre></div>
</details>
</div>
<section id="with-these-utility-functions-inplace-the-team-can-now-apply-these-methods-for-easier-access-to-the-2019-elections-data." class="level4">
<h4 class="anchored" data-anchor-id="with-these-utility-functions-inplace-the-team-can-now-apply-these-methods-for-easier-access-to-the-2019-elections-data.">With these utility functions inplace, the team can now apply these methods for easier access to the 2019 elections data.</h4>
<p>We can now compile all of the election results with the following line:</p>
<div class="cell" data-execution_count="6">
<details class="code-fold">
<summary>Compiling provinces data with NCR data</summary>
<div class="sourceCode cell-code" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb6-1">tree <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'/mnt/data/public/elections/nle2019/results/*/*/*'</span></span>
<span id="cb6-2">ncr_tree <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'/mnt/data/public/elections/nle2019/results/*/*/*/*'</span></span>
<span id="cb6-3">df_results <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> get_all_province_coc(tree)</span>
<span id="cb6-4">df_results <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df_results.append(get_all_ncr_coc(ncr_tree))</span>
<span id="cb6-5">df_results.drop_duplicates(inplace<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span></code></pre></div>
</details>
</div>
<p>Let’s see what we have:</p>
<table class="caption-top table">
<colgroup>
<col style="width: 5%">
<col style="width: 10%">
<col style="width: 5%">
<col style="width: 5%">
<col style="width: 10%">
<col style="width: 10%">
<col style="width: 5%">
<col style="width: 10%">
<col style="width: 10%">
<col style="width: 30%">
</colgroup>
<thead>
<tr class="header">
<th style="text-align: left;">vbc</th>
<th>cc</th>
<th>bo</th>
<th>v</th>
<th>tot</th>
<th>per</th>
<th>ser</th>
<th>region_raw</th>
<th>province</th>
<th>region</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td style="text-align: left;">0</td>
<td>89550</td>
<td>1.0</td>
<td>1.0</td>
<td>2004.0</td>
<td>1708769.0</td>
<td>0.11</td>
<td>2800.0</td>
<td>REGION I</td>
<td>ILOCOS NORTE</td>
</tr>
<tr class="even">
<td style="text-align: left;">1</td>
<td>89550</td>
<td>1.0</td>
<td>2.0</td>
<td>1607.0</td>
<td>1708769.0</td>
<td>0.09</td>
<td>2800.0</td>
<td>REGION I</td>
<td>ILOCOS NORTE</td>
</tr>
<tr class="odd">
<td style="text-align: left;">2</td>
<td>89550</td>
<td>1.0</td>
<td>3.0</td>
<td>8772.0</td>
<td>1708769.0</td>
<td>0.51</td>
<td>2800.0</td>
<td>REGION I</td>
<td>ILOCOS NORTE</td>
</tr>
<tr class="even">
<td style="text-align: left;">3</td>
<td>89550</td>
<td>1.0</td>
<td>4.0</td>
<td>1767.0</td>
<td>1708769.0</td>
<td>0.10</td>
<td>2800.0</td>
<td>REGION I</td>
<td>ILOCOS NORTE</td>
</tr>
<tr class="odd">
<td style="text-align: left;">4</td>
<td>89550</td>
<td>1.0</td>
<td>5.0</td>
<td>5068.0</td>
<td>1708769.0</td>
<td>0.29</td>
<td>2800.0</td>
<td>REGION I</td>
<td>ILOCOS NORTE</td>
</tr>
</tbody>
</table>
</section>
<section id="next-let-us-examine-the-obtained-dataset-with-actual-election-results." class="level3">
<h3 class="anchored">Next, let us examine the obtained dataset with actual election results.</h3>
<p>By cross checking the results with <a href="https://www.comelec.gov.ph/?r=2019NLE/ListsOfCandidates/CertifiedListofCandidates">Comelec data</a>, we can identify the senators and party names.</p>
<p>Just to check our data, we can look at an example senator from the dataset. By choosing <code>cc=1</code> and <code>bo=46</code>, we are actually highlighting Imee Marcos’ senatorial candidacy results.</p>
<div class="cell" data-execution_count="7">
<details class="code-fold">
<summary>Code of creating a bar graph for Imee Marcos highest voting province in ascending order</summary>
<div class="sourceCode cell-code" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb7-1">fig, ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots()</span>
<span id="cb7-2">ax.set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Votes'</span>)</span>
<span id="cb7-3">df_marcos <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df_results.query(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'cc == 1 &amp; bo == 46'</span>).copy()</span>
<span id="cb7-4">df_marcos.groupby(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region'</span>).<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>()[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'v'</span>].sort_values(</span>
<span id="cb7-5">    ascending<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>).plot.barh(figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>),</span>
<span id="cb7-6">                              title<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Contestant: 46 - Imee Marcos'</span>,</span>
<span id="cb7-7">                              color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'#BF5209'</span>, ax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>ax)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div>
</details>
</div>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://sandrosilva.site/posts/2023-04-14-Elections/image1.png" class="img-fluid figure-img"></p>
<figcaption>FIGURE: Total Votes for Imee Marcos by Region</figcaption>
</figure>
</div>
<p>Additionally, let us check some descriptive statistics for the 2019 Elections dataset. More specifically, let us examine the <code>v</code> or <code>votes</code> column. The group will be highly dependent on the <code>votes</code> data so let us first do some initial statistics and visualizations.</p>
<div class="cell" data-execution_count="8">
<details class="code-fold">
<summary>Code to groupby sum up by region and province</summary>
<div class="sourceCode cell-code" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb8-1">df_regions <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df_results.groupby([<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'province'</span>])[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'v'</span>].<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>().to_frame()</span>
<span id="cb8-2">df_regions <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df_regions.rename(columns<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>{<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'v'</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'votes'</span>})</span>
<span id="cb8-3">df_regions.head(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16</span>)</span></code></pre></div>
</details>
</div>
<table class="caption-top table">
<thead>
<tr class="header">
<th style="text-align: left;">region</th>
<th>province</th>
<th>votes</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td style="text-align: left;">BARMM</td>
<td>BASILAN</td>
<td>2093067.0</td>
</tr>
<tr class="even">
<td style="text-align: left;"></td>
<td>LANAO DEL SUR</td>
<td>4770462.0</td>
</tr>
<tr class="odd">
<td style="text-align: left;"></td>
<td>MAGUINDANAO</td>
<td>5917983.0</td>
</tr>
<tr class="even">
<td style="text-align: left;"></td>
<td>SULU</td>
<td>3529555.0</td>
</tr>
<tr class="odd">
<td style="text-align: left;"></td>
<td>TAWI-TAWI</td>
<td>1874486.0</td>
</tr>
<tr class="even">
<td style="text-align: left;">CAR</td>
<td>ABRA</td>
<td>1923481.0</td>
</tr>
<tr class="odd">
<td style="text-align: left;"></td>
<td>APAYAO</td>
<td>703002.0</td>
</tr>
<tr class="even">
<td style="text-align: left;"></td>
<td>BENGUET</td>
<td>2426397.0</td>
</tr>
<tr class="odd">
<td style="text-align: left;"></td>
<td>IFUGAO</td>
<td>1408688.0</td>
</tr>
<tr class="even">
<td style="text-align: left;"></td>
<td>KALINGA</td>
<td>1621414.0</td>
</tr>
<tr class="odd">
<td style="text-align: left;"></td>
<td>MOUNTAIN PROVINCE</td>
<td>1074249.0</td>
</tr>
<tr class="even">
<td style="text-align: left;">NCR</td>
<td>NATIONAL CAPITAL REGION - FOURTH DISTRICT</td>
<td>22896771.0</td>
</tr>
<tr class="odd">
<td style="text-align: left;"></td>
<td>NATIONAL CAPITAL REGION - MANILA</td>
<td>13461229.0</td>
</tr>
<tr class="even">
<td style="text-align: left;"></td>
<td>NATIONAL CAPITAL REGION - SECOND DISTRICT</td>
<td>29803007.0</td>
</tr>
<tr class="odd">
<td style="text-align: left;"></td>
<td>NATIONAL CAPITAL REGION - THIRD DISTRICT</td>
<td>18481014.0</td>
</tr>
<tr class="even">
<td style="text-align: left;"></td>
<td>TAGUIG - PATEROS</td>
<td>10018306.0</td>
</tr>
</tbody>
</table>
<p>Just to explore, the code and image below shows the total votes in region 3. Notice that Bulacan has the highest number of votes, followed by Nueva Ecija, then Pampanga.</p>
<div class="cell" data-execution_count="9">
<details class="code-fold">
<summary>Code to plot summary for Region 3 total votes</summary>
<div class="sourceCode cell-code" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb9-1">fig, ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots()</span>
<span id="cb9-2">ax.set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Votes'</span>)</span>
<span id="cb9-3">df_test.loc[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'REGION III'</span>,<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"votes"</span>].plot.barh(color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'#BF5209'</span>, ax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>ax)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div>
</details>
</div>
<div class="quarto-figure quarto-figure-left">
<figure class="figure">
<p><img src="https://sandrosilva.site/posts/2023-04-14-Elections/image2.png" class="img-fluid figure-img"></p>
<figcaption>FIGURE: Votes Distribution in Region III</figcaption>
</figure>
</div>
<p>Here we explore the vote distribution in the National Capital Region. The classification of district and cities were broken down by area (Manila, Taguig-Pateros, Second District, Third District, and Fourth District).The top number of votes came from the second district (mainly because of Quezon City), followed by the Fourth District, then the Third District.</p>
<div class="cell" data-execution_count="10">
<details class="code-fold">
<summary>Code to plot summary for NCR total votes</summary>
<div class="sourceCode cell-code" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb10-1">fig, ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots()</span>
<span id="cb10-2">ax.set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Votes'</span>)</span>
<span id="cb10-3">df_test.loc[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'NCQ'</span>,<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"votes"</span>].plot.barh(color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'#BF5209'</span>, ax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>ax)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div>
</details>
</div>
<div class="quarto-figure quarto-figure-left">
<figure class="figure">
<p><img src="https://sandrosilva.site/posts/2023-04-14-Elections/image3.png" class="img-fluid figure-img"></p>
<figcaption>FIGURE: Votes Distribution in the National Capital Region</figcaption>
</figure>
</div>
<p>Next, we explore the distribution of votes in Region 4-A. Unsurprisingly, the population of votes is high in the population centers of Cavite, then Batangas, then Laguna.</p>
<div class="cell" data-execution_count="11">
<details class="code-fold">
<summary>Code to plot summary for Region 4-A total votes</summary>
<div class="sourceCode cell-code" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb11-1">fig, ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots()</span>
<span id="cb11-2">ax.set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Votes'</span>)</span>
<span id="cb11-3">df_test.loc[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'REGION IV-A'</span>,<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"votes"</span>].plot.barh(color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'#BF5209'</span>, ax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>ax)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div>
</details>
</div>
<div class="quarto-figure quarto-figure-left">
<figure class="figure">
<p><img src="https://sandrosilva.site/posts/2023-04-14-Elections/image4.png" class="img-fluid figure-img"></p>
<figcaption>FIGURE: Votes Distribution in the Region IV-A</figcaption>
</figure>
</div>
<p>For now, let us also examine the distribution of election votes in region 7. Unsurprisingly, the votes are concentrated first in Cebu, followed by Bohol and Siquijor.</p>
<div class="cell" data-execution_count="12">
<details class="code-fold">
<summary>Code to plot summary for Region 7 total votes</summary>
<div class="sourceCode cell-code" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb12-1">fig, ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots()</span>
<span id="cb12-2">ax.set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Votes'</span>)</span>
<span id="cb12-3">df_test.loc[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'REGION VII'</span>,<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"votes"</span>].plot.barh(color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'#BF5209'</span>, ax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>ax)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div>
</details>
</div>
<div class="quarto-figure quarto-figure-left">
<figure class="figure">
<p><img src="https://sandrosilva.site/posts/2023-04-14-Elections/image5.png" class="img-fluid figure-img"></p>
<figcaption>FIGURE: Votes Distribution in the Region VII</figcaption>
</figure>
</div>
<p>To match the contestant ID to the contestant name, the <code>contest</code> files were also downloaded from the <a href="https://2019electionresults.comelec.gov.ph/#/dashboard">Commission of Elections’ 2019 National and Local Elections website</a> and stored in the local repository. Similar to the <code>results</code> directory, the <code>contest</code> directory contained json files for each contest type/position. Upon inspection of a sample file within the directory, the following values were obtained:</p>
<p>The pertinent keys from each json files were:</p>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Parameter</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>cc</td>
<td>Contest code</td>
</tr>
<tr class="even">
<td>cn</td>
<td>Contest code name - location</td>
</tr>
<tr class="odd">
<td>ccc</td>
<td>Contest code name</td>
</tr>
<tr class="even">
<td>type</td>
<td>Contest type</td>
</tr>
<tr class="odd">
<td>bos</td>
<td>list of candidate parameters</td>
</tr>
</tbody>
</table>
<p>Under the <code>bos</code> key, we can extract each of the candidates’ parameters. The more useful ones for the group’s study include:</p>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Parameter</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>boc</td>
<td>Contestant ID</td>
</tr>
<tr class="even">
<td>bon</td>
<td>Contestant Name</td>
</tr>
<tr class="odd">
<td>pn</td>
<td>Party Name</td>
</tr>
</tbody>
</table>
<h3 class="anchored">
Step 2: Extract and collect the 2019 Elections (Contestant) data
</h3>
<p>The group also created utility functions for easier retrieval of the contestant datasets. This is to ensure each dataset is ready for aggregation.</p>
<p>Similar to the <code>get_province_coc</code>, the <code>get_contestant_attrib</code> method unpacks each key and value from the <code>{contest_number}.json</code> dictionary into a cleaned up dataframe. The method converts the <code>bos</code> directory into an additional list, which will also be appended into the resulting dataframe.</p>
<p>There are two (2) major political coalitions fighting for the senate seats:</p>
<ol type="1">
<li>Hugpong ng Pagbabago (HNP)</li>
<li>Otso Diretso</li>
</ol>
<p>Similar to the <code>get_all_province_coc</code>, the <code>get_contestants_attrib</code> method is a walker that goes through each of the <code>contest</code> directory. The method will first append all <code>{contest_numer}.json</code> files into a singular dataframe. Next, the method creates a new column that identifies who among the senatorial candidates are part of the <strong>Hugpong ng Pagbabago (HNP)</strong> or <strong>Otso Diretso campaign</strong>.</p>
<div class="cell" data-execution_count="13">
<details class="code-fold">
<summary>Function for get_contestant_attrib()</summary>
<div class="sourceCode cell-code" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb13-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_contestant_attrib(filepath):</span>
<span id="cb13-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb13-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Returns the contestant json file into a dataframe</span></span>
<span id="cb13-4"></span>
<span id="cb13-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Parameters</span></span>
<span id="cb13-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    ----------</span></span>
<span id="cb13-7"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    filepath   : string</span></span>
<span id="cb13-8"></span>
<span id="cb13-9"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Returns</span></span>
<span id="cb13-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    ----------</span></span>
<span id="cb13-11"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    df         : pd.DataFrame of contestnat attributes</span></span>
<span id="cb13-12"></span>
<span id="cb13-13"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    """</span></span>
<span id="cb13-14"></span>
<span id="cb13-15">    contestants_values <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb13-16">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">open</span>(filepath, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'r'</span>) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">file</span>:</span>
<span id="cb13-17">        data <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> json.load(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">file</span>)</span>
<span id="cb13-18">        attrib_keys <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [key <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> key <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>(data.keys())</span>
<span id="cb13-19">                       <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">isinstance</span>(key, (<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>))]</span>
<span id="cb13-20">        attrib_values <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [value <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> value <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>(data.values())</span>
<span id="cb13-21">                         <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">isinstance</span>(value, (<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>))]</span>
<span id="cb13-22">        contest_values <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>(contest.values()) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> contest <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> data[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'bos'</span>]]</span>
<span id="cb13-23">        df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.DataFrame(contest_values,</span>
<span id="cb13-24">                          columns<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>(data[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'bos'</span>][<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].keys()))</span>
<span id="cb13-25">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> k, v <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">zip</span>(attrib_keys, attrib_values):</span>
<span id="cb13-26">            df[k] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> v</span>
<span id="cb13-27">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> df</span></code></pre></div>
</details>
</div>
<div class="cell" data-execution_count="14">
<details class="code-fold">
<summary>Function for get_contestants_attrib</summary>
<div class="sourceCode cell-code" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb14-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_contestants_attrib(filepath):</span>
<span id="cb14-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb14-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Returns ALL contestant json files into a dataframe</span></span>
<span id="cb14-4"></span>
<span id="cb14-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Parameters</span></span>
<span id="cb14-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    ----------</span></span>
<span id="cb14-7"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    filepath   : string</span></span>
<span id="cb14-8"></span>
<span id="cb14-9"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Returns</span></span>
<span id="cb14-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    ----------</span></span>
<span id="cb14-11"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    df         : pd.DataFrame of contestant attributes</span></span>
<span id="cb14-12"></span>
<span id="cb14-13"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    """</span></span>
<span id="cb14-14">    df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.DataFrame()</span>
<span id="cb14-15">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> each_filepath <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> glob.glob(filepath):</span>
<span id="cb14-16">        df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df.append(get_contestant_attrib(each_filepath))</span>
<span id="cb14-17">    senators <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df[df.cc <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>].copy()</span>
<span id="cb14-18">    senators[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'bon'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> senators[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'bon'</span>].<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>.extract(pat<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'(.*?) \('</span>)</span>
<span id="cb14-19">    party <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df[df.cc <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5567</span>].copy()</span>
<span id="cb14-20">    df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> senators.append(party)</span>
<span id="cb14-21">    df.drop_duplicates(inplace<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb14-22">    df.rename(columns<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>{<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'boc'</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'bo'</span>}, inplace<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb14-23">    otso <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'AQUINO, BENIGNO BAM '</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'DIOKNO, CHEL'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'HILBAY, PILO'</span>,</span>
<span id="cb14-24">            <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'MACALINTAL, MACAROMY'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'GUTOC, SAMIRA'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'ALEJANO, GARY'</span>,</span>
<span id="cb14-25">            <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'ROXAS, MAR'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'TAÑADA,LORENZO ERIN TAPAT'</span>]</span>
<span id="cb14-26">    hnp <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'ANGARA, EDGARDO SONNY'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'BONG REVILLA, RAMON JR'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'CAYETANO, PIA'</span>,</span>
<span id="cb14-27">           <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'DELA ROSA, BATO'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'EJERCITO, ESTRADA JV'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'ESTRADA, JINGGOY'</span>,</span>
<span id="cb14-28">           <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'GO, BONG GO'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'MANGUDADATU, DONG'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'MANICAD, JIGGY'</span>,</span>
<span id="cb14-29">           <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'MARCOS, IMEE'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'PIMENTEL, KOKO'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'TOLENTINO, FRANCIS'</span>, </span>
<span id="cb14-30">           <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'VILLAR, CYNTHIA'</span>]</span>
<span id="cb14-31">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> o <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> otso:</span>
<span id="cb14-32">        df.loc[df.bon <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> o, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'coalition'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Otso Diretso"</span></span>
<span id="cb14-33">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> h <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> hnp:</span>
<span id="cb14-34">        df.loc[df.bon <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> h, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'coalition'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"HNP"</span></span>
<span id="cb14-35">    df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'coalition'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'coalition'</span>].fillna(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'None'</span>)</span>
<span id="cb14-36">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> df</span></code></pre></div>
</details>
</div>
<p>Let us run the <code>get_contestants_attrib</code>. This will be used later in the blog for our further analysis.</p>
<div class="cell" data-execution_count="15">
<details class="code-fold">
<summary>Executing get_contestants_attrib function</summary>
<div class="sourceCode cell-code" id="cb15" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb15-1">contestant_filepaths <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'/mnt/data/public/elections/nle2019/contests/*'</span></span>
<span id="cb15-2">df_contestants <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> get_contestants_attrib(contestant_filepaths)</span>
<span id="cb15-3">df_contestants.head()</span></code></pre></div>
</details>
</div>
<div class="table">
<table class="caption-top table">
<colgroup>
<col style="width: 2%">
<col style="width: 3%">
<col style="width: 2%">
<col style="width: 2%">
<col style="width: 3%">
<col style="width: 3%">
<col style="width: 2%">
<col style="width: 3%">
<col style="width: 3%">
<col style="width: 10%">
<col style="width: 10%">
<col style="width: 10%">
<col style="width: 10%">
<col style="width: 10%">
<col style="width: 10%">
<col style="width: 10%">
<col style="width: 10%">
</colgroup>
<thead>
<tr class="header">
<th style="text-align: right;">bo</th>
<th style="text-align: left;">bon</th>
<th style="text-align: left;">boi</th>
<th style="text-align: right;">to</th>
<th style="text-align: right;">pc</th>
<th style="text-align: left;">pn</th>
<th style="text-align: right;">pcc</th>
<th style="text-align: right;">pcy</th>
<th style="text-align: right;">pcm</th>
<th style="text-align: right;">pck</th>
<th style="text-align: left;">cc</th>
<th style="text-align: right;">cn</th>
<th style="text-align: left;">ccc</th>
<th style="text-align: right;">ccn</th>
<th style="text-align: left;">pre</th>
<th style="text-align: left;">type</th>
<th style="text-align: left;">coalition</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td style="text-align: right;">37</td>
<td style="text-align: left;">HILBAY, PILO</td>
<td style="text-align: left;">52.png</td>
<td style="text-align: right;">37</td>
<td style="text-align: right;">2</td>
<td style="text-align: left;">AKSYON DEMOKRATIKO</td>
<td style="text-align: right;">1</td>
<td style="text-align: right;">1</td>
<td style="text-align: right;">1</td>
<td style="text-align: right;">1</td>
<td style="text-align: left;">1</td>
<td style="text-align: right;">SENATOR PHILIPPINES</td>
<td style="text-align: left;">1</td>
<td style="text-align: right;">SENATOR</td>
<td style="text-align: left;">3</td>
<td style="text-align: left;">national</td>
<td style="text-align: left;">Otso Diretso</td>
</tr>
<tr class="even">
<td style="text-align: right;">7</td>
<td style="text-align: left;">ALUNAN, RAFFY</td>
<td style="text-align: left;">53.png</td>
<td style="text-align: right;">7</td>
<td style="text-align: right;">3</td>
<td style="text-align: left;">BAGUMBAYAN VOLUNTEERS FOR A NEW PHILIPPINES</td>
<td style="text-align: right;">1</td>
<td style="text-align: right;">1</td>
<td style="text-align: right;">1</td>
<td style="text-align: right;">1</td>
<td style="text-align: left;">1</td>
<td style="text-align: right;">SENATOR PHILIPPINES</td>
<td style="text-align: left;">1</td>
<td style="text-align: right;">SENATOR</td>
<td style="text-align: left;">3</td>
<td style="text-align: left;">national</td>
<td style="text-align: left;">None</td>
</tr>
<tr class="odd">
<td style="text-align: right;">14</td>
<td style="text-align: left;">BALDEVARONA, BALDE</td>
<td style="text-align: left;">35.png</td>
<td style="text-align: right;">14</td>
<td style="text-align: right;">7</td>
<td style="text-align: left;">FILIPINO FAMILY PARTY</td>
<td style="text-align: right;">1</td>
<td style="text-align: right;">1</td>
<td style="text-align: right;">1</td>
<td style="text-align: right;">1</td>
<td style="text-align: left;">1</td>
<td style="text-align: right;">SENATOR PHILIPPINES</td>
<td style="text-align: left;">1</td>
<td style="text-align: right;">SENATOR</td>
<td style="text-align: left;">3</td>
<td style="text-align: left;">national</td>
<td style="text-align: left;">None</td>
</tr>
<tr class="even">
<td style="text-align: right;">18</td>
<td style="text-align: left;">CASIÑO, TOTI</td>
<td style="text-align: left;">20.png</td>
<td style="text-align: right;">18</td>
<td style="text-align: right;">8</td>
<td style="text-align: left;">KATIPUNAN NG DEMOKRATIKONG PILIPINO(KDP)</td>
<td style="text-align: right;">1</td>
<td style="text-align: right;">1</td>
<td style="text-align: right;">1</td>
<td style="text-align: right;">1</td>
<td style="text-align: left;">1</td>
<td style="text-align: right;">SENATOR PHILIPPINES</td>
<td style="text-align: left;">1</td>
<td style="text-align: right;">SENATOR</td>
<td style="text-align: left;">3</td>
<td style="text-align: left;">national</td>
<td style="text-align: left;">None</td>
</tr>
<tr class="odd">
<td style="text-align: right;">21</td>
<td style="text-align: left;">CHONG, GLENN</td>
<td style="text-align: left;">61.png</td>
<td style="text-align: right;">21</td>
<td style="text-align: right;">8</td>
<td style="text-align: left;">KATIPUNAN NG DEMOKRATIKONG PILIPINO(KDP)</td>
<td style="text-align: right;">1</td>
<td style="text-align: right;">1</td>
<td style="text-align: right;">1</td>
<td style="text-align: right;">1</td>
<td style="text-align: left;">1</td>
<td style="text-align: right;">SENATOR PHILIPPINES</td>
<td style="text-align: left;">1</td>
<td style="text-align: right;">SENATOR</td>
<td style="text-align: left;">3</td>
<td style="text-align: left;">national</td>
<td style="text-align: left;">None</td>
</tr>
</tbody>
</table>
</div>
<p>We now have two dataframes: <code>df_results</code> containing the 2019 election results, and <code>df_contestants</code> containing the contestant information. These two dataframes can now be merged into a single dataframe. Let us also drop certain columns which we have deemed as unimportant.</p>
<div class="cell" data-execution_count="16">
<details class="code-fold">
<summary>Function for merge_comelec()</summary>
<div class="sourceCode cell-code" id="cb16" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb16-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> merge_comelec(results, contestants):</span>
<span id="cb16-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb16-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Merge results dataframe with contestants dataframe</span></span>
<span id="cb16-4"></span>
<span id="cb16-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Parameters</span></span>
<span id="cb16-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    ----------</span></span>
<span id="cb16-7"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    results    : pd.DataFrame</span></span>
<span id="cb16-8"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    contestants: pd.DataFrame</span></span>
<span id="cb16-9"></span>
<span id="cb16-10"></span>
<span id="cb16-11"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Returns</span></span>
<span id="cb16-12"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    ----------</span></span>
<span id="cb16-13"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    df         : pd.DataFrame of contestant attributes</span></span>
<span id="cb16-14"></span>
<span id="cb16-15"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    """</span></span>
<span id="cb16-16"></span>
<span id="cb16-17">    df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.merge(results, contestants, on<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'bo'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'cc'</span>], how<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'left'</span>)</span>
<span id="cb16-18">    df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df.drop([<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'vbc'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'boi'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'to'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'pc'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'pcc'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'pcy'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'pcm'</span>,</span>
<span id="cb16-19">                  <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'pck'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'ccc'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'pre'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'ser'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'cn'</span>], axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb16-20">    df.columns <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'position'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'candidate_id'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'votes_per_province'</span>,</span>
<span id="cb16-21">                  <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'total_votes'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'votes_in_pct'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region_raw'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'province'</span>,</span>
<span id="cb16-22">                  <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'candidate_name'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'party_name'</span>,</span>
<span id="cb16-23">                  <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'contest_position'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'contest_type'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'coalition'</span>]</span>
<span id="cb16-24">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> df</span></code></pre></div>
</details>
</div>
<p>Let’s merge the tables, then just check the unique regions using the <code>unique</code> method.</p>
<div class="cell" data-execution_count="17">
<details class="code-fold">
<summary>Merging the results and contestants dataframes</summary>
<div class="sourceCode cell-code" id="cb17" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb17-1">nle2019 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> merge_comelec(df_results, df_contestants)</span>
<span id="cb17-2">nle2019.region.unique()</span>
<span id="cb17-3"></span>
<span id="cb17-4">array([<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'REGION I'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'REGION IV-B'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'BARMM'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'REGION II'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'REGION III'</span>,</span>
<span id="cb17-5">       <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'REGION V'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'REGION VI'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'NIR'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'REGION VII'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'REGION VIII'</span>,</span>
<span id="cb17-6">       <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'REGION IX'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'REGION X'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'REGION XI'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'REGION XII'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'REGION XIII'</span>,</span>
<span id="cb17-7">       <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'REGION IV-A'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'CAR'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'NCR'</span>], dtype<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">object</span>)</span></code></pre></div>
</details>
</div>
<h3 class="anchored">
Step 3: Load <code>Geopandas</code> for geospatial processing
</h3>
<h4 class="anchored">
Loading the geospatial data
</h4>
<p>The Philippines is composed of <strong>seventeen (17) administrative regions</strong>. We can use the <code>geopandas</code> module to manage and pre-process geospatial data.</p>
<p>Let us first load up a geopandas graph of the Philippines.</p>
<div class="cell" data-execution_count="18">
<details class="code-fold">
<summary>Code to plot a map of the Philippines</summary>
<div class="sourceCode cell-code" id="cb18" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb18-1">fig, ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span>), frameon<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb18-2"></span>
<span id="cb18-3">ph0 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> gpd.GeoDataFrame.from_file(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ph_regions.shp"</span>)</span>
<span id="cb18-4">ph0.plot(ax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>ax, cmap<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Greens'</span>, edgecolor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'#555555'</span>, k<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">18</span>)</span>
<span id="cb18-5">ax.set_title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Regions of the Philippines'</span>)</span>
<span id="cb18-6">ax.spines[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'top'</span>].set_visible(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>)</span>
<span id="cb18-7">ax.spines[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'right'</span>].set_visible(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>)</span>
<span id="cb18-8">ax.spines[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'bottom'</span>].set_visible(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>)</span>
<span id="cb18-9">ax.spines[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'left'</span>].set_visible(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>)</span>
<span id="cb18-10"></span>
<span id="cb18-11"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> ind, row <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> ph0.iterrows():</span>
<span id="cb18-12">    ax.text(row[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"geometry"</span>].centroid.x, row[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"geometry"</span>].centroid.y,</span>
<span id="cb18-13">            row[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"region"</span>])</span></code></pre></div>
</details>
</div>
<div class="quarto-figure quarto-figure-left">
<figure class="figure">
<p><img src="https://sandrosilva.site/posts/2023-04-14-Elections/image6-map.png" class="img-fluid figure-img"></p>
<figcaption>FIGURE: Map of the Philippines</figcaption>
</figure>
</div>
<h4 class="anchored">
Looking at Senatorial Results
</h4>
<p>Let us look at the senatorial candidates. Let us total up the votes by candidate and see the top 12 winners.</p>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Index</th>
<th>Candidate</th>
<th>Votes</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>61</td>
<td>VILLAR, CYNTHIA</td>
<td>23653546.0</td>
</tr>
<tr class="even">
<td>54</td>
<td>POE, GRACE</td>
<td>20877585.0</td>
</tr>
<tr class="odd">
<td>33</td>
<td>GO, BONG GO</td>
<td>18979132.0</td>
</tr>
<tr class="even">
<td>18</td>
<td>CAYETANO, PIA</td>
<td>18287782.0</td>
</tr>
<tr class="odd">
<td>23</td>
<td>DELA ROSA, BATO</td>
<td>17396249.0</td>
</tr>
<tr class="even">
<td>7</td>
<td>ANGARA, EDGARDO SONNY</td>
<td>16826634.0</td>
</tr>
<tr class="odd">
<td>39</td>
<td>LAPID, LITO</td>
<td>16181906.0</td>
</tr>
<tr class="even">
<td>45</td>
<td>MARCOS, IMEE</td>
<td>14735294.0</td>
</tr>
<tr class="odd">
<td>59</td>
<td>TOLENTINO, FRANCIS</td>
<td>14264142.0</td>
</tr>
<tr class="even">
<td>15</td>
<td>BONG REVILLA, RAMON JR</td>
<td>13899831.0</td>
</tr>
<tr class="odd">
<td>14</td>
<td>BINAY, NANCY</td>
<td>13864931.0</td>
</tr>
<tr class="even">
<td>53</td>
<td>PIMENTEL, KOKO</td>
<td>13529531.0</td>
</tr>
</tbody>
</table>
<p>Let’s visualize this with a plot:</p>
<div class="cell" data-execution_count="19">
<details class="code-fold">
<summary>Code to plot top senators by vote</summary>
<div class="sourceCode cell-code" id="cb19" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb19-1">fig, ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>))</span>
<span id="cb19-2">plt.rcParams.update({<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'font.size'</span>: <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">14</span>})</span>
<span id="cb19-3">df_senator.set_index(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Candidate'</span>).head(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>).sort_values(</span>
<span id="cb19-4">    by<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Votes'</span>, ascending<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>).plot.barh(ax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>ax,</span>
<span id="cb19-5">    title<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Top 12 Candidates, in Millions'</span>, color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'#BF5209'</span>, legend<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb19-6">ax.set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Total Votes'</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span>im</span></code></pre></div>
</details>
</div>
<div class="quarto-figure quarto-figure-left">
<figure class="figure">
<p><img src="https://sandrosilva.site/posts/2023-04-14-Elections/image7-top12.png" class="img-fluid figure-img"></p>
<figcaption>FIGURE:Top 12 senators by vote</figcaption>
</figure>
</div>
<h4 class="anchored">
Top Senator Per Region
</h4>
<p>We want to find out won across all the regions. If there is any bias for cetain candidates. Based on our findings, we can see that candidate Cynthia Villar won majority of the regions.</p>
<p>It is interesting to note that the top ranking senator for Ilocos Region (Region I) and the Cordillera Administrative Region (CAR) is <strong>Imee Marcos</strong>, which hails from that region. This confirms that there is a “Solid North”, and that support for the Marcoses still exists in that area.</p>
<p>For the Mindanao regions, the top candidate is <strong>Bong Go</strong>, former special assistant to President Duterte, who is from Mindanao.</p>
<p>These show that Philippine politics is <strong>very regional in nature</strong>. Voters will naturally support their hometown candidate, regardless of the issues surrounding that candidate.</p>
<div class="cell" data-execution_count="20">
<details class="code-fold">
<summary>Code to get top senator by region and the associated number of votes</summary>
<div class="sourceCode cell-code" id="cb20" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb20-1">df_senator_region <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df_senators.groupby(</span>
<span id="cb20-2">    [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'candidate_name'</span>]).agg({<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'votes_per_province'</span>: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>})</span>
<span id="cb20-3">df_senator_region[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'rank'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df_senator_region.groupby(</span>
<span id="cb20-4">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region'</span>)[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'votes_per_province'</span>].rank(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'dense'</span>, ascending<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>)</span>
<span id="cb20-5">df_senator_region <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df_senator_region[df_senator_region[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'rank'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>].reset_index()</span>
<span id="cb20-6">df_senator_region.columns <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Region'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Candidate Name'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Votes'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Rank'</span>]</span>
<span id="cb20-7">df_senator_region</span></code></pre></div>
</details>
</div>
<table class="caption-top table">
<thead>
<tr class="header">
<th style="text-align: right;"></th>
<th style="text-align: left;">Region</th>
<th style="text-align: left;">Candidate Name</th>
<th style="text-align: right;">Votes</th>
<th style="text-align: right;">Rank</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td style="text-align: right;">0</td>
<td style="text-align: left;">BARMM</td>
<td style="text-align: left;">GO, BONG GO</td>
<td style="text-align: right;">768037</td>
<td style="text-align: right;">1</td>
</tr>
<tr class="even">
<td style="text-align: right;">1</td>
<td style="text-align: left;">CAR</td>
<td style="text-align: left;">MARCOS, IMEE</td>
<td style="text-align: right;">348303</td>
<td style="text-align: right;">1</td>
</tr>
<tr class="odd">
<td style="text-align: right;">2</td>
<td style="text-align: left;">NCR</td>
<td style="text-align: left;">VILLAR, CYNTHIA</td>
<td style="text-align: right;">3345089</td>
<td style="text-align: right;">1</td>
</tr>
<tr class="even">
<td style="text-align: right;">3</td>
<td style="text-align: left;">NIR</td>
<td style="text-align: left;">VILLAR, CYNTHIA</td>
<td style="text-align: right;">856992</td>
<td style="text-align: right;">1</td>
</tr>
<tr class="odd">
<td style="text-align: right;">4</td>
<td style="text-align: left;">REGION I</td>
<td style="text-align: left;">MARCOS, IMEE</td>
<td style="text-align: right;">1661318</td>
<td style="text-align: right;">1</td>
</tr>
<tr class="even">
<td style="text-align: right;">5</td>
<td style="text-align: left;">REGION II</td>
<td style="text-align: left;">VILLAR, CYNTHIA</td>
<td style="text-align: right;">915393</td>
<td style="text-align: right;">1</td>
</tr>
<tr class="odd">
<td style="text-align: right;">6</td>
<td style="text-align: left;">REGION III</td>
<td style="text-align: left;">VILLAR, CYNTHIA</td>
<td style="text-align: right;">3056167</td>
<td style="text-align: right;">1</td>
</tr>
<tr class="even">
<td style="text-align: right;">7</td>
<td style="text-align: left;">REGION IV-A</td>
<td style="text-align: left;">VILLAR, CYNTHIA</td>
<td style="text-align: right;">3660112</td>
<td style="text-align: right;">1</td>
</tr>
<tr class="odd">
<td style="text-align: right;">8</td>
<td style="text-align: left;">REGION IV-B</td>
<td style="text-align: left;">VILLAR, CYNTHIA</td>
<td style="text-align: right;">688494</td>
<td style="text-align: right;">1</td>
</tr>
<tr class="even">
<td style="text-align: right;">9</td>
<td style="text-align: left;">REGION IX</td>
<td style="text-align: left;">GO, BONG GO</td>
<td style="text-align: right;">663927</td>
<td style="text-align: right;">1</td>
</tr>
<tr class="odd">
<td style="text-align: right;">10</td>
<td style="text-align: left;">REGION V</td>
<td style="text-align: left;">POE, GRACE</td>
<td style="text-align: right;">1417114</td>
<td style="text-align: right;">1</td>
</tr>
<tr class="even">
<td style="text-align: right;">11</td>
<td style="text-align: left;">REGION VI</td>
<td style="text-align: left;">VILLAR, CYNTHIA</td>
<td style="text-align: right;">1064681</td>
<td style="text-align: right;">1</td>
</tr>
<tr class="odd">
<td style="text-align: right;">12</td>
<td style="text-align: left;">REGION VII</td>
<td style="text-align: left;">VILLAR, CYNTHIA</td>
<td style="text-align: right;">1307605</td>
<td style="text-align: right;">1</td>
</tr>
<tr class="even">
<td style="text-align: right;">13</td>
<td style="text-align: left;">REGION VIII</td>
<td style="text-align: left;">VILLAR, CYNTHIA</td>
<td style="text-align: right;">1132757</td>
<td style="text-align: right;">1</td>
</tr>
<tr class="odd">
<td style="text-align: right;">14</td>
<td style="text-align: left;">REGION X</td>
<td style="text-align: left;">GO, BONG GO</td>
<td style="text-align: right;">949392</td>
<td style="text-align: right;">1</td>
</tr>
<tr class="even">
<td style="text-align: right;">15</td>
<td style="text-align: left;">REGION XI</td>
<td style="text-align: left;">GO, BONG GO</td>
<td style="text-align: right;">1002771</td>
<td style="text-align: right;">1</td>
</tr>
<tr class="odd">
<td style="text-align: right;">16</td>
<td style="text-align: left;">REGION XII</td>
<td style="text-align: left;">VILLAR, CYNTHIA</td>
<td style="text-align: right;">983354</td>
<td style="text-align: right;">1</td>
</tr>
<tr class="even">
<td style="text-align: right;">17</td>
<td style="text-align: left;">REGION XIII</td>
<td style="text-align: left;">GO, BONG GO</td>
<td style="text-align: right;">777931</td>
<td style="text-align: right;">1</td>
</tr>
</tbody>
</table>
<div class="cell" data-execution_count="21">
<details class="code-fold">
<summary>Code to get top senator by region and the associated number of votes</summary>
<div class="sourceCode cell-code" id="cb21" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb21-1">(df_senator_region[df_senator_region[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Rank'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>].reset_index().groupby(</span>
<span id="cb21-2">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Candidate Name'</span>)[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Rank'</span>].<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>().to_frame().sort_values(by<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Rank'</span>)</span>
<span id="cb21-3"> .reset_index())</span></code></pre></div>
</details>
</div>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Candidate Name</th>
<th>Count</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>POE, GRACE</td>
<td>1.0</td>
</tr>
<tr class="even">
<td>MARCOS, IMEE</td>
<td>2.0</td>
</tr>
<tr class="odd">
<td>GO, BONG GO</td>
<td>5.0</td>
</tr>
<tr class="even">
<td>VILLAR, CYNTHIA</td>
<td>10.0</td>
</tr>
</tbody>
</table>
<div class="cell" data-execution_count="22">
<details class="code-fold">
<summary>Code</summary>
<div class="sourceCode cell-code" id="cb22" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb22-1"> fig, ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots()</span>
<span id="cb22-2">(df_senator_region[df_senator_region[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Rank'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>].reset_index().groupby(</span>
<span id="cb22-3">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Candidate Name'</span>)[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Rank'</span>].<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>().to_frame().sort_values(by<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Rank'</span>).plot</span>
<span id="cb22-4"> .barh(color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'#BF5209'</span>, ax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>ax))<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb22-5">ax.set_xlabel(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Rank'</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div>
</details>
</div>
<div class="quarto-figure quarto-figure-left">
<figure class="figure">
<p><img src="https://sandrosilva.site/posts/2023-04-14-Elections/image8-rank.png" class="img-fluid figure-img"></p>
<figcaption>FIGURE: Instances of candidate ranking 1 per province</figcaption>
</figure>
</div>
<p>As we can see, Cynthia Villar was ranked 1st 10 times, followed by Bong Go at 5 times, Imee Marcos at 2 times, and Grace Poe 1 time.</p>
<h3 class="anchored">
Step 4: Finding the Dominant Party Per Region
</h3>
<p>There are three main political parties vying for the senatorial seats:</p>
<ol>
<li>
Liberal Party
</li><li>
Nacionalista Party
</li><li>
Partito Demokratiko Pilipino Lakas ng Bayan (PDP-Laban)
</li></ol>
<p>We looked at the <font color="BF5209">dominant or majority political party</font> per administrative region, and identify if any regions have any affiliations to a certain party.</p>
<div class="cell" data-execution_count="23">
<details class="code-fold">
<summary>Code to retrieve top Party Per Region</summary>
<div class="sourceCode cell-code" id="cb23" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb23-1">df_party <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df_senators.groupby([<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region_raw'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'party_name'</span>]).agg({</span>
<span id="cb23-2">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'votes_per_province'</span>: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>})</span>
<span id="cb23-3">df_party[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'rank'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df_party.groupby(</span>
<span id="cb23-4">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region_raw'</span>)[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'votes_per_province'</span>].rank(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'dense'</span>, ascending<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>)</span>
<span id="cb23-5">df_party.reset_index(inplace<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb23-6">df_leading_party <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df_party[df_party[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'rank'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>].copy()</span>
<span id="cb23-7">df_leading_party.columns <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Region'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Party'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Votes'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Rank'</span>]</span>
<span id="cb23-8">df_leading_party.sort_values([<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Region'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Rank'</span>], inplace<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb23-9">df_leading_party.drop([<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Rank'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'index'</span>], inplace<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span></code></pre></div>
</details>
</div>
<p>This is the resulting table:</p>
<table class="caption-top table">
<colgroup>
<col style="width: 16%">
<col style="width: 68%">
<col style="width: 14%">
</colgroup>
<thead>
<tr class="header">
<th>Region</th>
<th>Party</th>
<th>Votes</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>BARMM</td>
<td>PARTIDO DEMOKRATIKO PILIPINO LAKAS NG BAYAN</td>
<td>2596572.0</td>
</tr>
<tr class="even">
<td>CAR</td>
<td>PARTIDO DEMOKRATIKO PILIPINO LAKAS NG BAYAN</td>
<td>1028536.0</td>
</tr>
<tr class="odd">
<td>NCR</td>
<td>PARTIDO DEMOKRATIKO PILIPINO LAKAS NG BAYAN</td>
<td>10400476.0</td>
</tr>
<tr class="even">
<td>REGION I</td>
<td>NACIONALISTA PARTY</td>
<td>4361859.0</td>
</tr>
<tr class="odd">
<td>REGION II</td>
<td>NACIONALISTA PARTY</td>
<td>2474544.0</td>
</tr>
<tr class="even">
<td>REGION III</td>
<td>PARTIDO DEMOKRATIKO PILIPINO LAKAS NG BAYAN</td>
<td>7804389.0</td>
</tr>
<tr class="odd">
<td>REGION IV-A</td>
<td>PARTIDO DEMOKRATIKO PILIPINO LAKAS NG BAYAN</td>
<td>9542856.0</td>
</tr>
<tr class="even">
<td>REGION IV-B</td>
<td>PARTIDO DEMOKRATIKO PILIPINO LAKAS NG BAYAN</td>
<td>1733733.0</td>
</tr>
<tr class="odd">
<td>REGION IX</td>
<td>PARTIDO DEMOKRATIKO PILIPINO LAKAS NG BAYAN</td>
<td>2571518.0</td>
</tr>
<tr class="even">
<td>REGION V</td>
<td>LIBERAL PARTY</td>
<td>4885924.0</td>
</tr>
<tr class="odd">
<td>REGION VI</td>
<td>LIBERAL PARTY</td>
<td>4335427.0</td>
</tr>
<tr class="even">
<td>REGION VII</td>
<td>PARTIDO DEMOKRATIKO PILIPINO LAKAS NG BAYAN</td>
<td>5480074.0</td>
</tr>
<tr class="odd">
<td>REGION VIII</td>
<td>PARTIDO DEMOKRATIKO PILIPINO LAKAS NG BAYAN</td>
<td>3442654.0</td>
</tr>
<tr class="even">
<td>REGION X</td>
<td>PARTIDO DEMOKRATIKO PILIPINO LAKAS NG BAYAN</td>
<td>3697535.0</td>
</tr>
<tr class="odd">
<td>REGION XI</td>
<td>PARTIDO DEMOKRATIKO PILIPINO LAKAS NG BAYAN</td>
<td>3654361.0</td>
</tr>
<tr class="even">
<td>REGION XII</td>
<td>PARTIDO DEMOKRATIKO PILIPINO LAKAS NG BAYAN</td>
<td>3861166.0</td>
</tr>
<tr class="odd">
<td>REGION XIII</td>
<td>PARTIDO DEMOKRATIKO PILIPINO LAKAS NG BAYAN</td>
<td>2858376.0</td>
</tr>
</tbody>
</table>
<p>Next, let us generate the code to create a map with majority winners.</p>
<div class="cell" data-execution_count="24">
<details class="code-fold">
<summary>Code to create a map of majority winners</summary>
<div class="sourceCode cell-code" id="cb24" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb24-1">merged <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ph0.merge(df_leading_party, left_on<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region'</span>, right_on<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Region'</span>)</span>
<span id="cb24-2">colors <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">18</span></span>
<span id="cb24-3">color_map <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'PARTIDO DEMOKRATIKO PILIPINO LAKAS NG BAYAN'</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'red'</span>, </span>
<span id="cb24-4">             <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'LIBERAL PARTY'</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'yellow'</span>,</span>
<span id="cb24-5">             <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'NACIONALISTA PARTY'</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'green'</span>}</span>
<span id="cb24-6"></span>
<span id="cb24-7">fig, ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, figsize <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>))<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb24-8">ax.set_title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Dominant political party per region'</span>, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb24-9"></span>
<span id="cb24-10"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> party <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>(merged[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Party'</span>].unique()):</span>
<span id="cb24-11">    color_map[party]</span>
<span id="cb24-12">    merged[merged[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Party'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> party].plot(ax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>ax, color <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> color_map[party], </span>
<span id="cb24-13">                                          categorical <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>, </span>
<span id="cb24-14">                                          figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>), legend<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb24-15"></span>
<span id="cb24-16">merged.geometry.boundary.plot(color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>,edgecolor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'k'</span>,linewidth <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">.5</span>,ax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>ax)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb24-17">plt.rcParams.update({<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'font.size'</span>: <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">18</span>})</span></code></pre></div>
</details>
</div>
<div class="quarto-figure quarto-figure-left">
<figure class="figure">
<p><img src="https://sandrosilva.site/posts/2023-04-14-Elections/image9-mapmajority.png" class="img-fluid figure-img"></p>
<figcaption>FIGURE: Top Party by Region</figcaption>
</figure>
</div>
<p>We can clearly see a voting bias of each region.</p>
<p>Majority of Region 1 and Region 2 has a voting preference towards the <bold>Nacionalista Party</bold>. This can be attributed to the fact that Imee Marcos, who hails from Ilocos Norte, is a Nacionalista.</p>
<p>Majority of Region 5 and Region 6 has a voting preference towards the <bold>LIberal Party</bold>. This is also expected since Leni Robredo, incumbent Vice President who is from the Liberal Party, is a Bicolano.</p>
<p>The remainder of the Philippines has a voting preference towards the <bold>PDP-LABAN</bold>.</p>
<h3 class="anchored">
Step 5: Finding the Dominant Coalition Per Region
</h3>
<p>Aside from individual candidates and parties, we also looked at the <strong>dominant coalition per region</strong> by counting the number of senate seats obtained by each coalition. The results indicate that HNP gained a majority of the seats across all regions, especially in Mindanao.</p>
<p>The only regions where HNP did not gain a solid majority are in Bicol Region (Region V) and Eastern Visayas (Region VI), known bailwicks of the Liberal Party. Below we created a function to get the number of seats won per coalition per region, and the associated map. The more seats won, the darker the color.</p>
<div class="cell" data-execution_count="25">
<details class="code-fold">
<summary>Function for get_coalition_sets()</summary>
<div class="sourceCode cell-code" id="cb25" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb25-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_coalition_seats():</span>
<span id="cb25-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb25-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Returns a dataframe of the number of seats won per coalition per region</span></span>
<span id="cb25-4"></span>
<span id="cb25-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Returns</span></span>
<span id="cb25-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    -------</span></span>
<span id="cb25-7"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    coalition : pd.DataFrame</span></span>
<span id="cb25-8"></span>
<span id="cb25-9"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    """</span></span>
<span id="cb25-10">    coalition_seats <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> nle2019.query(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'position == 1'</span>)</span>
<span id="cb25-11"></span>
<span id="cb25-12">    coalition_seats <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> coalition_seats.groupby(</span>
<span id="cb25-13">        [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'candidate_name'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'coalition'</span>],</span>
<span id="cb25-14">        as_index<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>).agg({<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'votes_per_province'</span>: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>})</span>
<span id="cb25-15">    coalition_seats <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> coalition_seats.sort_values(</span>
<span id="cb25-16">        by<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'votes_per_province'</span>], ascending<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>])</span>
<span id="cb25-17">    coalition_seats.set_index(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region'</span>, inplace<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb25-18"></span>
<span id="cb25-19">    coalition_seats[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'rank'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(</span>
<span id="cb25-20">        coalition_seats.candidate_name.unique())<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\</span></span>
<span id="cb25-21">        <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(coalition_seats.index.unique())</span>
<span id="cb25-22">    coalition_seats[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'is_top_12'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>(coalition_seats[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'rank'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>)</span>
<span id="cb25-23">    coalition_seats <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> coalition_seats.reset_index()</span>
<span id="cb25-24">    coalition_seats <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.pivot_table(</span>
<span id="cb25-25">        coalition_seats, index<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region'</span>, columns<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'coalition'</span>,</span>
<span id="cb25-26">        values<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'is_top_12'</span>, aggfunc<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>)</span>
<span id="cb25-27">    coalition_seats[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'coalition_seats_total'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> coalition_seats.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>(axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb25-28"></span>
<span id="cb25-29">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> coalition <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> coalition_seats.columns[:<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]:</span>
<span id="cb25-30">        coalition_seats[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'party_seats_pct_'</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> coalition] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\</span></span>
<span id="cb25-31">            coalition_seats[coalition] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\</span></span>
<span id="cb25-32">            coalition_seats[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'coalition_seats_total'</span>]</span>
<span id="cb25-33">        coalition_seats.rename(</span>
<span id="cb25-34">            columns<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>{coalition: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'coalition_seats_count_'</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> coalition},</span>
<span id="cb25-35">            inplace<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb25-36"></span>
<span id="cb25-37">    coalition_seats <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> coalition_seats.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">round</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>)</span>
<span id="cb25-38">    coalition_seats <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> coalition_seats.reset_index()</span>
<span id="cb25-39">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> coalition_seats</span></code></pre></div>
</details>
</div>
<div class="cell" data-execution_count="26">
<details class="code-fold">
<summary>Code to merge coalition dataframe and coalition_seat_counts, code to display heat map.</summary>
<div class="sourceCode cell-code" id="cb26" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb26-1">coalition <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> get_coalition_seats()</span>
<span id="cb26-2">merged <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ph0.merge(coalition[[</span>
<span id="cb26-3">                   <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'coalition_seats_count_HNP'</span>]], left_on<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region'</span>,</span>
<span id="cb26-4">                   right_on<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region'</span>)</span>
<span id="cb26-5"></span>
<span id="cb26-6">fig, ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span>))</span>
<span id="cb26-7">merged.plot(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'coalition_seats_count_HNP'</span>, ax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>ax, cmap<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'YlOrRd'</span>, legend<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb26-8">ax.set_title(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Number of HNP senate seats won'</span>, fontsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">24</span>)</span>
<span id="cb26-9">merged.geometry.boundary.plot(color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>, edgecolor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'k'</span>, linewidth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, ax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>ax)</span></code></pre></div>
</details>
</div>
<div class="quarto-figure quarto-figure-left">
<figure class="figure">
<p><img src="https://sandrosilva.site/posts/2023-04-14-Elections/image10-hnp.png" class="img-fluid figure-img"></p>
<figcaption>FIGURE: Number of HNP Senate Seats Won</figcaption>
</figure>
</div>
<h3 class="anchored">
Step 6: Is Demographics Related To Voting Preferences?
</h3>
<p>Is the voting preference of a region related to its demographics such as literacy rate and religious affiliation? To answer this, we obtained the <code>2015 Census Data</code>. The directory is a collection of excel files, where each excel file corresponds to a certain region and province. If we explore each file, we can see that each sheet corresponds to a different demographic feature table. For this analysis, we are intrested at sheets <code>T8</code> and <code>T11</code>.</p>
<p>The <code>get_census_religion</code> loads the imporant columns and rows from sheet <code>T8</code>. It also adds an additional column based on the region. Similarly, the <code>get_census_education</code> loads the imporant columns and rows from sheet <code>T11</code>. It also aggregates each individual years experience column into a singular cumulative column.</p>
<p>Finally, the <code>read_census_files</code> aggregates the 2016 regional data into singular dataframe by using <code>get_census_religion</code> and <code>get_census_education</code> functions. To extract only the regional files, the <code>read_census_files</code> uses regex to get filenames with only underscores in the beginning (this is an indicator of regional data).</p>
<div class="cell" data-execution_count="27">
<details class="code-fold">
<summary>Function for get_censis_religion()</summary>
<div class="sourceCode cell-code" id="cb27" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb27-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_census_religion(path):</span>
<span id="cb27-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb27-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Returns a consolidated DataFrame of census data by religion</span></span>
<span id="cb27-4"></span>
<span id="cb27-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Parameters</span></span>
<span id="cb27-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    ----------</span></span>
<span id="cb27-7"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    path      : string, filepath to census directory</span></span>
<span id="cb27-8"></span>
<span id="cb27-9"></span>
<span id="cb27-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Returns</span></span>
<span id="cb27-11"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    ----------</span></span>
<span id="cb27-12"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    df        : pd.DataFrame</span></span>
<span id="cb27-13"></span>
<span id="cb27-14"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    """</span></span>
<span id="cb27-15">    filename <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> os.path.basename(path)</span>
<span id="cb27-16">    df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.read_excel(path, sheet_name<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'T8'</span>, header<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>,</span>
<span id="cb27-17">                       usecols<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>],</span>
<span id="cb27-18">                       skiprows<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>, skip_blank_lines<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>,</span>
<span id="cb27-19">                       skipfooter<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>,</span>
<span id="cb27-20">                       names<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'religion'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'total'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'m'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'f'</span>])</span>
<span id="cb27-21">    df.sort_values(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'total'</span>, ascending<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>, inplace<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb27-22">    df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> re.search(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r'\_(.*?)\_'</span>, os.path.basename(path)).group(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb27-23">    cols <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'religion'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'m'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'f'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'total'</span>]</span>
<span id="cb27-24">    df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df[cols]</span>
<span id="cb27-25">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> df</span></code></pre></div>
</details>
</div>
<div class="cell" data-execution_count="28">
<details class="code-fold">
<summary>Function for get_census_education()</summary>
<div class="sourceCode cell-code" id="cb28" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb28-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_census_education(path):</span>
<span id="cb28-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb28-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Returns a consolidated DataFrame of census data by education</span></span>
<span id="cb28-4"></span>
<span id="cb28-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Parameters</span></span>
<span id="cb28-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    ----------</span></span>
<span id="cb28-7"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    path      : string, filepath to census directory</span></span>
<span id="cb28-8"></span>
<span id="cb28-9"></span>
<span id="cb28-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Returns</span></span>
<span id="cb28-11"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    ----------</span></span>
<span id="cb28-12"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    df        : pd.DataFrame</span></span>
<span id="cb28-13"></span>
<span id="cb28-14"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    """</span></span>
<span id="cb28-15">    filename <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> os.path.basename(path)</span>
<span id="cb28-16">    df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.read_excel(path, sheet_name<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'T11'</span>,</span>
<span id="cb28-17">                       usecols<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">17</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">18</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">19</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>],</span>
<span id="cb28-18">                       skiprows<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>,</span>
<span id="cb28-19">                       skip_blank_lines<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>, nrows<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>,</span>
<span id="cb28-20">                       names<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'education'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'18'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'19'</span>,</span>
<span id="cb28-21">                              <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'20_24'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'25_29'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'30_34'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'35_above'</span>])</span>
<span id="cb28-22">    df.dropna(how<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'any'</span>, inplace<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb28-23">    df.reset_index(inplace<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>, drop<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb28-24">    df.drop(df.index[[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">7</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">9</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">13</span>]], inplace<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb28-25">    df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'total'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'18'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'19'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'20_24'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'25_29'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb28-26">                   df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'30_34'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'35_above'</span>])</span>
<span id="cb28-27">    df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> re.search(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r'\_(.*?)\_'</span>, os.path.basename(path)).group(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb28-28">    cols <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'education'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'18'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'19'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'20_24'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'25_29'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'30_34'</span>,</span>
<span id="cb28-29">            <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'35_above'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'total'</span>]</span>
<span id="cb28-30">    df <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df[cols]</span>
<span id="cb28-31">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> df</span></code></pre></div>
</details>
</div>
<div class="cell" data-execution_count="29">
<details class="code-fold">
<summary>Function for get_census_files()</summary>
<div class="sourceCode cell-code" id="cb29" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb29-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> read_census_files(path):</span>
<span id="cb29-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">'''</span></span>
<span id="cb29-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Reads all census regional files</span></span>
<span id="cb29-4"></span>
<span id="cb29-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Parameter</span></span>
<span id="cb29-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    ---------</span></span>
<span id="cb29-7"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    path      : string, filepath to census directory</span></span>
<span id="cb29-8"></span>
<span id="cb29-9"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Returns</span></span>
<span id="cb29-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    -------</span></span>
<span id="cb29-11"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Dictionary of dataframes</span></span>
<span id="cb29-12"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    '''</span></span>
<span id="cb29-13">    total <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'religion'</span>: pd.DataFrame(),</span>
<span id="cb29-14">             <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'education'</span>: pd.DataFrame()}</span>
<span id="cb29-15"></span>
<span id="cb29-16">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> filepath <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> glob.glob(path <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">".xls"</span>, recursive<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>):</span>
<span id="cb29-17">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> re.match(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'_(?!PHILIPPINES)'</span>, os.path.basename(filepath)):</span>
<span id="cb29-18">            total[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'religion'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (total[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'religion'</span>]</span>
<span id="cb29-19">                                 .append(get_census_religion(filepath)))</span>
<span id="cb29-20">            total[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'education'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (total[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'education'</span>]</span>
<span id="cb29-21">                                  .append(get_census_education(filepath)))</span>
<span id="cb29-22">    total[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'religion'</span>].reset_index(inplace<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>, drop<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb29-23">    total[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'education'</span>].reset_index(inplace<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>, drop<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb29-24"></span>
<span id="cb29-25">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> df <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> total.values():</span>
<span id="cb29-26">        df.loc[(df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ARMM"</span>), <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'BARMM'</span></span>
<span id="cb29-27">        df.loc[(df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"MIMAROPA"</span>), <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'REGION IV-B'</span></span>
<span id="cb29-28">        df.loc[(df[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"CARAGA"</span>), <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'REGION XIII'</span></span>
<span id="cb29-29">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> total</span></code></pre></div>
</details>
</div>
<div class="cell" data-execution_count="30">
<details class="code-fold">
<summary>Code to execute get_census_education amd get_census_religion</summary>
<div class="sourceCode cell-code" id="cb30" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb30-1">census_path <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'/mnt/data/public/census/*'</span></span>
<span id="cb30-2">census_dict <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> read_census_files(census_path)</span></code></pre></div>
</details>
</div>
<h3 class="anchored">
Step 6.1: Is literacy rate related to voting preference?
</h3>
<p>We looked at the number of seats obtained by each coalition per region, then correlated it to literacy rate. Education information was obtained from the 2015 Census data.</p>
<p>We looked at the literacy rate <img src="https://latex.codecogs.com/png.latex?%5Cfrac%7Bn_%7Beducated%7D%7D%7Bn_%7Btotal%7D%7D"> of each administrative region:</p>
<div class="cell" data-execution_count="31">
<details class="code-fold">
<summary>Function for get_education_percent()</summary>
<div class="sourceCode cell-code" id="cb31" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb31-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_education_percent():</span>
<span id="cb31-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">'''</span></span>
<span id="cb31-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Gets percentage of educational level per region</span></span>
<span id="cb31-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    '''</span></span>
<span id="cb31-5">    education <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> census_dict[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'education'</span>].groupby(</span>
<span id="cb31-6">        [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'education'</span>], as_index<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>).<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>()</span>
<span id="cb31-7">    education <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.pivot_table(</span>
<span id="cb31-8">        education, index<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region'</span>, columns<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'education'</span>, values<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'total'</span>)</span>
<span id="cb31-9">    education.columns <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'education_pct_'</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> educ <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> educ <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> education.columns]</span>
<span id="cb31-10">    education[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'education_total'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> education.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>(axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb31-11">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> educ <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> education.columns[:<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]:</span>
<span id="cb31-12">        education[educ] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/=</span> education[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'education_total'</span>]</span>
<span id="cb31-13">    education.drop(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'education_total'</span>, axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, inplace<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb31-14">    education <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> education.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">round</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>)</span>
<span id="cb31-15"></span>
<span id="cb31-16">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> education</span></code></pre></div>
</details>
</div>
<div class="cell" data-execution_count="32">
<details class="code-fold">
<summary>Function for get_agg_education_percent()</summary>
<div class="sourceCode cell-code" id="cb32" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb32-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_agg_education_percent():</span>
<span id="cb32-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">'''</span></span>
<span id="cb32-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Gets aggregated percentage of educational level per region</span></span>
<span id="cb32-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    '''</span></span>
<span id="cb32-5">    df_educ <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> get_education_percent()</span>
<span id="cb32-6">    df_educ <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df_educ.reset_index()</span>
<span id="cb32-7">    df_educ[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'educated'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> df_educ[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'education_pct_No Grade Completed'</span>]</span>
<span id="cb32-8">                           <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> df_educ[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'education_pct_Not Stated'</span>])</span>
<span id="cb32-9">    df_educ[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'not_educated'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df_educ[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'education_pct_No Grade Completed'</span>]</span>
<span id="cb32-10">    df_educ[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'unknown'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df_educ[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'education_pct_Not Stated'</span>]</span>
<span id="cb32-11">    df_educ.drop(columns<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'education_pct_Academic Degree Holder'</span>,</span>
<span id="cb32-12">                          <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'education_pct_College Undergraduate'</span>,</span>
<span id="cb32-13">                          <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'education_pct_Elementary'</span>,</span>
<span id="cb32-14">                          <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'education_pct_High School'</span>,</span>
<span id="cb32-15">                          <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'education_pct_No Grade Completed'</span>,</span>
<span id="cb32-16">                          <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'education_pct_Not Stated'</span>,</span>
<span id="cb32-17">                          <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'education_pct_Post Baccalaureate'</span>,</span>
<span id="cb32-18">                          <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'education_pct_Post-Secondary'</span>,</span>
<span id="cb32-19">                          <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'education_pct_Pre-School'</span>,</span>
<span id="cb32-20">                          <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'education_pct_Special Education'</span>], inplace<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb32-21">    df_educ.set_index(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region'</span>, inplace<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb32-22">    df_educ.reset_index(inplace<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb32-23">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> df_educ</span></code></pre></div>
</details>
</div>
<div class="cell" data-execution_count="33">
<details class="code-fold">
<summary>Code to run get_agg_education_percent()</summary>
<div class="sourceCode cell-code" id="cb33" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb33-1">df_educ <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> get_agg_education_percent()</span>
<span id="cb33-2">df_educ</span></code></pre></div>
</details>
</div>
<p>The output table shows the literacy table per region. The main columns shows the percentage that are <code>educated</code>, <code>not_educated</code> and <code>unknown</code>.</p>
<table class="caption-top table">
<thead>
<tr class="header">
<th>region</th>
<th>educated</th>
<th>not_educated</th>
<th>unknown</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>BARMM</td>
<td>0.85355</td>
<td>0.14105</td>
<td>0.00540</td>
</tr>
<tr class="even">
<td>CAR</td>
<td>0.97376</td>
<td>0.02622</td>
<td>0.00002</td>
</tr>
<tr class="odd">
<td>NCR</td>
<td>0.99234</td>
<td>0.00221</td>
<td>0.00545</td>
</tr>
<tr class="even">
<td>NIR</td>
<td>0.98085</td>
<td>0.01882</td>
<td>0.00033</td>
</tr>
<tr class="odd">
<td>REGION I</td>
<td>0.99321</td>
<td>0.00679</td>
<td>0.00000</td>
</tr>
<tr class="even">
<td>REGION II</td>
<td>0.98610</td>
<td>0.01389</td>
<td>0.00001</td>
</tr>
<tr class="odd">
<td>REGION III</td>
<td>0.99355</td>
<td>0.00615</td>
<td>0.00030</td>
</tr>
<tr class="even">
<td>REGION IV-A</td>
<td>0.99473</td>
<td>0.00519</td>
<td>0.00008</td>
</tr>
<tr class="odd">
<td>REGION IV-B</td>
<td>0.96573</td>
<td>0.03417</td>
<td>0.00010</td>
</tr>
<tr class="even">
<td>REGION IX</td>
<td>0.96456</td>
<td>0.03486</td>
<td>0.00058</td>
</tr>
<tr class="odd">
<td>REGION V</td>
<td>0.99126</td>
<td>0.00851</td>
<td>0.00023</td>
</tr>
<tr class="even">
<td>REGION VI</td>
<td>0.98721</td>
<td>0.01257</td>
<td>0.00022</td>
</tr>
<tr class="odd">
<td>REGION VII</td>
<td>0.98753</td>
<td>0.01209</td>
<td>0.00038</td>
</tr>
<tr class="even">
<td>REGION VIII</td>
<td>0.97679</td>
<td>0.02297</td>
<td>0.00024</td>
</tr>
<tr class="odd">
<td>REGION X</td>
<td>0.98095</td>
<td>0.01856</td>
<td>0.00049</td>
</tr>
<tr class="even">
<td>REGION XI</td>
<td>0.97818</td>
<td>0.02050</td>
<td>0.00132</td>
</tr>
<tr class="odd">
<td>REGION XII</td>
<td>0.94792</td>
<td>0.05034</td>
<td>0.00174</td>
</tr>
<tr class="even">
<td>REGION XIII</td>
<td>0.98487</td>
<td>0.01503</td>
<td>0.00010</td>
</tr>
</tbody>
</table>
<p>We then checked if the number of seats obtained by each coalition is correlated to the literacy rate of that region. First, we obtained the number of seats obtained by each coalition per region:</p>
<div class="cell" data-execution_count="34">
<details class="code-fold">
<summary>Function for get_coalition_rank()</summary>
<div class="sourceCode cell-code" id="cb34" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb34-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_coalition_rank():</span>
<span id="cb34-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb34-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Get number of seats obtained by each coalition</span></span>
<span id="cb34-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    """</span></span>
<span id="cb34-5">    coalition_seats <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> nle2019.query(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'position == 1'</span>)</span>
<span id="cb34-6">    coalition_seats <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> coalition_seats.groupby(</span>
<span id="cb34-7">        [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'candidate_name'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'coalition'</span>], as_index<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>).agg({<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'votes_per_province'</span>: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>})</span>
<span id="cb34-8">    coalition_seats <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> coalition_seats.sort_values(</span>
<span id="cb34-9">        by<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'votes_per_province'</span>], ascending<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>])</span>
<span id="cb34-10">    coalition_seats.set_index(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region'</span>, inplace<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb34-11"></span>
<span id="cb34-12">    coalition_seats[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'rank'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(</span>
<span id="cb34-13">        coalition_seats.candidate_name.unique())<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(coalition_seats.index.unique())</span>
<span id="cb34-14">    coalition_seats[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'is_top_12'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>(coalition_seats[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'rank'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>)</span>
<span id="cb34-15">    coalition_seats.reset_index(inplace<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb34-16"></span>
<span id="cb34-17">    coalition_seats <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.pivot_table(</span>
<span id="cb34-18">        coalition_seats, index<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region'</span>, columns<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'coalition'</span>, values<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'is_top_12'</span>, aggfunc<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>)</span>
<span id="cb34-19">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> coalition_seats</span></code></pre></div>
</details>
</div>
<p>We then merge this with the education dataframe, then get the correlation by using python’s <code>corr</code> method:</p>
<div class="cell" data-execution_count="35">
<details class="code-fold">
<summary>Code to run get_agg_education_percent() and create a a correlation graph.</summary>
<div class="sourceCode cell-code" id="cb35" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb35-1">df_coal_educ <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> get_agg_education_percent().set_index(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region'</span>).join(get_coalition_rank())</span>
<span id="cb35-2">df_coal_educ[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Educated'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df_coal_educ[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'educated'</span>]</span>
<span id="cb35-3">df_coal_educ[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Not Educated'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df_coal_educ[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'not_educated'</span>]</span>
<span id="cb35-4">corr <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df_coal_educ.corr().loc[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Otso Diretso'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'HNP'</span>],[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Educated'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Not Educated'</span>]]</span>
<span id="cb35-5">colormap <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sns.diverging_palette(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, n <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)</span>
<span id="cb35-6">sns.heatmap(corr, cmap<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>colormap, annot<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>, vmin <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, vmax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div>
</details>
</div>
<div class="quarto-figure quarto-figure-left">
<figure class="figure">
<p><img src="https://sandrosilva.site/posts/2023-04-14-Elections/image11-correlation.png" class="img-fluid figure-img"></p>
<figcaption>FIGURE: Correlation Matrix between Education and Coalition</figcaption>
</figure>
</div>
<p>The Census and election data show that the voting preference of a region has no correlation with its literacy rate. We now look at religion to see if it has a correlation with the voting preference.</p>
<h3 class="anchored">
Step 6.2: Is literacy rate related to voting preference?
</h3>
<p>We also looked into the religious affiliation per region, and checked if it is correlatd with voting preference.</p>
<p>First, we obtained the distribution of religions per region from the Census data:</p>
<div class="cell" data-execution_count="36">
<details class="code-fold">
<summary>Function for get_religion_percent()</summary>
<div class="sourceCode cell-code" id="cb36" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb36-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_religion_percent():</span>
<span id="cb36-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb36-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Get percentages of religion per region</span></span>
<span id="cb36-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    """</span></span>
<span id="cb36-5">    religion <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> census_dict[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'religion'</span>].groupby(</span>
<span id="cb36-6">        [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'religion'</span>], as_index<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>).<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>()</span>
<span id="cb36-7">    religion <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pd.pivot_table(</span>
<span id="cb36-8">        religion, index<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'region'</span>, columns<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'religion'</span>, values<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'total'</span>)</span>
<span id="cb36-9">    religion.columns <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'religion_pct_'</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> rel <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> rel <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> religion.columns]</span>
<span id="cb36-10">    religion[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'religion_total'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> religion.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>(axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb36-11">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> rel <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> religion.columns[:<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]:</span>
<span id="cb36-12">        religion[rel] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/=</span> religion[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'religion_total'</span>]</span>
<span id="cb36-13">    religion.drop(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'religion_total'</span>, axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, inplace<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb36-14">    religion <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> religion.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">round</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>)</span>
<span id="cb36-15">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> religion</span>
<span id="cb36-16"></span>
<span id="cb36-17"></span>
<span id="cb36-18">df_rel <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> get_religion_percent()</span></code></pre></div>
</details>
</div>
<p>We then merged the religion census data with the coalition ranking data to check if religion has correlation with the number of seats obtained by each coalition:</p>
<div class="cell" data-execution_count="37">
<details class="code-fold">
<summary>Joining the coalition rank dataframe with the output from the get_religion_percent() function.</summary>
<div class="sourceCode cell-code" id="cb37" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb37-1">df_coal_rel <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> get_religion_percent().join(get_coalition_rank())</span></code></pre></div>
</details>
</div>
<p>From getting the correlation of the religion data with the number of seats per coalition, it is apparent that the Voting preference of a region has <strong>no correlation with its religious affiliation</strong>.</p>
<div class="cell" data-execution_count="38">
<details class="code-fold">
<summary>Code to get a correlation graph between Religion and Top Coalition Party.</summary>
<div class="sourceCode cell-code" id="cb38" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb38-1">df_coal_rel[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Roman Catholic'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df_coal_rel[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'religion_pct_Roman Catholic, including Catholic Charismatic'</span>]</span>
<span id="cb38-2">df_coal_rel[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Islam'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df_coal_rel[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'religion_pct_Islam'</span>]</span>
<span id="cb38-3">df_coal_rel[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Iglesia ni Cristo'</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df_coal_rel[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'religion_pct_Iglesia ni Cristo'</span>]</span>
<span id="cb38-4">corr <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> df_coal_rel.corr().loc[</span>
<span id="cb38-5">    [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Roman Catholic'</span>,<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Islam'</span>,<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Iglesia ni Cristo'</span>],[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'HNP'</span>,<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Otso Diretso'</span>]]</span>
<span id="cb38-6">colormap <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sns.diverging_palette(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, n <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)</span>
<span id="cb38-7">sns.heatmap(corr, cmap<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>colormap, annot<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>, vmin <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, vmax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div>
</details>
</div>
<div class="quarto-figure quarto-figure-left">
<figure class="figure">
<p><img src="https://sandrosilva.site/posts/2023-04-14-Elections/image12-correlation.png" class="img-fluid figure-img"></p>
<figcaption>FIGURE: Correlation Matrix between Religion and Coalition</figcaption>
</figure>
</div>
<h2 class="anchored" data-anchor-id="next-let-us-examine-the-obtained-dataset-with-actual-election-results.">
Conclusion
</h2>
<p>Upon checking both the Comelec 2019 Election Results and the 2015 Philippine Census data, we found out that voting preference is characterized by high regionality.</p>
<p>Candidates have a homecourt advantage, and voters tend to vote candidates or parties affiliated with their home region.</p>
<p>Also, literacy rate and religious affiliation is not correlated to voting preference.</p>
<hr>
<p><i class="appendix">Images: https://primer.com.ph/blog/2016/02/04/philippine-elections-the-culture-the-drama-the-battle-2/</i></p>


</section>

 ]]></description>
  <category>python</category>
  <category>geospatial</category>
  <guid>https://sandrosilva.site/posts/2023-04-14-Elections/</guid>
  <pubDate>Sun, 17 Apr 2022 00:00:00 GMT</pubDate>
  <media:content url="https://sandrosilva.site/posts/2023-04-14-Elections/thumbnail.jpeg" medium="image" type="image/jpeg"/>
</item>
</channel>
</rss>
