<?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>Rahul Katyayan, PhD</title>
<link>https://r2rahul.github.io/r2rahul/blog.html</link>
<atom:link href="https://r2rahul.github.io/r2rahul/blog.xml" rel="self" type="application/rss+xml"/>
<description>Technology, Mathematics, AI/ML and Finance</description>
<generator>quarto-1.9.36</generator>
<lastBuildDate>Wed, 08 Jul 2026 22:00:00 GMT</lastBuildDate>
<item>
  <title>The Notes I Did Not Want to Lose, while writing analysis code</title>
  <dc:creator>Rahul </dc:creator>
  <link>https://r2rahul.github.io/r2rahul/posts/2026-07-09-wiki-code-space/</link>
  <description><![CDATA[ 




<section id="why-this-started" class="level2 page-columns page-full">
<h2 class="anchored" data-anchor-id="why-this-started">Why This Started</h2>
<p>I began coding with a paper lab notebook beside me. In my first scientific computing exercise (a Fortran 77 bisection program), the code handled computation, but the notebook held the important reasoning: why relative error was better than absolute error in one case, why an iteration cap was necessary, and what assumptions made results trustworthy. That context made the work understandable.</p>
<p>Today, AI agents can write code quickly, but the same old problem remains: rationale gets scattered across prompts, plans, and specs. I kept losing decisions in file sprawls of prompts and agent planning docs, including simple but important choices like default parameter values and why they were chosen. I did not need more notes. I needed better links between ideas, code, and decisions <span class="citation" data-cites="karpathy_llm_wiki_2026 ond">(Karpathy 2026; Rahul 2012)</span>.</p>
<div class="no-row-height column-margin column-container"><div id="ref-karpathy_llm_wiki_2026" class="csl-entry">
Karpathy, Andrej. 2026. <em>LLM Wiki</em>. GitHub Gist. <a href="https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f">https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f</a>.
</div><div id="ref-ond" class="csl-entry">
Rahul. 2012. <em>A Survey of Wiki Based Collaborative Learning Environments for the Interdisciplinary Training of the Students in Maths and Biology</em>. Teaching. Waterloo, Canada.
</div></div></section>
<section id="how-i-built-it" class="level2 page-columns page-full">
<h2 class="anchored" data-anchor-id="how-i-built-it">How I Built It</h2>
<p><code>wiki_code_space</code> is my practical answer. It uses a lightweight wiki, semantic links, and repeatable update steps so reasoning stays close to implementation.</p>
<p>The wiki is plain Markdown in an Obsidian-friendly structure, versioned with the code, and readable by both humans and agents. It is a living layer that evolves with implementation, so context does not drift away from code over time. The prompts are designed to capture information that Graphify can interpret easily for semantic relationship inference, which supports token efficiency and faster workspace navigation in my quantitative research workflow. Because these prompts live in the wiki folder, they can be tuned to project-specific needs <span class="citation" data-cites="graphify_labs_graphify_2026">(Graphify Labs 2026)</span>.</p>
<div class="no-row-height column-margin column-container"><div id="ref-graphify_labs_graphify_2026" class="csl-entry">
Graphify Labs. 2026. <em>Graphify</em>. GitHub repository. <a href="https://github.com/Graphify-Labs/graphify">https://github.com/Graphify-Labs/graphify</a>.
</div></div><p>The wiki-code-space is a reusable template for agent-first quantitative analysis code development. So, that work becomes more reproducible, understandable, and maintainable for both <em>humans and AI agents</em>.</p>
<p>GitHub repository: <a href="https://github.com/r2rahul/wiki-code-space">https://github.com/r2rahul/wiki-code-space</a> <sup>1</sup></p>
<div class="no-row-height column-margin column-container"><div id="fn1"><p><sup>1</sup>&nbsp;The repository contains a template for a wiki-code-space project, adaptable to user specific needs.</p></div></div></section>
<section id="what-i-learned" class="level2 page-columns page-full">
<h2 class="anchored" data-anchor-id="what-i-learned">What I Learned</h2>
<p>The idea is simple: when relationships are explicit, both humans and agents work better. The idea that is conveyed is to treat code as living memory, not just execution. The workflow is similar to how we do git commits: as one unit of work is completed in our coding workflow, the wiki is similarly LLM maintained update as one unit of conceptual decisions <sup>2</sup> is made.</p>
<div class="no-row-height column-margin column-container"><div id="fn2"><p><sup>2</sup>&nbsp;The conceptual update is guided by the prompt with deterministic set of instructions to LLM, capturing what, why and where with other user specifications</p></div></div><hr>
</section>
<section id="acknowledgements" class="level2 page-columns page-full">
<h2 class="anchored" data-anchor-id="acknowledgements">Acknowledgements</h2>
<p>Code development and blog writing were assisted by Posit AI <span class="citation" data-cites="posit_ai_2026">(Posit PBC 2026)</span> and OpenAI Codex <span class="citation" data-cites="openai_codex_2021">(OpenAI 2021)</span>.</p>


<div class="no-row-height column-margin column-container"><div id="ref-posit_ai_2026" class="csl-entry">
Posit PBC. 2026. <em>Posit <span>AI</span></em>. Web. <a href="https://posit.ai/">https://posit.ai/</a>.
</div><div id="ref-openai_codex_2021" class="csl-entry">
OpenAI. 2021. <em><span>OpenAI Codex</span></em>. Web. <a href="https://openai.com/codex/">https://openai.com/codex/</a>.
</div></div>
</section>


 ]]></description>
  <category>LLM</category>
  <category>AI</category>
  <category>MCP</category>
  <category>Tutorials</category>
  <guid>https://r2rahul.github.io/r2rahul/posts/2026-07-09-wiki-code-space/</guid>
  <pubDate>Wed, 08 Jul 2026 22:00:00 GMT</pubDate>
