<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Alexander Tsoskounoglou on Medium]]></title>
        <description><![CDATA[Stories by Alexander Tsoskounoglou on Medium]]></description>
        <link>https://medium.com/@alexander.tsoskounoglou?source=rss-e3674ac63c40------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*oe8xkgotjipEWjYbCXRFrg.jpeg</url>
            <title>Stories by Alexander Tsoskounoglou on Medium</title>
            <link>https://medium.com/@alexander.tsoskounoglou?source=rss-e3674ac63c40------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 13:55:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alexander.tsoskounoglou/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Delta-Vega Hedging Using Variance Swaps]]></title>
            <link>https://medium.com/@alexander.tsoskounoglou/delta-vega-hedging-using-variance-swaps-dc52977de7c7?source=rss-e3674ac63c40------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc52977de7c7</guid>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[options-trading]]></category>
            <category><![CDATA[investing]]></category>
            <category><![CDATA[quantitative-finance]]></category>
            <dc:creator><![CDATA[Alexander Tsoskounoglou]]></dc:creator>
            <pubDate>Tue, 03 Jun 2025 08:59:20 GMT</pubDate>
            <atom:updated>2025-06-05T07:52:18.523Z</atom:updated>
            <content:encoded><![CDATA[<h3>Delta–Vega Hedging with Variance Swaps: How to Reduce Risk and Exposure to Unexpected Shocks.</h3><p>In this article I am going to walk you through the process of using Variance swaps for hedging a European option. Also we are going to perform a series of tests to analyze the effectiveness of using variance swaps under different assumptions, including unexpected market shocks.</p><ul><li>Find the code for this article here: <a href="https://github.com/ithakis/Delta-Vega-Hedging-with-Swing-Options">Github Repo</a></li><li>Connect with me in <a href="https://www.linkedin.com/in/atsoskounoglou/">LinkedIn</a></li></ul><h4><strong>Contents:</strong></h4><ol><li>Introduction</li><li>Stochastic Process Used: Heston Model</li><li>Delta Hedging a European Option</li><li>Variance Swaps</li><li>Hedging Results: With vs Without Variance Swaps</li><li>Sensitivity Analysis —Delta-Vega Hedging vs different Assumptions</li><li>Modeling an Earnings Gap</li><li>Delta vs Delta-Vega Hedging Under Jump Risk</li><li>Profit and Risk Across Earnings Gap Sizes</li><li>Discussion &amp; Conclusion</li></ol><h3>Introduction</h3><p>What is (Delta) hedging quickly? It is the process of constructing a portfolio which reduces the risk associated with selling an option. In its simplest case, it consists of the option(s) sold and the underlying asset which the option is based. Where, <strong>porfolio Π(t)</strong> consists of: (1) <strong>Delta_t units of the underlying S_t</strong>, and (2) <strong>one short option with value V(t, S_t)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/185/1*Ymq__JB_0tNdwgBZIzyB_g.png" /></figure><p>Assuming the S_t follows an Itô process with general drift and volatility (possible stochastic)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/1*6bqjN45osgN308Y0PG_Fvg.png" /></figure><p>Here, <strong>μ_t</strong> is the instantaneous drift, <strong>σ_t</strong> is an adapted process representing the (possible stochastic) instantaneous volatility, <strong>W_t</strong> is a standard Weiner process.</p><p>Using Itô’s Lemma for the Value of the Option. Let the option price be V(t,S_t), assumed smooth enough. Then using Itô’s lemma:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*EnGMvV0UtyPYyHE-zezrpw.png" /></figure><p>From the Stochastic Deferential Equation (SDE) of S_t:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/144/1*zLuB7v29Bwl2gcidjsgxRw.png" /></figure><p>So:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*JSJCsf-hy-7dhxgc53LT_w.png" /></figure><p>Now computing the portfolio change:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/165/1*cTvqCPEuyuCJ3ZgXM3x21w.png" /></figure><p>Substituting from above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*_2bEUwXepa-kySyT0ncYxA.png" /></figure><p>Grouping the terms together:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*gAHO604KzCECXzyOYRFirA.png" /></figure><p>Since the dW_t term is the only stochastic one; as the dt term is deterministic, meaning that we know by how much the Portfolio’s value will change over time with (thus no risk); we need to eliminate the dW_t term by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/1*80ndYizkb9UQ4TkbQ9arLg.png" /></figure><blockquote><em>Thus to construct a locally riskless portfolio, the position in the underlying must equal the option’s rate of change over the underlying.</em></blockquote><h3>Stochastic Process Used: Heston Model</h3><p>In this study we will use a <strong>stochastic volatility model</strong>, to model the changes in uncertainty in the payoff between the signing of the option and expiration of the option. Specifically, the Heston stochastic volatility model is used with SDE:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*SpQsWEhKyWo1jdNau4eiFw.png" /></figure><p>where, <strong>μ</strong> is the drift of the underlying (r-q),<strong> κ</strong> is the mean-reversion rate of the variance, <strong>θ</strong> is the long term variance, <strong>ζ</strong> is the volatility of the volatility, <strong>ρ</strong> is the correlation between Brownian motions dW^S and dW^v with dW^S*dW^v=ρ*dt.</p><p>*QuantLib python is used for the pricing of the European Options using a Fast Fourier Method, allowing the pricing of a single option to be performed around the 10millisecond range.</p><h4>Calculation of Delta</h4><p>If V(t,S_t, v_t) is the value of the European option from the pricing engine, then the rate of change of V over S_t is calculated with finite differences and 5 stensils:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*vaoRXxGkoGT4qvepQERBmQ.png" /></figure><p>Which yilds a 4th-order, O(ds⁴) accurate estimate of the first derivate dV/dS centered at S_t.</p><h3>Delta Hedging a European Option</h3><p>In this example we hedge a European call option with 31 days to expiry, (S = K = 100) once per trading day. A S&amp;P 500 stock usually has 10–20bp bid–ask spread at the open/close. Because the book contains offsetting short calls and puts, roughly <strong>98–99 % of the gross delta cancels</strong>, leaving <strong>1–2 % residual delta</strong> to hedge externally. Applying the raw 10–20 bp spread to that 1–2 % hedge flow gives an <strong>all-in transaction cost of ≈ 0.2 bp per rebalance.</strong></p><p>The Heston Parameters are: r=q=0%, v0=θ=(10%)², κ=4, ζ=0.1, ρ=-0.7</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UUaasp_1k9ox3vnmBSUZJg.png" /><figcaption>S_t and v_t over the duration of the option</figcaption></figure><p>Bellow is a visualization of the Delta-Hedge process (without buying any variance swaps), using 16.384 Monte-Carlo paths.</p><figure><img alt="Delta Hedging Visualization" src="https://cdn-images-1.medium.com/max/1024/1*VMuRZ7Io41grCJoouzp6Ig.png" /><figcaption>Delta Hedging visualization for a European call.</figcaption></figure><h4>With Results:</h4><pre>Option Price :  1.15883, Spread Earned: 0.00579<br>PnL mean     : -0.005305  CI [-0.00934,-0.00128]<br>PnL std      :  0.200697<br>VaR95        : -0.3439  CI [-0.3541,-0.3340]<br>CVaR95       : -0.4680  CI [-0.4836,-0.4524]<br>Mean Δ cost  :  0.004521</pre><p>The above visualization and results show the running PnL of the hedging portfolio (1,1) and (1,2), the value of the assets in the portfolio (2,1), the costs incurred from buying/selling the underlying (2,2), and the net delta exposure which needs to be re-hedged at each step (3,2).</p><p>The final Returns are not normal as you can see bellow, with the p value of the D’Agostino K² and Kolmogorov-Smirnov tests being practically zero.</p><p><strong>The Mean-PnL should equal the transaction costs of the hedging strategy </strong>assuming a large enough sample and that the realized parameters of the stochastic process do not deviate from the assumed ones. <strong>Additionally, the VaR and CVaR seem to have a significant initial increase and then a linear increase until the last days which seems to accelerate </strong>(bell shaped)<strong>.</strong></p><figure><img alt="Normality test for the cumulative PnL of a delta hedging method." src="https://cdn-images-1.medium.com/max/1024/1*6c4VF0m-VoQzkYNjAboWDA.png" /><figcaption>Normality test for the Cumulative PnL of Delta Hedging.</figcaption></figure><h3>Variance Swaps</h3><p>Variance swaps is a derivative with (potentially) the same underlying as the European option, whose goal is to exchange (swap) the risk associated with the uncertainty in the returns of the underlying from the beginning till the end of the swap. In a variance swap the swap seller pays when the average realized variance is greater than the strike (initially agreed variance), and the swap buyer pays when the realized variance is lower.</p><blockquote>A variance swap is a derivative used to hedge/speculate on volatility.</blockquote><p><strong>Its payoff is</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/1*QG2SYLnZvDrkGxnHf4G-tg.png" /></figure><p>Where, <strong>Notional: </strong>Variance notional (e.g., $1,000 per variance point), <strong>σ²_realized</strong>: Realized variance over the life of the contract,<strong> K_var</strong>: Variance strike (implied variance at inception).</p><p>Where the <strong>realized variance</strong> is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*i862zNrT_jSc9aaZfOi4Ew.png" /></figure><p><strong>N</strong> Number of observation intervals (typically trading days), <strong>252</strong>: Annualization factor for daily returns.</p><blockquote><strong>Variance Swaps usually have</strong> <strong>zero</strong> <strong>value at t=0</strong>, reflecting the fact that the strike equals the expected variance. In practice the variance seller, would want to sell at a higher strike than the internally calculated expected one, to cover costs and profits. Thus its price is zero, but its expected payoff is negative!</blockquote><p>In finance usually the difference between a derivative and insurance, is in the ability to replicate the payoff of the instrument with another portfolio of assets. Variance swaps can be statically replicated + delta hedging, in theory with a portfolio of weighted European options with the same maturity, with the Swap Strike (K_var) (or expected variance) equalling:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*I10uo6WvI7-Xp9sdqEjE9g.png" /></figure><p>In 1998, Carr-Madam showed that a swap option can be replicated by using a continuum of <strong>out-of-the-money European options</strong> across all strikes. (the above is the discrete version)</p><p>Where, <strong>P(K_i​)</strong>: Price of the i-th put option with strike K_i&lt;F, <strong>C(K_j​)</strong>: Price of the j-th call option with strike K_j&gt;F, <strong>F</strong>: Forward price of the underlying asset,<strong> ΔK_i</strong>​: Width between adjacent strikes, <strong>T</strong>: Time to maturity, <strong>r</strong>: Risk-free rate.</p><h4><strong>Variance Swap Strike Calculation</strong></h4><p>Since the Heston model is used, we can derive the strike value from the calibrated Heston model with discrete sampling using the following analytical equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*ZozBnuYzLCZjK_9Sw4BMqw.png" /></figure><p>where, <strong>N</strong> is the number of discrete sampling intervals, Δt is the time step between samples, the rest are the previously stated Heston parameters. *N in our case equals with 30, since variance swaps are usually calculated in a daily log returns basis.</p><h4>Variance Swap Notional Calculation</h4><p>Since the variance swap pays when short variance increases and we pay when it decreases:</p><blockquote>To use a variance swap to hedge Vega, we need to offset the risk associated with a change in short variance (v_t), where the notional needs to equal with; the rate of change of V over initial short variance v0, over the rate of change of the value of the swap over the short variance.</blockquote><p>Bellow is the equation used to calculate the Notional of the variance swap, so the variance swap cancels out changes to the short variance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*iVSUUqiz4bVeNIOjaqUwSA.png" /></figure><p>To calculate the rate of change of the value of the European call option, again Finite Differences method is used. Where, <strong>τ</strong> is the annualized time to maturity. (The swap and the option should have the same maturity.)</p><h4>Running Variance Swap Value</h4><p>When revaluing the value of an existing swap, one can obtain its value based on the bellow equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*6L061LmCgE5_SYRbRkSgbQ.png" /></figure><p>Where <strong>RV_t</strong> is the <strong>realized variance</strong> up to time t:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/199/1*H7mq2x3BkwnFs9itzY1UTA.png" /></figure><p>and <strong>EV_t</strong>​ is the <strong>expected future variance</strong> under the Heston model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*SKlI2x3qSToKs1YBDjU-6Q.png" /></figure><p>Combined the running value of a swap equals:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*YR2JyOKzVau50ogzDJWMDA.png" /></figure><h3>Variance Swap Hedging Analysis</h3><p>In this section we are going to analyze the impact of adding a variance swap to our hedging portfolio.</p><p>First let&#39;s visualize and validate the Value-at-Risk over different amounts of v0 (short variance) hedged. From the graph bellow, it is clear that hedging 100% of the short variance leads to the greatest reduction in risk (VaR), where transaction costs increase linearly with the percent Hedged.</p><p>*Technically dC/dv0 is not Vega, since it represents the sensitivity to changes to the short variance, while Vega is dC/dσ, the sensitivity to changes in implied volatility. However for abbreviation, those two will be used interchangeably in this article.</p><p>Additionally, I assume a 1% transaction cost for purchasing the variance swap. An option seller, based on their calibrated Heston parameters, typically prices options with implied volatility exceeding realized volatility on average, this spread forms the basis of their profits and covers associated costs. However, because variance swaps carry additional risks, pose greater replication challenges compared to European options, and are less liquid than standard European calls; I assume a strike that is 1% higher than the level implied by the Heston model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*LuwMx2CrxqkgulcfVLUeAw.png" /></figure><p>*Since the slope of the VaR decreases near the top, and costs grow linearly a partial hedge is more value for money, say around 70–80%.</p><h3>Hedging Results w/ vs w/o a Variance Swap</h3><p>Bellow is a visual comparison of the Delta hedging (Left) versus the Delta-Vega (Right) hedging with the variance swap. Note that the axis limits are not the same in both cases. Notice how the first row has y limits [-0.4, 0.4] vs [-0.2, 0.2].</p><figure><img alt="Delta Hedging vs Delta-Vega hedging (1)" src="https://cdn-images-1.medium.com/max/1024/1*Wpy6a2HSHO_fK2Emj-6Vxw.png" /><figcaption>Delta Hedging (left) vs Delta-Vega hedging (right) [1]</figcaption></figure><figure><img alt="Delta Hedging vs Delta-Vega hedging (2)" src="https://cdn-images-1.medium.com/max/1024/1*jtIBTNGMdW4-CjflNx9rrQ.png" /><figcaption>Delta Hedging (left) vs Delta-Vega hedging (right) [2]</figcaption></figure><pre>-- Without Variance Swap --------------------------<br>Option Price :  1.15883, Spread Earned: 0.00579<br>PnL mean     : -0.005305  CI [-0.00934,-0.00128]<br>PnL std      :  0.200697<br>VaR95        : -0.3439  CI [-0.3541,-0.3340]<br>CVaR95       : -0.4680  CI [-0.4836,-0.4524]<br>Mean Δ cost  :  0.004521<br><br>-- With Variance Swap --------------------------<br>Option Price :  1.15883, Spread Earned: 0.00579<br>PnL mean     : -0.005288  CI [-0.00752,-0.00321]<br>PnL std      :  0.105709<br>VaR95        : -0.1608  CI [-0.1660,-0.1544]<br>CVaR95       : -0.2294  CI [-0.2388,-0.2198]<br>Mean Δ cost  :  0.004521<br>Vswap Notiona: 58.2176  Strike: 0.0101<br>Mean Swap PnL: -0.0058 CI [-0.0093,-0.0023]</pre><h4>Comparison Points</h4><ul><li><strong>The results show a significant reduction in risk (VaR, CVaR, Std[PnL]).</strong> For example, a 53.2% reduction in VaR, 50.98 in CVaR, and %47.33% in Std[PnL].</li><li>On [1] in the first row, the running VaR is much smaller on average, with the Delta-Vega hedge showing exponential increase in risk, which associated with the exponential increase of gamma.</li><li>The cost of the variance swap is -0.0058, which is associated with the strike value being 1% higher.</li></ul><p>Bellow you can see the difference in the final PnL distribution (Left) when using and when not using a variance swap for hedging. On the right you see the final PnL distribution for the Variance swap, following the CIR process. You can also see how the average PnL of the swap is less than zero, validating the expected loss occurred from the expected transaction costs (higher strike)</p><figure><img alt="PnL Distribution of Variance Swap Hedging Strategy" src="https://cdn-images-1.medium.com/max/1024/1*sosjW9vkldNMnP8KYkj97g.png" /><figcaption>PnL Distribution of Variance Swap Hedging Strategy</figcaption></figure><h4>Across Different Time to Maturities</h4><p>Bellow you can see how the VaR changes over time over <em>different time to maturities</em>, when using and when not using a variance swap with 100% Vega hedged.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5fmndNHOyA2w48BwneDsvw.png" /></figure><blockquote>When using a variance swap the VaR is lower across all maturities, the absolute difference is the smallest in shorter maturities, with the spread between having and not having the variance swap increasing as time to maturity increases.</blockquote><h4>Across Different Levels of Volatility</h4><p>Bellow you can see how the VaR changes over time over <em>different volatility levels assumed for the underlying</em>, when using and when not using a variance swap with 100% Vega hedged.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I-chmuIBD6CfE3_nXJnpOQ.png" /></figure><blockquote>As variance swaps are used to hedge volatility risk, it is to be expected that the greater the volatility the greater their effectiveness to reduce risk, though with increased expected cost</blockquote><h4><strong>Across Different Levels of Volatility of Volatility</strong></h4><p>Bellow you can see how the VaR changes over time over <em>different volatility of volatility levels assumed for the underlying</em>, when using and when not using a variance swap with 100% Vega hedged. *Note that volvol does not impact the price of the variance swap when calculated with the Heston model. Since the variance swap strike is based on the expected variance in the duration of the option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eITPJHIYr3osdw9NW7uBHA.png" /></figure><blockquote>Uncertainty in the value of the volatility changes the shape of the distribution, not the expectation. Volvol risk can be effectively be reduced with the use of variance swaps, independently of the magnitude of its value.</blockquote><h4><strong>Across Different Amounts of Hedging Steps</strong></h4><p>Bellow you can see how the VaR changes over time over <em>different number of hedging steps</em>, when using and when not using a variance swap with 100% Vega hedged. 30 hedging steps, equals daily hedging, with 15 being every two days, and so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NDYvEQJZvldjhI5dwQb70Q.png" /></figure><blockquote>Variance swaps allow for less frequent hedging as they reduce Vega risk, allowing for less frequent rebalancing.</blockquote><h3>Modeling an Earnings Gap or Systemic Risk</h3><p>In the next section we want to analyze the impact an earnings gap/surprise (or a large unexpected change in the value of the underlying) would have on our hedging strategy. We assume that on day 15 out of 31 of our European option, the underlying company releases its earnings, which include a surprise.</p><blockquote><strong>We can’t predict the direction or exactly by how much</strong>, but given an internal model we expect a jump in the price of the underlying, with a predicted variance.</blockquote><h4>Structural Modeling of Earnings Jumps</h4><p>A theoretically rigorous approach models the earnings announcement jump as an exogenously scheduled discrete event. Under this method, we assume:</p><ul><li><strong>Announcement Timing</strong>: The jump occurs at a known, predetermined time (e.g., earnings release date).</li><li><strong>Economic Rationale (Central Limit Theorem)</strong>: Earnings surprises (actual earnings minus consensus forecast) aggregate numerous small independent analyst forecast errors. Hence, the earnings surprise ε, is modeled as:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/107/1*acEAdD19bJpff_Vc17jxUQ.png" /></figure><ul><li><strong>Price Sensitivity</strong>: The equity price reacts proportionally to the earnings surprise. This sensitivity (or elasticity), denoted by β, converts the earnings surprise into a log-return jump :</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/355/1*35oCSkAdRnBWCRx2ue3ZZA.png" /></figure><p>The mean adjustment ensures no arbitrage under the risk-neutral measure Q:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/91/1*meneUNBcl5tbwxJo1iI0tg.png" /></figure><h4>Parameter Choices</h4><ul><li><strong>Surprise Volatility</strong>: σ_ε=0.08(8%) is typical for a medium-volatility firm. For a calm firm (5%), for a volatile firm (10%)</li><li><strong>Elasticity</strong>: β=1.0, indicating a 1% surprise yields approximately a 1% equity jump. For a calm firm β=0.5, for a volatile firm β=1.5%.</li><li>Resulting jump: Standard deviation approximately 8%, and mean 0.0%.</li></ul><pre>...<br>sigma_eps = 0.08<br>beta = 1.0<br>mu_J = -0.5 * (_beta * _sigma_eps) ** 2<br>sigma_J = _beta * _sigma_eps<br><br># Simulate jump<br>J_path = np.random.normal(mu_J, sigma_J, MC_paths)<br><br># Apply jump at earnings announcement step<br>t = earnings_step<br>S[t] += J_path<br>...<br><br>S = np.exp(S) <br></pre><h4>Visualization of the Jump size</h4><p>The intuition behind the earnings gap, is the same as the one of the <strong>Merton Jump-Diffusion model </strong>or of the <strong>Compound Poisson Process with Normally Distributed Jumps</strong>. Since the jump size in log-space follows a normal distribution, <strong>the resulting distribution of S affter applying the jump, is the Lognormal one</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*uMDzMFmr6OB8cm8BMRjAzA.png" /></figure><h4>Underlying Asset Paths after Modeling Earnings Gap Jump</h4><p>Bellow you see a visualization of the stochastic paths. Notice how the quantiles in the underlying paths jump but the average is still zero, reflecting that we speculate on the earnings gap size not the direction.</p><p>Similarly, the CIR process of the stochastic volatility is unaffected, since the earnings’ gap in this case is priced in within the daily interval of the simulation.</p><p>*In practice the Heston parameters change from day to day, with an earnings gap definitely affecting the dynamics of the expected future behavior of a stock. However, it is not very unreasonable to argue that the gap will be quickly reflected in the price and then the stock will continue to behave randomly. Thus, since we do not have a way to predict the distribution afterwards, might as well assume the current one. One could model the impact of the Earnings gap in the Heston parameters model, but it is an extension of this work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8cjDQY0t8zA9G99RoVPJ8Q.png" /></figure><h4>Hedging Visualization of Delta versus Delta-Vega Hedging</h4><p>Bellow is a visual comparison of the Delta hedging (Left) versus the Delta-Vega (Right) hedging with the variance swap given an earnings gap with σ_ε=8%, β=1, with the variance swap hedging 100% Vega.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Cco-I3NhwFuG0o1CnoUXw.png" /><figcaption><strong>Delta Hedging</strong> (Left) versus <strong>Delta-Vega Hedging</strong> (Right) [1]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KTF6hZXNOxIP2pGMmVtrvw.png" /><figcaption><strong>Delta Hedging</strong> (Left) versus <strong>Delta-Vega Hedging</strong> (Right) [2]</figcaption></figure><pre>-- Without Variance Swap --------------------------<br>Option Price :  1.15883, Spread Earned: 0.00579<br>PnL mean     : -2.269341  CI [-2.33162,-2.21223]<br>PnL std      :  2.792880<br>VaR95        : -8.0855  CI [-8.3779,-7.8468]<br>CVaR95       : -10.7284  CI [-11.0474,-10.3998]<br>Mean Δ cost  :  0.004120<br><br>-- With Variance Swap --------------------------<br>Option Price :  1.15883, Spread Earned: 0.00579<br>PnL mean     : 2.168670  CI [2.07997,2.24970]<br>PnL std      :  4.441689<br>VaR95        : -0.3034  CI [-0.3138,-0.2904]<br>CVaR95       : -0.4077  CI [-0.4206,-0.3953]<br>Mean Δ cost  :  0.004124<br>Vswap Notiona: 58.2176  Strike: 0.0101<br>Mean Swap PnL: 4.4224 CI [4.2971,4.5441]<br>&gt;Expected Mean Swap PnL: -0.005822</pre><h4>Comparison Points</h4><ul><li>Given that the jump is quite substantial, it increases realized volatility significantly. When realized volatility increases, the variance swap pays, thus the difference between expected payoff of the vswap being -0.005822, and realized being 4.4224.</li><li>Under those assumptions for the jump size, the variance swap significantly reduces the risk as it is evident by the PnL distribution at maturity, with the VaR being -8.0855 (without the vswap), and being -0.3034 (with the vswap).</li><li>Since the variance swap has a linear payoff, the profit we have in this simulation is linear with the size of the notional.</li></ul><h4>Profit and Risk over Different Amounts of Jump Size Variance</h4><p>Bellow is a visualization of the profit and loss of the Delta-Vega hedging strategy with a variance swap, hedging 100% Vega.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mfWa637BAYylIHKIWsdZ8Q.png" /></figure><p><strong>Profit:</strong><br>Here it is evident that there is an exponential relationship between the profit and the size of the earnings surprise/gap. This is explained by the fact that the stock’s PnL is already stochastic, and we see a profit in the variance swap when the jump is significantly greater than the expected variance.</p><p><strong>Risk:<br></strong>The variance swap can be used <strong>very effectively</strong> to reduce potential increases in VaR from earnings surprises/gaps. Since, it remains stable throughout the size of the surprise/gap.</p><h3>Discussion</h3><p>This article demonstrated a comprehensive quantitative analysis of Delta-Vega hedging effectiveness using variance swaps under a Heston stochastic volatility framework. Specifically, it detailed:</p><ol><li><strong>Delta Hedging Simulation:</strong> A clear methodology for performing delta hedging simulations on a 30-day European call option using the Heston model, highlighting the dynamics and sensitivities involved.</li><li><strong>Variance Swaps Mechanics:</strong> An in-depth explanation of variance swaps, including their theoretical pricing, calculation of optimal notionals for hedging stochastic volatility exposure, and their replication through portfolios of European options.</li><li><strong>Risk Mitigation Efficiency:</strong> Empirical validation showing a significant reduction in portfolio risk metrics, notably a 53% reduction in Value-at-Risk (VaR) at maturity, when incorporating variance swaps into delta-hedging strategies.</li><li><strong>Hedging Against Earnings Shocks:</strong> Analysis of hedging effectiveness under unexpected market shocks such as earnings announcements. The simulation illustrated how variance swaps not only effectively mitigate the risk associated with sudden large price jumps but can also generate substantial profits under scenarios of elevated realized volatility relative to initial market expectations.</li></ol><p>Overall, this study underscores the strategic advantage of integrating variance swaps into traditional delta-hedging frameworks, emphasizing their role in robust volatility risk management and highlighting potential profitability under extreme market events.</p><h3>Conclusion</h3><p>Variance swaps, as derivatives referencing the same underlying asset as a European call option but with fundamentally distinct payoff structures, are highly effective when used alongside a portfolio of short European options. This combination significantly mitigates the risk inherent in selling individual European call options.</p><p>Practically, this implies that strategically purchasing a diversified portfolio of European options across the entire implied volatility smile <strong>can substantially offset the primary risks associated with writing a single European option. </strong>However, the associated hedging costs reduce the net profitability of this option-writing strategy.</p><p><strong>Hedging Perspective<br>1. </strong>Variance swaps provide an efficient mechanism for significantly reducing the volatility risk associated with selling European options.<br><strong>2. </strong>A full Vega hedge (100%) typically exhibits poor cost-efficiency. Practitioners therefore often prefer partial hedges, with the precise level determined by specific risk management objectives and desk risk tolerance.<br><strong>3.</strong> Profits from an earnings surprise typically exhibit exponential behavior; consequently, a hedging strategy can be highly sensitive to sudden large shocks. In such scenarios, deploying additional derivatives (e.g., option spreads) may yield superior hedging efficacy.</p><p><strong>Speculation Perspective<br>1. </strong>Using variance swaps for pure speculation on realized volatility generally yields negative expected returns, as swap strikes typically incorporate premiums above historical realized volatility. Consequently, speculators must forecast realized volatility substantially above the swap strike — a challenging proposition given market efficiency.<br><strong>2. </strong>Speculating on volatility spikes arising from earnings announcements via variance swaps is suboptimal. Significant jumps are required for profitability, and the strategy exposes the holder to extraneous volatility risks until maturity. Alternative structured option strategies, such as spreads, often offer a more targeted and cost-effective speculative approach.</p><blockquote><strong>Variance swaps</strong> can be used as a<strong> hedging instrument to reduce exposure to volatility swings</strong>, or they can be used as an <strong>instrument on speculating on volatility</strong>. The question is; if your risk reduction or bet justifies their cost.</blockquote><h3>The End</h3><p>I hope you liked my article, feel free to connect with me at <a href="https://www.linkedin.com/in/atsoskounoglou/">LinkedIn</a> and share your thoughts and feedback with me.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc52977de7c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simulating the Heston model with Quadratic Exponential]]></title>
            <link>https://medium.com/@alexander.tsoskounoglou/simulating-the-heston-model-with-quadratic-exponential-50cf2b1366b5?source=rss-e3674ac63c40------2</link>
            <guid isPermaLink="false">https://medium.com/p/50cf2b1366b5</guid>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[options]]></category>
            <category><![CDATA[simulation]]></category>
            <dc:creator><![CDATA[Alexander Tsoskounoglou]]></dc:creator>
            <pubDate>Tue, 30 Jul 2024 11:33:04 GMT</pubDate>
            <atom:updated>2024-07-30T11:34:36.595Z</atom:updated>
            <content:encoded><![CDATA[<h3>Simulating the Heston model with the Quadratic Exponential scheme</h3><p>Fast and accurate Python implementation of the Quadratic-Exponential scheme for simulating the Heston model.</p><ul><li>Github code: <a href="https://github.com/ithakis/Heston-Model-Quadratic-Exponential-QE-">Link</a></li><li>My Linkedin: <a href="https://www.linkedin.com/in/alexander-tsoskouonglou-13a391162/">Link</a></li></ul><h4><strong>Contents:</strong></h4><ul><li>Heston Model Mathematics</li><li>Why we need the Quadratic Exponential to simulate the Heston Model</li><li>Quadratic Exponential scheme for Simulating the Heston model</li><li>Explaining the Mathematics of the Quadratic Exponential Scheme</li><li>Numerical Results for pricing European Call Options vs Analytical Solutions.</li></ul><h4>Why I am writing this article:</h4><p><strong>After looking, I couldn’t find a QE implementation in python which is fast and efficient. </strong>There are only some Github repos, which over complicate the procedure proposed by Andersen (2005) “Efficient Simulation of the Heston Stochastic Volatility Model” [1]. So, I embarked on a journey to make my own. As a computational scientist this is an interesting and challenging topic for me, which is also important for another project I am working on.</p><h3>Heston Model Mathematics</h3><figure><img alt="Heston dynamics" src="https://cdn-images-1.medium.com/max/585/0*tAgllM7FW7wiMuVe.png" /></figure><p>Published at 1993 from Steven L. Heston, in the article “A Closed-Form Solution for Options with Stochastic Volatility with Applications to Bond and Currency Options” [2]; the Heston model has a lot of benefits, which make it ideal for modelling Stocks.</p><ol><li>It has a stochastic volatility component which is a more realistic assumption about the underlying.</li><li>The volatility follows a mean reverting process where the kappa*(theta— v_t)dt, which assumes that volatility tends to have a long term mean (theta) with a force (kappa) that when it deviates from the expected average, it brings it back close to that average.</li><li>The square root of in front of the dW of v_t means that the close v_t gets to zero, the smaller variability v_t has. Preventing negative values, which are not possible when talking about volatility.</li><li>The rho captures the negative relationship between increases in stock prices and volatility. (When Stock prices increase, volatility tends to decrease, and vice versa)</li><li>While difficult, it is possible to derive semi-analytical solutions for options which only depend on the expiration (not for American style). Which makes the pricing of derivatives with the Heston Model, computationally efficient.</li><li>The Heston model can be used for longer time horizons than the observed data which is calibrated against.</li></ol><h4>Feller condition</h4><p>The Feller condition is a necessary condition to ensure that the variance process v_t remains strictly positive. It is given by:</p><figure><img alt="Feller condition" src="https://cdn-images-1.medium.com/max/69/0*VMvujTQCmNRSoc4C.png" /></figure><h3>Why we need the Quadratic Exponential to simulate the Heston Model</h3><p>One of the most popular ways to simulate the Heston model is the Euler-Maruyama scheme, which uses the analytical solution for the S_{t+1} increment, and deals with the possible negative values of the V_{t+1} by setting those values to zero when they are negative.</p><figure><img alt="Euler-Maruyama method for the Heston Model" src="https://cdn-images-1.medium.com/max/584/0*DqvStUv2X1N31eHS.png" /></figure><p><strong>The problem is that by taking the max, we change the simulated distribution. </strong>The stochastic process that the volatility follows is called CIR (Cox-Ingresoll-Ross) [3] which Andersen (the researcher behind the QE scheme for the Heston model) showed in 2006 [4] what the moments of the CIR distribution should be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/0*GYvQACjIU0F6zste.png" /></figure><p><strong>Using those equations we can validate if a Monte-Carlo simulation produces accurate results for V_t.</strong> Bellow is the Python code which I wrote to simulate the Heston model using the Euler-Maruyama scheme:</p><pre>def sim_heston_simple(S0, V0, rho, theta, sigma, kappa, r, dt, T_steps, N_paths):<br>    # Pre-allocate arrays for stock prices and variances<br>    X_paths = np.zeros((T_steps + 1, N_paths))<br>    V_paths = np.zeros((T_steps + 1, N_paths))<br><br>    # Initial values<br>    X_paths[0, :] = log(S0)<br>    V_paths[0, :] = V0<br><br>    # Generate random numbers for the Brownian motions<br>    Z1 = np.random.normal(size=(T_steps, N_paths))<br>    Z2 = np.random.normal(size=(T_steps, N_paths))<br>    W1 = Z1<br>    W2 = rho * Z1 + np.sqrt(1 - rho ** 2) * Z2<br><br>    for t in range(1, T_steps + 1):<br>        # Ensure non-negativity of variance<br>        V_paths[t, :] = np.maximum(V_paths[t - 1, :] + kappa * (theta - V_paths[t - 1, :]) * dt + sigma * np.sqrt(V_paths[t - 1, :] * dt) * W2[t - 1, :], 0)<br>        <br>        # Calculate stock prices<br>        X_paths[t, :] = X_paths[t - 1, :] + ((r - 0.5 * V_paths[t - 1, :]) * dt + np.sqrt(V_paths[t - 1, :] * dt) * W1[t - 1, :])<br><br>    return exp(X_paths).T, V_paths.T</pre><p>Executing the code above for following parameters:</p><pre>S0      = 100  # initial stock price <br>r       = 0.05<br>q       = 0.00  # risk-free rate and dividend yield<br>v0      = 0.0228  # initial variance<br>theta   = 0.0363  # long-term mean variance<br>kappa   = 0.0807  # rate of mean reversion<br>sigma   = 1.1760  # volatility of variance<br>rho     = -0.3021   # correlation between stock and variance<br>N_paths = 100_000  ;    N_paths = int(2 ** np.ceil(np.log2(N_paths)))   # number of paths<br>T_steps = 100  # time horizon<br>T       = 1  # time horizon<br>dt      = 1/T_steps  # time step</pre><p>Creates the following results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d8F24Ivgx1JNwZwbOMdjbA.png" /><figcaption>Monte Carlo paths for the Simple Heston model simulation.</figcaption></figure><h4>Comparing Empirical Results to Analytical</h4><p>Using the following formulas we can empirically calculate the first 4 moments:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/151/0*LvXqouPqrU8UU27k.png" /><figcaption>Empirical way to derive the moments of a distribution</figcaption></figure><p>We can also calculate the 95th confidence interval of the empirical values based on the Standard Error (SE):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/0*EV45eWgm-l0U8rC1.png" /><figcaption>Standard Error in the approximation of the First Moment (Average)</figcaption></figure><p><strong>The same equation can be repeat for each moment, producing a confidence interval which we can test if the analytical version is inside of. </strong>I used 128 because the number of paths are in the power of two (the Sobol generator likes the number of paths to be in the power of two).</p><pre>m1_vol_Em   = v_T_array_QE[:,-1].mean()<br>m1_vol_SE   = v_T_array_QE[:,-1].reshape(128,-1).mean(axis=0).std() / sqrt(128)<br><br>m2_vol_Em   = ((v_T_array_QE[:,-1])**2).mean()<br>m2_vol_SE   = ((v_T_array_QE[:,-1])**2).reshape(128,-1).mean(axis=0).std() / sqrt(128)<br><br>Std_vol_Em  = v_T_array_QE[:,-1].std()<br>Std_vol_SE  = v_T_array_QE[:,-1].reshape(128,-1).std(axis=0).std() / sqrt(128)<br>Std_vol_An = np.sqrt(Var_vol_An)<br><br>m3_vol_Em   = ((v_T_array_QE[:,-1])**3).mean()<br>m3_vol_SE   = ((v_T_array_QE[:,-1])**3).reshape(128,-1).mean(axis=0).std() / sqrt(128)<br><br>m4_vol_Em   = ((v_T_array_QE[:,-1])**4).mean()<br>m4_vol_SE   = ((v_T_array_QE[:,-1])**4).reshape(128,-1).mean(axis=0).std() / sqrt(128)</pre><p>You can see the results for 131,072 paths in the table bellow, which <strong>with 95% confidence the Empirical moments are not equal to the Analytically calculated moments.</strong> The difference is quite big actually! (See bellow the IV plot which compares the QE with the simple vs an Analytical solution)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c605a110fd24190094353ae28af67ae/href">https://medium.com/media/5c605a110fd24190094353ae28af67ae/href</a></iframe><h3>Quadratic Exponential scheme for Simulating the Heston model</h3><p>Lets now see how the QA scheme works which based on the work of Andersen (2007) “Efficient Simulation of the Heston Stochastic Volatility Model” [1]. Andersen in his article proves that the QE scheme with the Martingale correction produces correct results for the simulation of the V(t) process. Let&#39;s see bellow how it works.</p><p>To simulate the Heston model, we use a Quadratic Exponential (QE) scheme for variance V_t and a log-normal process for the asset price S_t. The QE scheme approximates the conditional distribution of V_t given V_{t-1} by either <em>a non-central chi-squared distribution</em> or an <em>exponential distribution</em>, depending on a threshold value psi (ψ).</p><h4>The first Step:</h4><p>Is to calculate the conditional moments of the distribution (like in the CIR moments above)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/0*OqSgBkDrMlIcoC2S" /></figure><p>Where <strong>ψ </strong>is calculated to be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/111/0*H93psmkSFYqp7SHE" /></figure><p><strong>If ψ ≤ 1.5</strong>, the non-central chi-squared distribution approximation is used for <em>V_t</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/0*vx-zH2iJRF2_MLRr" /></figure><p><strong>If ψ &gt; 1.5, </strong>the exponential distribution approximation is used for <em>V_t</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/0*yJ7ZzoXKk6XLSCRY" /></figure><p>Where <em>Z_v</em> is a standard normal random variable and <em>U_v</em> is a uniform random variable on [0, 1]. <strong>The combination of the non-central chi-squared distribution and the exponential distribution, is a very good approximation of the CIR stochastic process.</strong></p><h4>Second Step:</h4><p>The S_t is calculated based on the following equations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qIxEobaQYS6XDM-W" /></figure><h4>Quadratic Exponential in Python</h4><p>The code representation of the mathematical formulas above looks like:</p><pre>def QESim(S0, V0, rho, theta, sigma, kappa, r, q, dt, T_steps, N_paths, psiC=1.5, gamma1=0.5, gamma2=0.5, Martingale_Correction=True, _show_progress=True):<br>    &quot;&quot;&quot;<br>    Simulates the Heston model using the Quadratic Exponential (QE) scheme.<br><br>    Parameters<br>    ----------<br>    S0 : float<br>        Initial stock price.<br>    V0 : float<br>        Initial variance.<br>    rho : float<br>        Correlation between the two Brownian motions.<br>    theta : float<br>        Long-term mean of the variance.<br>    sigma : float<br>        Volatility of the variance process (vol of vol).<br>    kappa : float<br>        Rate at which variance reverts to theta.<br>    r : float<br>        Risk-free interest rate.<br>    q : float<br>        Dividend yield.<br>    dt : float<br>        Time increment.<br>    T_steps : int<br>        Number of time steps.<br>    N_paths : int<br>        Number of simulated paths.<br>    psiC : float, optional<br>        Threshold parameter for the QE scheme (default is 1.5).<br>    gamma1 : float, optional<br>        Gamma parameter for the QE scheme (default is 0.5).<br>    gamma2 : float, optional<br>        Gamma parameter for the QE scheme (default is 0.5).<br>    Martingale_Correction : bool, optional<br>        If True, applies Martingale correction (default is True).<br>    _show_progress : bool, optional<br>        If True, displays progress of the simulation (default is True).<br><br>    Returns<br>    -------<br>    S : ndarray<br>        Simulated stock prices, shape (N_paths, T_steps+1).<br>    V : ndarray<br>        Simulated variances, shape (N_paths, T_steps+1).<br><br>    Notes<br>    -----<br>    The function uses Sobol sequences for generating random numbers and the inverse cumulative normal distribution to<br>    obtain normally distributed random variables. The QE scheme is used to handle the variance process.<br>    <br>    Martingale correction dynamics:<br>    - When psi &lt;= psiC:<br>      \[<br>      K_0^* = -\frac{A b^2 a}{1 - 2 A a} + \frac{1}{2} \log(1 - 2 A a) - (K_1 + \frac{1}{2} K_3) V_{t-1}<br>      \]<br>    - When psi &gt; psiC:<br>      \[<br>      K_0^* = -\log\left(p + \frac{\beta (1 - p)}{\beta - A}\right) - (K_1 + \frac{1}{2} K_3) V_{t-1}<br>      \]<br><br>    Examples<br>    --------<br>    S_T_array_QE, V_T_array_QE = QESim(S0=100, V0=0.04, rho=-0.7, theta=0.04, sigma=0.2, kappa=1.5, r=0.05, q=0.02, dt=1/252,<br>                                       T_steps=252, N_paths=10000, Martingale_Correction=True)<br><br>    References<br>    ----------<br>    Andersen, L. (2008). Simple and efficient simulation of the Heston stochastic volatility model. Journal of Computational Finance, 11(3), 1-42.<br>    &quot;&quot;&quot;<br>    E = np.exp(-kappa * dt)<br>    K0 = -(kappa * rho * theta) / sigma * dt<br>    K1 = (kappa * rho / sigma - 1 / 2) * gamma1 * dt - rho / sigma<br>    K2 = (kappa * rho / sigma - 1 / 2) * gamma2 * dt + rho / sigma<br>    K3 = (1 - rho ** 2) * gamma1 * dt<br>    K4 = (1 - rho ** 2) * gamma2 * dt<br>    A = K2 + 0.5 * K4<br>    if Martingale_Correction: K0_star = np.empty(N_paths)<br><br><br>    sobol_gen = qmc.Sobol(d=T_steps + 1)<br>    Uv = sobol_gen.random(n=N_paths).T<br>    Us = sobol_gen.random(n=N_paths).T<br>    Zv, Zs = norm.ppf(Uv), norm.ppf(Us)<br><br>    S = np.zeros((T_steps+1, N_paths))<br>    V = np.zeros((T_steps+1, N_paths))<br><br>    S[0] = log(S0)<br>    V[0] = V0<br><br>    for t in trange(1, T_steps+1, desc=&quot;Simulating Paths&quot;, position=0, leave=False, disable=not _show_progress):<br>        m = theta + (V[t - 1] - theta) * E<br>        s2 = (V[t - 1] * sigma**2 * E)/kappa * (1 - E) + (theta * sigma**2)/(2 * kappa)*(1 - E)**2 # Correct<br>        psi = s2 / m ** 2<br><br>        idx = psi &lt;= psiC<br>        # When psi &lt;= psiC<br>        b = np.sqrt(2/psi[idx] - 1 + np.sqrt(2/psi[idx] * (2/psi[idx] - 1)))<br>        a = m[idx] / (1 + b**2)     <br>        V[t, idx] = a * (b + Zv[t, idx]) ** 2<br><br>        # When psi &gt; psiC<br>        p = (psi[~idx] - 1) / (psi[~idx] + 1)<br>        beta = (1 - p ) / m[~idx]<br>        idx2 = (Uv[t, ~idx] &lt;= p)<br>        V[t, ~idx] = np.where(idx2, 0, 1 / beta * np.log((1 - p) / (1 - Uv[t, ~idx])))<br><br>        if Martingale_Correction:<br>            K0_star[idx]  = - (A * b**2 * a) / (1 - 2 * A * a) + 0.5 * np.log(1 - 2 * A * a) - (K1 + 0.5 * K3) * V[t-1, idx]<br>            K0_star[~idx] = - np.log(p + (beta * (1 - p)) / (beta - A)) - (K1 + 0.5 * K3) * V[t-1, ~idx]<br><br>            S[t] = S[t - 1] + (r - q) * dt + K0_star + K1 * V[t - 1] + K2 * V[t] + np.sqrt(K3 * V[t - 1] + K4 * V[t]) * Zs[t]<br>        else:<br>            S[t] = S[t - 1] + (r - q) * dt + K0      + K1 * V[t - 1] + K2 * V[t] + np.sqrt(K3 * V[t - 1] + K4 * V[t]) * Zs[t]<br>    <br>    S = exp(S).T<br>    V = V.T<br><br>    # Find if there are NaN values and replace those paths with the expectation E[S_t] and E[V_t]<br>    idx = np.isnan(S).sum(axis=1) == 0<br>    if idx.sum() &lt; N_paths :<br>        print(f&quot;Warning: {N_paths - idx.sum()} paths removed due to NaN values and replaced with E[S_t] and E[V_t]&quot;)<br>        S[~idx] = S0*exp((r-q)*np.arange(T_steps+1)*dt)<br>        V[~idx] = V0 * np.exp(-kappa * np.arange(T_steps+1)*dt) + theta * (1 - np.exp(-kappa * np.arange(T_steps+1)*dt))<br><br>    return S, V</pre><p>Simulating for 1 year with 131,072 MC paths with 100 steps (0.01dt) produces the following results:</p><figure><img alt="Monte Carlo paths for the Quadratic Exponential model, Monte Carlo simulation." src="https://cdn-images-1.medium.com/max/1024/1*Xdpgd0ivJaPMUNI67QWCNQ.png" /><figcaption>Monte Carlo paths for the Quadratic Exponential model, Monte Carlo simulation.</figcaption></figure><p>With the following results:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0cd2bfdebfe7aee06fb565663457648f/href">https://medium.com/media/0cd2bfdebfe7aee06fb565663457648f/href</a></iframe><p><strong>As you can see with 95% confidence the Empirical moments of V_t are the same as the Analytical, </strong>since the difference is smaller than the 95% CI. Since those results as so amazing. Lets take a look on how the mathematics of the QE are derived so we get a better understanding of the magic of the QE scheme.</p><h3>Mathematics of the Quadratic Exponential Scheme</h3><p><strong>First</strong> lets start with the log transformed asset X_t = log(S_t) which equals to the equation bellow, where the second line is with the Cholesky decomposition:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/0*lAga7suG048GqFLm" /></figure><p><strong>Second</strong>, lets start with integrating the SDE of V_t with the goal of finding V_{t+Dt}</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/0*tP8CfC9HQbFXxDby" /></figure><p>Which can be be rearranged to solve for the integral:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ERldI2Tku1cFwx2Q" /></figure><p><strong>Now if we integrate the dlog(S) from [t, t+Dt] to find log(S_{t+Dt}) it becomes:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N4FvbFMJE3Dn8--w" /></figure><p>Where <strong>the integral of V_u can be approximated with</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/0*lLZJQq8Ff8Mlp0Pp" /></figure><p><strong>In QE gamma_1 and gamma_2 equal to 1/2</strong>, which is the simple approximation, but Andersen mentions that there can be more fancy ways to calculate gammas. Which can match the moments of the resulting distribution, but for simplicity and efficiency sake, we use 1/2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*K2biW9873Jwm4KoT" /></figure><p>Where:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/0*N0d9BNGaGF_yB4lG" /></figure><p>Andersen showed that S_T is not going to be a martingale, where:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/0*U6BxLvMOSI_2WVxU" /></figure><p>Where for S_{t+Dt} to be a martingale K0 needs to equal to the equation bellow, where K0* will be used in place of K0 in the ln(S_{t+Dt}) equation above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/0*-g8bLaoLAhPOgrcl" /></figure><h3>Numerical Results</h3><h4>Implied Volatility Smile</h4><p>The first thing that it is worth looking into is the implied volatility curve produced by the Euler and the QE schemes for the Heston model. Where the analytic solution to a European Call option using the Heston model can be derived with the following code:</p><pre>from scipy.integrate import quad<br>from functools import partial<br><br>def Heston_FFT(S0, K, T, r, kappa, theta, sigma, v0, rho, opt_type):<br>    def Q1(k, cf, right_lim):<br>        &quot;&quot;&quot;<br>        P(X&lt;k) - Probability to be in the money under the stock numeraire.<br>        cf: characteristic function<br>        right_lim: right limit of integration<br>        &quot;&quot;&quot;<br><br>        def integrand(u):<br>            return np.real((np.exp(-u * k * 1j) / (u * 1j)) * cf(u - 1j) / cf(-1.0000000000001j))<br><br>        return 1 / 2 + 1 / np.pi * quad(integrand, 1e-15, right_lim, limit=2000)[0]<br><br><br>    def Q2(k, cf, right_lim):<br>        &quot;&quot;&quot;<br>        P(X&lt;k) - Probability to be in the money under the money market numeraire<br>        cf: characteristic function<br>        right_lim: right limit of integration<br>        &quot;&quot;&quot;<br><br>        def integrand(u):<br>            return np.real(np.exp(-u * k * 1j) / (u * 1j) * cf(u))<br><br>        return 1 / 2 + 1 / np.pi * quad(integrand, 1e-15, right_lim, limit=2000)[0]<br><br>    def cf_Heston_good(u, t, v0, mu, kappa, theta, sigma, rho):<br>        &quot;&quot;&quot;<br>        Heston characteristic function as proposed by Schoutens (2004)<br>        &quot;&quot;&quot;<br>        xi = kappa - sigma * rho * u * 1j<br>        d = np.sqrt(xi**2 + sigma**2 * (u**2 + 1j * u))<br>        g1 = (xi + d) / (xi - d)<br>        g2 = 1 / g1<br>        cf = np.exp(<br>            1j * u * mu * t<br>            + (kappa * theta) / (sigma**2) * ((xi - d) * t - 2 * np.log((1 - g2 * np.exp(-d * t)) / (1 - g2)))<br>            + (v0 / sigma**2) * (xi - d) * (1 - np.exp(-d * t)) / (1 - g2 * np.exp(-d * t))<br>        )<br>        return cf<br><br>    cf_H_b_good = partial(cf_Heston_good, t=T, v0=v0, mu=r, theta=theta, sigma=sigma, kappa=kappa, rho=rho)<br><br>    k = np.log(K / S0)  # log moneyness<br>    limit_max = 1000  # right limit in the integration<br>    call = S0 * Q1(k, cf_H_b_good, limit_max) - K * np.exp(-r * T) * Q2(k, cf_H_b_good, limit_max)<br><br>    return call if opt_type == &#39;c&#39; else call + K * np.exp(-r * T) - S0</pre><p><strong>The code for the analytic solution is obtained from Nicola Cantarutti’s Github repo: (</strong><a href="https://github.com/cantaro86/Financial-Models-Numerical-Methods/blob/master/1.3%20Fourier%20transform%20methods.ipynb">Link</a>). I have my self worked on that problem approaching the pricing of European options using the Fourier Transform (<a href="https://medium.com/@alexander.tsoskounoglou/pricing-options-with-fourier-series-p3-the-heston-model-d157369a217a">Link</a>), but the Fourier Transform is an approximation which might now match the theoretical results 1:1.</p><p>The resulting IV smile for all 3 approaches is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*SF6UmU1UygKqd8OOA_IsHQ.png" /><figcaption>IV smile for Quadratic Exponential — Euler — Analytical Methods</figcaption></figure><p>From the shaded area you can see the uncertainty (95%CI) in the pricing deep out of the money options increases the lower the strike price. (To mitigate this somebody can use importance sampling. But thats not the focus of this article) <strong>The Quadratic Exponential scheme matches perfectly the IV smile that the analytical code produces! </strong>Bellow you can see a summary to compare the moments of the V_T between the QE and the Euler schemes for 131,072 paths. Quadratic Exponential is clearly matching the moments!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25b0bf5151d724dbf1dbac6ec627c432/href">https://medium.com/media/25b0bf5151d724dbf1dbac6ec627c432/href</a></iframe><h4>Moments of V_T as a Function of Time Steps</h4><p>Doing an analysis on the difference between the Monte-Carlo results and the analytical solution, we can see that (as promised) the QE scheme is ver accurate in its moment matching capabilities starting from 1 step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XY6-00Ti_sjurK-NOzCJ4w.png" /></figure><p><strong>You can see in the tables bellow the plotted results above which indicate that the Euler scheme exhibits a constant bias in the moments of the V_T.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09c08ec48c395d7f5852324d018750eb/href">https://medium.com/media/09c08ec48c395d7f5852324d018750eb/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/113623839fc7df2cca0e9f56d8c6dd6a/href">https://medium.com/media/113623839fc7df2cca0e9f56d8c6dd6a/href</a></iframe><h4>Moments of V_T as a Function of Number of Paths</h4><p>Performing the same analysis as above to see if the number of paths plays a role in the accuracy of the simulation of the volatility, its evident that <strong>the number of paths decreases the error in the moments for the QE but for the Euler scheme it does not.</strong> (Speaking for the first 2 moments which are the main focus here)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gs9ydoB1Ui8blcHtWTUCNQ.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7026f25e74dd2aab34a73562bb3b87c/href">https://medium.com/media/a7026f25e74dd2aab34a73562bb3b87c/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/527c04e68687394da6175e8b3d65b520/href">https://medium.com/media/527c04e68687394da6175e8b3d65b520/href</a></iframe><p><strong>Convergence Behaviour of S(T)</strong></p><p>As discussed by Andersen [1]<strong> there is no analytical solution to the moments of S_t</strong>, which<strong> to validate the results of the QE scheme, a comparison between an option priced with the QE scheme vs the analytical solution</strong> from Cantarutti’s code.</p><p><strong>Based on the equation bellow we can price a European Call option using the results from the QE scheme. With the use of Control Variates, which vastly reduce the standard error in the calculation of C_0, we can test the convergence of C_0 against the analytical solution.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/0*Uy1mJMtEmxdTFnPQ" /></figure><p>Bellow is the results using 524,288 paths and 100 time steps, which from the Moment analysis above we established that it is an acceptable accuracy, when it comes to the moments of V_t.</p><ul><li>E[S_T]: Empirical(105.06) — Analytical(105.13)</li><li>Analytical: 6.66626</li><li>Unadjusted C_0: 6.62633</li><li>&gt;&gt;Difference: <strong>0.03992</strong></li><li>CI95 of the unadjusted payoff: <strong>0.02593</strong></li><li>Adjusted C_0: 6.66135</li><li>&gt;&gt;Difference: <strong>0.00491</strong></li><li>CI95 of the adjusted payoff: <strong>0.01576</strong></li></ul><p>The results indicate that without the use of Control variates the results of the QE scheme are not accurate enough to price European options. As the difference in the value of C_0 between the analytical and the MC solution is greater than the 95% confidence interval.</p><p><strong>However with the use of control variates, we can see that the difference is much less that the (reduced) 95% confidence interval. </strong>Bellow is an analysis on the convergence in the analytical price over the number of time steps with the use of 65,536 paths for 1 year.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*JCmHrnWtbtxyS2Vs-Yd79w.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f57320eb0a71a14d500f9fccfa29793/href">https://medium.com/media/1f57320eb0a71a14d500f9fccfa29793/href</a></iframe><p><strong>From the results above I would consider a dt of 1 day to be very usable for an accurate simulation of the Heston Model, with all the simulations that have a dt smaller than 1/52 being within the CI.</strong></p><h3>Discussion and Conclusions</h3><h4>What we learned:</h4><ul><li>The Euler scheme is not producing correct result, thus the need for a more sophisticated model is needed.</li><li>The Quadratic-Exponential scheme for the Heston model is an alternative, where the of the non-central chi distribution and the exponential distribution are used to approximate the V_t with great success.</li><li><strong>With a dt &lt; 0.01 the QE scheme produces accurate Monte-Calro simulation results which have the same solution (within 95%CI) as the analytical solution.</strong></li></ul><h4>Future Work and limitations</h4><ul><li>There is also another scheme the “NCI-QE” for the Heston Model, which apparently is a bit more accurate for the same number of time steps than the QE. But this remains to be a story for another time. If you want to learn more please read [5].</li></ul><h3>Thank you for Reading</h3><h4>References:</h4><p>[1] Andersen, L. B. (2007). Efficient simulation of the Heston stochastic volatility model. <em>Available at SSRN 946405</em>.</p><p>[2] Heston, S. L. (1993). A Closed-Form Solution for Options with Stochastic Volatility with Applications to Bond and Currency Options. <em>Review of Financial Studies</em>, 6(2), 327–343.</p><p>[3] Cox, J. C., Ingersoll, J. E. Jr., &amp; Ross, S. A. (1985). A Theory of the Term Structure of Interest Rates. <em>Econometrica</em>, 53(2), 385–407.</p><p>[4] Andersen, L. B. G., &amp; Piterbarg, V. V. (2007). Distributional properties of continuous time processes: From CIR to Bates. <em>Finance and Stochastics</em>, 11(1), 77–105.</p><p>[5] Van Haastrecht, A., &amp; Pelsser, A. (2010). Efficient, almost exact simulation of the Heston stochastic volatility model. <em>International Journal of Theoretical and Applied Finance</em>, <em>13</em>(01), 1–43.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50cf2b1366b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pricing Options with Fourier Series P3 — The Heston Model]]></title>
            <link>https://medium.com/@alexander.tsoskounoglou/pricing-options-with-fourier-series-p3-the-heston-model-d157369a217a?source=rss-e3674ac63c40------2</link>
            <guid isPermaLink="false">https://medium.com/p/d157369a217a</guid>
            <category><![CDATA[fourier-transform]]></category>
            <category><![CDATA[mathematical-modeling]]></category>
            <category><![CDATA[options-trading]]></category>
            <category><![CDATA[finance]]></category>
            <dc:creator><![CDATA[Alexander Tsoskounoglou]]></dc:creator>
            <pubDate>Sun, 17 Sep 2023 09:59:41 GMT</pubDate>
            <atom:updated>2023-10-15T11:55:02.335Z</atom:updated>
            <content:encoded><![CDATA[<h3>Pricing Options with Fourier Series P3 — The Heston Model</h3><p>Unlock the Power of Fourier Transform &amp; The Heston Model to Master European Options Pricing — Dive into Part 3 of our Fourier Series journey. Missed the basics? Check out <a href="https://medium.com/@alexander.tsoskounoglou/pricing-options-with-fourier-series-p1-5bf60443ba0c">Part 1</a> &amp; <a href="https://medium.com/@alexander.tsoskounoglou/pricing-options-with-fourier-series-p2-fa7328bd942b">Part 2</a>!</p><ul><li>👨‍💻 Interactive Guide: Grab the <a href="https://github.com/ithakis/Pricing-Options-with-Black-Scholes/blob/main/Heston%20Model%20Calibration.ipynb">Github</a>!</li><li>📖 Based on cutting-edge “Stochastic Calculus” lectures by Prof. Michel Vellekoop at the University of Amsterdam. Also I included the articles which this project is based on.</li></ul><h4>Contents:</h4><ul><li>Recap: Fourier Transformation, characteristic function</li><li>Material used: The Heston Model, Characteristic Function of the Heston Model, Integration Limits (cumulants)</li><li>Method of calculating IV, Risk Free Rate Model (Nelson Siegel Svensson)</li><li>Collecting Option chain Data from yfinance</li><li>3D Option Chain Plots: (Price, IV) vs (Time) vs (Strike)</li><li>Calibration of Heston Model Parameters. min IV(predicted) vs IV(observed)</li><li>Error Analysis: Weighted RMSE</li><li>Heston IV surface</li><li>Discussion: Limitations of this method. Why Deep In/Out of the money options are hard to price correctly. (“The Fourier Trap”)</li></ul><p><em>“As far as the laws of mathematics refer to reality, they are not certain, and as far as they are certain, they do not refer to reality.”</em><br><strong>Albert Einstein</strong></p><h3>Fourier Transformation, characteristic function of Random Variable</h3><p>Let’s quickly revisit the mathematical tool we’re using to price a European Put option. In <a href="https://medium.com/@alexander.tsoskounoglou/pricing-options-with-fourier-series-p1-5bf60443ba0c">Part 1</a>, I delved into the Fourier Transformation, a technique that converts a function into a series of cosine waves. In <a href="https://medium.com/@alexander.tsoskounoglou/pricing-options-with-fourier-series-p2-fa7328bd942b">Part 2</a>, I discussed how to leverage the characteristic function of a random variable’s distribution to accurately approximate its PDF/CDF. This allows us to <strong>price the European Put option</strong> effectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dfBSALDIG_lkTD06jV7CQg.png" /><figcaption>Recap: Fourier Transformation of pricing an Option with the characteristic function</figcaption></figure><p>What’s missing from our toolkit are the characteristic function of the distribution and the integration limits (cumulants), both of which were covered in <a href="https://medium.com/@alexander.tsoskounoglou/pricing-options-with-fourier-series-p2-fa7328bd942b">Part 2</a>. There, I demonstrated how to price a European Put option using Geometric Brownian Motion (GBM) and compared it to its analytical counterpart. The results showed that this method is highly accurate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*fnNiqCiTmR5n5RybPYmZ1w.png" /><figcaption>The characteristic function of the Geometric Brownian Motion</figcaption></figure><h3>The Heston Model</h3><p>Below are the equations that the Heston model uses to describe the rate of change of <em>S</em>(<em>t</em>) through a stochastic volatility model. I’m going to assume you’re already familiar with the Heston Model. Instead of rehashing its basics, let’s focus on some of its key properties that make Fourier Transform (FT) a valuable tool for this model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*YqTQTfrbVEtQjl2rj0Fk4Q.png" /><figcaption>Heston Model Equations for modeling the rate of change of S_t and sigma_t.</figcaption></figure><p><strong>If we employ Euler-Monte Carlo (MC) to approximate <em>dS</em>, we run into two issues:</strong></p><ul><li><strong>Time Efficiency</strong>: MC takes significantly longer than FT. When calibrating across an option chain containing approximately 6,000 European options, each set of parameters tested in MC took around 10 minutes. In contrast, FT took less than a second. This makes MC computationally infeasible when you have to test hundreds of parameter combinations.</li><li><strong>Negative Values in <em>Vt</em></strong>​: The term ζ×sqrt{<em>dt</em>×<em>Vt}</em>×Z can yield negative values for <em>Vt</em>​. This is problematic because the square root of a negative number is undefined in the realm of real numbers. While you can modify the model to use |<em>Vt</em>​| and a very small <em>dt</em>, this workaround makes it impossible to compare MC and FT results.</li></ul><p>There are alternative approaches for MC, such as adding more Ito terms or explicitly calculating the <em>Vt</em>​ integral.</p><p><em>Source: Milan Mrázek and Jan Pospíšil [1]</em></p><h3><strong>Characteristic Function of The Heston Model</strong></h3><p>I highly recommend taking a look at “The Little Heston Trap”[2]. This source offers an in-depth explanation of the correct equation and dynamics for the characteristic function of the Heston model. Understanding this characteristic function is crucial for achieving stable approximations, regardless of the parameters you’re working with.</p><p>For this project, I relied on the characteristic function provided in my “Stochastic Calculus” course. The equation is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*bJRXHHQfBdvMuZZPUf4jJA.png" /><figcaption>Heston Model Characteristic Function</figcaption></figure><pre>def heston_char(u): <br>    t0 = 0.0 ;  q = 0.0<br>    m = log(S0) + (r - q)*(T-t0)<br>    D = sqrt((rho*zeta*1j*u - kappa)**2 + zeta**2*(1j*u + u**2))<br>    C = (kappa - rho*zeta*1j*u - D) / (kappa - rho*zeta*1j*u + D)<br>    beta = ((kappa - rho*zeta*1j*u - D)*(1-exp(-D*(T-t0)))) / (zeta**2*(1-C*exp(-D*(T-t0))))<br>    alpha = ((kappa*theta)/(zeta**2))*((kappa - rho*zeta*1j*u - D)*(T-t0) - 2*log((1-C*exp(-D*(T-t0))/(1-C))))<br>    return exp(1j*u*m + alpha + beta*v0)</pre><p>🚨 Heads Up: Be cautious with the <em>α</em> and <em>β</em> values in the equation. They are not the same as the integration limits. (Don’t ask me how I know.)</p><h3>Integration Limits, cumulants</h3><p>Cumulants, as defined by <a href="https://en.wikipedia.org/wiki/Cumulant">Wikipedia</a>, are essentially the exponentiated central moments of a distribution. The characteristic function and the cumulants are intrinsically linked, allowing us to use the second cumulant to calculate the variance. This, in turn, helps us define the integration limits [<em>a</em>,<em>b</em>].</p><p>In <a href="https://medium.com/@alexander.tsoskounoglou/pricing-options-with-fourier-series-p2-fa7328bd942b">Part 2</a>, I discussed the first and second cumulants for the GBM and how they relate to the integration limits. Similarly, the Heston Model has a cumulant-generating function from which <em>c</em>2​ is derived.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*nkfTTS-9BBz7Re3XNTvbeA.png" /><figcaption>First and Second Cumulants of the GBM and the Integration limits</figcaption></figure><p>Similarly, the Heston Model has a cumulant-generating function from which <em>c</em>2​ is derived. Source: <em>“A Generalized Fourier Transform Approach to Risk Measures” </em>[3]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*itL69uuf-IyF0SSe9YuCJg.png" /><figcaption>First and Second Cumulants of the Heston Model and the Integration limits</figcaption></figure><p><strong>Defining these limits can be as challenging as the main model itself.</strong> The Heston PDF/CDF is notably skewed and exhibits higher kurtosis compared to GBM. While we previously used <em>z</em>=12, a higher z<em>z</em> value, such as <strong><em>z</em>=24, yields better results here.</strong></p><p>🔗 The Fourier Trap: <strong>The values of <em>Z</em> (integration limits) and <em>N</em> (number of terms) are interconnected</strong>. <strong>Increasing <em>Z</em> necessitates a higher <em>N</em>,</strong> but there’s a limit to this, on which I’ll elaborate later on as “The Fourier Trap.”</p><h4>Python Code for Pricing a European Option</h4><p>Below is the complete Python code that allows you to price a European Option using the Fourier Transformed Heston Model. A couple of key points to note:</p><ul><li>We’re pricing a put option, and the formula <em>C</em>=<em>P</em>+<em>S</em>0​−<em>K</em>×exp(−<em>r</em>×<em>T</em>) is used to price a call option.</li><li>This function was a labor of love, so if you find it useful, consider having a drink in my honor and maybe link back to this blog.</li></ul><p>🍻 Cheers to Numba: Using a Just-In-Time (<strong>JIT</strong>) compiler like <strong>Numba</strong> can <strong>speed up the code execution by a whopping 164 times!</strong> We’re talking <strong>26 ms (Numpy) vs. 159 µs (Numba)</strong>. So, let’s raise a glass to Numba for making this process lightning-fast in Python.</p><pre>import numpy as np<br>from numpy import sqrt, exp, pi, cos, sin, log, abs<br>from numba import njit<br><br>@njit<br>def Fourier_Heston_Put(S0, K, T, r, <br>                  # Heston Model Paramters<br>                  kappa, # Speed of the mean reversion <br>                  theta, # Long term mean<br>                  rho,   # correlation between 2 random variables<br>                  zeta,  # Volatility of volatility<br>                  v0,    # Initial volatility <br>                  opt_type,<br>                  N = 1_012,<br>                  z = 24<br>                  ):<br><br>  def heston_char(u): <br>    t0 = 0.0 ;  q = 0.0<br>    m = log(S0) + (r - q)*(T-t0)<br>    D = sqrt((rho*zeta*1j*u - kappa)**2 + zeta**2*(1j*u + u**2))<br>    C = (kappa - rho*zeta*1j*u - D) / (kappa - rho*zeta*1j*u + D)<br>    beta = ((kappa - rho*zeta*1j*u - D)*(1-exp(-D*(T-t0)))) / (zeta**2*(1-C*exp(-D*(T-t0))))<br>    alpha = ((kappa*theta)/(zeta**2))*((kappa - rho*zeta*1j*u - D)*(T-t0) - 2*log((1-C*exp(-D*(T-t0))/(1-C))))<br>    return exp(1j*u*m + alpha + beta*v0)<br>  <br>  # # Parameters for the Function to make sure the approximations are correct.<br>  c1 = log(S0) + r*T - .5*theta*T<br>  c2 = theta/(8*kappa**3)*(-zeta**2*exp(-2*kappa*T) + 4*zeta*exp(-kappa*T)*(zeta-2*kappa*rho) <br>        + 2*kappa*T*(4*kappa**2 + zeta**2 - 4*kappa*zeta*rho) + zeta*(8*kappa*rho - 3*zeta))<br>  a = c1 - z*sqrt(abs(c2))<br>  b = c1 + z*sqrt(abs(c2))<br>  <br>  h       = lambda n : (n*pi) / (b-a) <br>  g_n     = lambda n : (exp(a) - (K/h(n))*sin(h(n)*(a - log(K))) - K*cos(h(n)*(a - log(K)))) / (1 + h(n)**2)<br>  g0      = K*(log(K) - a - 1) + exp(a)<br>  <br>  F = g0 <br>  for n in range(1, N+1):<br>    h_n = h(n)<br>    F += 2*heston_char(h_n) * exp(-1j*a*h_n) * g_n(n)<br><br>  F = exp(-r*T)/(b-a) * np.real(F)<br>  F = F if opt_type == &#39;p&#39; else F + S0 - K*exp(-r*T)<br>  return F if F &gt; 0 else 0<br><br>print(&#39;Speed Analysis of Fourier_Heston_Put: Per Option&#39;)<br>%timeit Fourier_Heston_Put(S0,K, T, r, kappa, theta, rho, zeta, v0, &#39;p&#39;, N = 1_012, z = 24)<br><br>&quot;&quot;&quot; Results (Macbook Air M1):<br>Speed Analysis of Fourier_Heston_Put: Per Option<br>159 µs ± 8.51 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)<br>&quot;&quot;&quot;</pre><h3>Implied Volatility (IV) and the Risk-Free Rate Model (Nelson Siegel Svensson Model)</h3><h4>Calculating Implied Volatility (IV)</h4><p>When dealing with deep in-the-money or out-of-the-money options, calculating IV becomes a numerical game. This task can be as computationally intensive as the Fourier Transformation (FT). Typically, a Newton method-based approach is employed, which, while accurate, can be time-consuming due to its iterative nature.</p><p>🛠 Tool of Choice: For this reason, I opted for the py_vollib_vectorized.vectorized_implied_volatility library. It leverages Numba for faster calculations and is incredibly user-friendly.</p><pre>import py_vollib_vectorized<br>price = 0.10 ; S = 95 ; K = 100 ; t = .2 ; r = .2 ; flag = &#39;c&#39;<br><br>def implied_volatility(price, S, K, t, r, flag):<br>  return py_vollib_vectorized.vectorized_implied_volatility(<br>    price, S, K, t, r, flag, q=0.0, on_error=&#39;ignore&#39;, model=&#39;black_scholes_merton&#39;,return_as=&#39;numpy&#39;) <br><br>print(&#39;Speed Analysis of the implied volatility Function: Per Option&#39;)<br>%timeit implied_volatility(price, S, K, t, r, flag)<br><br>&quot;&quot;&quot; Result (Mackbook Air M1):<br>Speed Analysis of the implied volatility Function: Per Option<br>49 µs ± 2.79 µs per loop (mean ± std. dev. of 7 runs, 10,000 loops each)<br>&quot;&quot;&quot;</pre><h4>Risk-Free Rate (RFR) Curve</h4><p>To determine the RFR, I used U.S. Treasury bonds, which can be accessed through this <a href="https://home.treasury.gov/resource-center/data-chart-center/interest-rates/TextView?type=daily_treasury_yield_curve&amp;field_tdr_date_value_month=202306">link</a>.</p><h4>Nelson Siegel Svensson Method</h4><p>To generate a yield curve, I employed the Nelson Siegel Svensson method. The equation for this method is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VQlRU453ntK1dyfV8Er0Jg.png" /><figcaption>Nelson Siegel Svensson method</figcaption></figure><p>📈 Implementation: The process is straightforward. First, <strong>collect the yields from the U.S. Treasury</strong>. Then, <strong>fit these yields using the Nelson Siegel Svensson model</strong> with the Python library nelson_siegel_svensso(<a href="https://pypi.org/project/nelson-siegel-svensson/">link</a>).</p><pre>from nelson_siegel_svensson.calibrate import calibrate_nss_ols<br># Collected at : 06/01/2023<br>yield_maturities = np.array([1/12, 2/12, 3/12, 4/12, 6/12, 1, 2, 3, 5, 7, 10, 20, 30])<br>yields           = np.array([5.30,5.39,5.50,5.50,5.44,5.11,4.33,3.98,3.70,3.66,3.61,3.98,3.84])<br><br>#NSS model calibrate<br>curve_fit, status = calibrate_nss_ols(yield_maturities,yields)<br>#Results: NelsonSiegelSvenssonCurve(beta0=1.2595121714700128, beta1=4.367186541206554, beta2=-1457.4165045532893, beta3=1458.9304400823748, tau1=6.83997027106895, tau2=6.877834685907713)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PTEtjN_FhAe9Hi4WHHq59Q.png" /><figcaption>Resulting Fit based on the provided data.- Source: <a href="https://github.com/ithakis/Pricing-Options-with-Black-Scholes/blob/main/Heston%20Model%20Calibration.ipynb">Notebook</a></figcaption></figure><h3>Collecting Option Chain Data from yfinance</h3><h4>Focus on ^SPX (S&amp;P 500 Options)</h4><p>We’ll be using the yfinance platform to access a complete option chain for ^SPX (S&amp;P 500 Options). But before diving into the analysis, it’s crucial to clean and format the data.</p><ol><li>Retrieve the expiration dates and the last closing price of the S&amp;P 500. This sets the stage for the rest of the analysis.</li></ol><pre>SPX = yf.Ticker(&quot;^SPX&quot;)<br><br># Step 1: get last clossing price<br>S0 = SPX.history(perdiod=&#39;3mo&#39;)[&#39;Close&#39;][-1] ; print(f&#39;S0={S0}&#39;)<br><br># Step 2: get Expiration Dates<br>expiration_dates = SPX.options</pre><p>2. <strong>Looping Through Expiration Dates</strong>: Iterate over all expiration dates to collect data on both Puts and Calls, giving us a comprehensive view of the option chain.</p><ul><li><strong>Days Since Last Traded</strong>: Calculate the number of days since each option was last traded.</li><li><strong>Option Weight</strong>: Compute the weight of each option, which is essential for calibrating the Heston parameters.</li><li><strong>Option Price</strong>: Assume the price of each option to be the midpoint between the bid and ask prices. Note that this may not be accurate for illiquid options, but these will carry less weight in our analysis due to their spread.</li><li><strong>Maturity</strong>: Calculate the maturity date for each option based on its expiration date.</li></ul><pre>from tqdm  import tqdm<br>from datetime import datetime<br>import yfinance as yf<br>from tqdm  import tqdm<br><br>df = []<br>for expiration_date in tqdm(expiration_dates, desc=&#39;Collecting Option Data&#39;):<br>  # Collect all Calls<br>  _df = SPX.option_chain(expiration_date).calls<br>  _df[&#39;DaysSinceLastTraded&#39;] = (pd.to_datetime(_df[&#39;lastTradeDate&#39;]).dt.tz_localize(None) - pd.to_datetime(datetime.now())).dt.days<br>  _df = _df[_df[&#39;DaysSinceLastTraded&#39;] &gt; -14]<br>  _df[&#39;Weight&#39;] = 1 / (_df[&#39;bid&#39;] - _df[&#39;ask&#39;])**2<br>  _df[&#39;price&#39;]  = (_df[&#39;bid&#39;] + _df[&#39;ask&#39;])/2<br>  _df[&#39;maturity&#39;] = (pd.to_datetime(expiration_date) - pd.to_datetime(datetime.now())).days / 365<br>  _df[&#39;Type&#39;]     = &#39;c&#39;<br>  _df[&#39;S&#39;]        = S0<br>  df.append(_df)<br><br>  # Collect all Puts<br>  _df = SPX.option_chain(expiration_date).puts<br>  _df[&#39;DaysSinceLastTraded&#39;] = (pd.to_datetime(_df[&#39;lastTradeDate&#39;]).dt.tz_localize(None) - pd.to_datetime(datetime.now())).dt.days<br>  _df = _df[_df[&#39;DaysSinceLastTraded&#39;] &gt; -14]<br>  _df[&#39;Weight&#39;] = 1 / (_df[&#39;bid&#39;] - _df[&#39;ask&#39;])**2<br>  _df[&#39;price&#39;]  = (_df[&#39;bid&#39;] + _df[&#39;ask&#39;])/2<br>  _df[&#39;maturity&#39;] = (pd.to_datetime(expiration_date) - pd.to_datetime(datetime.now())).days / 365<br>  _df[&#39;Type&#39;]     = &#39;p&#39;<br>  _df[&#39;S&#39;]        = S0<br>  df.append(_df)<br><br>df = pd.concat(df)<br>df = df[df[&#39;maturity&#39;] &gt; 0]</pre><p>3. <strong>Filter the options based on their last trade date</strong> to minimize fitting issues related to “irrelevant” options. Ideally, having precise details like the time at which an option was sold and the S&amp;P 500’s position at that moment would aid in calculating the Implied Volatility (IV). However, this level of granularity is generally unavailable. Alternative methods for approximating option price, beyond simply taking the midpoint between bid and ask, could be explored.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uFPaqQPWE7B7w-lsL29QvQ.png" /><figcaption>Distribution of the expiration dates and the number of options available, vs DaysSinceLastTraded — Source: <a href="https://github.com/ithakis/Pricing-Options-with-Black-Scholes/blob/main/Heston%20Model%20Calibration.ipynb">Notebook</a></figcaption></figure><p>4. <strong>Apply the Nelson-Siegel-Svensson model</strong> to estimate the risk-free rate corresponding to each option’s maturity. This model offers a robust way to account for the term structure of interest rates.</p><pre>volSurfaceLong[&#39;rate&#39;] = volSurfaceLong[&#39;maturity&#39;].apply(curve_fit) / 100<br>volSurfaceLong         = volSurfaceLong.reset_index()</pre><h3>3D Option Chain Plots: Price, IV vs Time vs Strike</h3><p>For European Options available on the S&amp;P 500, I’ve employed Plotly to visualize the option chain, as it excels in rendering 3D plots.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*lnoDCYLB4Si4QptykQeFHA.png" /><figcaption>Visualized options offered for SPX. Maturity vs Strike vs Option Price</figcaption></figure><p>We will utilize py_vollib_vectorized to compute the Implied Volatility (IV) for these options.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*NxdEE9kpAwEXRGkzoykJRA.png" /><figcaption>Visulized options offered for SPX. Maturity vs Strike vs Implied Volatility — Source: <a href="https://github.com/ithakis/Pricing-Options-with-Black-Scholes/blob/main/Heston%20Model%20Calibration.ipynb">Notebook</a></figcaption></figure><h4>Key Observations:</h4><p>The following points stand out from the plots:</p><ol><li><strong>Smirk or Smile</strong>: A pronounced smirk or smile is evident, particularly in the IV plot.</li><li><strong>Symmetry in IV</strong>: For options with the same strike and maturity, the IVs of calls and puts are remarkably close.</li><li><strong>Low IV Near Expiry</strong>: Options that are both close to expiration and at-the-money exhibit the lowest IV.</li><li><strong>Skewed IV for Short Expirations</strong>: IV tends to be both higher and more skewed for options with shorter expirations.</li></ol><h4>Modeling Considerations:</h4><p>These observations need to be encapsulated effectively by any model we decide to employ.</p><p><em>Note on IV Calculation:</em> Given that our data collection and IV calculation methods aren’t flawless, there’s a potential for inaccuracies. For instance, if incorrect inputs are fed into py_vollib_vectorized, it defaults to zero. Given that IV is particularly sensitive for options near expiration, it&#39;s crucial to accurately input <em>S</em>0​ and the transactional option price.</p><h3>Calibration of Heston Model Parameters</h3><p>Now that we have a tool for pricing European options based on specific parameters and inputs, the next step is to identify the optimal parameters of the Heston model that best align with market data. Let’s explore the challenges and nuances involved in this calibration:</p><ul><li><strong>Optimization Metric</strong>: Option Price or <strong>Implied Volatility</strong> (% Annualized) — Critical. Implied Volatility (IV) treats all options equally, unlike option price, which gives more weight to deep in-the-money or out-of-the-money options.</li><li><strong>Optimization</strong> <strong>Method</strong>: <strong>Sequential Least Squares Programming optimizer (SLSQP)</strong>, Simulated Annealing (SA), etc. — High. Your choice here impacts both the quality of the fit and the convergence time. I opted for SLSQP for its efficiency and reliability.</li><li><strong>Error Function</strong>: MAE, <strong>MSE</strong>, MAPE (Mean Absolute Percentage Error) — High. MSE might seem tempting due to its sensitivity to outliers and quicker convergence, but it’s not always the best choice.</li><li><strong>Weight</strong>: <strong>1/(spread²)</strong>,1/(|spread|), 1/(√spread)​ — Medium. The choice of weighting is discretionary, although, in my experience, options closer to expiration and at-the-money tend to have smaller spreads.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*d1VsSFc9TfLJWRdE8YIJrg.png" /><figcaption><em>Equation: Minimize the weighted Mean Squared Error (MSE) of the IV between the observed and predicted values.</em></figcaption></figure><ul><li><strong>Initial Heston Parameters and Search Space Limits</strong>: Refer to those used in the project — High. The initial parameters should be “reasonable” to enable effective convergence. That’s why others prefer methods like SA, but starting from a strong initial point makes SLSQP more advantageous.</li><li><strong>Tolerance</strong> (tol, ftol): I set this at 1×10−51×10−5, which is sufficient for our needs, given the % annualized IV like 30.05%. If the improvement is smaller, the algorithm exits — usually before hitting the max iterations.</li><li><strong>Handling Errors</strong>: When dealing with options close to expiration or with high strike prices, the Fourier Transform may struggle. You can either filter out these options or set their IV to zero. I chose the latter to maintain a robust set of parameters.</li></ul><p>By leveraging both Fourier Transform (FT) and Numba, calibrating a full option chain of 4,200 calls and puts takes under 6 minutes on a single-core laptop. The results? A minimum weighted RMSE(IV) of 3.4009 and a MAE(IV) of 2.7232 (weighted) and 1.3806 (non-weighted). That’s an average annualized % volatility error of just 1%.</p><p><strong>Example of Resulting Fit</strong></p><pre>Results:<br>v0=0.0228 ; kappa=0.0807 ; theta=0.0363 ; zeta=1.1760 ; rho=-0.3021 <br>&gt;&gt;Zeros : 1<br><br># -------------------------------- Error for Prices --------------------------------<br>MAE of Price     :  13.6089<br>WMAE of Price    :  1.2354<br><br>MAPE of Price    :  54.966 %<br>WMAPE of Price   :  77.121 %<br>Max APE of Price :  4961.760 %<br><br>RMSE of Price    :  31.5974<br>WRMSE of Price   :  3.9844<br><br># -------------------------------- Error for IV --------------------------------<br><br>MAE of IV     :  2.7232<br>WMAE of IV    :  1.3806<br><br>MAPE of IV    :  15.250 %<br>WMAPE of IV   :  6.704 %<br>Max APE of IV :  230.815 %<br><br>RMSE of IV    :  4.2373<br>-&gt; WRMSE of IV:  3.4009</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*10o5XTabzhnrzopJGzqlbQ.png" /><figcaption>Resulting Fit — Source: <a href="https://github.com/ithakis/Pricing-Options-with-Black-Scholes/blob/main/Heston%20Model%20Calibration.ipynb">Notebook</a></figcaption></figure><p>The Weighted Percent Error shows the weak spots in the algorithm’s fit, particularly for short-expiration and deep out/in-the-money options, which are inherently more challenging to price.</p><h4>What We Expect from the Optimization Algorithm</h4><ol><li>Converge to robust parameters.</li><li>Execute efficiently, leveraging prior attempts.</li><li>Avoid getting stuck by exploring various regions of the parameter space.</li></ol><h4>Code — Implementation</h4><pre>from scipy.optimize import minimize<br># Define variables to be used in optimization<br>_K      = volSurface[&#39;strike&#39;].to_numpy()<br>_C      = volSurface[&#39;price&#39;].to_numpy()<br>_type   = volSurface[&#39;Type&#39;].to_numpy(dtype=str)<br>_T      = volSurface[&#39;maturity&#39;].to_numpy()<br>_r      = volSurface[&#39;rate&#39;].to_numpy()<br>_S      = np.full_like(_K, S0)<br>_IV     = volSurface[&#39;IV&#39;].to_numpy()<br>_Weight = volSurface[&#39;Weight&#39;].to_numpy()<br><br># Parameters to search for in the simualation: --------------------------------<br>params = {<br>        &quot;v0&quot;:     {&quot;x0&quot;: 0.002874,            &quot;lbub&quot;: [1e-3,  1.2]}, <br>        &quot;kappa&quot;:  {&quot;x0&quot;: 1.6891,              &quot;lbub&quot;: [1e-3,  10]},  <br>        &quot;theta&quot;:  {&quot;x0&quot;: 0.0190,              &quot;lbub&quot;: [1e-3,  1.2]}, <br>        &quot;zeta&quot;:   {&quot;x0&quot;: 3.7472,              &quot;lbub&quot;: [1e-2,  4]},<br>        &quot;rho&quot;:    {&quot;x0&quot;: -0.2731,             &quot;lbub&quot;: [-1,    1]},<br>        }<br>x0   = [param[&quot;x0&quot;] for key, param in params.items()]<br>bnds = [param[&quot;lbub&quot;] for key, param in params.items()]<br><br>def SqErr(x):<br>    v0, kappa, theta, zeta, rho = [param for param in x]<br>    <br>    # Prices Using Heston Model<br>    Price_Heston    = get_resutls_array_Heston(volSurface, v0=v0, kappa=kappa, theta=theta, zeta=zeta, rho=rho, N=1_012, z=24)<br><br>    # Inverse approximation of implied Volatilities<br>    IV_Heston       = implied_volatility(price=Price_Heston, S=_S, K=_K, t=_T, r=_r, flag=_type)<br>    <br>    # Safty Feature: Exclude the IV caluclations which are not definable.<br>    diff            = IV_Heston - _IV<br>    idx             = np.isnan(diff) | np.isinf(diff)<br>    diff[idx]       = 0 - _IV[idx]<br>    IV_Heston[idx]  = 0<br>    <br>    # RMSE<br>    rmse  = sqrt(np.mean((diff*100)**2 * _Weight))<br><br>    zeros = int(np.where(IV_Heston==0, 1,0).sum())<br>    wmae  = np.mean(np.abs(diff*100) * _Weight)<br><br>    print(f&quot;&gt;&gt;v0={v0:7.4}; kappa={kappa:5.4f}; theta={theta:5.4f}; zeta={zeta:5.4f}; rho={rho:6.4f} | WMAE(IV): {wmae:5e} | Nulls: {(idx).sum()}/{idx.shape[0]} | Zeros: {zeros}/{idx.shape[0]} | WRMSE(IV): {rmse:5e}&quot;)<br>    return rmse<br><br># Perform scipy minimize to find the best parameters in the Heston Model which match the observed values<br>result = minimize(SqErr, x0, tol = 1e-5, method=&#39;SLSQP&#39;, options={&#39;maxiter&#39;: 80 , &#39;ftol&#39;: 1e-5, &#39;disp&#39;:True}, bounds=bnds, jac=&#39;3-point&#39;)<br>v0, kappa, theta, zeta, rho = [param for param in result.x]<br><br>&quot;&quot;&quot; Example output:<br>&gt;&gt;v0=0.01459; kappa=1.0330; theta=0.0268; zeta=3.5362; rho=-0.2757 | WMAE(IV): 1.606438e+00 | Nulls: 0/4283 | Zeros: 6/4283 | WRMSE(IV): 3.789558e+00<br>&gt;&gt;v0=0.01459; kappa=1.0330; theta=0.0268; zeta=3.5362; rho=-0.2757 | WMAE(IV): 1.606397e+00 | Nulls: 0/4283 | Zeros: 6/4283 | WRMSE(IV): 3.789579e+00<br>&gt;&gt;v0=0.01459; kappa=1.0330; theta=0.0268; zeta=3.5362; rho=-0.2757 | WMAE(IV): 1.606400e+00 | Nulls: 0/4283 | Zeros: 6/4283 | WRMSE(IV): 3.789582e+00<br>&gt;&gt;v0=0.01459; kappa=1.0330; theta=0.0268; zeta=3.5362; rho=-0.2757 | WMAE(IV): 1.606403e+00 | Nulls: 0/4283 | Zeros: 6/4283 | WRMSE(IV): 3.789586e+00<br>...<br>    Current function value: 3.4043308974510307<br>    Iterations: 41<br>    Function evaluations: 486<br>    Gradient evaluations: 41<br>Time: 5:52mins</pre><h4>Visualizing the Fit</h4><p>Predicted prices diverge more for options with longer expirations, primarily because the algorithm focuses on fitting options closer to expiration due to their smaller spreads. The same logic applies when considering IV, making it a logical fit metric for the Heston Model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*OdhTtEldU0EFJU7zxz5cVQ.png" /><figcaption>Goodness of fit — Option Prices — Source: <a href="https://github.com/ithakis/Pricing-Options-with-Black-Scholes/blob/main/Heston%20Model%20Calibration.ipynb">Notebook</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*fLxMeIwg_mbdiJHbVVmCEg.png" /><figcaption>Goodness of fit — Option IV — Source: <a href="https://github.com/ithakis/Pricing-Options-with-Black-Scholes/blob/main/Heston%20Model%20Calibration.ipynb">Notebook</a></figcaption></figure><h3><strong>Heston IV surface</strong></h3><p>The ultimate goal here is to construct a 3D surface plot for the Heston Implied Volatility (IV). By generating a 2D array containing data from 15,000 options, we can visualize the characteristics of this IV surface.</p><p>In a previous discussion about the Observed IV surface, the following properties were highlighted:</p><ol><li><strong>Presence of a smirk or smile </strong>— This feature is apparent in our Heston model.</li><li><strong>Lowest IV for options that are both at-the-money and close to expiration </strong>— This holds true in the Heston model as well.</li><li><strong>Increased and skewed IV for short-term expirations </strong>— Again, the model corroborates this.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*M9CFQrt2vOLbiik86N0wpg.png" /><figcaption>Heston Implied Volatility (IV) Surface Plot — Source: <a href="https://github.com/ithakis/Pricing-Options-with-Black-Scholes/blob/main/Heston%20Model%20Calibration.ipynb">Notebook</a></figcaption></figure><p><strong><em>With parameters: </em></strong><br><em>Heston: v0=0.001 ; kappa=1.6483 ; theta=0.0261 ; zeta=4.0000 ; rho=-0.0832<br>S(0)=4</em>405.71 USD</p><h3>Addressing Numerical Instabilities</h3><p>One challenge that arises is the model’s failure to accurately calculate option values under certain parameters. <strong>This is particularly evident in the following plot, which focuses on options with maturities of less than one year.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*Ev-8sSVR1VArdWhPCQxW3A.png" /><figcaption>Numerical Instabilities to the Fourier Transformed Heston Model — Source: <a href="https://github.com/ithakis/Pricing-Options-with-Black-Scholes/blob/main/Heston%20Model%20Calibration.ipynb">Notebook</a></figcaption></figure><h3>“The Fourier Trap”: Understanding the Pitfalls of Option Pricing with FT</h3><p>To shed light on these intricacies, I revisited the previous code to plot the Probability Density Function (PDF) of the Heston model. The parameters remain consistent with the implied volatility (IV) surface plot discussed earlier. The PDF corresponds to an option set to expire in one day, i.e., T=1/365.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CZMxCL8P9pPQk3kdWqXLUw.png" /><figcaption>Plot 1: Heston PDF — Log Density — N=10,000 — Source: <a href="https://github.com/ithakis/Pricing-Options-with-Black-Scholes/blob/main/Fourier%20Transform%20Density%20Function.ipynb">Notebook</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MNRTbYWmZMaJgvRIy4WTag.png" /><figcaption>Plot 2: Heston PDF — Log Density — N=1,000 — Source: <a href="https://github.com/ithakis/Pricing-Options-with-Black-Scholes/blob/main/Fourier%20Transform%20Density%20Function.ipynb">Notebook</a></figcaption></figure><p>It’s readily apparent that the plot with fewer terms (N=1,000) demonstrates more instability than its counterpart with more terms (N=10,000). So, what gives? Revisiting <a href="https://medium.com/@alexander.tsoskounoglou/pricing-options-with-fourier-series-p1-5bf60443ba0c">Part 1</a>, we recall that as <em>N</em> approaches infinity, the Fourier series converges to the original function. The caveat, though, is that until that point, we’re working with approximations. <strong>Since our approximation leverages sinusoidal waves, an original function that’s close to zero becomes notoriously hard to approximate, especially for extreme z-scores.</strong></p><pre>def Fourier_cosine_char_function(char_function, x:np.array, a, b, N:int):<br>    A  = lambda n : 2/(b-a) * np.real(char_function((n*pi)/(b-a))*exp((-1j*n*pi*a)/(b-a)) )<br>    fx = .5*A(0)<br>    for n in np.arange(1, N+1):<br>        fx += A(n) * cos(n*pi * (x-a)/(b-a))<br>    return fx</pre><h4>The Fourier Trap</h4><p>One might suspect that these inconsistencies have something to do with the Heston PDF’s peculiarities. However, that assumption is not corroborated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yxK7p7voz-ruCBUM8zARJQ.png" /><figcaption>Normal PDF using Fourier Transform and Characteristic Function — N=128 — Source: <a href="https://github.com/ithakis/Pricing-Options-with-Black-Scholes/blob/main/Fourier%20Transform%20Density%20Function.ipynb">Notebook</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*612QIAFzOWsvuB_Tuy6lrw.png" /><figcaption>Normal PDF using Fourier Transform and Characteristic Function — N=100,000 — Source: <a href="https://github.com/ithakis/Pricing-Options-with-Black-Scholes/blob/main/Fourier%20Transform%20Density%20Function.ipynb">Notebook</a></figcaption></figure><p>It’s evident that <strong>regardless of the number of terms used (N), the approximation reaches a point where it ceases to converge to the original function</strong>. This pitfall is what I’ve coined as the “Fourier Trap”. My assumption is that a similar phenomenon occurs in the pricing of Put options.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2RIGgssRKGohuUFFVW5iAw.png" /><figcaption>Normal CDF using Fourier Transform and Characteristic Function — N=100,000 — Source: <a href="https://github.com/ithakis/Pricing-Options-with-Black-Scholes/blob/main/Fourier%20Transform%20Density%20Function.ipynb">Notebook</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IpJGTKCFV0yQezY0AF4snA.png" /><figcaption>Normal CDF using Fourier Transform — Abs Residuals — N=100,000 — Source: <a href="https://github.com/ithakis/Pricing-Options-with-Black-Scholes/blob/main/Fourier%20Transform%20Density%20Function.ipynb">Notebook</a></figcaption></figure><h4>Conclusion: The Fourier Trap</h4><p><strong>The plots above explains why the numerical instabilities occure in the left side of the calculation. </strong>The blue values are negative, which is impossible in a CDF. Similarly in the heston model the area which is missing is because there are negative values in the Heston-CDF which results to the price of the derivative to equal to 0.</p><h3>Addressing the Problem</h3><ul><li><strong>Boosting the Term Count</strong> (N): Online sources generally skimp on terms while calculating options, focusing mainly on “convenient” maturities and near-the-money options. Given that adding terms in Fourier Series is computationally cheap, there’s no harm in using 1,024 terms. However past that point, benefits appear to plateau. For instance, upping the term count from 1,024 to 10,000 shows negligible improvements in reducing numerical instabilities but increases computation time by a factor of 10.</li><li><strong>Choosing Optimal Cumulants</strong> (c1, c2): While many articles overlook integral limits, Article [3] (2018) is an exception. Many methodologies, like in Article [4] (2008), seem to lack rigor. First off, the cumulants differ from those in [3]. Second, the proposed range of ±12*std falls short for short maturities or deep in/out-of-the-money options. Finally, they don’t thoroughly analyze the different Heston parameters. After extensive testing, using cumulants from Article [3] in conjunction with z=±24 yielded the lowest Mean Squared Error (MSE).</li><li><strong>Setting an Appropriate Range</strong> (z): Given the high kurtosis and skewness in the Heston Probability Density Function (PDF), especially when rho is significantly less than zero, it’s crucial to employ a broad enough range. A value of z=±24 seems optimal, based on the lowest MSE results</li><li><strong>Penalising Heston Parameters which result to numerical instabilities during fitting: </strong>During fitting we can artificially increase the MSE when the values cause numerical instabilies. That way we can ensure that we are going to converge to a set of values which are more stable. This has the drawback that the resulting fit might not be as good. But its hard to quantify “the penalty” of not being able to price some of the options in the chain. Without any penalty, less than 10/~6000 options are unable to be priced. (see point 5 and 6 bellow) The process of penalising the fit for numerical instabilities is another story its self, but in its simplest form you can test “hard to price” options and see how many numerical instabilities there are and penalize accordingly. Or a second option would be to increase MSE very much if there are any options which cannot be priced.</li></ul><p><strong>Let’s dive into some revealing plots:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V3YI8055N36d5eGA8galKg.png" /><figcaption>Heston PDF — N=1,024 — T=1 week</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I5qVu92xr3J68wznmE6kPw.png" /><figcaption>Heston PDF — N=10,024 — T=1 week</figcaption></figure><h4>Insights on the Fourier Trap in the Heston Model</h4><ol><li>A larger z helps in pricing deep in/out-of-the-money options.</li><li>The higherthe <em>z</em> value, the less stable the results.</li><li>Increasing z demands a higher N for stable outcomes.</li><li>A larger z enhances the value of the density at the tails, possibly indicating greater accuracy.</li><li>The left tail tends to be more susceptible to breakdown, particularly when rho is negative (e.g., rho=-0.5).</li><li>Numerical stability varies based on specific Heston parameters:<br>- Higher <em>v0</em> relative to theta(θ) yields more stable results.<br>- A higher kappa(κ) improves stability.<br>- Elevated zeta(ζ) leads to instability.<br>- Rho(ρ) doesn’t noticeably influence result stability.</li></ol><h4><strong>Further Work</strong></h4><ul><li>Objective 1: Develop a function to optimize the variables z<em>z</em> and N<em>N</em> based on the given Heston model parameters. The aim is to minimize numerical instabilities across a variety of option contracts.</li><li>Objective 2: Dive deep into the underlying mathematical framework to identify potential modifications that could solve the Fourier Trap issue. An immediate area of investigation is the simultaneous use of sine and cosine functions, as their interaction may nullify each other, potentially yielding more stable, near-zero values.</li></ul><h4>The End</h4><h3>Sources</h3><ul><li>[1] <em>“Calibration and simulation of Heston model”, </em><a href="https://www.degruyter.com/document/doi/10.1515/math-2017-0058/html?lang=en#j_math-2017-0058_ref_038"><em>link</em></a></li><li>[2] “<em>The Little Heston Trap</em>”<em>, </em><a href="https://perswww.kuleuven.be/~u0009713/HestonTrap.pdf"><em>link</em></a></li><li>[3] <em>“A Generalized Fourier Transform Approach to Risk Measures”, </em><a href="https://arxiv.org/pdf/0909.3978.pdf"><em>link</em></a></li><li>[4] <em>“A NOVEL PRICING METHOD FOR EUROPEAN OPTIONS BASED ON FOURIER-COSINE SERIES EXPANSIONS”, </em><a href="https://mpra.ub.uni-muenchen.de/8914/4/MPRA_paper_8914.pdf"><em>link</em></a><em> (2008)</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d157369a217a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pricing Options with Fourier Series P2]]></title>
            <link>https://medium.com/@alexander.tsoskounoglou/pricing-options-with-fourier-series-p2-fa7328bd942b?source=rss-e3674ac63c40------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa7328bd942b</guid>
            <category><![CDATA[options-trading]]></category>
            <category><![CDATA[fourier-transform]]></category>
            <category><![CDATA[derivatives-trading]]></category>
            <dc:creator><![CDATA[Alexander Tsoskounoglou]]></dc:creator>
            <pubDate>Sun, 25 Jun 2023 15:33:35 GMT</pubDate>
            <atom:updated>2023-09-17T14:12:30.528Z</atom:updated>
            <content:encoded><![CDATA[<p>The how to go from knowing what a Fourier Series is to being able to price Options under Black-.</p><ul><li>Please check out the <a href="https://medium.com/@alexander.tsoskounoglou/pricing-options-with-fourier-series-p1-5bf60443ba0c">Part 1</a> if you want to see more about the fundamentals of the Fourier Series.</li><li>Accompanied Notebook: <a href="https://github.com/ithakis/Pricing-Options-with-Black-Scholes/blob/main/Pricing%20Options%20with%20Fourier.ipynb">Github</a></li><li>This article is based on notes from my course in Stochastic Calculus (2023) at the University of Amsterdam under Professor Michel Vellekoop.</li><li>Check out part 3: <a href="https://medium.com/@alexander.tsoskounoglou/pricing-options-with-fourier-series-p3-the-heston-model-d157369a217a">Link</a></li></ul><h4>Contents:</h4><ul><li>Fourier cosine expansion</li><li>The density function of S(T)</li><li>Euler&#39;s formula for cosine</li><li>The characteristic function — The characteristic function of the Geometric Brownian motion.</li><li>Option Pricing formulas</li><li>Convergence over N terms and the importance of picking good limits</li><li>Error analysis over the analytical solution</li></ul><p><em>“There is nothing impossible to him who will try”</em><br><strong>Alexander the Great</strong></p><h3><strong>Fourier cosine expansion</strong></h3><p>Similar to the Sine-Cosine Expansion, we can do the same thing with only the cos part of the equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*gc1F92D1VE7vuhZiBLOOUw.png" /><figcaption>Going from the Cosine-Sine transformation to the Cosine Transformation</figcaption></figure><p>You can see from the following function which we also did in Part 1, that the cosine is able to approximate very well the same functions</p><pre>def get_fourier_approx(f, x:np.array, a:float, b:float, N:int):<br>    fa = lambda x, n : f(x) * cos((2*pi*n*x)/(b - a))<br>    fb = lambda x, n : f(x) * sin((2*pi*n*x)/(b - a))<br><br>    A0 = 1/(b - a) * quad(f, a, b, limit=200)[0]<br><br>    Cosine_Sine_Sum = np.zeros_like(x)<br>    for n in range(1, N+1):<br>        A = 2/(b - a) * quad(fa, a, b, args=(n), limit=200)[0]<br>        B = 2/(b - a) * quad(fb, a, b, args=(n), limit=200)[0]<br>        Cosine_Sine_Sum += A*cos((2*pi*n*x)/(b - a)) + B*sin((2*pi*n*x)/(b - a))<br><br>    fx = A0 + Cosine_Sine_Sum<br>    return fx<br><br>mean = 100<br>std  = .1 *sqrt(5)*100 <br>f    = lambda x : (1/(std*sqrt(2*pi))) * exp(-(x-mean)**2/(2*std**2)) #*12/0.0175<br><br>a = mean - 12 * std<br>b = mean + 12 * std</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0NT96gHFa3i8YyU2WE3zsw.png" /><figcaption>Square Function — Source:<a href="https://github.com/ithakis/Pricing-Options-with-Black-Scholes/blob/main/Pricing%20Options%20with%20Fourier.ipynb">Notebook</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gPDu0bqpUCMdXdI3BkIOYg.png" /><figcaption>Line Function — Source: <a href="https://github.com/ithakis/Pricing-Options-with-Black-Scholes/blob/main/Pricing%20Options%20with%20Fourier.ipynb">Notebook</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vZ8D2mjrHCnXkwLvpwZBAg.png" /><figcaption>Normal Distribution — Source: <a href="https://github.com/ithakis/Pricing-Options-with-Black-Scholes/blob/main/Pricing%20Options%20with%20Fourier.ipynb">Notebook</a></figcaption></figure><pre>Avg Residuals<br>N   Square f   Line f      Normal Distribution<br>8   1.311711   0.447389    1.593045e-04<br>16  0.784683   0.264635    1.214211e-07<br>32  0.440387   0.153540    7.100142e-18<br>64  0.268449   0.088745    3.628299e-14<br>128 0.154604   0.052147    2.992953e-12</pre><h4>Remarks</h4><ul><li>The conclusions are the same as Part 1, that the normal distribution fits very well and we need to take an adequate range in the values [a, b]</li><li>Since only the cosine part is used. It simplifies a lot of the next steps we have to do and speeds up the process as we have to calculate fewer things.</li></ul><h3>Density Function of S(T)</h3><p>To start gaining intuition on the problem we have to solve it’s good to start by making a function and its Fourier transform, which given some initial values, S0, T, r, sigma it calculates the Probability of S_T = X.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*q5vlNeIm01B_4He42WspBQ.png" /><figcaption>Method to calculate the density function of S(T)</figcaption></figure><p>It&#39;s important to note that an interval of [-12 sigma, 12 sigma] covers 99. plus another 33 9s! Someone could say it&#39;s extreme but it&#39;s important to use a high sigma so the density function covers deep out-of-the-money options. (I will come back later to that)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TktAW61hTJK4PZAFbJm1pg.png" /><figcaption>Density function of S(T) with S0=100, T=5Y, r=5%, sigma=10% — Source: <a href="https://github.com/ithakis/Pricing-Options-with-Black-Scholes/blob/main/Pricing%20Options%20with%20Fourier.ipynb">Notebook</a></figcaption></figure><pre>N    Avg Residual<br>8    1.897794e-02<br>16   7.159815e-03<br>32   5.616416e-04<br>64   2.326956e-06<br>128  1.384069e-10</pre><h3>Pricing Options with Fourier Series</h3><h4><strong>Step 1: Euler’s Formula to transform cos(x)</strong></h4><p>We gonna start our journey of deriving a function to price an option with Fourier Series by using Euler’s Formula to transform the cos(x). This will help with the next steps we have to do.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rseYtfSZv51r-TjynYmzXA.png" /></figure><h4>Step 2: Characteristic Function of a random variable</h4><p>In probability theory, a characteristic function is a complex-valued function defined for a random variable. It captures the moments and distribution properties of the random variable, allowing for the analysis of various statistical properties using techniques such as Fourier transforms. For example for a random variable following a normal distribution or a Poisson distribution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*TWyeC4deaxl3wRss1KTSvA.png" /><figcaption>Characteristic Function of a Random Variable</figcaption></figure><h4>Step 3: Analytical solution to the integral using the characteristic function</h4><p>In our use case, we can transform the density function of i.e.<em> log(S_T)</em>. Continuing the transformation of <em>f(x)</em> from Step 1 of <em>An </em>in combination with Step 2 and knowing that <em>f(x) </em>is the density of a random variable with a known characteristic function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vi8szpf33gf-Svefli1KxA.png" /></figure><p>Knowing that we can transform the integral to the characteristic function allows us to explicitly calculate the integral which I did numerically with the quad from scipy before. The expectation is assumed for a large enough interval of [a, b] since <em>f(z)</em> is the density function of a random variable.</p><p><strong>Step 4: Tying it all together to calculate explicitly the <em>An</em> coefficients</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*qbFh3Bx6IfuVepPo66ucgw.png" /></figure><p>Where <em>En</em> is part of the integral outside of <em>[a,b]</em> which is very small if for probability mass <em>f(x)</em> we pick <em>a,b</em> where <em>f(x)</em> is close to zero (±12sigma, for the normal). A similar concept can be applied if <em>f(x)</em> is the payoff of an option and the payoff is very small for <em>a,b</em></p><pre>def Fourier_cosine_char_function(char_function, x:np.array, a, b, N:int):<br>    A  = lambda n : 2/(b-a) * np.real( char_function((n*pi)/(b-a))*exp((-1j*n*pi*a)/(b-a))  )<br>    fx = .5*A(0)<br>    for n in range(1, N+1):<br>        fx += A(n) * cos(n*pi * (x-a)/(b-a))<br>    <br>    return fx<br><br>S0      = 100<br>K       = 100<br>r       = 0.05<br>sigma   = 0.1<br>T       = 5.0<br><br># For normal distribution <br>mu      = 100<br>sigma   = 25<br>char_function = lambda u: exp(1j*u*mu -.5*sigma**2*u**2)<br>f             = lambda x: norm.pdf(x, loc=mu, scale=sigma)<br><br>a   = 100 - 12 * sigma<br>b   = 100 + 12 * sigma</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T7sih1qbw11JnLA8Slzslw.png" /><figcaption>The density of a normal distribution using an explicit solution with the characteristic function - Source: <a href="https://github.com/ithakis/Pricing-Options-with-Black-Scholes/blob/main/Pricing%20Options%20with%20Fourier.ipynb">Notebook</a></figcaption></figure><pre>N   Avg. Residual    Execution Time<br>8   1.182498e-03     0.000059<br>16  1.588727e-04     0.000092<br>32  1.160981e-07     0.000180<br>64  2.983220e-18     0.000358<br>128 2.986019e-18     0.000767</pre><h4>Remarks</h4><ul><li>As you can see we are doing very well. Execution time is low, and we get a very quick convergence with only 32 terms</li><li>Using the characteristic function increases the accuracy of the Fourier Series approximation and makes the calculations simpler.</li><li>Using the imaginary numbers transformation for cos allows us to transform the integral in the coefficients to the characteristic function of a density function.</li></ul><h3><strong>Option pricing using the Fourier series</strong></h3><h4>Step 1: Recap</h4><p>For a function <em>f</em> where it represents the density function of a random variable <em>z,</em> we have the Fourier cosine expansion:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*EFkQBDYx1WfNjJXNwaXp-A.png" /><figcaption>Density Function of random variable z with known characteristic function</figcaption></figure><h4>Step 2: <strong>Characteristic function of the density of future asset prices</strong></h4><p>When we price assets we have a density function of the log of the value of an asset which accepts parameters: t, T, S(t), r, sigma, and outputs the probability of S(T). It is straightforward in stochastic calculus to calculate the characteristic function of a random variable, based on Step 2 of the previous section. We are going to use this new tool to price a derivative <em>F</em> with a defined payoff <em>F(T, S_T)</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JWPvVRhLorHP87YC5EaWsg.png" /><figcaption>Formula to calculate the price of a derivative with a known payoff at T</figcaption></figure><p>The steps that I did above are:</p><ul><li>Discount the value of the expected payoff of the derivative at T. (line 1)</li><li>Substitute to the density function the Fourier Series Transformation we derived above. (line 2)</li><li>Separate the terms which contain <em>z </em>and package them to the coefficient <em>gn</em></li></ul><h4>Step 3: Solving g(n) analytically</h4><p>Since the integral in gn is for values at T we can analytically calculate the integral if the payoff function is explicit. In this case, we will try to price a European Put Option with payoff max{K-S(T), 0}. Therefore:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*92QybrjC323FBy0ePj-KMQ.png" /><figcaption>Analytical solution for Gn coefficients</figcaption></figure><p>To obtain the solutions shown here you can use an online definite integral calculator, and for <em>g0</em> you are going to use the limit of <em>gn</em> as n approaches <em>0</em> to get a solution as substituting <em>n=0</em> means <em>g0</em> cannot be defined.</p><h4>Step 4: <strong>GBM Characteristic function</strong></h4><p>Now that we have our “weapon” we only miss the bullets. In this case, the random variable z is assumed to follow a geometric Brownian motion under Q. With a characteristic function the “bullets”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*4hcY4Z3BVEDXMi6dhAuq3A.png" /><figcaption>The characteristic function of Geometric Brownian motion</figcaption></figure><pre>def Fourier_BS_Put(S0, K, T, sigma, r, N):<br>    _sigma, _T = max(.1, sigma), max(1, T)<br>    a = log(S0) + r * _T - 12 * _sigma * np.sqrt(_T) # Upper limit -12 std from the expected value<br>    b = log(S0) + r * _T + 12 * _sigma * np.sqrt(_T) # Lower limit -12 std from the expected value<br><br>    h       = lambda n : (n*pi) / (b-a) <br>    g       = lambda n : (exp(a) - (K/h(n))*sin(h(n)*(a - log(K))) - K*cos(h(n)*(a - log(K)))) / (1 + h(n)**2)<br>    g0      = K*(log(K) - a - 1) + exp(a)<br>    <br>    m       = log(S0) + (r - .5*sigma**2)*(T)<br>    gbm_char= lambda u : exp(1j * u * m -0.5*(u**2 * sigma**2)*T)<br><br>    F = g0 <br>    for n in range(1, N+1):<br>        h_n = h(n)<br>        F += 2*bs_char(h_n) * exp(-1j*a*h_n) * g(n)<br><br>    F = exp((-r*T))/(b-a) * np.real(F)<br>    return F</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LjmjJVQC58N9m6LwDF_l7g.png" /><figcaption>Price of an option over different strike prices. S0=100, T=5Y, r=5%, sigma=10% — Source: <a href="https://github.com/ithakis/Pricing-Options-with-Black-Scholes/blob/main/Pricing%20Options%20with%20Fourier.ipynb">Notebook</a></figcaption></figure><pre>N  avg_residuals Ex. Time<br>8   5.075343e-01 0.000185<br>16  2.556765e-02 0.000179<br>32  5.810656e-06 0.000265<br>64  2.319065e-14 0.000461<br>128 2.319066e-14 0.000787</pre><h4>Remarks</h4><ul><li>This method is proving to be a very fast and efficient way to calculate the value of a European Put Option</li><li>The only things that we control to influence the error in the approximation are N, the number of terms, and the interval [a, b] of the values of S(T) which we look at.</li></ul><h3>Picking the correct limits [a, b]</h3><p>The graph below illustrates 2 very important things someone needs to understand when using the Fourier series.<br>1. That the limits [a=S_T(-z_score), b=S_T(z_score)] need to cover all possible strike prices<br>2. As sigma increases so does the error in the approximation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D0TE9K5oFGEg1PKI5zFJaQ.png" /><figcaption>Illustration of selecting correctly the limits to the distribution and how the error in the approximation increases with larger sigmas — Source: <a href="https://github.com/ithakis/Pricing-Options-with-Black-Scholes/blob/main/Pricing%20Options%20with%20Fourier.ipynb">Notebook</a></figcaption></figure><p>In the first subplot, you can see that if we had a strike price at S(T) = 600 we would not be able to price it correctly since we simulated for values only S(-12) to S(12). Therefore <strong>you can see in the second plot that the value of such a strike price would be very wrong!<br></strong>In the third plot, you can see the sigmas covering a wide range of strike prices. However, due to the shape of the payoff it&#39;s harder to approximate the function accurately with the same number of terms. Therefore <strong>as sigma increases you may need to increase the number of terms N.</strong></p><p>The average error of the first subplot is: 7.676e-12<br>The average error of the first subplot is: 2.830e-02<br>The average error of the first subplot is: 1.405e-03<br>*for N = 128</p><h3>Error in the approximation over a different number of terms N</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vihmmbOqSXWJ-B_ZkhADrw.png" /><figcaption>Error in approximating the Analytical solution of a European Put option — Source: <a href="https://github.com/ithakis/Pricing-Options-with-Black-Scholes/blob/main/Pricing%20Options%20with%20Fourier.ipynb">Notebook</a></figcaption></figure><p>I conducted a simple experiment to see how the error is reduced over a different number of terms. You can see that we have an exponential convergence while the computational cost is linear. The dream of every computational scientist. This means that when we replace the characteristic function with the Heston model’s we don&#39;t have to pay the penalty of the Monte Carlo numerical integration, in which the error decreases with the square root of N.</p><h4>Error analysis over all possible input values for a European Put</h4><p>For a Stock of value 100 EUR. I simulated the conditions of pricing a Put where:<br>K = [0, 500]<br>T = [0, 30Y]<br>r = [-3%, 20%]<br>sigma = [0.5%, 100%]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TfMdiCkMXFn4PK30oZND7A.png" /><figcaption>Visualization of average error over different values of the parameters — Source: <a href="https://github.com/ithakis/Pricing-Options-with-Black-Scholes/blob/main/Pricing%20Options%20with%20Fourier.ipynb">Notebook</a></figcaption></figure><h4>Remarks</h4><ul><li>It appears that for options at expiration <em>T=0</em>, the approximation has increased error but this is attributed to the known payoff which is a line function that I showed at the beginning of the article, which is more challenging to approximate than a curvy function. To combat this, a higher number of terms can be used.</li><li>Sigma has a linear relationship with the error in the approximation as it changes the shape of the function to something that is harder to approximate. (As I showed earlier) Again, to combat this, a higher number of terms can be used.</li></ul><p><strong>The Total Average Error: 0.00289 EUR </strong>over all the given ranges of values K, T, r, and sigma I defined earlier.</p><h3>Conclusion</h3><p>Step by step I explained how to go from the general Fourier transformation to custom-made functions for calculating the payoff of a European Put option.<br>However, if you want to price derivatives where the payoff does not depend on fixed intervals, you have to use more complex numerical techniques. Like Finite Difference, or Monte-Carlo.</p><p>Despite this being a ‘useless’ tool so far <strong>we laid the groundwork for pricing options using the Heston model which we can&#39;t do analytically. Hopeful you can use the same principles for pricing options with</strong></p><p>I hope you found this article useful I hope to see you in Part 3/3 which we are going to see <strong>how to use the Heston model with the Fourier Series </strong>and <strong>how to calibrate it over on the Option chain.</strong></p><p>Link to part 3: <a href="https://medium.com/@alexander.tsoskounoglou/pricing-options-with-fourier-series-p3-the-heston-model-d157369a217a">Link</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa7328bd942b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pricing Options with Fourier Series P1]]></title>
            <link>https://medium.com/@alexander.tsoskounoglou/pricing-options-with-fourier-series-p1-5bf60443ba0c?source=rss-e3674ac63c40------2</link>
            <guid isPermaLink="false">https://medium.com/p/5bf60443ba0c</guid>
            <category><![CDATA[fourier-series]]></category>
            <category><![CDATA[derivatives-trading]]></category>
            <category><![CDATA[options-trading]]></category>
            <category><![CDATA[fourier-transform]]></category>
            <category><![CDATA[finance]]></category>
            <dc:creator><![CDATA[Alexander Tsoskounoglou]]></dc:creator>
            <pubDate>Mon, 19 Jun 2023 10:40:16 GMT</pubDate>
            <atom:updated>2023-10-15T15:36:23.509Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Theory and intuition on how to use Fourier Series to price derivatives.</strong><br><strong>Part 1 out of 3.</strong></p><ul><li>Notebook: <a href="https://github.com/ithakis/Pricing-Options-with-Black-Scholes/blob/main/Pricing%20Options%20with%20Fourier.ipynb">Github</a></li><li>Please check out the <a href="https://medium.com/@alexander.tsoskounoglou/pricing-options-with-fourier-series-p2-fa7328bd942b">Part 2</a> and <a href="https://medium.com/@alexander.tsoskounoglou/pricing-options-with-fourier-series-p3-the-heston-model-d157369a217a">Part 3</a> if you want to see more.</li></ul><p>This is the first article where I am going to help you gain an intuition behind how to use this new powerful tool to solve semi-analytical problems in finance and replace your Monte-Carlo Methods.</p><h3><strong>Introduction</strong></h3><p>We all know and love the monte carlo methods to numerically integrate but what if I told you that you can use imaginary numbers and Fourier Series to replace Monte Carlo?<br>The main benefit is <strong>speed </strong>which in option pricing is very important. This is very important as the Heston model for pricing stock options needs to numerically integrate which with <strong>Monte Carlo would take around 100ms </strong>and with the <strong>Fourier Series a dozen of μs </strong>as you can see in <a href="https://medium.com/@alexander.tsoskounoglou/pricing-options-with-fourier-series-p3-the-heston-model-d157369a217a"><strong>Part 3</strong></a><strong> </strong>of my article series.</p><h3>Section 1: But what is a Fourier Series?</h3><p>For any function <em>f </em>and for an interval <em>a,b</em> we can approximate <em>f(x)</em> as the infinite sum of cosines and sines, with L = b-a.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*zbFTG4tRiIM2kDMn0TiwsQ.png" /></figure><h3>Section 2: Apply the math formulas to Python</h3><pre>def get_fourier_approx(f, x:np.array, a:float, b:float, N:int):<br>    fa = lambda x, n : f(x) * cos((2*pi*n*x)/(b - a))<br>    fb = lambda x, n : f(x) * sin((2*pi*n*x)/(b - a))<br><br>    A0 = 1/(b - a) * quad(f, a, b, limit=200)[0]<br><br>    Cosine_Sine_Sum = np.zeros_like(x)<br>    for n in range(1, N+1):<br>        A = 2/(b - a) * quad(fa, a, b, args=(n), limit=200)[0]<br>        B = 2/(b - a) * quad(fb, a, b, args=(n), limit=200)[0]<br>        Cosine_Sine_Sum += A*cos((2*pi*n*x)/(b - a)) + B*sin((2*pi*n*x)/(b - a))<br><br>    fx = A0 + Cosine_Sine_Sum<br>    return fx</pre><pre>a = -6<br>b = 6<br>x = np.linspace(a, b, 1_000)<br>y = f(x)<br><br>fig, (ax1, ax2) = plt.subplots(2, figsize=(20,12))<br>blue_shades = [&#39;#0000FF&#39;, &#39;#3399FF&#39;, &#39;#66B2FF&#39;, &#39;#99CCFF&#39;, &#39;#CCE5FF&#39;]<br><br>avg_residuals = []<br>Ns = [8, 16, 32, 64, 128]<br>for i, N in enumerate(Ns):<br>    fx = get_fourier_approx(f=f, x=x, a=a, b=b, N=N)<br>    ax1.plot(x,fx, blue_shades[i], label=f&#39;N = {N}&#39;)<br>    ax2.plot(x,y-fx, blue_shades[i], label=f&#39;N = {N}&#39;)<br>    avg_residuals.append(np.abs(y-fx).mean())<br><br>ax1.set_title(&#39;Fourier Transform of f(x)&#39;)<br>ax1.plot(x,y,&#39;tab:red&#39;, linestyle=&#39;--&#39;)<br>ax2.set_title(&#39;Residuals&#39;)<br>plt.tight_layout() ; ax1.legend();ax2.legend() ; plt.show()<br><br>pd.Series(avg_residuals, index=Ns, name=&#39;Avg Residual&#39;)</pre><h4>Square Function:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3MRXB47qy7-N5nKbGGdvwA.png" /><figcaption>Source: <a href="https://github.com/ithakis/Pricing-Options-with-Black-Scholes/blob/main/Pricing%20Options%20with%20Fourier.ipynb">Notebook</a></figcaption></figure><pre>N      Avg. Residual<br>--------------------<br>8      1.311711<br>16     0.784683<br>32     0.440387<br>64     0.268449<br>128    0.154604</pre><h4>Line Function:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TCE3wRloCHzc7HKBkfbsLw.png" /><figcaption>Source: <a href="https://github.com/ithakis/Pricing-Options-with-Black-Scholes/blob/main/Pricing%20Options%20with%20Fourier.ipynb">Notebook</a></figcaption></figure><pre>N      Avg. Residual<br>--------------------<br>8      0.447389<br>16     0.264635<br>32     0.153540<br>64     0.088745<br>128    0.052147</pre><h4>Normal Distribution</h4><ul><li>Scaled so y in [0, 12] with:<br>- mean = 100<br>- std = 0.1 *sqrt(5)*100<br>- a = 100 -12 * std<br>- b = 100 +12 * std</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_I_LwEbPwbX_UwyUAC_v5w.png" /><figcaption>Source: <a href="https://github.com/ithakis/Pricing-Options-with-Black-Scholes/blob/main/Pricing%20Options%20with%20Fourier.ipynb">Notebook</a></figcaption></figure><pre>N      Avg. Residual<br>--------------------<br>8      1.092374e-01<br>16     8.326020e-05<br>32     6.878539e-14<br>64     5.721031e-14<br>128    5.170898e-14</pre><h4>Remarks</h4><ol><li>All the distributions are scaled such that y ranges from [0,12], so we can compare the magnitude of the residuals.</li><li>You can see from the plots and the residuals, that the more curvy a function is, the faster the Fourier series converges to the correct value. We leverage this property as the normal and the log-normal doesn&#39;t need a lot of terms to calculate with sufficient accuracy in our approximation.</li><li>There is a significantly higher error at the beginning and the end of the data. Therefore it&#39;s a good practice to include higher limits than what is intended to be used. For example, calculate ±4std when you need ±3. This makes deep out-of-the-money options trickier to calculate.</li></ol><h3>Section 3: Log-normal Distribution of S(T)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*XKEo1JdxVfiKQpVC6c3qlw.png" /></figure><p>S_T follows a simple GBM under Q, where we can derive the probability density of S_T using the following equations:</p><p>Now we can define f(S_T) in Python with the following functions and define the lower limit as ( 0, S_0*exp(r*T) + 12 * sigma*sqrt(T)*S_0 )</p><pre>S0      = 100<br>r       = 0.05<br>sigma   = 0.1<br>T       = 5.0<br><br>Z = lambda St : np.where(St &gt; 0, ((log(St/S0) - (r - .5*sigma)*T)/(sqrt(T)*sigma)), -np.inf)<br>f = lambda x : norm.pdf(Z(x))<br><br>a   = S0*exp(r*T) - 12 * sigma*sqrt(T)*S0<br>b   = S0*exp(r*T) + 12 * sigma*sqrt(T)*S0</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P2LxgEsfqPRobz1zJToxjA.png" /><figcaption>Source: <a href="https://github.com/ithakis/Pricing-Options-with-Black-Scholes/blob/main/Pricing%20Options%20with%20Fourier.ipynb">Notebook</a></figcaption></figure><pre>N       Avg. (scaled) Residual      Avg. Residual       Execution Time (sec)<br>----------------------------------------------------------------------------<br>8       0.176429                    5.880975e-03        0.112720<br>16      0.004235                    1.411566e-04        0.246473<br>32      0.000030                    9.855127e-07        0.624209<br>64      0.000027                    8.918504e-07        1.936948<br>128     0.000026                    8.530034e-07        6.741019</pre><h4>Remarks:</h4><ol><li>I have included both scaled and non-scaled residuals. Scaled Residuals correspond to the (incorrectly) scaled probability such that max{y}=12, wherein the (correct) non-scaled, max{y}=0.4. This was done to compare the fit of the log-normal distribution to the rest of the functions plotted above.</li><li>We can deduce that the log-normal distribution is harder to fit that the normal distribution due to the nonsymmetrical shape.</li><li>We can see that with 64 terms in the non-scaled version, the expected error in calculating P(S_T=x) is very small, less than 0.0001%.</li><li><strong>It&#39;s very important to center the distribution around the expected value at T, with 12stds symmetrically left and right. </strong>I made a version where a, and b are not symmetrical, and the residuals are not evenly spread out. Intuitively, you would take a=0+ but it will not generate desirable outcomes. *The residuals of S_T are calculated for values of S_T&gt;0 since it&#39;s not possible and we don&#39;t care about values less than 0.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RLt8XIcix3F-AyE-5zpE-w.png" /><figcaption>The density of S_T with a=1e-8, showing undesirable properties at the residuals. Source: <a href="https://github.com/ithakis/Pricing-Options-with-Black-Scholes/blob/main/Pricing%20Options%20with%20Fourier.ipynb">Notebook</a></figcaption></figure><h4>Limitations — Drawbacks — Improvements:</h4><ol><li>There is no benefit in approximating any of the previously mentioned functions as a Fourier series and using the numerical integration as a means to calculate An and Bn.</li><li>It is very important to calculate the An and Bn coefficients analytically so the only numerical part is calculating the series.</li><li>The benefit lies elsewhere. It is when f(x) does not have an explicit form and numerical integration is needed, and we can solve the problem semi-analytically with the characteristic function and Fourier series.</li><li>If we were to price an Option with standard BS in Python with scipy.norm it takes around 0.06 milliseconds. So it doesn&#39;t make sense to use Fourier for the standard BS. <br>However, if we analytically solve the integrals A0, An, Bn, and use the version with complex numbers we get around 0.6miliseconds, which is comparable. We will use this to our benefit in the Heston model which is the industry standard for pricing such options, in part 3.</li></ol><h3>Next Article: Part 2</h3><p>Medium: <a href="https://medium.com/@alexander.tsoskounoglou/pricing-options-with-fourier-series-p2-fa7328bd942b">Link</a></p><p>In the next article, we see how to use this knowledge in combination with the <strong>characteristic function</strong>, (the use of imaginary numbers) to calculate the <strong>value of a European Call option</strong> using the standard Black-Scholes model.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5bf60443ba0c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Insurance Portfolio Hedging with Neural Networks]]></title>
            <link>https://medium.com/@alexander.tsoskounoglou/insurance-portfolio-hedging-with-neural-networks-b58cf4a35d62?source=rss-e3674ac63c40------2</link>
            <guid isPermaLink="false">https://medium.com/p/b58cf4a35d62</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[portfolio]]></category>
            <category><![CDATA[liability]]></category>
            <category><![CDATA[insurance]]></category>
            <category><![CDATA[hedging]]></category>
            <dc:creator><![CDATA[Alexander Tsoskounoglou]]></dc:creator>
            <pubDate>Sun, 23 Apr 2023 12:33:27 GMT</pubDate>
            <atom:updated>2025-01-06T17:12:29.231Z</atom:updated>
            <content:encoded><![CDATA[<p>How neural networks can be used to hedge a liability containing both financial and actuarial risks satisfying VaR constraints.</p><p>A replicating portfolio strategy will be constructed using bonds and stocks, to replicate the payoff of the liability S at time T (expiration). Please find the accompanying Jupyter notebook <a href="https://github.com/ithakis/Option-Replicating-Portfolio-with-Neural-Networks/blob/main/Multi%20Time%20Step.ipynb">here</a> and how I calculated the parameters <a href="https://github.com/ithakis/Option-Replicating-Portfolio-with-Neural-Networks/blob/main/Extra:%20Stochastic%20Volatility.ipynb">here</a>.</p><p>Honorable mentions: UvA Actuarial research group, prof. Daniel Linders, prof. Yannick Dillschneider. <br>The research paper that this project is based on: “Insurance valuation: A two-step generalised regression approach” by Karim Barigou. <a href="https://arxiv.org/abs/2012.04364">Link</a></p><h3>The Liability S — The Insurance Product</h3><p>We have <strong>N </strong>amount of insurers at time t=0 (in this example N(0)=10,000) which invest <strong>P </strong>premium each (P=100 US), a total of 1,000,000 US at t=0. The insurance product states that liability <strong>S(T)</strong> (what is needed to be paid off) equals the number of people that are alive at T, times the premium they gave at t=0, times the maximum of Y(T), Y(0). Where Y is a risky asset, in this case, the SnP500 index<strong>:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PDsPpy_N1VSCEKV4159o1Q.png" /><figcaption>The payoff at T of liability S</figcaption></figure><h4>Monte Carlo simulation of Y(t) using GBM and stochastic Volatility (Cox-Ross)</h4><p><strong>Y</strong> (SnP500) follows a Brownian motion with stochastic volatility and drift under P probability space (calibrated on historical data of SnP500):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gWzrNwtvLPkTZBzd-ZEbtw.png" /><figcaption>Geometric Brownian Motion under P with stochastic volatility.</figcaption></figure><p>Where <strong>mu</strong> is the expected return of the risky asset, <strong>a </strong>is the speed of the mean reversion, <strong>b</strong> is the long-term mean, and <strong>c</strong> is the volatility of the volatility. All the above-mentioned variables are calibrated from the data of the last 10 years of SnP500. <strong>W1</strong> and <strong>W2</strong> are noncorrelated Weiner processes. (I believe that the model can be improved if they are modeled as corrected stochastic processes)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-2OIpgQ9tVVsH8FdkFxfwg.png" /><figcaption>Monte Carlo paths of Y(t) and sigma(t) — source: <a href="https://github.com/ithakis/Option-Replicating-Portfolio-with-Neural-Networks/blob/main/Multi%20Time%20Step.ipynb">jupyter notebook</a></figcaption></figure><h4>Monte Carlo simulation of N(t) using force of mortality model.</h4><p><strong>N(t)</strong> is the number of people that are alive at time t. Only people that are alive at <strong>T</strong> can claim the insurance product. We hope that the number of people that are going to die before T is going to offset the probability of Y(T) &lt; Y(0). <strong>Using the last 10 years to calibrate the model the probability of Y(T) &lt; Y(0) is ~5.37%. </strong>The reason I believe that it&#39;s a good idea to implement a stochastic volatility model is to improve the accuracy of such approximation.</p><p>The functions used to calculate <strong>N(t+dt)</strong>, with N(0)=10,000, and lambda(0)=0.01:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hKrSxqgt-6ko9vrpCDhPEg.png" /><figcaption>The model of N(t)</figcaption></figure><p>Where <strong>gamma</strong> is the drift term for the force of mortality (as people get older the chance they are going to die increases), <strong>ita</strong> is the volatility of the force of mortality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rnO1v73z6GR2X4VlNTkF-Q.png" /><figcaption>Modeling the force of mortality lambda(t) and N(t) using monte carlo — <a href="https://github.com/ithakis/Option-Replicating-Portfolio-with-Neural-Networks/blob/main/Multi%20Time%20Step.ipynb">source</a></figcaption></figure><p>The expected number of people to be alive at T is <strong>8,617/10,000</strong>. <strong>However, we are not going to stop at calculating the expectation. We are going to use the lambda(t), N(t) MC paths in combination with the Y(t) MC paths as inputs to the NN to calculate our replicating portfolio assets at each time step.</strong></p><p><strong>Parameters Used:<br>Y(t)</strong>: underlying risky asset — calibrated on SnP500. Y(0)=1<br><strong>B</strong>: the risk-free interest rate. r=0.03 <br><strong>T</strong>: Duration of the product. T=10 Years<br><strong>mu:</strong> the drift of risky asset. mu=0.09464<br><strong>sigma(t):</strong> stochastic volatility. sigma(0)=0.15965 annualized<br><strong>a:</strong> mean reversion of stochastic vol = 0.00332<br><strong>b:</strong> long-term volatility = 0.15629<br><strong>c:</strong> volatility of volatility = 0.01583</p><p><strong>N(t)</strong>: Number of people that are alive. N(0)=10,000<br><strong>lambda(t):</strong> force of mortality. lambda(0) = 0.01<br><strong>gamma</strong>: the drift of force of mortality = 0.075<br><strong>ita</strong>: volatility of the force of mortality = 0.000597</p><p><strong>dt</strong>: step size of the simulations. = 1/365 (daily steps size)<br><strong>n_paths</strong>: Number of Monte Carlo paths for Y and N. = 4,096<br><strong>rebalancing</strong> <strong>frequency</strong>: the interval in which the replicating portfolio is constructed. = 1/4 (quarterly)</p><p>Since the stochastic volatility and the force of mortality are Eurler approximations we have to use a small step size <strong>dt</strong> to have good accuracy. Furthermore, <strong>n_paths</strong> need to be big enough to leverage the law of the large number where the subsequent calculations converge to the true mean. But, the computational cost of calculating the replicating portfolio value equals <strong>O(n_paths * T * rebalancing_frequncy). </strong>That&#39;s the reason why Sobol Monte Carlo was implemented to significantly reduce the variance of the estimations while keeping the number of paths low.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5N8H22ZtyOgaPxUvud7kFA.png" /><figcaption>Distribution of Y, N, S at T. Number of bins = 100 — <a href="https://github.com/ithakis/Option-Replicating-Portfolio-with-Neural-Networks/blob/main/Multi%20Time%20Step.ipynb">source</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*36hCHjeg6ws_K3n3BYfFEw.png" /><figcaption>Results of the Monte Carlo Estimations</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wsNdRHAEW7lPbwHZyhC9EA.png" /><figcaption>Payoff of S(T) — Result of Binomial distributions of N(t) and GBM of Y(t) with payoff max(Y(T),Y(0))</figcaption></figure><h3><strong>Replicating Portfolio — </strong>Neural Networks</h3><p>In its basic form, using the equations below the only unknown is V(t-dt) after performing a ML optimization task to find the best phi and psi given Y(t-dt). It is a very simple and cool trick! However, we need a powerful ML algorithm to perform this task. Since NN are very good at approximating nonlinear functions and are computationally efficient, they are a very good candidate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rSHewk3ueUzgebM6iFrnuQ.png" /></figure><p>The next important concept to understand is that V(T) = S(T) so essentially using a NN we can find the number of bonds and stocks to replicate the value of S(T) and calculate V(T-dt) using the phi and psi that minimized the error for V(T).</p><h4>VaR — Value at Risk constraint</h4><p>The goal of this project is to construct a replicating portfolio of assets, risk-free bonds, and risky assets (stocks), which at time T will equal the value of S(T), satisfying a very important constraint of VaR(0.99) &lt;0. This means that <strong>with 99% confidence, the insurance company will be able to pay back the liability</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*O6JfMxr3VQl4rspl_FCDjQ.png" /></figure><h4>Interpretation of the function above</h4><p>The residuals of our model equal the profit and loss of our replicating portfolio at each time step. If we just use MSE (R1) we are fitting the expectation of each time step. <strong>This means that 50% of the time we are going to be able to cover the liability. This is not okay. </strong>(See the left graph below). <strong>In order to cover the liability with 99% confidence, we combine R1 and R2 to produce the results in the right graph below. Satisfying the VaR(0.99)!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7osWKo816S5xPkUPh3Z4oA.png" /><figcaption>Illustration of the 2 minimization functions at work, so VaR(.99, Residuals) &lt; 0 — For a single step replicating portfolio. — <a href="https://github.com/ithakis/Option-Replicating-Portfolio-with-Neural-Networks/blob/main/Single%20Time%20Step.ipynb">source</a></figcaption></figure><p>I used the quantile loss functions with a quantile of 99% to hedge the residuals of the MSE, so the VAR constraints are satisfied. A cost of capital (i) of 0.1 was used. The functions above are used at each time step to calculate the phi/psi values which best fit the MC paths.</p><p><strong>Psedualgorithm of the process described above</strong></p><pre>model1 = Compiled network (1) above with MSE -&gt; model1<br>model2 = Compiled network (2) above quantile loss function -&gt; model2<br><br>for t in linspace(T-dt, 0, dt):<br>  # Y(t), N(t), lambda(t) are used to calculate phi and psi<br>  # Which are then multiplied with the provided Y(t+dt), B(t+dt) or Y(t), B(t)<br>  # First,  you fit to find the best phi and psi for t+dt<br>  # Second, you use that phi and psi to calculate V(T)<br><br>  inputs(t+dt) = Y(t), N(t), lambda(t), Y(t+dt), B(t+dt)<br>  inputs(t)    = Y(t), N(t), lambda(t), Y(t), B(t)<br><br>  model1.fit( inputs(t+dt), V(t+dt) )<br>  model2.fit( inputs(t+dt), V(t+dt) )<br>  <br>  g(t) = model1.predict( inputs(t) )<br>  h(t) = model2.predict( inputs(t) )<br><br>  V(t) = g(t) + i(h(t) - g(t))</pre><h4><strong>Neural Network Architecture used to calculate phi and psi</strong></h4><p>To perform the minimization of the residuals and find the best phi and psi for the given parameters, we are going to make a nice custom Neural Network which looks like this:</p><pre>Model: &quot;Replicating_Portfolio_MSE&quot;<br>__________________________________________________________________________________________________<br>Layer (type)                    Output Shape         Param #     Connected to                     <br>==================================================================================================<br>input: S_{t}, N_{t}, l_{t} (Inp [(None, 3)]          0                                            <br>__________________________________________________________________________________________________<br>LeakyReLU_1 (Dense)             (None, 8)            32          input: S_{t}, N_{t}, l_{t}[0][0] <br>__________________________________________________________________________________________________<br>LeakyReLU_2 (Dense)             (None, 8)            72          LeakyReLU_1[0][0]                <br>__________________________________________________________________________________________________<br>Phi_Psi (Dense)                 (None, 2)            18          LeakyReLU_2[0][0]                <br>__________________________________________________________________________________________________<br>input: S_{t}, B_{t} (InputLayer [(None, 2)]          0                                            <br>__________________________________________________________________________________________________<br>V_t (Dot)                       (None, 1)            0           Phi_Psi[0][0]                    <br>                                                                 input: S_{t}, B_{t}[0][0]        <br>==================================================================================================<br>Total params: 122<br>Trainable params: 122<br>Non-trainable params: 0<br>__________________________________________________________________________________________________</pre><h4>Single-Step Replicating Portfolio Results:</h4><p>It is very important to understand the basic property of the replicating portfolio in order to be able to interpret the results correctly. If we assume that the<strong> probability of Y(T) &lt; Y(0) is zero 0</strong>, <strong>the value of the replicating portfolio at t=0 would equal the discounted payoff under P</strong>. Meaning that we should invest all assets in stocks. If we assume that the <strong>probability of Y(T) &lt; Y(0) is zero 1</strong>, the value of the replicating portfolio is the payoff discounted under Q. This means that we should only buy bonds since Y(T) will be less than Y(0).</p><p><strong>As the probability of Y(T)&lt;Y(0) increases, the value of V(0) will start getting closer to exp(-r*dt)S(T).</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qmb3uFlo_yZMYfFpDqlusw.png" /><figcaption>Singe step replicating portfolio of S(T) — <a href="https://github.com/ithakis/Option-Replicating-Portfolio-with-Neural-Networks/blob/main/Multi%20Time%20Step.ipynb">source</a></figcaption></figure><p>Value at t_0 (Replicating-P) = <strong>896,842.837 </strong><br>Discounted Eq[S] ADJ = 1,652,441.266 <br> Difference = -755,598.429 : -45.726% <br>Discounted Ep[S] ADJ = 865,761.121 <br> Difference = 31,081.716 : <strong>3.590% </strong><br>Total Premium at t0 = 1,000,000 <br>Profit w/o TC = <strong>103,157</strong></p><h4>Multi-Step Replicating Portfolio Results:</h4><p>Now we do the same procedure but for multiple steps, since Y(t) and N(t) are stochastic variables. We want to have the ability to re-hedge multiple times while satisfying the VaR constraints since we can over and underestimate the P(Y(T)&lt;Y(0)). Overestimating means that the insurance company will claim less profit at t=T. Underestimating means that it could not be able to pay off the liability.</p><p>Reasons for overestimating the probability: Increased assumed volatility, realized mu is higher than historical mu.</p><p>Reasons for underestimating the probability: the opposite of the above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1oqWyXnDd8HdLyrw2lu1VQ.png" /><figcaption>Value at Risk over time. The constraints of Var98 &lt;0 a — <a href="https://github.com/ithakis/Option-Replicating-Portfolio-with-Neural-Networks/blob/main/Multi%20Time%20Step.ipynb">source</a></figcaption></figure><p>Overall VaR(<strong>98.5</strong>%) = <strong>-121.96 EUR </strong><br>Overall VaR(<strong>99.0</strong>%) = <strong>54.38 EUR </strong><br>Overall VaR(<strong>99.5</strong>%) =<strong> 1160.76 EUR</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_dsjapJXZlbjYD2fr7_SFA.png" /></figure><p>Phi(t=0) : <strong>643,687 Stocks </strong><br>Psi(t=0) : <strong>350,888 Bonds</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dFhsRCNnQZwRE-xJ1lypaw.png" /></figure><p>Value at t_0 (Replicating-P) = <strong>981,038.213 </strong><br>Discounted Eq[S] ADJ = 1,653,394.334 <br> Difference = -672,356.121 : -40.665% <br>Discounted Ep[S] ADJ = 866,260.460 <br> Difference = 114,777.752 : <strong>13.250% </strong><br>Total Premium at t0 = 1,000,000 <br>Profit w/o TC = <strong>18,962</strong></p><p><strong>From the results and graphs above we can see that:</strong><br>- For each step the VAR constraints are satisfied<br>- How the number of stocks and bonds vary over time, where the close we get to T the more stocks are bought and fewer bonds are bought and the tighter the distribution.<br>- The multi-step replicating portfolio is more expensive than the single step. (I believe that the error of the estimations is larger when the hedging is performed multiple times and/or because rebalancing multiple times results in a more expensive portfolio.)</p><h3>Tips and Tricks for the NN</h3><p>First, at time step 0, we train with a higher amount of epochs (500 vs 100) since the network has not been trained before. This allows a very good fit which only needs to be updated (refitted) for the next timesteps. <br>Second, is that we initialize the weights of the NN so at T without any training the mean of the network equals the mean of the payoff (which we are trying to fit), this saves a lot of computation time and helps with more consistent convergence. <br>Third, changed from a ReLU to a LeakyReLY which is better at approximating non-linear functions in shallow NNs. <br>Forth, I implemented a cooling regime in learning, starting with a learning rate of 1e-2 and reducing it to 1e-5 which is one of the best techniques in NNs to ensure a quick, consistent, and good fit. <br>Fifth and last, I monitored the loss in case it has not been improved in the last 7 epochs which stops the training and restores the best weights.</p><h3>Discussion</h3><p>Possible limitations are:<br>- Use the term structure of VIX options to calibrate the Cox-Ross parameters (Heston Model).<br>- Since we are rebalancing we are exposed to the interest rates. I have performed a bump and revalue and found that the <strong>V(0) is more expensive when interest rates are lower. This means that it is more difficult to hedge/replicate the claim of S(T).</strong><br>-&gt; <strong>Low-interest rates and high volatility is bad for this replicating portfolio strategy</strong>. A possibility is to buy swaptions to hedge against the possibility of low-interest rates. And/Or buy options on VIX to hedge against the increase in volatility.</p><p><strong>I would love to hear your thoughts and feedback on my work!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b58cf4a35d62" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Option Hedging with Neural Network]]></title>
            <link>https://medium.com/@alexander.tsoskounoglou/option-hedging-with-neural-network-de4cb92964ae?source=rss-e3674ac63c40------2</link>
            <guid isPermaLink="false">https://medium.com/p/de4cb92964ae</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[hedging]]></category>
            <category><![CDATA[finance-and-banking]]></category>
            <dc:creator><![CDATA[Alexander Tsoskounoglou]]></dc:creator>
            <pubDate>Sun, 19 Mar 2023 15:40:30 GMT</pubDate>
            <atom:updated>2023-03-19T23:50:58.807Z</atom:updated>
            <content:encoded><![CDATA[<h3>Option Hedging with Neural Networks</h3><p>How to hedge an Option using Monte-Carlo and Neural Networks.</p><p>Github Link: <a href="https://github.com/ithakis/Option-Replicating-Portfolio-with-Neural-Networks/blob/main/Value%20of%20portfolio%20using%20BS.ipynb">https://github.com/ithakis/Option-Replicating-Portfolio-with-Neural-Networks/blob/main/Value%20of%20portfolio%20using%20BS.ipynb</a></p><p>The 2 steps that this project is divided into are:</p><ul><li>Advanced Monte-Carlo technique of Quasi-Monte Carlo (Sobol) for the path simulation of the stock.</li><li>After we calculate the option’s payoff at time T. How we can create a replicating portfolio strategy to value the option at t=0.</li></ul><h3>Quasi-Monte Carlo</h3><p>Since the SE of the mean of the approximation of an option’s value is reduced with the square root of the number of paths that we simulate. We should invest some time to use a more advanced technique to reduce the variance in the estimation. Such techniques are antithetic variates, control variates, and stratified sampling. You can check this like to find out more about variance reduction techniques in MC in financial applications. (<a href="https://quantpy.com.au/monte-carlo/pseudo-vs-quasi-random-numbers/">https://quantpy.com.au/monte-carlo/pseudo-vs-quasi-random-numbers/</a>)</p><p>Using the following piece of code we can generate normally distributed variables to be used in the stock path simulation using geometric brownian motion for the log of S (stock)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*u_g-pBG2-xrVBdiAwmyYfw.png" /><figcaption>GBM for the log of a stock</figcaption></figure><pre>import scipy.stats as stats<br>from scipy.stats import qmc<br><br>def sobol_norm(m, d=1):<br>    sampler = qmc.Sobol(d, scramble=True)<br>    x_sobol = sampler.random_base2(m)<br>    return stats.norm.ppf(x_sobol)<br><br>&quot;&quot;&quot; Simulate Stock Data &quot;&quot;&quot;<br>W       = sobol_norm(n_paths, d=n_time_steps)<br>S_paths = np.empty((2**n_paths, n_time_steps))<br>S_paths[:,0] = S<br>for t in range(1,n_time_steps):<br>    S_paths[:,t] = (S_paths[:,t-1] * np.exp((r-sigma**2/2)*dt + sigma * np.sqrt(dt)*W[:,t] ).squeeze())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s3yCtHL6lKFDUlQU_BHB-g.png" /><figcaption>Monte Carlo simulation of Stock Prices</figcaption></figure><p>Now for this example, a European Option was used where its payoff at time T is calculated max(S_T -K, 0).</p><h3>Neural Network</h3><p>The replication theory is used where the value of an option equals an amount of stock (phi) and an amount of bond (psi). Since we have more than 2 possible outcomes for S_t, now the problem is transformed into a minimization of the error. Where we try to find values psi and phi which will replicate the value of V_t as closely as possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*QjESwNkb8xTEo0QI2oOblw.png" /><figcaption>Replicating Portfolio of an Option using a Stock and a Bond</figcaption></figure><p>To anybody that has worked with machine learning before, alarms should be going off now, about how we can try to fit a function to perform this task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h-omqJZl8gJ-DTLGb2I7Vw.png" /><figcaption>The problem we are trying to minimize</figcaption></figure><p>(1) Start at t=T-1 where V_{t+1} is known</p><p>(2) Pass to the NN: S_{t+1}, B_{t+1}, V_{t+1} to fit.</p><p>(2) Predict V_{t}, given S_{t}, B_{t}</p><p>(3) Use the predicted V_{t} as input for step 1</p><p>(4) Repeat until the value at t=0 is calculated</p><h4>The Neural Network architecture</h4><p>S_{t} passes through a NN architecture that outputs the estimated psi and phi values which are then doted with S_{t} and B_{t} to calculate V_{t}. In this example, sigmoid activations are vastly superior to ReLU. However extensive hyper parameter tuning was not performed.</p><p>The hyper-parameters used :</p><ul><li>‘MSE’ as the loss function</li><li>Adam with lr: 1e-2</li><li>epochs per fit time step: 10 (except 300 for the first step)</li><li>batch size: 512 (large batch size is important to ensure representative sampling at each back propagation)</li></ul><p>Some tricks and tips that help reduce the error:</p><ul><li>Repeat the fitting over the period of the option more than one time. In this example, it was repeated 5 times.</li><li>Have a high number of epochs in the first time fit is performed. Since the error in the value approximation propagates its very optimum to allow the network to learn the parameters as much as possible in the first go. Afterward, the epochs can be reduced to save on training time.</li><li>Perform bootstrapping over all periods, to estimate the average std of the mean portfolio value for all time steps.</li></ul><pre>Model: &quot;Replicating_Portfolio&quot;<br>__________________________________________________________________________________________________<br>Layer (type)                    Output Shape         Param #     Connected to                     <br>==================================================================================================<br>input: S_{t}  (InputLayer)      [(None, 1)]          0                                            <br>__________________________________________________________________________________________________<br>Sigmoid_1 (Dense)               (None, 8)            16          input: S_{t} [0][0]              <br>__________________________________________________________________________________________________<br>Sigmoid_2 (Dense)               (None, 8)            72          Sigmoid_1[0][0]                  <br>__________________________________________________________________________________________________<br>linear (Dense)                  (None, 2)            18          Sigmoid_2[0][0]                  <br>__________________________________________________________________________________________________<br>input: S_{t}, B_{t}  (InputLaye [(None, 2)]          0                                            <br>__________________________________________________________________________________________________<br>V_t (Dot)                       (None, 1)            0           linear[0][0]                     <br>                                                                 input: S_{t}, B_{t} [0][0]       <br>==================================================================================================<br>Total params: 106<br>Trainable params: 106<br>Non-trainable params: 0<br>__________________________________________________________________________________________________</pre><p>In the Graph below you can see how the value of the portfolio over the period of the stock until t=0. It&#39;s important to note that the error of the prediction of V_{t} (red line) is higher at the initial backward steps the algorithm takes. If the error is minimized further by different NN architects or different hps. The value will converge more accurately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8AMkPI_kOWCtTE6xnZyuYg.png" /><figcaption>Source: Github Notebook</figcaption></figure><p>Parameters used in the experiment:</p><ul><li>S = 100, K = 100, T = 1.0, r = .055, sigma = 0.3, dt = 1/100</li></ul><p>Since we are valuing a European Option we can analytically calculate its value which equals to:</p><ul><li>Black-Scholes for European Call: 14.47320</li><li>Replicating Portfolio Euro Call: 14.49997</li><li>Replicating-P SE = 0.0508</li><li>Total execution time with 10,000 MC paths, 100 time steps, and 5 loops: ~14 mins (tensorflow on M1, with metal and GPU enabled)</li></ul><h4>Hedging Parameters</h4><p>The layer outputs of the ‘linear’ layer can be used how match stock and bond assets that need to be bought at time t = 0</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C3S4hQERainw6it8fWXFuw.png" /><figcaption>Hedging parameters — stock and bond at time t=0</figcaption></figure><p>Using the mean or the expectation the total amount that needs to be invested at t=0 is:</p><ul><li>Mean Phi: 0.6238</li><li>Mean Psi: -47.9307</li></ul><h3>Future Work</h3><p>Now that it has been shown that NN can be used to perform the task of calculating the value of an option with a replicating portfolio there is additional work that needs to be done to apply this method in practice.</p><ul><li>Construct a replicating portfolio with more assets</li><li>Optimize the NN architecture and hyper parameters for faster training/higher accuracy. (Use faster hardware)</li><li>More complex simulation models, since the simulation of the prices, is independent of the valuation.</li><li>Exotic derivatives</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de4cb92964ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Credit Valuation Adjustment for Interest Rate Swaps with CDS Data]]></title>
            <link>https://medium.com/@alexander.tsoskounoglou/credit-valuation-adjustment-for-interest-rate-swaps-with-cds-data-49d961485c64?source=rss-e3674ac63c40------2</link>
            <guid isPermaLink="false">https://medium.com/p/49d961485c64</guid>
            <category><![CDATA[valuation]]></category>
            <category><![CDATA[quantitative-finance]]></category>
            <category><![CDATA[cva]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[credit-risk]]></category>
            <dc:creator><![CDATA[Alexander Tsoskounoglou]]></dc:creator>
            <pubDate>Sat, 19 Nov 2022 17:36:37 GMT</pubDate>
            <atom:updated>2022-11-19T17:36:37.790Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog post, I will guide you through the convoluted nature of calculating <strong>CVA</strong> for an <strong>IRS</strong> step by step. Please find the accompanying Python Notebooks on my GitHub <a href="https://github.com/ithakis/CVA-with-CDS-data/blob/main/CVA.ipynb">page</a>. We will take a look at the <strong>8 steps required to calculate the Credit Valuation Adjustment (CVA) </strong>for hedging against the <strong>risk of default of the counterparty</strong> when entering an <strong>Interest Rate Swap</strong> <strong>(IRS)</strong> using <strong>Credit Default Swaps (CDS) </strong>data. My name is Alexander Tsoskonoglou and welcome to my blog post.</p><ul><li><em>Accompanying Python Notebook link: </em><a href="https://github.com/ithakis/CVA-with-CDS-data/blob/main/CVA.ipynb"><em>Here</em></a></li></ul><h3>What is Credit Valuation Adjustment?</h3><p>Buying or Selling an<strong> Over-the-Counte</strong>r (OTC) financial security with future payoff(s), comes with the inherent risk that the counterparty will default, which will lead to a loss for the issuer. This is because the counterparty will not pay the remaining future payments (cashflows) of the interest rate swap (IRS).</p><p>The 3 main components of CVA are:</p><ul><li>(1) Loss Given Default (<strong>LGD)</strong></li><li>(2) Expected Positive Exposure (<strong>EPE)</strong></li><li>(3) Probability of Default (<strong>PD)</strong></li></ul><p><strong>Loss Given Default</strong> <strong>(LGD)</strong> is the non-recoverable percentage of the debt in case of default for a company. If we assume that company x has dept 100M to bank y, with LGD 40%. For example, in case of default it is expected that 60M will be recovered. When a company defaults, it does not mean that all debt will be lost, but depending on the financials, accountants will calculate LGD based on the assets of the company/organization holds. A commonly used LGD value is 40%. When calculating CVA, this number will be known/derived through the CDS data or will be approximated.</p><p>The <strong>Expected Positive Exposure</strong> <strong>(EPE)</strong> is the expected amount that will be lost at time <em>t </em>in case the counterparty defaults. To calculate EPE we have to revalue the swap in the future with adjusted term structures (discount factors &amp; future curves) which are calculated using the Hull-White Interest rate modeling techniques. Since EPE is the main challenge of calculating CVA in Interest Rate Swaps (IRS) we will discuss this extensively later.</p><p>The <strong>Probability of Default (PD) </strong>is calculated based on <strong>Credit Default Swaps (CDS)</strong> that are traded for the counterparty’s/organization Bonds. CDS is measured in bps (basis points: 1/10,000) and is the difference between the Risk-Free Yield (usually a AAA bond, i.e. German or US Government Bonds) and the Company’s Bond Yield. For example, if a risk-free zero-coupon bond with a maturity of 5Y has 2%yield and the same zero-coupon bond of company X has 3%yield then the spread between the two will be 100 bps.</p><p>Therefore, intuitively the <strong>higher the spread</strong> <strong>the more risk is associated with </strong>company X. Subsequently the <strong>PD</strong> for company X will be higher than company Y which has a spread of 50bps.</p><h3>What is an Interest Rate Swap?</h3><p>I cover the process of pricing an <strong>Interest Rate Swap (IRS)</strong> here. But a quick refresher is: <strong>Swapping floating interest payments, for fixed interest payments over the duration of the IRS. </strong>*IRS can also be floating-to-floating and highly customizable as they are OTC financial derivatives tailored to the specifics of the customer. The concepts that are needed to calculate an IRS are:</p><ul><li>1. The <strong>floating payment frequency</strong> (3M or 6M usually)</li><li>2. The <strong>fixed payment frequency</strong> (3M or 6M usually)</li><li>3. The <strong>Swap rate</strong> and <strong>Fixed rate</strong> (usually swap rate equals fixed rate so IRS has 0 value at t=0)</li><li>4. <strong>Forward Curve</strong> of Intra-bank Interest rate (i.e. EURIBOR)</li><li>5. <strong>Discount Factors</strong> derived from the forward curve of Risk-Free Interest rate (EONIA)</li><li>6. <strong>Maturity </strong>of IRS, <strong>T</strong> (can be from 1Y up to 30Y)</li></ul><h3><strong>The 8 steps to Calculate CVA</strong></h3><ul><li><strong>1. Interpolating current term structures</strong></li><li><strong>2. Short-Rate simulation with Hull-White Model</strong></li><li><strong>3. Computing future discount factor curves</strong></li><li><strong>4. Computing future floating rate term structures</strong></li><li><strong>5. Revaluate IRS for the duration of the Swap</strong></li><li><strong>6. Calculating Expected Positive Exposure</strong></li><li><strong>7. Probability of Default based on CDS Data</strong></li><li><strong>7. Probability of Default when CDS Data is missing</strong></li><li><strong>8. CVA value with Standard Error</strong></li></ul><p><em>**I think it&#39;s a good time to mention that this is the most convoluted and mentally challenging project I have ever done. So strap in, as I am going to do my best to help you avoid getting as confused and frustrated as I once was.</em></p><h4><strong>Step 1: Interpolating Current Term Structure</strong></h4><p>To start you will need to interpolate the forward rate of EONIA or EURIBOR (used in this example) to the frequency that the simulation is going to be run (dt=1/52: weekly). Interpolation is the technique of filling missing values between known values. Since our simulation interval is weekly or even daily, and the data that is observed in the market is quarterly or even annually available, we need to fill in a “smooth” way the missing values.</p><p>In this case for a floating-to-fixed rate IRS, with a <strong>fixed payment frequency of 3M</strong> and a <strong>floating payment frequency of 3M, </strong>you will need <strong>EONIA3M and EURIBOR3M forward curves </strong>respectively.<strong> </strong>If your IRS payments are of different frequency, you will need a different version of those products, i.e. EONIA1M, EONIA6M, EONIA1Y. Take a look here about a potential source of data: <a href="https://www.chathamfinancial.com/technology/european-forward-curves">https://www.chathamfinancial.com/technology/european-forward-curves</a></p><p>In this particular case, I experimented with the options provided by pandas interpolate function (<a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.interpolate.html">link</a>). Where ‘piecewise_polynomial’ was both very fast (0.01sec per curve) and passed from all given data points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xk17R5LzzWb27Ih-qyBzWQ.png" /><figcaption>This graph illustrates the difference between forward fill and piecewise polynomial interpolation techniques. Source: <a href="https://github.com/ithakis/CVA-with-CDS-data/blob/main/CVA.ipynb">Accompanying Notebook</a></figcaption></figure><p>An example of the impact the interpolation technique can have is the difference between the swap rate of a 30Y IRS using ffill vs piecewise as the interpolation method:</p><p>Swap rate with ffill = -0.1640 %</p><p>Swap rate with piecewise = -0.1585 %</p><p><strong>A 3.5% relative difference</strong>. Meaning that the issuer of the swap (the bank) would receive 3.5% less money for the duration of the swap if they used ffill!</p><h4>Step 2: <strong>Simulate Short Rates Using Hull White Monte Carlo Simulation</strong></h4><p>The formula below is used to numerically integrate the future short-rate. The formula is used both for RFR and Intrabank.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QGYNbEFSVEf8YaNKUvMkkA.png" /></figure><p>The results below illustrate how the Monte-Carlo (MC) simulation of short rates looks like. The mean of the MC at any single point is g(t) with the standard deviation intuitively increasing in a conical shape as time increases. A simulation with 1.500 paths and weekly interval (dt) is a good enough tradeoff between speed and accuracy. (If we used Euler’s Method of discretizing the HW function we would need lower dt and would still not be as accurate as with the original HW equation)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vZlemUTzpNwv3ElxFSIwKw.png" /><figcaption>Source: <a href="https://github.com/ithakis/CVA-with-CDS-data/blob/main/CVA.ipynb">Accompanying Notebook</a>, Macbook M1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yvInsFn02dBk7SL0KtQ4Zg.png" /><figcaption>Source: <a href="https://github.com/ithakis/CVA-with-CDS-data/blob/main/CVA.ipynb">Accompanying Notebook</a></figcaption></figure><h4>Step <strong>3. Computing future discount factor curves</strong></h4><p>Now that we calculated the short rate we can plug it in the following formula to calculate the Discount Factors <strong>P(t, T) </strong>for both risk-free-rate RFR and Intrabank rate. The concept is a bit difficult to catch at a quick glance but the quick way to put it is:</p><p>“In one year (t=1Y) from now how much 1EUR, 2 years from then (T=2Y, 3 years from now) is worth discounted back at time t (t=1Y): given that we receive cc interest rate r, where t≤T.”</p><p>We replace one year with (t) and 2 years with (T). This way we can calculate how much we need to discount the future payments when we value the IRS in the future. We apply this formula to first, calculate component <em>5: Discount Factors, </em>(look in the introduction) of the IRS, and second, we use it as input in the next step to calculate component <em>4: Forward Curve </em>of the IRS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ElAXhF4w0J7UWrYC_Yf7rQ.png" /><figcaption>Function to used to calculate discount factors — P(t,T)</figcaption></figure><p>The first graph is an illustration of how the resulting distribution for the MC paths is over the years, where t is constant (t=1Y). A sanity check is for a small t (~less than 1Y) the mean of MC should be very close to the observed data (orange line). As we increase t the mean of the MC is going to deviate more and more from the observed. The second plot is going to show you (for example, 9 years from now, <em>the red line</em>) how the rest of the cashflow payments need to be discounted back to t=9 P(9, T), where T≥t.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*70pLkackN4TO27aVo55JMg.png" /><figcaption>Constant (t), all MC paths vs Variable (t), Mean MC path. Source: <a href="https://github.com/ithakis/CVA-with-CDS-data/blob/main/CVA.ipynb">Accompanying Notebook</a></figcaption></figure><h4>Step <strong>4. Computing future floating rate term structures</strong></h4><p>For step 4 we will use the results we calculated from step 3 for the Intrabank (EURIBOR) to derive the forward curve for each t using this formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2RRk4wolBYWG4kiyjxJVGw.png" /></figure><p>Again the intuition on the following graph is the same as the one for the discount factors.</p><p>“In one year from now (t=1Y) if I want to borrow for 3 months (EURIBOR3M) 2 years from then (T=2Y, 3 years in total). How much interest I am going to have to pay (cc interest in this case)”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kKwcnPA4ctwHFl_2FF-Zvg.png" /><figcaption>Source: <a href="https://github.com/ithakis/CVA-with-CDS-data/blob/main/CVA.ipynb">Accompanying Notebook</a></figcaption></figure><h4>Step 5. <strong>Re-evaluate IRS for the remaining duration of the Swap.</strong></h4><p>To calculate the EPE we need to calculate the value of the IRS continuously until its expiry. Since we numerically approximate the result with 1500 MC paths and weekly interval we use this data to calculate the Value of the IRS at times t. Where, we have all the components necessary (Forward curves f(t,T), Discount Factors P(t,T), and initially agreed/calculated Fixed rate r) for re-evaluating the IRS. We iterate over the 2D matrices we generated (forward curves, discount factors) to calculate for each underlying HW path how much the swap is going to be worth V at time t, V(t).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zzhnDkq8VDohOKzymbnR7w.png" /></figure><p>The graph below visualizes at time 0 the cashflows for the duration of a 30Y IRS, where the fixed payment frequency is quarterly and the floating payment frequency is semi-annually. The net present value (NPV) floating payments equal the NPV of the fixed payments. The value of the Swap at t=0 is <strong>zero. </strong>(*This illustrates how IRS swaps can change the payment frequency to something more convenient for the receiver).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x-qUj39nGEAepTCMifJWgw.png" /><figcaption>Source: <a href="https://github.com/ithakis/CVA-with-CDS-data/blob/main/CVA.ipynb">Accompanying Notebook</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1zTNdNuwniU0MPhTliT-3w.png" /></figure><h4>Step 6: <strong>Calculating Expected Positive Exposure</strong></h4><p>Now that we have calculated the value of the swap for each HW (interest rate) path, we can calculate the Expected Positive Exposure (<strong>EPE</strong>) at times (t) by first discounting the V(t) to today&#39;s money and second by conditioning V(t) for values where the exposure is greater than 0. Intuitively the issuer cares only for the scenarios where they are going to lose money if the counterparty defaults, for calculating CVA.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LgjuLXMv_2Vy1WzA4k_M3g.png" /></figure><p>So to its whole glory, this is the subsequent chart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-YAc6CtyzBK8AGb_iK-c7g.png" /><figcaption>Source: Accompanying Notebook</figcaption></figure><h4><strong>Step 7: Probability of Default based on CDS Data</strong></h4><p>Using a data provider (or the data sample provided alongside the notebook) you can derive very straightforward the PD for the CDS spread of company X for maturity T with constant recovery R.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DNljqIwvSysgnLkxNwzuCg.png" /></figure><p>For example, TOSH is a company with a credit rating of CCC and rich CDS data that we can interpolate the PD directly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FbuLInPKycqnDY23-Zk0pg.png" /><figcaption>Source: <a href="https://github.com/ithakis/CVA-with-CDS-data/blob/main/CVA.ipynb">Accompanying Notebook</a></figcaption></figure><h4>Step 8: <strong>CVA value with Standard Error</strong></h4><p>Now it’s game time! Let&#39;s arrive at our beloved result and congratulate ourselves for going through with this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K7FQT_-gMnrPyuSX6r8aCw.png" /></figure><p>Any kind of estimation that uses MC integration is crucial to use bootstrapping to calculate the Standard Error of your calculation. ±2.5 times your SE gives you the 99% confidence interval. Therefore you know how good of an estimation you made.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g_1MsGuPX9Bipaz6EMCO8g.png" /><figcaption>CVA for TOSH for 30Y IRS. Source: <a href="https://github.com/ithakis/CVA-with-CDS-data/blob/main/CVA.ipynb">Accompanying Notebook</a></figcaption></figure><p>For TOSH, for a 30Y IRS with the data available (2020–12–22), you would need 15% of your notional to be kept aside as security against the probability of default of TOSH. If the <strong>Notional is 100M </strong>then the issuer (bank) would need to <strong>keep aside 15M for security.</strong> Quite a significant amount, which cannot be used for something else or earn interest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1zg94zZif-4MU_ksvZYAGw.png" /><figcaption>Source: <a href="https://github.com/ithakis/CVA-with-CDS-data/blob/main/CVA.ipynb">Accompanying Notebook</a></figcaption></figure><p>Using bootstrapping we split the 10,000 paths into 100 subsets (see more about bootstrapping <a href="https://en.wikipedia.org/wiki/Bootstrapping_(statistics)">here</a>) and use the standard deviation of the means to determine the standard error of the estimation of the CVA value. (Means follow a normal distribution: CLT, (Graph 1)). The second graph shows CVA as a function of CDS which is calculated by shifting all the CDS data by x amount, which shows the sensitivity of the CVA value relative to changes in the underlying credit risk of the receiver.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hhdBDzpVHYfShv82sc4qKQ.png" /><figcaption>Source: <a href="https://github.com/ithakis/CVA-with-CDS-data/blob/main/CVA.ipynb">Accompanying Notebook</a></figcaption></figure><p>In the graph below on the x-axis, we see how CVA changes for different maturities, and on the y-axis, the CVA value is given when we shift the curve by y amount. (same procedure as in the graph above)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZV0JpobCjDoYfP2wylJn5A.png" /><figcaption>Source: <a href="https://github.com/ithakis/CVA-with-CDS-data/blob/main/CVA.ipynb">Accompanying Notebook</a></figcaption></figure><h4><strong>Steps 7b and 8: Probability of Default when CDS Data is missing</strong></h4><p>As ‘easy’ as it is to calculate CVA for a company with rich CDS data, there are about 200–300 companies where CDS is available for them. If we enter an IRS with a company where there is no CDS data (product) available, we need to derive its PD and LGD from a proxy.</p><p>In the graph below, you can see how the PD changes for different credit ratings. You can see 2 main things, first that higher credit ratings (AA) have lower PD, and second most importantly how big of a spread (variance in PD) there is in each bin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KVwXZiG4dXFS-wFiIgjzWQ.png" /><figcaption>Source: <a href="https://github.com/ithakis/CVA-with-CDS-data/blob/main/CVA.ipynb">Accompanying Notebook</a></figcaption></figure><p>Therefore by combining more ‘where’ clauses to our selection of companies with CDS data that match our company, we can get a more narrow spread between the PD of the bin. For example, a AA Technology company in Europe would have a mean CVA of 5% :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xSnlP7Ac2PcTBTdSQvQdFg.png" /></figure><p>Assuming a recovery of 40% (LGD=60%) we can calculate the mean CVA value as well as the 5th and 95th percentiles of it. The graph below shows the distribution of PD for AA, Technology companies in Europe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d77ptjA-gMkMvifPRci_pg.png" /><figcaption>Source: <a href="https://github.com/ithakis/CVA-with-CDS-data/blob/main/CVA.ipynb">Accompanying Notebook</a></figcaption></figure><p>Unfortunately, the deviation between the two CVA extremes (1.5% and 10%) is still very large therefore in the industry there are currently implemented more advanced proxy methods which result in less variance in the estimation of the PD (UvA research <a href="https://pure.uva.nl/ws/files/26579519/Liquidity_risk_in_derivatives_valuation.pdf">link</a>). Such methods take into account equity data (returns, volatility) to reduce the Error in the estimation. Another proposed method is to construct groups of companies using again returns and volatility historical data to group them into similarly behaving groups where the PD is going to be similar across the group.</p><h3>The end</h3><p>Disclaimer: This project was done (started) as part of my course in Advance Topics in Computational Finance under the direction of Professor Drona Kandhai and Professor Sumit Sourabh. I want to thank Nils Breeman whom I did this project together and had a lot of fun exploring the subject.</p><p>The goal of writing this blog is to help fellow colleagues get access to a complete guide on how to calculate CVA with CDS data and provide them with a comprehensive accompanying Python Notebook. I am by no means an expert in CVA however, I believe that sharing my experience would help a lot of people trying to start this convoluted journey.</p><p>Any constructive criticism is more than welcome as we can improve the level of access to quality information together!</p><p>Thank you for your attention!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49d961485c64" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>