Skip to content

Commit

Permalink
first phase of reducing dependencies
Browse files Browse the repository at this point in the history
  • Loading branch information
rageSpin committed Jun 23, 2024
1 parent 8ce9442 commit 1638f88
Show file tree
Hide file tree
Showing 35 changed files with 465 additions and 82 deletions.
Binary file added assets/images/sections/skills/cloud.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
8 changes: 3 additions & 5 deletions content/posts/finance/monte_carlo/Black-Scholes/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,13 @@ For a European call option, the Black-Scholes formula is:

$$
C = S₀N(d_1) - Ke^{-rT}N(d_2)
$$

Where:

$$
d_1 = \frac{(ln(S_0/K) + (r + σ²/2)T)}{(σ\sqrt{T})}, \quad
d_2 = d_1 - \sigma \sqrt{T}
$$

- C: Call option price
Expand Down Expand Up @@ -86,9 +84,9 @@ Monte Carlo methods use repeated random sampling to obtain numerical results. In

For option pricing, we model the stock price movement using a stochastic differential equation:

```
dS = μSdt + σSdW
```
$$
dS = \mu Sdt + \sigma SdW
$$

Where:

Expand Down
4 changes: 2 additions & 2 deletions hugo.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ module:
# # target: data
- source: assets
target: assets
- source: static
target: static
# - source: static
# target: static
mounts:
- source: static/files
target: static/files
Expand Down
44 changes: 44 additions & 0 deletions public/categories/finance/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,50 @@



<div class="post-card">
<div class="card">
<div class="card-head">
<a href="/posts/finance/monte_carlo/black-scholes/" class="post-card-link">
<img class="card-img-top" src='/posts/finance/monte_carlo/black-scholes/Option-Pricing-Models-1.jpg' alt="Hero Image">
</a>
</div>
<div class="card-body">
<a href="/posts/finance/monte_carlo/black-scholes/" class="post-card-link">
<h5 class="card-title">Monte Carlo Simulation for Option Pricing</h5>
<p class="card-text post-summary">1. Introduction In the dynamic world of finance, options play a crucial role in risk management, speculation, and portfolio optimization. An option is a contract that gives the holder the right, but not the obligation, to buy (call option) or sell (put option) an underlying asset at a predetermined price (strike price) within a specific time frame. The challenge lies in accurately pricing these financial instruments, given the uncertainties in market movements.</p>
</a>

<div class="tags">
<ul style="padding-left: 0;">


<li class="rounded"><a href="/tags/finance/" class="btn btn-sm btn-info">Finance</a></li>


<li class="rounded"><a href="/tags/options/" class="btn btn-sm btn-info">Options</a></li>


<li class="rounded"><a href="/tags/statistics/" class="btn btn-sm btn-info">Statistics</a></li>

</ul>
</div>


</div>
<div class="card-footer">
<span class="float-start">
Sunday, June 23, 2024
| 6 minutes </span>
<a
href="/posts/finance/monte_carlo/black-scholes/"
class="float-end btn btn-outline-info btn-sm">Read</a>
</div>
</div>
</div>




<div class="post-card">
<div class="card">
<div class="card-head">
Expand Down
11 changes: 10 additions & 1 deletion public/categories/finance/index.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,16 @@
<description>Recent content in Finance on Stefano Giannini</description>
<generator>Hugo -- gohugo.io</generator>
<language>en</language>
<lastBuildDate>Sun, 16 Jun 2024 00:00:00 +0100</lastBuildDate><atom:link href="http:https://localhost:1313/categories/finance/index.xml" rel="self" type="application/rss+xml" /><item>
<lastBuildDate>Sun, 23 Jun 2024 00:08:25 +0100</lastBuildDate><atom:link href="http:https://localhost:1313/categories/finance/index.xml" rel="self" type="application/rss+xml" /><item>
<title>Monte Carlo Simulation for Option Pricing</title>
<link>http:https://localhost:1313/posts/finance/monte_carlo/black-scholes/</link>
<pubDate>Sun, 23 Jun 2024 00:08:25 +0100</pubDate>