</item>
<item>
  <title>Reproducing Gabillon (1991): Model-Implied Term Structures</title>
  <dc:creator>Rahul </dc:creator>
  <link>https://r2rahul.github.io/r2rahul/posts/2026-05-03-gabillon-model-note/</link>
  <description><![CDATA[ 




<section id="motivation" class="level2 page-columns page-full">
<h2 class="anchored" data-anchor-id="motivation">Motivation</h2>
<p>The paper by Gabillon (1991) <span class="citation" data-cites="gabillon1991">(Gabillon 1991)</span> presents a structural model of commodity futures prices that generates a rich variety of term-structure shapes and dynamics. A practical application of this model is critical for a Risk desk, much like the implementation I developed for the Trafigura Oil Trading desk while working under the Chief Risk Officer. Risk management teams require these models to accurately value complex volatile commodity derivatives, stress-test portfolios against term-structure deformations (like backwardation and contango shifts), and calculate reliable Value-at-Risk (VaR) metrics by capturing the distinct behaviors of short- and long-term price dynamics.</p>
<div class="no-row-height column-margin column-container"></div><p>Because I am intimately familiar with the model and the code required to reproduce it, I designed this project as a practical exercise in AI-assisted coding. My focus was on building the implementation plan and guiding the agent if it deviated from the set path. With minimal assistance, GitHub Copilot successfully reproduced the complex model figures purely from the analytical equations and parameter values reported in the paper.</p>
<p>It took me roughly 2-3 hours to plan the architecture and guide Copilot to produce the complete pipeline and report. Without an AI assistant, writing the boilerplate, pipeline orchestration, and analytical code manually would likely have taken 10-12 hours. This serves as a strong example of how AI can save substantial time and effort, acting as a powerful force multiplier that makes domain experts significantly more efficient in their work.</p>
</section>
<section id="study-objective-and-reconstruction-scope" class="level2 page-columns page-full">
<h2 class="anchored" data-anchor-id="study-objective-and-reconstruction-scope">Study Objective and Reconstruction Scope</h2>
<p>In this note, I reproduce the model-implied term-structure figures that can be generated directly from the analytical system and the fixed parameter values reported by Gabillon (1991) <span class="citation" data-cites="gabillon1991">(Gabillon 1991)</span>. The scope is intentionally restricted to Figures 5-9, because these panels are determined by structural equations and parameterized scenarios rather than by historical market reconstruction.</p>
<div class="no-row-height column-margin column-container"><div id="ref-gabillon1991" class="csl-entry">
Gabillon, Jacques. 1991. <span>“The Term Structure of Oil Futures Prices.”</span> <em>Oxford Institute for Energy Studies Working Paper</em>.
</div></div><p>Taken together, the figures provide a compact visual summary of the model’s main economic behaviors: Figures 5 and 6 isolate the baseline contango and backwardation regimes, Figures 7 and 8 show how short-term effects deform the front end of the curve, and Figure 9 shifts attention to the maturity profile of volatility. In practice, such figure-based intuition is useful in commodity derivatives work, including calendar-spread option analysis.</p>
<p>The reconstruction therefore emphasizes comparative statics and the geometric properties of the futures curves rather than empirical fit to dated contracts. That boundary is deliberate for a personal technical blog: the objective is to preserve an academic style of exposition while keeping the exercise fully reproducible from deterministic inputs stored in the project configuration files.</p>
</section>
<section id="model-specification-summary" class="level2 page-columns page-full">
<h2 class="anchored" data-anchor-id="model-specification-summary">Model Specification Summary</h2>
<p>Let <img src="https://latex.codecogs.com/png.latex?%5Ctau%20=%20T%20-%20t"> denote time to maturity. The constant-parameter representation (Equation 26) is implemented as:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0AF_%7B26%7D(t,%20T)%20=%20A(%5Ctau)%20S%5E%7BB(%5Ctau)%7D%20L%5E%7B1%20-%20B(%5Ctau)%7D,%0A"></p>
<p>with</p>
<p><img src="https://latex.codecogs.com/png.latex?%0AB(%5Ctau)%20=%20e%5E%7B-%5Cbeta%20%5Ctau%7D,%0A%5Cquad%0AA(%5Ctau)%20=%20%5Cexp%5Cleft(%5Cfrac%7Bv%7D%7B4%5Cbeta%7D%5Cleft(e%5E%7B-%5Cbeta%20%5Ctau%7D%20-%20e%5E%7B-2%5Cbeta%20%5Ctau%7D%5Cright)%5Cright).%0A"></p>
<p>The short-term effect specification (Equation 28) is implemented as:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0AF_%7B28%7D(t,%20T)%20=%20%5Cexp%5Cleft(%5Cfrac%7Bv%7D%7B4%5Cbeta%7D%5Cleft(e%5E%7B-%5Cbeta%20%5Ctau%7D%20-%20e%5E%7B-2%5Cbeta%20%5Ctau%7D%5Cright)%20-%20%5Cfrac%7B%5Ctheta%7D%7B%5Cbeta%20-%20q%7D%20e%5E%7B-qT%7D%5Cleft(1%20-%20e%5E%7B-(%5Cbeta%20-%20q)%5Ctau%7D%5Cright)%5Cright)%20S%5E%7BB(%5Ctau)%7D%20L%5E%7B1%20-%20B(%5Ctau)%7D.%0A"></p>
<p>For volatility term structures (Equation 23-consistent form), the instantaneous futures volatility is</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Csigma_F(%5Ctau)%20=%20%5Csqrt%7B(%5Csigma_s%20B(%5Ctau))%5E2%20+%20(%5Csigma_l(1-B(%5Ctau)))%5E2%20+%202%5Crho%5Csigma_s%5Csigma_l%20B(%5Ctau)(1-B(%5Ctau))%20%7D.%0A"></p>

<div class="no-row-height column-margin column-container"><div class="margin-aside">
<p>Parameter roles: <img src="https://latex.codecogs.com/png.latex?S"> and <img src="https://latex.codecogs.com/png.latex?L"> govern short- and long-run price anchors, <img src="https://latex.codecogs.com/png.latex?%5Cbeta"> controls mean-reversion speed, <img src="https://latex.codecogs.com/png.latex?v"> scales convexity, while <img src="https://latex.codecogs.com/png.latex?(%5Ctheta,%20q)"> govern local short-term deformation in Equation 28.</p>
</div></div><div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode markdown code-with-copy"><code class="sourceCode markdown"><span id="cb1-1"><span class="in" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">```{r setup}</span></span>
<span id="cb1-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(tidyverse)</span>
<span id="cb1-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(scales)</span>
<span id="cb1-4"></span>
<span id="cb1-5">candidate_paths <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(</span>
<span id="cb1-6">  params<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>report_data_path,</span>
<span id="cb1-7">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">file.path</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"output"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"model_only_report_inputs.rds"</span>)</span>
<span id="cb1-8">)</span>
<span id="cb1-9"></span>
<span id="cb1-10">resolved_path <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> candidate_paths[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">file.exists</span>(candidate_paths)][<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb1-11"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(resolved_path)) {</span>
<span id="cb1-12">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stop</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Could not locate model_only_report_inputs.rds for report rendering."</span>)</span>
<span id="cb1-13">}</span>
<span id="cb1-14"></span>
<span id="cb1-15">report_inputs <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">readRDS</span>(resolved_path)</span>
<span id="cb1-16">fig5_df <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> report_inputs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>fig5_df</span>
<span id="cb1-17">fig6_df <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> report_inputs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>fig6_df</span>
<span id="cb1-18">fig7_df <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> report_inputs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>fig7_df</span>
<span id="cb1-19">fig8_df <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> report_inputs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>fig8_df</span>
<span id="cb1-20">fig9_df <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> report_inputs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>fig9_df</span>
<span id="cb1-21">cfg <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> report_inputs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>cfg</span>
<span id="cb1-22"></span>
<span id="cb1-23">base_theme <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_minimal</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">base_size =</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>
<span id="cb1-24">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(</span>
<span id="cb1-25">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.minor =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_blank</span>(),</span>
<span id="cb1-26">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.title.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"plot"</span></span>
<span id="cb1-27">  )</span>
<span id="cb1-28"><span class="in" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">```</span></span></code></pre></div></div>
</div>
</section>
<section id="figure-by-figure-interpretation" class="level2 page-columns page-full">
<h2 class="anchored" data-anchor-id="figure-by-figure-interpretation">Figure-by-Figure Interpretation</h2>
<section id="figure-5-and-figure-6-no-short-term-effect" class="level3">
<h3 class="anchored" data-anchor-id="figure-5-and-figure-6-no-short-term-effect">Figure 5 and Figure 6: No Short-Term Effect</h3>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode markdown code-with-copy"><code class="sourceCode markdown"><span id="cb2-1"><span class="in" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">```{r figure-5}</span></span>
<span id="cb2-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(fig5_df, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> tau_years, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> futures_price)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb2-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_line</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">color =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#1B4965"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb2-4">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(</span>
<span id="cb2-5">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Figure 5: Backwardation without short-term effect"</span>,</span>
<span id="cb2-6">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Time to maturity (years)"</span>,</span>
<span id="cb2-7">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Futures price"</span></span>
<span id="cb2-8">  ) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb2-9">  base_theme</span>
<span id="cb2-10"><span class="in" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">```</span></span></code></pre></div></div>
<div class="cell-output-display">
<div>
<figure class="figure">
<p><img src="https://r2rahul.github.io/r2rahul/posts/2026-05-03-gabillon-model-note/index_files/figure-html/figure-5-1.png" class="img-fluid figure-img" width="672"></p>
</figure>
</div>
</div>
</div>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode markdown code-with-copy"><code class="sourceCode markdown"><span id="cb3-1"><span class="in" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">```{r figure-6}</span></span>
<span id="cb3-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(fig6_df, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> tau_years, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> futures_price)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb3-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_line</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">color =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#5A7D7C"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb3-4">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(</span>
<span id="cb3-5">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Figure 6: Contango without short-term effect"</span>,</span>
<span id="cb3-6">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Time to maturity (years)"</span>,</span>
<span id="cb3-7">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Futures price"</span></span>
<span id="cb3-8">  ) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb3-9">  base_theme</span>
<span id="cb3-10"><span class="in" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">```</span></span></code></pre></div></div>
<div class="cell-output-display">
<div>
<figure class="figure">
<p><img src="https://r2rahul.github.io/r2rahul/posts/2026-05-03-gabillon-model-note/index_files/figure-html/figure-6-1.png" class="img-fluid figure-img" width="672"></p>
</figure>
</div>
</div>
</div>
<p>Under Equation 26, the sign of <img src="https://latex.codecogs.com/png.latex?(S-L)"> determines the global slope family. When <img src="https://latex.codecogs.com/png.latex?S%20%3E%20L"> (Figure 5), the curve declines toward the long-run anchor, producing classical backwardation. When <img src="https://latex.codecogs.com/png.latex?S%20%3C%20L"> (Figure 6), the curve increases toward <img src="https://latex.codecogs.com/png.latex?L">, yielding contango. In both cases, convexity reflects finite <img src="https://latex.codecogs.com/png.latex?v"> and exponential loading through <img src="https://latex.codecogs.com/png.latex?%5Cbeta">.</p>
</section>
<section id="figure-7-and-figure-8-non-zero-theta-and-q" class="level3">
<h3 class="anchored" data-anchor-id="figure-7-and-figure-8-non-zero-theta-and-q">Figure 7 and Figure 8: Non-Zero <img src="https://latex.codecogs.com/png.latex?%5Ctheta"> and <img src="https://latex.codecogs.com/png.latex?q"></h3>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode markdown code-with-copy"><code class="sourceCode markdown"><span id="cb4-1"><span class="in" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">```{r figure-7}</span></span>
<span id="cb4-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(fig7_df, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> tau_years, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> futures_price)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb4-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_line</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">color =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#A44A3F"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb4-4">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(</span>
<span id="cb4-5">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Figure 7: Backwardation with short-term effect"</span>,</span>
<span id="cb4-6">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Time to maturity (years)"</span>,</span>
<span id="cb4-7">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Futures price"</span></span>
<span id="cb4-8">  ) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb4-9">  base_theme</span>
<span id="cb4-10"><span class="in" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">```</span></span></code></pre></div></div>
<div class="cell-output-display">
<div>
<figure class="figure">
<p><img src="https://r2rahul.github.io/r2rahul/posts/2026-05-03-gabillon-model-note/index_files/figure-html/figure-7-1.png" class="img-fluid figure-img" width="672"></p>
</figure>
</div>
</div>
</div>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode markdown code-with-copy"><code class="sourceCode markdown"><span id="cb5-1"><span class="in" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">```{r figure-8}</span></span>
<span id="cb5-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(fig8_df, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> tau_years, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> futures_price)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb5-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_line</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">color =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#B07D3C"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb5-4">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(</span>
<span id="cb5-5">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Figure 8: Contango with short-term effect"</span>,</span>
<span id="cb5-6">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Time to maturity (years)"</span>,</span>
<span id="cb5-7">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Futures price"</span></span>
<span id="cb5-8">  ) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb5-9">  base_theme</span>
<span id="cb5-10"><span class="in" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">```</span></span></code></pre></div></div>
<div class="cell-output-display">
<div>
<figure class="figure">
<p><img src="https://r2rahul.github.io/r2rahul/posts/2026-05-03-gabillon-model-note/index_files/figure-html/figure-8-1.png" class="img-fluid figure-img" width="672"></p>
</figure>
</div>
</div>
</div>
<p>Allowing non-zero <img src="https://latex.codecogs.com/png.latex?(%5Ctheta,%20q)"> introduces localized near-maturity deformation relative to the baseline Equation 26 shape. Figure 7 shows this perturbation within a backwardated regime, while Figure 8 shows the corresponding effect under contango-type parameters. The primary qualitative effect is curvature adjustment close to the short end, while long-end anchoring remains governed by <img src="https://latex.codecogs.com/png.latex?L"> and <img src="https://latex.codecogs.com/png.latex?%5Cbeta">.</p>
</section>
<section id="figure-9-volatility-term-structures-by-correlation-rho" class="level3 page-columns page-full">
<h3 class="anchored" data-anchor-id="figure-9-volatility-term-structures-by-correlation-rho">Figure 9: Volatility Term Structures by Correlation <img src="https://latex.codecogs.com/png.latex?%5Crho"></h3>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode markdown code-with-copy"><code class="sourceCode markdown"><span id="cb6-1"><span class="in" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">```{r figure-9}</span></span>
<span id="cb6-2">fig9_labels <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span></span>
<span id="cb6-3">  fig9_df <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb6-4">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">group_by</span>(rho) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb6-5">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">filter</span>(tau_years <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;">max</span>(tau_years)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb6-6">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ungroup</span>()</span>
<span id="cb6-7"></span>
<span id="cb6-8"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(fig9_df, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> tau_years, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> futures_volatility, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">color =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(rho))) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-9">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_line</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-10">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_text</span>(</span>
<span id="cb6-11">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> fig9_labels,</span>
<span id="cb6-12">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">label =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste0</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rho="</span>, rho)),</span>
<span id="cb6-13">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">hjust =</span> <span class="sc" 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="cb6-14">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>,</span>
<span id="cb6-15">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">show.legend =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span></span>
<span id="cb6-16">  ) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-17">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_color_brewer</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">palette =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Dark2"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-18">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_y_continuous</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">labels =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">percent_format</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">accuracy =</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>
<span id="cb6-19">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(</span>
<span id="cb6-20">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Figure 9: Term structures of futures price volatilities"</span>,</span>
<span id="cb6-21">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Time to maturity (years)"</span>,</span>
<span id="cb6-22">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Instantaneous volatility"</span>,</span>
<span id="cb6-23">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">color =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rho"</span></span>
<span id="cb6-24">  ) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-25">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coord_cartesian</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">clip =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"off"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-26">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(</span>
<span id="cb6-27">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.margin =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">margin</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">5.5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">60</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">5.5</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">5.5</span>),</span>
<span id="cb6-28">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">legend.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"none"</span></span>
<span id="cb6-29">  ) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-30">  base_theme</span>
<span id="cb6-31"><span class="in" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">```</span></span></code></pre></div></div>
<div class="cell-output-display">
<div>
<figure class="figure">
<p><img src="https://r2rahul.github.io/r2rahul/posts/2026-05-03-gabillon-model-note/index_files/figure-html/figure-9-1.png" class="img-fluid figure-img" width="672"></p>
</figure>
</div>
</div>
</div>
<p>The volatility panel isolates correlation sensitivity in the two-factor loading system. For interior maturities, higher <img src="https://latex.codecogs.com/png.latex?%5Crho"> increases the covariance contribution and thus shifts volatility upward, whereas lower <img src="https://latex.codecogs.com/png.latex?%5Crho"> dampens that contribution. This reproduces the expected ordering across the configured <img src="https://latex.codecogs.com/png.latex?%5Crho"> grid.</p>

<div class="no-row-height column-margin column-container"><div class="margin-aside">
<p>In this implementation, <img src="https://latex.codecogs.com/png.latex?%5Crho%20%5Cin%20%5C%7B1.0,%200.5,%200.0,%20-0.5%5C%7D"> and all other volatility parameters are fixed, making Figure 9 a clean one-parameter comparative static.</p>
</div></div></section>
</section>
<section id="methodological-limitations-and-reproducibility-boundaries" class="level2">
<h2 class="anchored" data-anchor-id="methodological-limitations-and-reproducibility-boundaries">Methodological Limitations and Reproducibility Boundaries</h2>
<p>This model-only track does not attempt historical calibration, contract roll construction, or reconstruction of the paper’s full empirical environment. Consequently, the report supports qualitative validation of curve families and equation-consistent comparative statics, but not quantitative claims about realized market pricing errors or period-specific dynamics.</p>
<p>The boundary checks embedded in the pipeline enforce structural consistency, including <img src="https://latex.codecogs.com/png.latex?F(0)=S">, long-horizon convergence to <img src="https://latex.codecogs.com/png.latex?L">, monotonicity in baseline contango/backwardation scenarios, and deterministic section completeness for this report. These gates improve reproducibility and protect against silent drift in the analytical implementation.</p>
</section>
<section id="conclusion-on-parsimonious-parameterization" class="level2">
<h2 class="anchored" data-anchor-id="conclusion-on-parsimonious-parameterization">Conclusion on Parsimonious Parameterization</h2>
<p>The results show that a compact parameter set is sufficient to reproduce key geometric families of term structures discussed in Gabillon (1991). Without data calibration, the model already captures the principal directional and curvature regimes: baseline contango/backwardation patterns, short-end deformation from non-zero short-term effects, and volatility-shape sensitivity to correlation. This confirms the explanatory value of parsimonious structural parameterization for qualitative futures-curve analysis.</p>



</section>

 ]]></description>
  <category>Research</category>
  <category>R</category>
  <category>Commodities</category>
  <category>Tutorials</category>
  <guid>https://r2rahul.github.io/r2rahul/posts/2026-05-03-gabillon-model-note/</guid>
  <pubDate>Sat, 02 May 2026 22:00:00 GMT</pubDate>
</item>
<item>
  <title>A Practical Guide to Context Management in LLM Systems</title>
  <dc:creator>Rahul </dc:creator>
  <link>https://r2rahul.github.io/r2rahul/posts/2026-05-03-mcp-context-management/</link>
  <description><![CDATA[ 




<p>When an LLM answers a question, quality depends on what context it receives and when it receives it. Too little context leads to weak answers. Too much context leads to noisy reasoning. Model Context Protocol (MCP) provides a clean way to manage this tradeoff by exposing external capabilities as tools that the model can discover and call on demand.</p>
<section id="information-flow-with-mcp" class="level2">
<h2 class="anchored" data-anchor-id="information-flow-with-mcp">Information Flow with MCP</h2>
<div class="cell" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>
<pre class="mermaid mermaid-js">sequenceDiagram
    participant User
    participant AppServer as App Server
    participant MCPClient as MCP Client
    participant MCPServer as MCP Server
    participant LLM
    participant DataSystem as Data System

    Note over User,DataSystem: Context should be delivered only when needed
    User-&gt;&gt;AppServer: "What repositories do I have?"
    AppServer-&gt;&gt;MCPClient: Request available tools
    MCPClient-&gt;&gt;MCPServer: ListToolsRequest
    MCPServer-&gt;&gt;MCPClient: ListToolsResult
    MCPClient-&gt;&gt;AppServer: Tool list
    AppServer-&gt;&gt;LLM: Query + tool schemas
    LLM-&gt;&gt;AppServer: ToolUse request
    AppServer-&gt;&gt;MCPClient: Execute selected tool
    MCPClient-&gt;&gt;MCPServer: CallToolRequest
    MCPServer-&gt;&gt;DataSystem: Fetch data
    DataSystem-&gt;&gt;MCPServer: Response
    MCPServer-&gt;&gt;MCPClient: CallToolResult
    MCPClient-&gt;&gt;AppServer: Tool result
    AppServer-&gt;&gt;LLM: toolResult
    LLM-&gt;&gt;User: Final answer
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
</section>
<section id="why-this-matters" class="level2">
<h2 class="anchored" data-anchor-id="why-this-matters">Why This Matters</h2>
<p>MCP improves reliability because the model does not need every document upfront. It can ask for exactly what it needs at the moment it needs it.</p>
<p>Key idea: context should be staged, not dumped.</p>
<ul>
<li>Stage 1: user intent and minimal prompt instructions.</li>
<li>Stage 2: tool discovery and capability selection.</li>
<li>Stage 3: focused tool execution with scoped inputs.</li>
<li>Stage 4: response synthesis from verified outputs.</li>
</ul>
<p>This is often more controllable than building a broad retrieval layer that pushes large context windows into every request.</p>
</section>
<section id="step-by-step-reading-of-the-diagram" class="level2">
<h2 class="anchored" data-anchor-id="step-by-step-reading-of-the-diagram">Step-by-Step Reading of the Diagram</h2>
<ol type="1">
<li>A user asks a question through an application server.</li>
<li>The server asks the MCP layer what tools are available.</li>
<li>The model receives the user query and tool schemas, then decides whether to call a tool.</li>
<li>The selected tool is executed through MCP against an external data system.</li>
<li>The tool result returns to the model.</li>
<li>The model produces a grounded final answer for the user.</li>
</ol>
</section>
<section id="link-to-a-concrete-example" class="level2">
<h2 class="anchored" data-anchor-id="link-to-a-concrete-example">Link to a Concrete Example</h2>
<p>For a production-style implementation of this workflow, see my post on Excel model analysis with MCP:</p>
<p><a href="../../posts/2026-04-28-excel-formula-mcp/index.html">Turning Excel Workbooks into AI-Readable Data with an MCP Server</a></p>
<p>That article shows how MCP tools can expose formula structure, dependencies, and named ranges so an LLM can migrate legacy spreadsheet logic into maintainable Python code.</p>
</section>
<section id="practical-takeaway" class="level2">
<h2 class="anchored" data-anchor-id="practical-takeaway">Practical Takeaway</h2>
<p>If you are building LLM applications, treat MCP as your context routing layer:</p>
<ul>
<li>keep tool inputs narrow,</li>
<li>return structured outputs,</li>
<li>and only provide supplemental information when a tool call proves it is necessary.</li>
</ul>
<p>This approach yields better answers, lower token waste, and more predictable behavior.</p>


</section>

 ]]></description>
  <category>LLM</category>
  <category>AI</category>
  <category>MCP</category>
  <category>Tutorials</category>
  <guid>https://r2rahul.github.io/r2rahul/posts/2026-05-03-mcp-context-management/</guid>
  <pubDate>Sat, 02 May 2026 22:00:00 GMT</pubDate>