<guid>http:https://localhost:1313/posts/finance/monte_carlo/black-scholes/</guid>
<description>1. Introduction In the dynamic world of finance, options play a crucial role in risk management, speculation, and portfolio optimization. An option is a contract that gives the holder the right, but not the obligation, to buy (call option) or sell (put option) an underlying asset at a predetermined price (strike price) within a specific time frame. The challenge lies in accurately pricing these financial instruments, given the uncertainties in market movements.</description>
</item>

<item>
<title>MSFT Stock Prediction using LSTM or GRU</title>
<link>http:https://localhost:1313/posts/finance/stock_prediction/gru/</link>
<pubDate>Sun, 16 Jun 2024 00:00:00 +0100</pubDate>
Expand Down
2 changes: 1 addition & 1 deletion public/categories/index.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@
<description>Recent content in Categories on Stefano Giannini</description>
<generator>Hugo -- gohugo.io</generator>
<language>en</language>
<lastBuildDate>Sun, 16 Jun 2024 00:00:00 +0100</lastBuildDate><atom:link href="http:https://localhost:1313/categories/index.xml" rel="self" type="application/rss+xml" />
<lastBuildDate>Sun, 23 Jun 2024 00:08:25 +0100</lastBuildDate><atom:link href="http:https://localhost:1313/categories/index.xml" rel="self" type="application/rss+xml" />
</channel>
</rss>
15 changes: 0 additions & 15 deletions public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -951,11 +951,6 @@ <h1 class="text-center">



<div class="logo-holder">
<img class="company-logo light-logo" src="/images/sections/experience/stellantis_logo.png" alt="" />

</div>




Expand Down Expand Up @@ -1039,11 +1034,6 @@ <h6 class="text-heading">Responsibilities:</h6>



<div class="logo-holder">
<img class="company-logo light-logo" src="/images/sections/experience/smairthero.png" alt="" />

</div>




Expand Down Expand Up @@ -1115,11 +1105,6 @@ <h6 class="text-heading">Responsibilities:</h6>



<div class="logo-holder">
<img class="company-logo light-logo" src="/images/sections/experience/Soave_logo.jpg" alt="" />

</div>




Expand Down
2 changes: 1 addition & 1 deletion public/index.json

Large diffs are not rendered by default.

18 changes: 17 additions & 1 deletion public/posts/data-science/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,23 @@



<li><a class=" list-link" href="/posts/finance/monte_carlo/" title="Monte Carlo">Monte Carlo</a></li>
<li>
<i data-feather="plus-circle"></i><a class=" list-link" href="/posts/finance/monte_carlo/"> Monte Carlo</a>

<ul class="">







<li><a class=" list-link" href="/posts/finance/monte_carlo/black-scholes/" title="Option Pricing">Option Pricing</a></li>