</item>
<item>
  <title>Turning Excel Workbooks into AI-Readable Data with an MCP Server</title>
  <dc:creator>Rahul </dc:creator>
  <link>https://r2rahul.github.io/r2rahul/posts/2026-04-28-excel-formula-mcp/</link>
  <description><![CDATA[ 




<p>Excel is still where business logic lives. Pricing models, risk calculations, financial projections: they accumulate over years in workbooks that no single person fully understands anymore. When the time comes to migrate them to Python, you face the same problem every time: the formulas are all there, but the structure, the dependencies, the named ranges, and the computation order is invisible.</p>
<p>This post describes <code>excel-formula-mcp</code>, a read-only <a href="https://modelcontextprotocol.io">Model Context Protocol (MCP)</a> server that solves the structural visibility problem by exposing Excel formula analysis as structured, AI-consumable tools.</p>
<p>The inspiration to build this came from my own expereince with working with firms, which were trying to migrate there excel models to more systematic R models for automation and efficiency gain as part digitization effort within the firm. So, this is an <strong>opinionated</strong> MCP tool designed from the perspective of a quantitative analyst with the thinking hat of a forward-development engineer who frequently translates legacy Excel models into systematic Python or R models for automation and efficiency. While enterprise AI copilots have been a great help for my similar tasks, manual copy-pasting into chat is tedious. This tool automates that workflow via MCP, streamlining the process of translating Excel to Python with human-in-the-loop editing. While not a silver bullet, it provides a significant head start for understanding Excel models systematically with minimal prior Excel knowledge.</p>
<section id="the-problem-with-excel-migration" class="level2">
<h2 class="anchored" data-anchor-id="the-problem-with-excel-migration">The Problem with Excel Migration</h2>
<p>A typical legacy workbook has:</p>
<ul>
<li>Hundreds of formula cells spread across dozens of columns</li>
<li>Named ranges encoding business constants that are never documented</li>
<li>Cross-sheet references that create hidden dependencies</li>
<li>Formulas that vary row-to-row in subtle ways</li>
</ul>
<p>You can open the file in Excel and read the formulas. But reading is not understanding. To migrate faithfully to Python, you need to know:</p>
<ol type="1">
<li>Which columns are inputs (constants entered by a user) versus derived (computed from other columns)?</li>
<li>In what order must derived columns be computed?</li>
<li>What do the named ranges mean, and which formulas use them?</li>
</ol>
<p>Answering those questions manually for a 50-column workbook takes hours. With <code>excel-formula-mcp</code> and GitHub Copilot in agent mode, it takes minutes.</p>
</section>
<section id="what-is-mcp" class="level2">
<h2 class="anchored" data-anchor-id="what-is-mcp">What Is MCP?</h2>
<p>The Model Context Protocol is an open standard that lets language models call external tools in a structured, discoverable way. An MCP server declares tool schemas (name, description, input parameters). An MCP client (GitHub Copilot, Claude Desktop, or any compatible agent) can discover and call those tools dynamically during a conversation.</p>
<p>The key insight is that MCP decouples capability from model. The server knows how to read Excel files; the model knows how to reason about the results. Neither needs to know the internals of the other.</p>
</section>
<section id="architecture" class="level2">
<h2 class="anchored" data-anchor-id="architecture">Architecture</h2>
<pre class="text"><code>┌──────────────────────────────────────────────────────┐
│                    MCP Client                        │
│         (GitHub Copilot / Claude Desktop)            │
└─────────────────────┬────────────────────────────────┘
                      │ stdio (JSON-RPC)
┌─────────────────────▼────────────────────────────────┐
│              excel-formula-mcp server                │
│                  (FastMCP / Python)                  │
│                                                      │
│  ┌─────────────────┐   ┌───────────────────────────┐ │
│  │   excel_loader  │   │     formula_parser        │ │
│  │  (openpyxl +    │   │  (regex tokeniser for     │ │
│  │   LRU cache)    │   │   same-sheet, cross-sheet │ │
│  └────────┬────────┘   │   named range, external   │ │
│           │            │   refs)                   │ │
│           │            └──────────────┬────────────┘ │
│  ┌────────▼────────────────────────────▼───────────┐ │
│  │            dependency_builder                   │ │
│  │  (column-level adjacency map + flat graph)      │ │
│  └─────────────────────────────────────────────────┘ │
│                                                      │
│  Tools:                                              │
│  · excel_analyze_range                               │
│  · excel_get_column_formulas                         │
│  · excel_get_dependencies                            │
│  · excel_get_sheet_dependencies                      │
│  · excel_get_named_ranges                            │
└──────────────────────────────────────────────────────┘</code></pre>
<p>The server is intentionally layered. The three core modules handle one concern each:</p>
<ul>
<li><code>excel_loader</code>: loads and caches workbooks with <code>openpyxl</code> using an LRU cache (size 5) so repeated tool calls within a session avoid redundant disk reads.</li>
<li><code>formula_parser</code>: tokenizes raw formula strings using four compiled regular expressions to extract same-sheet references, cross-sheet references, named ranges, and external workbook references.</li>
<li><code>dependency_builder</code>: aggregates parser output across formulas to produce typed dependency details per column, then flattens those into a simple adjacency map for client consumption.</li>
</ul>
<p>The five tools are thin wrappers over these modules. They accept Pydantic v2 models for input validation, call the appropriate core functions, and return either JSON or Markdown depending on <code>response_format</code>.</p>
</section>
<section id="the-five-tools" class="level2">
<h2 class="anchored" data-anchor-id="the-five-tools">The Five Tools</h2>
<section id="excel_analyze_range" class="level3">
<h3 class="anchored" data-anchor-id="excel_analyze_range">excel_analyze_range</h3>
<p>The workhorse. Given a file path, sheet name, and A1-notation range, it returns a complete column-by-column inventory.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode json code-with-copy"><code class="sourceCode json"><span id="cb2-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb2-2">  <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">"columns"</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">:</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb2-3">    <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">"D"</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">:</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb2-4">      <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">"header"</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Revenue"</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb2-5">      <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">"formula_count"</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">:</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb2-6">      <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">"unique_templates"</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">:</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">[</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"=B{r}*C{r}"</span><span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">]</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb2-7">      <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">"constant_count"</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">:</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb2-8">      <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">"empty_count"</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">:</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb2-9">      <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">"is_fully_derived"</span><span class="fu" style="color: #4758AB;
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="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb2-10">      <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">"named_ranges_used"</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">:</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">[]</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb2-11">      <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">"cross_sheet_refs"</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">:</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">[]</span></span>
<span id="cb2-12">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb2-13">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">},</span></span>
<span id="cb2-14">  <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">"named_ranges_in_use"</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">:</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">[</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"UnitCost"</span><span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">]</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb2-15">  <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">"summary"</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">:</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">{}</span></span>
<span id="cb2-16"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">}</span></span></code></pre></div></div>
<p>This single call answers the question: what kind of column is this?</p>
</section>
<section id="excel_get_column_formulas" class="level3">
<h3 class="anchored" data-anchor-id="excel_get_column_formulas">excel_get_column_formulas</h3>
<p>Focused inspection of one column. Returns unique formula templates, formula count, constant count, and a sample of raw cell values.</p>
</section>
<section id="excel_get_dependencies" class="level3">
<h3 class="anchored" data-anchor-id="excel_get_dependencies">excel_get_dependencies</h3>
<p>Returns the column-level dependency graph. With <code>include_details: true</code>, each column entry lists four dependency categories:</p>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Category</th>
<th>Example</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>depends_on_columns</td>
<td>[“B”, “C”]</td>
</tr>
<tr class="even">
<td>depends_on_sheets</td>
<td>[“Data!B”]</td>
</tr>
<tr class="odd">
<td>depends_on_named_ranges</td>
<td>[“UnitCost”]</td>
</tr>
<tr class="even">
<td>external_references</td>
<td>[“[Rates.xlsx]”]</td>
</tr>
</tbody>
</table>
<p>With <code>include_details: false</code>, it returns a flat adjacency map that is easy to feed into a topological sort.</p>
</section>
<section id="excel_get_sheet_dependencies" class="level3">
<h3 class="anchored" data-anchor-id="excel_get_sheet_dependencies">excel_get_sheet_dependencies</h3>
<p>Returns a workbook-level inter-sheet dependency graph. It scans formula cells across all sheets (or an optional whitelist) and reports direct sheet-to-sheet edges, plus named-range bridges that implicitly connect sheets.</p>
</section>
<section id="excel_get_named_ranges" class="level3">
<h3 class="anchored" data-anchor-id="excel_get_named_ranges">excel_get_named_ranges</h3>
<p>Lists every defined name in the workbook. For each name it reports scope, target sheet, target range, and whether it is formula-based rather than a direct range reference.</p>
</section>
</section>
<section id="design-decisions" class="level2">
<h2 class="anchored" data-anchor-id="design-decisions">Design Decisions</h2>
<section id="column-level-granularity-not-cell-level" class="level3">
<h3 class="anchored" data-anchor-id="column-level-granularity-not-cell-level">Column-level granularity, not cell-level</h3>
<p>Cell-by-cell dependency graphs for a 500-row workbook are rarely usable for an LLM because they explode in edge count. Column granularity mirrors how analysts reason about spreadsheet models.</p>
</section>
<section id="read-only-by-design" class="level3">
<h3 class="anchored" data-anchor-id="read-only-by-design">Read-only by design</h3>
<p>All five tools carry read-only MCP hints. The server never writes to the workbook, which makes it safe to call repeatedly.</p>
</section>
<section id="lru-cached-workbook-loading" class="level3">
<h3 class="anchored" data-anchor-id="lru-cached-workbook-loading">LRU-cached workbook loading</h3>
<p>Large workbook loads are expensive. The LRU cache (keyed by absolute path) avoids repeated parse overhead across tool calls.</p>
</section>
<section id="pydantic-v2-input-validation" class="level3">
<h3 class="anchored" data-anchor-id="pydantic-v2-input-validation">Pydantic v2 input validation</h3>
<p>Each tool uses strict Pydantic models with <code>extra="forbid"</code>, and validates A1-range strings before any file I/O happens.</p>
</section>
</section>
<section id="the-migration-workflow" class="level2">
<h2 class="anchored" data-anchor-id="the-migration-workflow">The Migration Workflow</h2>
<p>The server includes two reusable VS Code prompt templates in <code>.github/prompts</code>.</p>
<section id="phase-1-4-analysis-excel-formula-analyze" class="level3">
<h3 class="anchored" data-anchor-id="phase-1-4-analysis-excel-formula-analyze">Phase 1-4: Analysis (/excel-formula-analyze)</h3>
<ol type="1">
<li><code>excel_get_named_ranges</code>: establish named constants vocabulary</li>
<li><code>excel_analyze_range</code>: classify columns as input, derived, or mixed</li>
<li><code>excel_get_dependencies</code> (<code>include_details: true</code>): build dependency graph and topological order</li>
<li><code>excel_get_sheet_dependencies</code>: map workbook-level cross-sheet structure</li>
</ol>
<p>Optionally, save all outputs into:</p>
<pre class="text"><code>reports/&lt;sheet_name&gt;-analysis.md</code></pre>
</section>
<section id="phase-5-migration-excel-formula-migrate" class="level3">
<h3 class="anchored" data-anchor-id="phase-5-migration-excel-formula-migrate">Phase 5: Migration (/excel-formula-migrate)</h3>
<p>The second prompt reads the analysis report and generates:</p>
<ul>
<li>Constants mapped from named ranges</li>
<li>Input schema as a typed dataclass</li>
<li>One computation stub per derived column in topological order</li>
<li>A <code>run_model()</code> orchestrator in dependency order</li>
<li>A context-sensitive migration checklist</li>
</ul>
<p>This split makes analysis reusable and allows iterative migration passes.</p>
</section>
</section>
<section id="using-the-server-with-vs-code" class="level2">
<h2 class="anchored" data-anchor-id="using-the-server-with-vs-code">Using the Server with VS Code</h2>
<p>The repository includes <code>.vscode/mcp.json</code> with a stdio server entry:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode json code-with-copy"><code class="sourceCode json"><span id="cb4-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb4-2">  <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">"servers"</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">:</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb4-3">    <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">"excel-formula-mcp"</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">:</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb4-4">      <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">"type"</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"stdio"</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb4-5">      <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">"command"</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"${env:VIRTUAL_ENV}/bin/python"</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb4-6">      <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">"args"</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">:</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">[</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"-m"</span><span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">,</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"excel_formula_mcp.server"</span><span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">]</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb4-7">      <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">"cwd"</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"${workspaceFolder}"</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb4-8">      <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">"env"</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">:</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb4-9">        <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">"PYTHONPATH"</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"${workspaceFolder}/src"</span></span>
<span id="cb4-10">      <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb4-11">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb4-12">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb4-13"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">}</span></span></code></pre></div></div>
<p>With the environment activated and the server registered, Copilot can call the tools directly from chat.</p>
<pre class="text"><code>Use excel_analyze_range to analyze sheet "Pricing" in data/stage/model.xlsx over range A1:H500, then generate a Python implementation plan.</code></pre>
</section>
<section id="limitations" class="level2">
<h2 class="anchored" data-anchor-id="limitations">Limitations</h2>
<ul>
<li><code>.xls</code> is not supported (<code>openpyxl</code> supports <code>.xlsx</code> and <code>.xlsm</code>)</li>
<li>No formula evaluation engine is included</li>
<li>No VBA analysis</li>
<li>No cross-workbook resolution</li>
<li>Dependency graph is column-level, not cell-level</li>
</ul>
</section>
<section id="stack" class="level2">
<h2 class="anchored" data-anchor-id="stack">Stack</h2>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Component</th>
<th>Library</th>
<th>Version</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>MCP server framework</td>
<td><code>mcp[cli]</code> (FastMCP)</td>
<td>&gt;= 1.3.0</td>
</tr>
<tr class="even">
<td>Excel parsing</td>
<td><code>openpyxl</code></td>
<td>&gt;= 3.1.2</td>
</tr>
<tr class="odd">
<td>Input validation</td>
<td><code>pydantic</code></td>
<td>&gt;= 2.7.0</td>
</tr>
<tr class="even">
<td>Caching</td>
<td><code>functools.lru_cache</code></td>
<td>stdlib</td>
</tr>
<tr class="odd">
<td>Tests</td>
<td><code>pytest</code> + <code>pytest-asyncio</code></td>
<td>&gt;= 8.0 / 0.23</td>
</tr>
<tr class="even">
<td>Build</td>
<td><code>hatchling</code></td>
<td>-</td>
</tr>
<tr class="odd">
<td>Python</td>
<td>Python</td>
<td>&gt;= 3.11</td>
</tr>
</tbody>
</table>
</section>
<section id="installation" class="level2">
<h2 class="anchored" data-anchor-id="installation">Installation</h2>
<p>GitHub repository: <a href="https://github.com/r2rahul/excel-formula-mcp">r2rahul/excel-formula-mcp</a></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb6-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">git</span> clone https://github.com/r2rahul/excel-formula-mcp.git</span>
<span id="cb6-2"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">cd</span> excel-formula-mcp</span>
<span id="cb6-3"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">uv</span> pip install <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-e</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">".[dev]"</span></span>
<span id="cb6-4"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">pytest</span></span></code></pre></div></div>
</section>
<section id="what-is-next" class="level2">
<h2 class="anchored" data-anchor-id="what-is-next">What Is Next</h2>
<ul>
<li>Add optional formula evaluation support</li>
<li>Add optional <code>.xls</code> ingestion path</li>
<li>Add optional cell-level dependency mode</li>
<li>Add Mermaid or DOT graph export support</li>
</ul>
<p>Source: <a href="https://github.com/r2rahul/excel-formula-mcp">excel-formula-mcp</a></p>


</section>

 ]]></description>
  <category>Python</category>
  <category>LLM</category>
  <category>AI</category>
  <category>MCP</category>
  <category>Tutorials</category>
  <category>Teaching</category>
  <guid>https://r2rahul.github.io/r2rahul/posts/2026-04-28-excel-formula-mcp/</guid>
  <pubDate>Mon, 27 Apr 2026 22:00:00 GMT</pubDate>
</item>
<item>
  <title>Simple Julia Code To Understand Merger Arbitrage Payoff</title>
  <dc:creator>Rahul </dc:creator>
  <link>https://r2rahul.github.io/r2rahul/posts/2025-03-26-merger/</link>
  <description><![CDATA[ 




<p>A simple model to calculate merger arbitrage payoff. By varying the input parameters like offer ratio will help students understand the payoff structure.</p>
<div id="2" class="cell" data-execution_count="1">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode markdown code-with-copy"><code class="sourceCode markdown"><span id="cb1-1"><span class="in" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">```{julia}</span></span>
<span id="cb1-2"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Define a struct for Merger Arbitrage parameters</span></span>
<span id="cb1-3"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">struct</span> MergerArbitrage</span>
<span id="cb1-4">    target_shares<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;">Int       </span><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Number of target shares purchased</span></span>
<span id="cb1-5">    acquirer_shares_short<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;">Int </span><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Number of acquirer shares shorted</span></span>
<span id="cb1-6">    target_price<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;">Float64    </span><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Current price of target shares</span></span>
<span id="cb1-7">    acquirer_price<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;">Float64  </span><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Current price of acquirer shares</span></span>
<span id="cb1-8">    offer_ratio<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;">Float64     </span><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Exchange ratio (e.g., 1:1, 2:1, etc.)</span></span>
<span id="cb1-9">    target_price_failure<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;">Float64 </span><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Expected price of target shares if merger fails</span></span>
<span id="cb1-10"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">end</span></span>
<span id="cb1-11"></span>
<span id="cb1-12"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Function to calculate payoff when merger succeeds</span></span>
<span id="cb1-13"><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;">calculate_success_payoff</span>(params<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;">MergerArbitrage</span>)</span>
<span id="cb1-14">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Calculate cost of buying target shares</span></span>
<span id="cb1-15">    cost_of_target <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> params.target_shares <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> params.target_price</span>
<span id="cb1-16">    </span>
<span id="cb1-17">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Calculate proceeds from short selling acquirer shares</span></span>
<span id="cb1-18">    proceeds_from_short <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> params.acquirer_shares_short <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> params.acquirer_price</span>
<span id="cb1-19">    </span>
<span id="cb1-20">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Calculate value of converted acquirer shares from target shares (post-merger)</span></span>
<span id="cb1-21">    converted_acquirer_shares <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> params.target_shares <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> params.offer_ratio</span>
<span id="cb1-22">    value_of_converted_acquirer_shares <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> converted_acquirer_shares <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> params.acquirer_price</span>
<span id="cb1-23">    </span>
<span id="cb1-24">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Use converted shares to cover short position (proceeds already received)</span></span>
<span id="cb1-25">    payoff <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> value_of_converted_acquirer_shares <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> cost_of_target <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> proceeds_from_short</span>
<span id="cb1-26">    </span>
<span id="cb1-27">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> payoff</span>
<span id="cb1-28"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">end</span></span>
<span id="cb1-29"></span>
<span id="cb1-30"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Function to calculate payoff when merger fails</span></span>
<span id="cb1-31"><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;">calculate_failure_payoff</span>(params<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;">MergerArbitrage</span>)</span>
<span id="cb1-32">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Calculate cost of buying target shares</span></span>
<span id="cb1-33">    cost_of_target <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> params.target_shares <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> params.target_price</span>
<span id="cb1-34">    </span>
<span id="cb1-35">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Calculate proceeds from short selling acquirer shares</span></span>
<span id="cb1-36">    proceeds_from_short <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> params.acquirer_shares_short <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> params.acquirer_price</span>
<span id="cb1-37">    </span>
<span id="cb1-38">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Calculate value of target shares after failure (expected drop in price)</span></span>
<span id="cb1-39">    value_of_target_after_failure <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> params.target_shares <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> params.target_price_failure</span>
<span id="cb1-40">    </span>
<span id="cb1-41">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Calculate cost to cover short position (repurchase acquirer shares)</span></span>
<span id="cb1-42">    cost_to_cover_short <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> params.acquirer_shares_short <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> params.acquirer_price</span>
<span id="cb1-43">    </span>
<span id="cb1-44">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Net payoff in case of failure</span></span>
<span id="cb1-45">    payoff <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> value_of_target_after_failure <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> cost_to_cover_short <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> proceeds_from_short <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> cost_of_target</span>
<span id="cb1-46">    </span>
<span id="cb1-47">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> payoff</span>
<span id="cb1-48"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">end</span></span>
<span id="cb1-49"></span>
<span id="cb1-50"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Example Usage</span></span>
<span id="cb1-51"></span>
<span id="cb1-52"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Define parameters for the merger arbitrage scenario</span></span>
<span id="cb1-53">params <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;">MergerArbitrage</span>(</span>
<span id="cb1-54">    <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">20000</span>,          <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># target_shares</span></span>
<span id="cb1-55">    <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">10000</span>,          <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># acquirer_shares_short</span></span>
<span id="cb1-56">    <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">19.0</span>,           <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># target_price</span></span>
<span id="cb1-57">    <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">42.0</span>,           <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># acquirer_price</span></span>
<span id="cb1-58">    <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.0</span>,            <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># offer_ratio</span></span>
<span id="cb1-59">    <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">15.0</span>            <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># target_price_failure</span></span>
<span id="cb1-60">)</span>
<span id="cb1-61"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Calculate payoffs for both scenarios</span></span>
<span id="cb1-62">success_payoff <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;">calculate_success_payoff</span>(params)</span>
<span id="cb1-63">failure_payoff <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;">calculate_failure_payoff</span>(params)</span>
<span id="cb1-64"></span>
<span id="cb1-65"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Print results</span></span>
<span id="cb1-66"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">println</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Payoff if merger succeeds: \$</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>(success_payoff)<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb1-67"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">println</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Payoff if merger fails: \$</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>(failure_payoff)<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb1-68"></span>
<span id="cb1-69"><span class="in" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">```</span></span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>Payoff if merger succeeds: $460000.0
Payoff if merger fails: $-80000.0</code></pre>
</div>
</div>



 ]]></description>
  <category>Julia</category>
  <category>Functional Programming</category>
  <category>Teaching</category>
  <category>Tutorials</category>
  <guid>https://r2rahul.github.io/r2rahul/posts/2025-03-26-merger/</guid>
  <pubDate>Tue, 25 Mar 2025 23:00:00 GMT</pubDate>