</ul>
</li>



Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
74 changes: 47 additions & 27 deletions public/posts/finance/monte_carlo/black-scholes/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -412,15 +412,16 @@ <h1>Monte Carlo Simulation for Option Pricing</h1>
<h2 id="1-introduction">1. Introduction</h2>
<p>In the dynamic world of finance, options play a crucial role in risk management, speculation, and portfolio optimization. An option is a contract that gives the holder the right, but not the obligation, to buy (call option) or sell (put option) an underlying asset at a predetermined price (strike price) within a specific time frame. The challenge lies in accurately pricing these financial instruments, given the uncertainties in market movements.</p>
<p>Traditional analytical methods, while powerful, often struggle with complex option structures or realistic market conditions. This is where Monte Carlo simulation steps in, offering a flexible and robust approach to option pricing. By leveraging the power of computational methods, Monte Carlo simulations can handle a wide array of option types and market scenarios, making it an indispensable tool in a quantitative analyst&rsquo;s toolkit.</p>
<p>For further explanation about <em>options pricing</em>, check <a href="https://www.investopedia.com/articles/optioninvestor/07/options_beat_market.asp" target="_blank" rel="noopener">Investopedia</a>.</p>
<h2 id="2-the-black-scholes-model">2. The Black-Scholes Model</h2>
<p>Before diving into Monte Carlo methods, it&rsquo;s crucial to understand the Black-Scholes model, a cornerstone in option pricing theory. Developed by Fischer Black, Myron Scholes, and Robert Merton in the early 1970s, this model revolutionized the field of quantitative finance.</p>
<h3 id="the-black-scholes-formula">The Black-Scholes Formula</h3>
<p>For a European call option, the Black-Scholes formula is:</p>
<p>$$
C = S₀N(d_1) - Ke^{-rT}N(d_2)
$$
Where:
$$
$$</p>
<p>Where:</p>
<p>$$
d_1 = \frac{(ln(S_0/K) + (r + σ²/2)T)}{(σ\sqrt{T})}, \quad
d_2 = d_1 - \sigma \sqrt{T}
$$</p>
Expand All @@ -447,24 +448,12 @@ <h3 id="assumptions-of-the-black-scholes-model">Assumptions of the Black-Scholes
<h3 id="limitations-of-the-black-scholes-model">Limitations of the Black-Scholes Model</h3>
<p>While groundbreaking, the Black-Scholes model has several limitations:</p>
<ol>
<li>
<p><strong>Constant Volatility</strong>: The model assumes volatility is constant, which doesn&rsquo;t hold in real markets where volatility can change dramatically.</p>
</li>
<li>
<p><strong>Log-normal Distribution</strong>: It assumes stock returns are normally distributed, which doesn&rsquo;t account for the fat-tailed distributions observed in reality.</p>
</li>
<li>
<p><strong>Continuous Trading</strong>: The model assumes continuous trading is possible, which isn&rsquo;t realistic in practice.</p>
</li>
<li>
<p><strong>No Dividends</strong>: It doesn&rsquo;t account for dividends, which can significantly affect option prices.</p>
</li>
<li>
<p><strong>European Options Only</strong>: The original model only prices European-style options, not American or exotic options.</p>
</li>
<li>
<p><strong>Risk-free Rate</strong>: It assumes a constant, known risk-free rate, which can vary in reality.</p>
</li>
<li><strong>Constant Volatility</strong>: The model assumes volatility is constant, which doesn&rsquo;t hold in real markets where volatility can change dramatically.</li>
<li><strong>Log-normal Distribution</strong>: It assumes stock returns are normally distributed, which doesn&rsquo;t account for the fat-tailed distributions observed in reality.</li>
<li><strong>Continuous Trading</strong>: The model assumes continuous trading is possible, which isn&rsquo;t realistic in practice.</li>
<li><strong>No Dividends</strong>: It doesn&rsquo;t account for dividends, which can significantly affect option prices.</li>
<li><strong>European Options Only</strong>: The original model only prices European-style options, not American or exotic options.</li>
<li><strong>Risk-free Rate</strong>: It assumes a constant, known risk-free rate, which can vary in reality.</li>
</ol>
<p>These limitations highlight why more flexible approaches like Monte Carlo simulation are valuable in option pricing.</p>
<h2 id="3-monte-carlo-simulation-theoretical-background">3. Monte Carlo Simulation: Theoretical Background</h2>
Expand All @@ -473,8 +462,10 @@ <h3 id="basic-principles">Basic Principles</h3>
<p>Monte Carlo methods use repeated random sampling to obtain numerical results. In the context of option pricing, we simulate many possible price paths for the underlying asset and then calculate the option&rsquo;s payoff for each path.</p>
<h3 id="application-to-option-pricing">Application to Option Pricing</h3>
<p>For option pricing, we model the stock price movement using a stochastic differential equation:</p>
<pre tabindex="0"><code>dS = μSdt + σSdW
</code></pre><p>Where:</p>
<p>$$
dS = \mu Sdt + \sigma SdW
$$</p>
<p>Where:</p>
<ul>
<li>S: Stock price</li>
<li>μ: Expected return</li>
Expand All @@ -491,14 +482,14 @@ <h2 id="4-implementing-monte-carlo-simulation-in-python">4. Implementing Monte C
</span></span><span style="display:flex;"><span> dt <span style="color:#f92672">=</span> T <span style="color:#f92672">/</span> num_steps
</span></span><span style="display:flex;"><span> paths <span style="color:#f92672">=</span> np<span style="color:#f92672">.</span>zeros((num_simulations, num_steps <span style="color:#f92672">+</span> <span style="color:#ae81ff">1</span>))
</span></span><span style="display:flex;"><span> paths[:, <span style="color:#ae81ff">0</span>] <span style="color:#f92672">=</span> S0
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">for</span> t <span style="color:#f92672">in</span> range(<span style="color:#ae81ff">1</span>, num_steps <span style="color:#f92672">+</span> <span style="color:#ae81ff">1</span>):
</span></span><span style="display:flex;"><span> z <span style="color:#f92672">=</span> np<span style="color:#f92672">.</span>random<span style="color:#f92672">.</span>standard_normal(num_simulations)
</span></span><span style="display:flex;"><span> paths[:, t] <span style="color:#f92672">=</span> paths[:, t<span style="color:#f92672">-</span><span style="color:#ae81ff">1</span>] <span style="color:#f92672">*</span> np<span style="color:#f92672">.</span>exp((r <span style="color:#f92672">-</span> <span style="color:#ae81ff">0.5</span> <span style="color:#f92672">*</span> sigma<span style="color:#f92672">**</span><span style="color:#ae81ff">2</span>) <span style="color:#f92672">*</span> dt <span style="color:#f92672">+</span> sigma <span style="color:#f92672">*</span> np<span style="color:#f92672">.</span>sqrt(dt) <span style="color:#f92672">*</span> z)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> option_payoffs <span style="color:#f92672">=</span> np<span style="color:#f92672">.</span>maximum(paths[:, <span style="color:#f92672">-</span><span style="color:#ae81ff">1</span>] <span style="color:#f92672">-</span> K, <span style="color:#ae81ff">0</span>)
</span></span><span style="display:flex;"><span> option_price <span style="color:#f92672">=</span> np<span style="color:#f92672">.</span>exp(<span style="color:#f92672">-</span>r <span style="color:#f92672">*</span> T) <span style="color:#f92672">*</span> np<span style="color:#f92672">.</span>mean(option_payoffs)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">return</span> option_price, paths
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e"># Example usage</span>
Expand Down Expand Up @@ -528,7 +519,31 @@ <h2 id="5-visualization-and-analysis">5. Visualization and Analysis</h2>
</span></span><span style="display:flex;"><span>plt<span style="color:#f92672">.</span>xlabel(<span style="color:#e6db74">&#34;Stock Price&#34;</span>)
</span></span><span style="display:flex;"><span>plt<span style="color:#f92672">.</span>ylabel(<span style="color:#e6db74">&#34;Frequency&#34;</span>)
</span></span><span style="display:flex;"><span>plt<span style="color:#f92672">.</span>show()
</span></span></code></pre></div><p>These visualizations show the range of possible stock price paths and the distribution of final stock prices, providing insight into the option&rsquo;s potential outcomes.</p>
</span></span></code></pre></div><img src="%5cposts%5cfinance%5cmonte_carlo%5cBlack-Scholes%5cimages%5csimulation_path.png"

alt="Results"





class="center"

>

<img src="/posts/finance/monte_carlo/Black-Scholes/images/simulation_histogram.png"

alt="Results"





class="center"

>

<p>These visualizations show the range of possible stock price paths and the distribution of final stock prices, providing insight into the option&rsquo;s potential outcomes.</p>
<h2 id="6-comparison-with-analytical-solutions">6. Comparison with Analytical Solutions</h2>
<p>To validate our Monte Carlo results, we can compare them with the Black-Scholes analytical solution:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-python" data-lang="python"><span style="display:flex;"><span><span style="color:#f92672">from</span> scipy.stats <span style="color:#f92672">import</span> norm
Expand All @@ -543,6 +558,11 @@ <h2 id="6-comparison-with-analytical-solutions">6. Comparison with Analytical So
</span></span><span style="display:flex;"><span>print(<span style="color:#e6db74">f</span><span style="color:#e6db74">&#34;Monte Carlo price: </span><span style="color:#e6db74">{</span>price<span style="color:#e6db74">:</span><span style="color:#e6db74">.2f</span><span style="color:#e6db74">}</span><span style="color:#e6db74">&#34;</span>)
</span></span><span style="display:flex;"><span>print(<span style="color:#e6db74">f</span><span style="color:#e6db74">&#34;Difference: </span><span style="color:#e6db74">{</span>abs(bs_price <span style="color:#f92672">-</span> price)<span style="color:#e6db74">:</span><span style="color:#e6db74">.4f</span><span style="color:#e6db74">}</span><span style="color:#e6db74">&#34;</span>)
</span></span></code></pre></div><p>The difference between the two methods gives us an idea of the Monte Carlo simulation&rsquo;s accuracy.</p>
<blockquote>
<p>Black-Scholes price: 11.270</p>
<p>Monte Carlo price: 11.445</p>
<p>Difference: 0.1744</p>
</blockquote>
<h2 id="7-advanced-topics-and-extensions">7. Advanced Topics and Extensions</h2>
<p>Monte Carlo simulation&rsquo;s flexibility allows for various extensions:</p>
<ol>
Expand Down
68 changes: 68 additions & 0 deletions public/posts/finance/monte_carlo/black-scholes/options.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 23 11:30:47 2024
@author: stefa
"""

import numpy as np
import matplotlib.pyplot as plt

def monte_carlo_option_pricing(S0, K, T, r, sigma, num_simulations, num_steps):
dt = T / num_steps
paths = np.zeros((num_simulations, num_steps + 1))
paths[:, 0] = S0

for t in range(1, num_steps + 1):
z = np.random.standard_normal(num_simulations)
paths[:, t] = paths[:, t-1] * np.exp((r - 0.5 * sigma**2) * dt + sigma * np.sqrt(dt) * z)

option_payoffs = np.maximum(paths[:, -1] - K, 0)
option_price = np.exp(-r * T) * np.mean(option_payoffs)

return option_price, paths

# Example usage
S0 = 100 # Initial stock price
K = 98.5 # Strike price
T = 1 # Time to maturity (in years)
r = 0.05 # Risk-free rate
sigma = 0.2 # Volatility
num_simulations = 10000
num_steps = 252 # Number of trading days in a year

price, paths = monte_carlo_option_pricing(S0, K, T, r, sigma, num_simulations, num_steps)
print(f"Estimated option price: {price:.3f}")

## Visualization
plt.figure(figsize=(10, 6))
plt.plot(paths[:100, :].T)
plt.title("Sample Stock Price Paths")
plt.xlabel("Time Steps")
plt.ylabel("Stock Price")
plt.show()
plt.savefig("images/simulation_path.png", dpi=300)

plt.figure(figsize=(10, 6))
plt.hist(paths[:, -1], bins=100)
plt.title("Distribution of Final Stock Prices")
plt.xlabel("Stock Price")
plt.ylabel("Frequency")
plt.vlines(S0, 0, 350, colors='r', linestyles='--', label=r'$S_0$')
plt.legend()
plt.show()
plt.savefig("images/simulation_histogram.png", dpi=300)


from scipy.stats import norm

def black_scholes_call(S0, K, T, r, sigma):
d1 = (np.log(S0 / K) + (r + 0.5 * sigma**2) * T) / (sigma * np.sqrt(T))
d2 = d1 - sigma * np.sqrt(T)
return S0 * norm.cdf(d1) - K * np.exp(-r * T) * norm.cdf(d2)


bs_price = black_scholes_call(S0, K, T, r, sigma)
print(f"Black-Scholes price: {bs_price:.3f}")
print(f"Monte Carlo price: {price:.3f}")
print(f"Difference: {abs(bs_price - price):.4f}")
18 changes: 17 additions & 1 deletion public/posts/finance/stock_prediction/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,23 @@



<li><a class=" list-link" href="/posts/finance/monte_carlo/" title="Monte Carlo">Monte Carlo</a></li>
<li>
<i data-feather="plus-circle"></i><a class=" list-link" href="/posts/finance/monte_carlo/"> Monte Carlo</a>

<ul class="">







<li><a class=" list-link" href="/posts/finance/monte_carlo/black-scholes/" title="Option Pricing">Option Pricing</a></li>



</ul>
</li>



Expand Down
Loading

0 comments on commit 1638f88

Please sign in to comment.