</item>
<item>
  <title>Project Euler: Problem 2</title>
  <dc:creator>Rahul </dc:creator>
  <link>https://r2rahul.github.io/r2rahul/posts/2025-02-02-peuler2/</link>
  <description><![CDATA[ 




<p>The report also available at: <a href="https://r2rahul.quarto.pub/projeuler-no2/">Project Euler Problem 2</a></p>
<section id="problem-statement" class="level2 page-columns page-full">
<h2 class="anchored" data-anchor-id="problem-statement">Problem Statement</h2>
<p>Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with <img src="https://latex.codecogs.com/png.latex?1"> and <img src="https://latex.codecogs.com/png.latex?2">, the first <img src="https://latex.codecogs.com/png.latex?10"> terms will be: <img src="https://latex.codecogs.com/png.latex?1,%202,%203,%205,%208,%2013,%2021,%2034,%2055,%2089,%20%5Cdots"></p>
<p>By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms<span class="citation" data-cites="projecteuler2">(Euler n.d.)</span>.</p>
<div class="no-row-height column-margin column-container"><div id="ref-projecteuler2" class="csl-entry">
Euler, Project. n.d. <em>Problem 2: Even Fibonacci Numbers</em>. <a href="https://projecteuler.net/problem=2">https://projecteuler.net/problem=2</a>.
</div></div></section>
<section id="understanding-the-problem" class="level2 page-columns page-full">
<h2 class="anchored" data-anchor-id="understanding-the-problem">Understanding the Problem</h2>
<p>First, let us understand the problem structure using recommended structure of Polya <span class="citation" data-cites="polya2014solve">(Polya 2014)</span>.</p>
<div class="no-row-height column-margin column-container"><div id="ref-polya2014solve" class="csl-entry">
Polya, G. 2014. <em>How to Solve It: A New Aspect of Mathematical Method</em>. Princeton Science Library. Princeton University Press.
</div></div><ol type="1">
<li><p>Understanding the problem:</p>
<ul>
<li>What is given?
<ul>
<li>The Fibonacci sequence starts with 1 and 2.</li>
<li>Each subsequent term is the sum of the two preceding ones.</li>
<li>We need to consider terms not exceeding 4 million.</li>
</ul></li>
<li>What is required?
<ul>
<li>To find the sum of even-valued terms in this sequence.</li>
</ul></li>
<li>What are the constraints?
<ul>
<li>Only consider terms up to 4 million.</li>
<li>Only sum the even-valued terms.</li>
</ul></li>
<li>Can we break it down?
<ul>
<li>Generate Fibonacci sequence up to 4 million.</li>
<li>Filter out odd terms.</li>
<li>Sum the remaining even terms.</li>
</ul></li>
</ul></li>
</ol>
<section id="computation-code-structure" class="level3 page-columns page-full">
<h3 class="anchored" data-anchor-id="computation-code-structure">Computation Code Structure</h3>
<section id="inputs" class="level4">
<h4 class="anchored" data-anchor-id="inputs">Inputs:</h4>
<ul>
<li>Fibonacci sequence starting with terms <code>1</code> and <code>2</code>.</li>
<li>Upper limit: <code>4,000,000</code>.</li>
</ul>
</section>
<section id="outputs" class="level4">
<h4 class="anchored" data-anchor-id="outputs">Outputs:</h4>
<ul>
<li>The sum of all even-valued terms in the sequence below <code>4,000,000</code>.</li>
</ul>
</section>
<section id="constraints" class="level4">
<h4 class="anchored" data-anchor-id="constraints">Constraints:</h4>
<ul>
<li>Sequence stops when a term exceeds <code>4,000,000</code>.</li>
</ul>
</section>
<section id="steps" class="level4 page-columns page-full">
<h4 class="anchored" data-anchor-id="steps">Steps:</h4>
<ol type="1">
<li>Iterate through Fibonacci sequence up to <code>4,000,000</code>.</li>
<li>Filter the sequence to keep only even-valued terms.</li>
<li>Compute the sum of the filtered terms.</li>
<li>Return the computed sum.</li>
</ol>
<p>Note: After some experimentation with different methods to generate the Fibonacci sequence to manage integer overflow and stack overflow errors in recursive formulas, I narrowed down to using Binet’s formula. The Binet implementation is adapted from Jan Vanhove’s blog <span class="citation" data-cites="j_fib">(Vanhove n.d.)</span>.</p>
<div class="no-row-height column-margin column-container"><div id="ref-j_fib" class="csl-entry">
Vanhove, Jan. n.d. <em>Adjusting to Julia: Generating the Fibonacci Sequence</em>. <a href="https://www.juliabloggers.com/adjusting-to-julia-generating-the-fibonacci-sequence/">https://www.juliabloggers.com/adjusting-to-julia-generating-the-fibonacci-sequence/</a>.
</div></div></section>
</section>
</section>
<section id="solution" class="level2 page-columns page-full">
<h2 class="anchored" data-anchor-id="solution">Solution</h2>
<div id="2" class="cell" data-execution_count="1">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="annotated-cell-1" style="background: #f1f3f5;"><pre class="sourceCode markdown code-annotation-code code-with-copy code-annotated"><code class="sourceCode markdown"><span id="annotated-cell-1-1"><span class="in" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">```{julia}</span></span>
<span id="annotated-cell-1-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">using</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">.Iterators</span></span>
<span id="annotated-cell-1-3"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="annotated-cell-1-4"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">    fib_binet(n::Integer) -&gt; BigInt</span></span>
<span id="annotated-cell-1-5"></span>
<span id="annotated-cell-1-6"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">Calculate the nth Fibonacci number using Binet's formula.</span></span>
<span id="annotated-cell-1-7"></span>
<span id="annotated-cell-1-8"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">This function uses Binet's formula to compute the nth Fibonacci number.</span></span>
<span id="annotated-cell-1-9"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">It's more efficient than recursive methods for large n, but may lose</span></span>
<span id="annotated-cell-1-10"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">precision for very large n due to floating-point arithmetic.</span></span>
<span id="annotated-cell-1-11"></span>
<span id="annotated-cell-1-12"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">Parameters:</span></span>
<span id="annotated-cell-1-13"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">    n::Integer : The index of the Fibonacci number to calculate (n ≥ 0)</span></span>
<span id="annotated-cell-1-14"></span>
<span id="annotated-cell-1-15"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">Returns:</span></span>
<span id="annotated-cell-1-16"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">    BigInt : The nth Fibonacci number</span></span>
<span id="annotated-cell-1-17"></span>
<span id="annotated-cell-1-18"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">Examples:</span></span>
<span id="annotated-cell-1-19"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">    julia&gt; fib_binet(10)</span></span>
<span id="annotated-cell-1-20"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">    BigInt(55)</span></span>
<span id="annotated-cell-1-21"></span>
<span id="annotated-cell-1-22"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">    julia&gt; fib_binet(100)</span></span>
<span id="annotated-cell-1-23"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">    BigInt(354224848179261915075)</span></span>
<span id="annotated-cell-1-24"></span>
<span id="annotated-cell-1-25"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">Note:</span></span>
<span id="annotated-cell-1-26"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">    This function returns a BigInt to handle large Fibonacci numbers.</span></span>
<span id="annotated-cell-1-27"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">    For very large n, consider using methods that don't rely on floating-point arithmetic.</span></span>
<span id="annotated-cell-1-28"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="annotated-cell-1-29"><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;">fib_binet</span>(n<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;">Integer</span>)</span>
<a class="code-annotation-anchor" data-target-cell="annotated-cell-1" data-target-annotation="1" onclick="event.preventDefault();">1</a><span id="annotated-cell-1-30" class="code-annotation-target">    <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">φ</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;">1</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;">sqrt</span>(<span class="fl" 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="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="annotated-cell-1-31">    ψ <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</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;">sqrt</span>(<span class="fl" 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="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<a class="code-annotation-anchor" data-target-cell="annotated-cell-1" data-target-annotation="2" onclick="event.preventDefault();">2</a><span id="annotated-cell-1-32" class="code-annotation-target">    fib_n <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</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;">sqrt</span>(<span class="fl" 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="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">φ</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;">-</span> ψ<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span>n)</span>
<a class="code-annotation-anchor" data-target-cell="annotated-cell-1" data-target-annotation="3" onclick="event.preventDefault();">3</a><span id="annotated-cell-1-33" class="code-annotation-target">    <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;">BigInt</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(fib_n))</span>
<span id="annotated-cell-1-34"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">end</span></span>
<span id="annotated-cell-1-35"></span>
<span id="annotated-cell-1-36"><span class="in" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">```</span></span><div class="code-annotation-gutter-bg"></div><div class="code-annotation-gutter"></div></code></pre></div></div>
<div class="cell-annotation">
<dl class="code-annotation-container-grid">
<dt data-target-cell="annotated-cell-1" data-target-annotation="1">1</dt>
<dd>
<span data-code-cell="annotated-cell-1" data-code-lines="30,31" data-code-annotation="1">Calculate the golden ratio (φ) and its conjugate (ψ)</span>
</dd>
<dt data-target-cell="annotated-cell-1" data-target-annotation="2">2</dt>
<dd>
<span data-code-cell="annotated-cell-1" data-code-lines="32" data-code-annotation="2">Apply Binet’s formula to compute the nth Fibonacci number</span>
</dd>
<dt data-target-cell="annotated-cell-1" data-target-annotation="3">3</dt>
<dd>
<span data-code-cell="annotated-cell-1" data-code-lines="33" data-code-annotation="3">Round the result and convert it to a BigInt for precision</span>
</dd>
</dl>
</div>
<div class="cell-output cell-output-display" data-execution_count="1">
<pre><code>Main.Notebook.fib_binet</code></pre>
</div>
</div>
<div id="4" class="cell" data-execution_count="1">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="annotated-cell-2" style="background: #f1f3f5;"><pre class="sourceCode markdown code-annotation-code code-with-copy code-annotated"><code class="sourceCode markdown"><span id="annotated-cell-2-1"><span class="in" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">```{julia}</span></span>
<span id="annotated-cell-2-2"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="annotated-cell-2-3"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">    sum_even_fibonacci(limit::Int) -&gt; BigInt</span></span>
<span id="annotated-cell-2-4"></span>
<span id="annotated-cell-2-5"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">Calculate the sum of even-valued Fibonacci numbers not exceeding the given limit.</span></span>
<span id="annotated-cell-2-6"></span>
<span id="annotated-cell-2-7"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">This function generates Fibonacci numbers using Binet's formula, filters for even terms,</span></span>
<span id="annotated-cell-2-8"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">and sums them up to the specified limit.</span></span>
<span id="annotated-cell-2-9"></span>
<span id="annotated-cell-2-10"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">Parameters:</span></span>
<span id="annotated-cell-2-11"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">    limit::Int : The upper bound for Fibonacci numbers to consider</span></span>
<span id="annotated-cell-2-12"></span>
<span id="annotated-cell-2-13"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">Returns:</span></span>
<span id="annotated-cell-2-14"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">    BigInt : The sum of even Fibonacci numbers not exceeding the limit</span></span>
<span id="annotated-cell-2-15"></span>
<span id="annotated-cell-2-16"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">Example:</span></span>
<span id="annotated-cell-2-17"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">    julia&gt; sum_even_fibonacci(4_000_000)</span></span>
<span id="annotated-cell-2-18"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">    BigInt(4613732)</span></span>
<span id="annotated-cell-2-19"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="annotated-cell-2-20"><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;">sum_even_fibonacci</span>(limit<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;">Int</span>)</span>
<span id="annotated-cell-2-21">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Create an infinite sequence of Fibonacci terms using Binet's formula</span></span>
<a class="code-annotation-anchor" data-target-cell="annotated-cell-2" data-target-annotation="1" onclick="event.preventDefault();">1</a><span id="annotated-cell-2-22" class="code-annotation-target">    fib_sequence <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;">fib_binet</span>(n) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> n <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="fl" 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="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">BigInt</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">typemax</span>(<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Int</span>)))</span>
<span id="annotated-cell-2-23"></span>
<span id="annotated-cell-2-24">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Take terms until they exceed the limit and collect into an array</span></span>
<a class="code-annotation-anchor" data-target-cell="annotated-cell-2" data-target-annotation="2" onclick="event.preventDefault();">2</a><span id="annotated-cell-2-25" class="code-annotation-target">    filtered_terms <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;">collect</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">takewhile</span>(x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> limit, fib_sequence))</span>
<span id="annotated-cell-2-26"></span>
<span id="annotated-cell-2-27">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Filter even terms and sum them</span></span>
<a class="code-annotation-anchor" data-target-cell="annotated-cell-2" data-target-annotation="3" onclick="event.preventDefault();">3</a><span id="annotated-cell-2-28" class="code-annotation-target">    even_sum <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;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">filter</span>(x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> x <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> <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</span>, filtered_terms))</span>
<span id="annotated-cell-2-29"></span>
<span id="annotated-cell-2-30">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> even_sum</span>
<span id="annotated-cell-2-31"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">end</span></span>
<span id="annotated-cell-2-32"><span class="in" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">```</span></span><div class="code-annotation-gutter-bg"></div><div class="code-annotation-gutter"></div></code></pre></div></div>
<div class="cell-annotation">
<dl class="code-annotation-container-grid">
<dt data-target-cell="annotated-cell-2" data-target-annotation="1">1</dt>
<dd>
<span data-code-cell="annotated-cell-2" data-code-lines="22" data-code-annotation="1">Generate an infinite sequence of Fibonacci numbers using the <code>fib_binet</code> function (assumed to be defined elsewhere).</span>
</dd>
<dt data-target-cell="annotated-cell-2" data-target-annotation="2">2</dt>
<dd>
<span data-code-cell="annotated-cell-2" data-code-lines="25" data-code-annotation="2">Use <code>takewhile</code> to collect Fibonacci numbers up to the specified limit.</span>
</dd>
<dt data-target-cell="annotated-cell-2" data-target-annotation="3">3</dt>
<dd>
<span data-code-cell="annotated-cell-2" data-code-lines="28" data-code-annotation="3">Filter the even terms and calculate their sum.</span>
</dd>
</dl>
</div>
<div class="cell-output cell-output-display" data-execution_count="1">
<pre><code>Main.Notebook.sum_even_fibonacci</code></pre>
</div>
</div>
<p>First draft of annotation generated with the assistance of Perplexity AI, then edited to enhance language specificity and clarity <span class="citation" data-cites="perplexity2025">(Perplexity AI 2025)</span>.</p>
<div class="no-row-height column-margin column-container"><div id="ref-perplexity2025" class="csl-entry">
Perplexity AI. 2025. <em>Perplexity AI</em>. <a href="https://www.perplexity.ai" class="uri">Https://www.perplexity.ai</a>.
</div></div><section id="result" class="level3">
<h3 class="anchored" data-anchor-id="result">Result</h3>
<div id="6" class="cell" data-execution_count="1">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode markdown code-with-copy"><code class="sourceCode markdown"><span id="cb3-1"><span class="in" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">```{julia}</span></span>
<span id="cb3-2">limit <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;">4_000_000</span></span>
<span id="cb3-3">result <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;">sum_even_fibonacci</span>(limit)</span>
<span id="cb3-4"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">println</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"The sum of even Fibonacci terms below </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>limit<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;"> is: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>result<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb3-5"><span class="in" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">```</span></span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>The sum of even Fibonacci terms below 4000000 is: 4613732</code></pre>
</div>
</div>



</section>
</section>

 ]]></description>
  <category>Julia</category>
  <category>Functional Programming</category>
  <category>Teaching</category>
  <category>Tutorials</category>
  <guid>https://r2rahul.github.io/r2rahul/posts/2025-02-02-peuler2/</guid>
  <pubDate>Thu, 13 Mar 2025 23:00:00 GMT</pubDate>
</item>
<item>
  <title>Estimating Pi through Monte Carlo Simualtion</title>
  <dc:creator>Rahul </dc:creator>
  <link>https://r2rahul.github.io/r2rahul/posts/2025-01-14-buffon/</link>
  <description><![CDATA[ 




<p>The report also available at: <a href="https://r2rahul.quarto.pub/estimating-pi-through-monte-carlo-simualtion/">estimating pi through monte carlo simualtion</a></p>
<section id="problem-statement" class="level2">
<h2 class="anchored" data-anchor-id="problem-statement">Problem Statement</h2>
<p>Implement a Monte Carlo simulation based on Buffon’s needle problem to estimate the value of <img src="https://latex.codecogs.com/png.latex?%5Cpi">. Buffon’s needle is a classic problem in probability theory that relates the probability of a needle crossing parallel lines on a plane to the value of <img src="https://latex.codecogs.com/png.latex?%5Cpi">.</p>
</section>
<section id="solution-plan-for-the-problem" class="level2 page-columns page-full">
<h2 class="anchored" data-anchor-id="solution-plan-for-the-problem">Solution Plan for the Problem</h2>
<ol type="1">
<li><p>Understanding the problem <span class="citation" data-cites="polya2014solve">(Polya 2014)</span>:</p>
<ul>
<li>What is given?
<ul>
<li>Buffon’s needle problem: A method to estimate <img src="https://latex.codecogs.com/png.latex?%5Cpi"> using Monte Carlo simulation.</li>
<li>We need to simulate dropping needles on a lined surface.</li>
</ul></li>
<li>What is required?
<ul>
<li>To estimate the value of <img src="https://latex.codecogs.com/png.latex?%5Cpi"> using this method.</li>
</ul></li>
<li>What are the key components?
<ul>
<li>A surface with parallel lines</li>
<li>Needles of a specific length</li>
<li>Random tosses of needles</li>
<li>Counting needle crossings with lines</li>
</ul></li>
<li>How does it relate to <img src="https://latex.codecogs.com/png.latex?%5Cpi">?
<ul>
<li>The probability of a needle crossing a line is related to <img src="https://latex.codecogs.com/png.latex?%5Cpi">.</li>
</ul></li>
<li>Can we break it down?
<ul>
<li>Define the surface and needle parameters</li>
<li>Implement a function to toss a needle</li>
<li>Implement a function to check if a needle crosses a line</li>
<li>Perform many tosses and count crossings</li>
<li>Use the count to estimate <img src="https://latex.codecogs.com/png.latex?%5Cpi"></li>
</ul></li>
</ul></li>
</ol>
<div class="no-row-height column-margin column-container"><div id="ref-polya2014solve" class="csl-entry">
Polya, G. 2014. <em>How to Solve It: A New Aspect of Mathematical Method</em>. Princeton Science Library. Princeton University Press.
</div></div><section id="simulation-steps-breakdown" class="level3">
<h3 class="anchored" data-anchor-id="simulation-steps-breakdown">Simulation Steps Breakdown</h3>
<section id="define-parameters" class="level4">
<h4 class="anchored" data-anchor-id="define-parameters">Define Parameters</h4>
<ul>
<li>Set floor width and line spacing</li>
<li>Set needle length</li>
<li>Set number of tosses</li>
</ul>
</section>
<section id="implement-needle-toss-function" class="level4">
<h4 class="anchored" data-anchor-id="implement-needle-toss-function">Implement Needle Toss Function</h4>
<ul>
<li>Generate random x-coordinate</li>
<li>Generate random angle</li>
</ul>
</section>
<section id="implement-line-crossing-check-function" class="level4">
<h4 class="anchored" data-anchor-id="implement-line-crossing-check-function">Implement Line Crossing Check Function</h4>
<ul>
<li>Calculate needle endpoints</li>
<li>Check if endpoints are on different sides of a line</li>
</ul>
</section>
<section id="perform-monte-carlo-simulation" class="level4">
<h4 class="anchored" data-anchor-id="perform-monte-carlo-simulation">Perform Monte Carlo Simulation</h4>
<ul>
<li>For each toss:
<ul>
<li>Toss a needle</li>
<li>Check if it crosses a line</li>
<li>Count total crosses</li>
</ul></li>
</ul>
</section>
<section id="estimate-pi" class="level4">
<h4 class="anchored" data-anchor-id="estimate-pi">Estimate <img src="https://latex.codecogs.com/png.latex?%5Cpi"></h4>
<ul>
<li>Use the formula:</li>
</ul>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cpi%20%5Capprox%20%5Cfrac%7B2%20*%20needle%5C_length%20*%20number%5C_of%5C_tosses%7D%7Bline%5C_spacing%20*%20number%5C_of%5C_crosses%7D%0A"></p>
</section>
</section>
</section>
<section id="solution" class="level2">
<h2 class="anchored" data-anchor-id="solution">Solution</h2>
<p>Stepwise implementation of the Problem in Julia code.</p>
<div id="2" class="cell" data-execution_count="1">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="annotated-cell-1" style="background: #f1f3f5;"><pre class="sourceCode markdown code-annotation-code code-with-copy code-annotated"><code class="sourceCode markdown"><span id="annotated-cell-1-1"><span class="in" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">```{julia}</span></span>
<a class="code-annotation-anchor" data-target-cell="annotated-cell-1" data-target-annotation="1" onclick="event.preventDefault();">1</a><span id="annotated-cell-1-2" class="code-annotation-target"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">using</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">Random</span></span>
<a class="code-annotation-anchor" data-target-cell="annotated-cell-1" data-target-annotation="2" onclick="event.preventDefault();">2</a><span id="annotated-cell-1-3" class="code-annotation-target"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">using</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">Distributed</span></span>
<a class="code-annotation-anchor" data-target-cell="annotated-cell-1" data-target-annotation="3" onclick="event.preventDefault();">3</a><span id="annotated-cell-1-4" class="code-annotation-target"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">Random</span>.<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seed!</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1275</span>)</span>
<span id="annotated-cell-1-5"><span class="in" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">```</span></span><div class="code-annotation-gutter-bg"></div><div class="code-annotation-gutter"></div></code></pre></div></div>
<div class="cell-annotation">
<dl class="code-annotation-container-grid">
<dt data-target-cell="annotated-cell-1" data-target-annotation="1">1</dt>
<dd>
<span data-code-cell="annotated-cell-1" data-code-lines="2" data-code-annotation="1">Import the Random module for generating random numbers</span>
</dd>
<dt data-target-cell="annotated-cell-1" data-target-annotation="2">2</dt>
<dd>
<span data-code-cell="annotated-cell-1" data-code-lines="3" data-code-annotation="2">Import the Distributed module for parallel computing capabilities</span>
</dd>
<dt data-target-cell="annotated-cell-1" data-target-annotation="3">3</dt>
<dd>
<span data-code-cell="annotated-cell-1" data-code-lines="4" data-code-annotation="3">Set a specific random seed for reproducibility</span>
</dd>
</dl>
</div>
<div class="cell-output cell-output-display" data-execution_count="1">
<pre><code>TaskLocalRNG()</code></pre>
</div>
</div>
<div id="4" class="cell" data-execution_count="1">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="annotated-cell-2" style="background: #f1f3f5;"><pre class="sourceCode markdown code-annotation-code code-with-copy code-annotated"><code class="sourceCode markdown"><span id="annotated-cell-2-1"><span class="in" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">```{julia}</span></span>
<span id="annotated-cell-2-2"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="annotated-cell-2-3"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">    toss_needle(d::Float64)</span></span>
<span id="annotated-cell-2-4"></span>
<span id="annotated-cell-2-5"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">Generate a random point inside a semicircle with radius `d/2`.</span></span>
<span id="annotated-cell-2-6"></span>
<span id="annotated-cell-2-7"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">Returns:</span></span>
<span id="annotated-cell-2-8"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">- A tuple `(x, θ)` where `x` is the distance from the center of the needle to the nearest line,</span></span>
<span id="annotated-cell-2-9"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">  and `θ` is the angle of the needle with the horizontal.</span></span>
<span id="annotated-cell-2-10"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="annotated-cell-2-11"><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;">toss_needle</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;">Float64</span>)</span>
<a class="code-annotation-anchor" data-target-cell="annotated-cell-2" data-target-annotation="1" onclick="event.preventDefault();">1</a><span id="annotated-cell-2-12" class="code-annotation-target">    x <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;">rand</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="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<a class="code-annotation-anchor" data-target-cell="annotated-cell-2" data-target-annotation="2" onclick="event.preventDefault();">2</a><span id="annotated-cell-2-13" class="code-annotation-target">    θ <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;">rand</span>() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">π</span></span>
<span id="annotated-cell-2-14">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> x, θ</span>
<span id="annotated-cell-2-15"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">end</span></span>
<span id="annotated-cell-2-16"><span class="in" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">```</span></span><div class="code-annotation-gutter-bg"></div><div class="code-annotation-gutter"></div></code></pre></div></div>
<div class="cell-annotation">
<dl class="code-annotation-container-grid">
<dt data-target-cell="annotated-cell-2" data-target-annotation="1">1</dt>
<dd>
<span data-code-cell="annotated-cell-2" data-code-lines="12" data-code-annotation="1">Generate a random distance from the nearest line, uniformly distributed between 0 and d/2</span>
</dd>
<dt data-target-cell="annotated-cell-2" data-target-annotation="2">2</dt>
<dd>
<span data-code-cell="annotated-cell-2" data-code-lines="13" data-code-annotation="2">Generate a random angle, uniformly distributed between 0 and <img src="https://latex.codecogs.com/png.latex?%5Cpi"> radians</span>
</dd>
</dl>
</div>
<div class="cell-output cell-output-display" data-execution_count="1">
<pre><code>Main.Notebook.toss_needle</code></pre>
</div>
</div>
<div id="6" class="cell" data-execution_count="1">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="annotated-cell-3" style="background: #f1f3f5;"><pre class="sourceCode markdown code-annotation-code code-with-copy code-annotated"><code class="sourceCode markdown"><span id="annotated-cell-3-1"><span class="in" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">```{julia}</span></span>
<span id="annotated-cell-3-2"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="annotated-cell-3-3"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">    cross_line(x::Float64, θ::Float64, L::Float64)</span></span>
<span id="annotated-cell-3-4"></span>
<span id="annotated-cell-3-5"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">Check if a point `(x, θ)` crosses a line parallel to the x-axis with a distance `L/2` from the center.</span></span>
<span id="annotated-cell-3-6"></span>
<span id="annotated-cell-3-7"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">Returns:</span></span>
<span id="annotated-cell-3-8"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">- `true` if the needle crosses the line, otherwise `false`.</span></span>
<span id="annotated-cell-3-9"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="annotated-cell-3-10"><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;">cross_line</span>(x<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;">Float64</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;">Float64</span>, L<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;">Float64</span>)</span>
<a class="code-annotation-anchor" data-target-cell="annotated-cell-3" data-target-annotation="1" onclick="event.preventDefault();">1</a><span id="annotated-cell-3-11" class="code-annotation-target">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> (L <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>) <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;">sin</span>(θ)</span>
<span id="annotated-cell-3-12"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">end</span></span>
<span id="annotated-cell-3-13"><span class="in" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">```</span></span><div class="code-annotation-gutter-bg"></div><div class="code-annotation-gutter"></div></code></pre></div></div>
<div class="cell-annotation">
<dl class="code-annotation-container-grid">
<dt data-target-cell="annotated-cell-3" data-target-annotation="1">1</dt>
<dd>
<span data-code-cell="annotated-cell-3" data-code-lines="11" data-code-annotation="1">Check if the needle crosses a line by comparing its x-coordinate to half its length times the sine of its angle</span>
</dd>
</dl>
</div>
<div class="cell-output cell-output-display" data-execution_count="1">
<pre><code>Main.Notebook.cross_line</code></pre>
</div>
</div>
<div id="8" class="cell" data-execution_count="1">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="annotated-cell-4" style="background: #f1f3f5;"><pre class="sourceCode markdown code-annotation-code code-with-copy code-annotated"><code class="sourceCode markdown"><span id="annotated-cell-4-1"><span class="in" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">```{julia}</span></span>
<span id="annotated-cell-4-2"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="annotated-cell-4-3"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">    estimate_pi_par(nb_tosses::Int64, L::Float64, d::Float64)</span></span>
<span id="annotated-cell-4-4"></span>
<span id="annotated-cell-4-5"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">Estimate π using Buffon's Needle method.</span></span>
<span id="annotated-cell-4-6"></span>
<span id="annotated-cell-4-7"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">Args:</span></span>
<span id="annotated-cell-4-8"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">- `nb_tosses`: The number of random tosses to perform.</span></span>
<span id="annotated-cell-4-9"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">- `L`: The length of the needle.</span></span>
<span id="annotated-cell-4-10"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">- `d`: The distance between the lines.</span></span>
<span id="annotated-cell-4-11"></span>
<span id="annotated-cell-4-12"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">Returns:</span></span>
<span id="annotated-cell-4-13"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">- An estimate of π based on the number of times the needle crosses a line.</span></span>
<span id="annotated-cell-4-14"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="annotated-cell-4-15"><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;">estimate_pi_par</span>(nb_tosses<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;">Int64</span>, L<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;">Float64</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;">Float64</span>)</span>
<a class="code-annotation-anchor" data-target-cell="annotated-cell-4" data-target-annotation="1" onclick="event.preventDefault();">1</a><span id="annotated-cell-4-16" class="code-annotation-target">    nb_crosses <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">@distributed</span> (<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span>) <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;">in</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>nb_tosses</span>
<a class="code-annotation-anchor" data-target-cell="annotated-cell-4" data-target-annotation="2" onclick="event.preventDefault();">2</a><span id="annotated-cell-4-17" class="code-annotation-target">        x, θ <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;">toss_needle</span>(d)</span>
<a class="code-annotation-anchor" data-target-cell="annotated-cell-4" data-target-annotation="3" onclick="event.preventDefault();">3</a><span id="annotated-cell-4-18" class="code-annotation-target">        <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cross_line</span>(x, θ, L) ? <span class="fl" 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="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="annotated-cell-4-19">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">end</span></span>
<a class="code-annotation-anchor" data-target-cell="annotated-cell-4" data-target-annotation="4" onclick="event.preventDefault();">4</a><span id="annotated-cell-4-20" class="code-annotation-target">    <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;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> L <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> nb_tosses) <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> nb_crosses)</span>
<span id="annotated-cell-4-21"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">end</span></span>
<span id="annotated-cell-4-22"><span class="in" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">```</span></span><div class="code-annotation-gutter-bg"></div><div class="code-annotation-gutter"></div></code></pre></div></div>
<div class="cell-annotation">
<dl class="code-annotation-container-grid">
<dt data-target-cell="annotated-cell-4" data-target-annotation="1">1</dt>
<dd>
<span data-code-cell="annotated-cell-4" data-code-lines="16" data-code-annotation="1">Use distributed computing to parallelize the Monte Carlo simulation</span>
</dd>
<dt data-target-cell="annotated-cell-4" data-target-annotation="2">2</dt>
<dd>
<span data-code-cell="annotated-cell-4" data-code-lines="17" data-code-annotation="2">Toss a needle, getting its position (x) and angle (<img src="https://latex.codecogs.com/png.latex?%5Ctheta">)</span>
</dd>
<dt data-target-cell="annotated-cell-4" data-target-annotation="3">3</dt>
<dd>
<span data-code-cell="annotated-cell-4" data-code-lines="18" data-code-annotation="3">Check if the needle crosses a line, returning 1 if true, 0 if false</span>
</dd>
<dt data-target-cell="annotated-cell-4" data-target-annotation="4">4</dt>
<dd>
<span data-code-cell="annotated-cell-4" data-code-lines="20" data-code-annotation="4">Calculate the estimate of <img src="https://latex.codecogs.com/png.latex?%5Cpi"> using the formula derived from Buffon’s needle problem</span>
</dd>
</dl>
</div>
<div class="cell-output cell-output-display" data-execution_count="1">
<pre><code>Main.Notebook.estimate_pi_par</code></pre>
</div>
</div>
<div id="10" class="cell" data-execution_count="1">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode markdown code-with-copy"><code class="sourceCode markdown"><span id="cb5-1"><span class="in" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">```{julia}</span></span>
<span id="cb5-2"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Parameters</span></span>
<span id="cb5-3">L <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.0</span>  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Length of the needle</span></span>
<span id="cb5-4">d <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.0</span>  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Distance between the lines</span></span>
<span id="cb5-5">nb_tosses <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_000_000</span>  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Number of tosses</span></span>
<span id="cb5-6"></span>
<span id="cb5-7"><span class="in" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">```</span></span></code></pre></div></div>
<div class="cell-output cell-output-display" data-execution_count="1">
<pre><code>1000000</code></pre>
</div>
</div>
<div id="12" class="cell" data-execution_count="1">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode markdown code-with-copy"><code class="sourceCode markdown"><span id="cb7-1"><span class="in" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">```{julia}</span></span>
<span id="cb7-2"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Estimate π</span></span>
<span id="cb7-3">π_estimate <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;">estimate_pi_par</span>(nb_tosses, L, d)</span>
<span id="cb7-4"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">println</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Estimated π: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">π</span>_estimate<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb7-5"><span class="in" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">```</span></span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>Estimated π: 3.1456828648362984</code></pre>
</div>
</div>



</section>

 ]]></description>
  <category>Julia</category>
  <category>Functional Programming</category>
  <category>Teaching</category>
  <category>Tutorials</category>
  <guid>https://r2rahul.github.io/r2rahul/posts/2025-01-14-buffon/</guid>
  <pubDate>Tue, 11 Mar 2025 23:00:00 GMT</pubDate>
</item>
</channel>
</rss>
