<?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 Bremphis on Medium]]></title>
        <description><![CDATA[Stories by Bremphis on Medium]]></description>
        <link>https://medium.com/@finardfr?source=rss-dc313bcc2ae3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1GBiGUwWBUMUgxC3aqD91w.jpeg</url>
            <title>Stories by Bremphis on Medium</title>
            <link>https://medium.com/@finardfr?source=rss-dc313bcc2ae3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 23:08:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@finardfr/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[PINNs: Neural Network Approach for solving Differential Equations in Python]]></title>
            <link>https://finardfr.medium.com/pinns-neural-network-approach-for-solving-differential-equations-in-python-2d55dab47cd7?source=rss-dc313bcc2ae3------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d55dab47cd7</guid>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ode]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[pinn]]></category>
            <dc:creator><![CDATA[Bremphis]]></dc:creator>
            <pubDate>Fri, 28 Mar 2025 14:29:36 GMT</pubDate>
            <atom:updated>2025-03-28T14:32:52.737Z</atom:updated>
            <content:encoded><![CDATA[<p>Last week, I had the opportunity to attend a short course over a few days at the University of Geneva titled <em>“Deep Learning for Economics and Finance”</em>, taught by <a href="https://sites.google.com/site/simonscheidegger/home?authuser=0">Simon Scheidegger</a>, Associate Professor at the Department of Economics, HEC Lausanne, Switzerland. Among the topics covered, one that particularly stood out to me was the use of neural networks to solve ODEs and PDEs.</p><h4>1. Boring way to solve an ODE</h4><p>Let us consider the differential equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/107/0*s-0uTeqdlMm7X_yy" /></figure><p>with the boundary conditions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/195/0*G6Y37Buwr3Q1Req_" /></figure><p>Since</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/76/0*OXzKVNKhSaLTqTyK" /></figure><p>integrating once with respect to x gives</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*H49LM-h0ug-ZhX6g" /></figure><p>Integrating a second time, we obtain</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/0*MqrzaaES23_Ejo04" /></figure><p>Now, applying the boundary conditions:</p><ol><li>For y(0)=1</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/0*M6MpZ47V-hldl0r_" /></figure><p>2. For y(2)=5:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/0*y1LdnL2oVL0auRmv" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/0*GTRHOgf97iXJp2k9" /></figure><p>Thus, the analytical solution is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/164/0*HgI-V3MvjF9h-_5t" /></figure><h4>2. Beautiful way to solve the ODE with Neural Networks</h4><p>This method is called PINN (Physics-Informed Neural Network) and works in our example as follow:</p><ol><li><strong>Neural Network Approximation:</strong></li></ol><ul><li>We define a neural network y(θ,x) where θ represents the network’s parameters (weights and biases). This network is designed to approximate the solution y(x) of the differential equation.</li><li>In our case, the neural network is a small fully connected network (with one or more hidden layers) that takes the spatial coordinate x as input and outputs an approximation of y(x).</li></ul><p><strong>2.</strong> <strong>Automatic Differentiation:</strong></p><ul><li>One of the key benefits of using neural networks in this context is that most modern deep learning libraries (like PyTorch) support automatic differentiation.</li><li>This means we can compute the derivatives y′(x) and y′′(x) directly from the network’s output with respect to the input x.</li></ul><p><strong>3.</strong> <strong>Residual Calculation:</strong></p><ul><li>For the ODE</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/107/0*s-0uTeqdlMm7X_yy" /></figure><p>we define the residual r(x) as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/130/0*lHzAPFs0OGDFrSCE" /></figure><p>At points where the network approximation is exact, the residual should be zero.</p><p><strong>4. Loss Function:</strong></p><ul><li>The loss function in the PINN approach is constructed as the sum of two parts:</li><li><strong><em>Residual Loss</em>:</strong> The mean squared error (MSE) of the residual r(x) computed at a set of interior collocation points within the domain. This term forces the network’s prediction to satisfy the differential equation.</li><li><strong><em>Boundary Condition Loss</em>:</strong> The MSE of the difference between the network’s predictions and the given boundary conditions.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/158/0*qdfk1098vaOumQ1d" /></figure><ul><li>The overall loss is then:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/0*Lzl-1drxc0Kd0JYH" /></figure><p>Now let’s code:</p><pre>import torch<br>import torch.nn as nn<br>import torch.optim as optim<br>import matplotlib.pyplot as plt<br>import numpy as np</pre><pre># Define the neural network approximator for y(x)<br>class ODE_Net(nn.Module):<br>    def __init__(self, hidden_units=20):<br>        super(ODE_Net, self).__init__()<br>        self.layer1 = nn.Linear(1, hidden_units)<br>        self.layer2 = nn.Linear(hidden_units, hidden_units)<br>        self.layer3 = nn.Linear(hidden_units, 1)<br>        self.activation = nn.Tanh()<br>        <br>    def forward(self, x):<br>        out = self.activation(self.layer1(x))<br>        out = self.activation(self.layer2(out))<br>        out = self.layer3(out)<br>        return out</pre><pre>def residual(model, x):<br>    &quot;&quot;&quot;<br>    Compute the ODE residual:<br>        y&#39;&#39;(x) - 3 = 0.<br>    &quot;&quot;&quot;<br>    # Enable gradients for x<br>    x.requires_grad_(True)<br>    y = model(x)<br>    <br>    # Compute first derivative: y&#39;(x)<br>    dydx = torch.autograd.grad(<br>        y, x,<br>        grad_outputs=torch.ones_like(y),<br>        create_graph=True<br>    )[0]<br>    <br>    # Compute second derivative: y&#39;&#39;(x)<br>    d2ydx2 = torch.autograd.grad(<br>        dydx, x,<br>        grad_outputs=torch.ones_like(dydx),<br>        create_graph=True<br>    )[0]<br>    <br>    # Compute the residual of the ODE: y&#39;&#39;(x) - 3<br>    res = d2ydx2 - 3.0<br>    return res</pre><pre>def boundary_loss(model):<br>    &quot;&quot;&quot;<br>    Compute the loss associated with the boundary conditions:<br>    y(0)=1 and y(2)=5.<br>    &quot;&quot;&quot;<br>    # Boundary condition at x=0: y(0)=1<br>    x0 = torch.tensor([[0.0]], device=device, requires_grad=True)<br>    y0 = model(x0)<br>    loss_bc0 = (y0 - 1.0)**2<br>    <br>    # Boundary condition at x=2: y(2)=5<br>    x2 = torch.tensor([[2.0]], device=device, requires_grad=True)<br>    y2 = model(x2)<br>    loss_bc2 = (y2 - 5.0)**2<br>    <br>    return loss_bc0 + loss_bc2</pre><pre>  # Initialize the model and optimizer<br>  model = ODE_Net(hidden_units=20).to(device)<br>  optimizer = optim.Adam(model.parameters(), lr=1e-3)<br>  num_epochs = 5000<br>  <br>  # Generate interior points in the domain [0,2]<br>  N_interior = 50<br>  x_interior = 2 * torch.rand(N_interior, 1, device=device)  # uniformly distributed in [0,2]<br><br>  # Training loop<br>  for epoch in range(num_epochs):<br>      model.train()<br>      optimizer.zero_grad()<br>      <br>      # Compute the residual loss at interior points<br>      r_interior = residual(model, x_interior)<br>      loss_res = torch.mean(r_interior**2)<br>      <br>      # Compute the boundary condition loss<br>      loss_bc = boundary_loss(model)<br>      <br>      # Total loss is the sum of the residual and boundary losses<br>      loss = loss_res + loss_bc<br>      loss.backward()<br>      optimizer.step()<br>      <br>      if epoch % 500 == 0:<br>          print(f&quot;Epoch {epoch}, Loss: {loss.item():.6e}&quot;)<br>  <br>  # Evaluate and compare the solution<br>  model.eval()<br>  x_test = torch.linspace(0, 2, 100, device=device).unsqueeze(1)<br>  y_pred = model(x_test).detach().cpu().numpy().flatten()<br>  x_test_np = x_test.cpu().numpy().flatten()</pre><pre>  # Analytical solution: y(x) = (3/2)x^2 - x + 1<br>  y_true = 1.5 * x_test_np**2 - x_test_np + 1<br>    <br>  plt.figure(figsize=(8, 4))<br>  plt.plot(x_test_np, y_pred, label=&quot;PINN Solution&quot;)<br>  plt.plot(x_test_np, y_true, &#39;--&#39;, label=&quot;Analytical Solution&quot;)<br>  plt.xlabel(&quot;x&quot;)<br>  plt.ylabel(&quot;y(x)&quot;)<br>  plt.legend()<br>  plt.title(&quot;ODE: y&#39;&#39;(x) - 3 = 0 with y(0)=1, y(2)=5&quot;)<br>  plt.show()</pre><p>In just 2.6 seconds it produces the following results:</p><pre>Epoch 0, Loss: 3.222174e+01<br>Epoch 500, Loss: 1.378794e-01<br>Epoch 1000, Loss: 5.264541e-03<br>Epoch 1500, Loss: 3.903809e-03<br>Epoch 2000, Loss: 3.040434e-03<br>Epoch 2500, Loss: 2.319159e-03<br>Epoch 3000, Loss: 1.656389e-03<br>Epoch 3500, Loss: 9.695904e-04<br>Epoch 4000, Loss: 4.545122e-04<br>Epoch 4500, Loss: 2.485181e-04</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*ly5oquIWLZw5f3lT65Qd_w.png" /></figure><p>In the following articles we will try to use this method applied to pricing options. Stay updated! :)</p><p>Francesco</p><h4>APPENDIX: Solving a more complex ODE with PINN</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/0*830J0B4nwcFoDx6U" /></figure><pre>class ODE_Net(nn.Module):<br>    def __init__(self, hidden_units=20):<br>        super(ODE_Net, self).__init__()<br>        self.layer1 = nn.Linear(1, hidden_units)<br>        self.layer2 = nn.Linear(hidden_units, hidden_units)<br>        self.layer3 = nn.Linear(hidden_units, hidden_units)<br>        self.layer4 = nn.Linear(hidden_units, 1)<br>        self.activation = nn.Tanh()<br><br>    def forward(self, x):<br>        out = self.activation(self.layer1(x))<br>        out = self.activation(self.layer2(out))<br>        out = self.activation(self.layer3(out))<br>        out = self.layer4(out)<br>        return out<br><br>def residual(model, x):<br>    x.requires_grad_(True)<br>    y = model(x)<br>    y_x = torch.autograd.grad(y, x, grad_outputs=torch.ones_like(y),<br>                                create_graph=True)[0]<br>    y_xx = torch.autograd.grad(y_x, x, grad_outputs=torch.ones_like(y_x),<br>                                 create_graph=True)[0]<br>    y_xxx = torch.autograd.grad(y_xx, x, grad_outputs=torch.ones_like(y_xx),<br>                                  create_graph=True)[0]<br>    y_xxxx = torch.autograd.grad(y_xxx, x, grad_outputs=torch.ones_like(y_xxx),<br>                                   create_graph=True)[0]    <br>    res = y_xxxx - 2*y_xxx + y_xx<br>    return res<br><br>def boundary_loss(model):<br>    x0 = torch.tensor([[0.0]], device=device, requires_grad=True)<br>    y0 = model(x0)<br>    <br>    y0_x = torch.autograd.grad(y0, x0, grad_outputs=torch.ones_like(y0),<br>                                 create_graph=True)[0]<br>    y0_xx = torch.autograd.grad(y0_x, x0, grad_outputs=torch.ones_like(y0_x),<br>                                  create_graph=True)[0]<br>    y0_xxx = torch.autograd.grad(y0_xx, x0, grad_outputs=torch.ones_like(y0_xx),<br>                                   create_graph=True)[0]<br>    <br>    bc1 = y0 - 1.0      # y(0) = 1<br>    bc2 = y0_x - 0.0    # y&#39;(0) = 0<br>    bc3 = y0_xx - (-1.0)  # y&#39;&#39;(0) = -1  -&gt; y0_xx + 1 = 0<br>    bc4 = y0_xxx - 2.0  # y&#39;&#39;&#39;(0) = 2<br>    <br>    loss_bc = bc1**2 + bc2**2 + bc3**2 + bc4**2<br>    return loss_bc<br><br>def main():<br>    model = ODE_Net(hidden_units=20).to(device)<br>    optimizer = optim.Adam(model.parameters(), lr=1e-3)<br>    num_epochs = 10000<br>    <br>    N_interior = 50<br>    x_interior = torch.rand(N_interior, 1, device=device)<br>    <br>    for epoch in range(num_epochs):<br>        model.train()<br>        optimizer.zero_grad()<br>        <br>        r_interior = residual(model, x_interior)<br>        loss_res = torch.mean(r_interior**2)<br>        <br>        loss_bc = boundary_loss(model)        <br>        loss = loss_res + loss_bc<br>        loss.backward()<br>        optimizer.step()<br>        <br>        if epoch % 500 == 0:<br>            print(f&quot;Epoch {epoch}, Loss: {loss.item():.6e}&quot;)<br>    <br>    model.eval()<br>    x_test = torch.linspace(0, 1, 100, device=device).unsqueeze(1)<br>    y_pred = model(x_test).detach().cpu().numpy().flatten()<br>    x_test_np = x_test.cpu().numpy().flatten()<br>    <br>    # Analytical solution: y(x) = 8 + 4x - 7e^x + 3xe^x<br>    y_true = 8 + 4*x_test_np - 7*np.exp(x_test_np) + 3*x_test_np*np.exp(x_test_np)<br>    <br>    plt.figure(figsize=(8,4))<br>    plt.plot(x_test_np, y_pred, label=&quot;Solution using PINN&quot;)<br>    plt.plot(x_test_np, y_true, &#39;--&#39;, label=&quot;Analytical solution&quot;)<br>    plt.xlabel(&quot;x&quot;)<br>    plt.ylabel(&quot;y(x)&quot;)<br>    plt.legend()<br>    plt.show()<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><pre>Epoch 0, Loss: 6.779857e+00<br>Epoch 500, Loss: 2.092192e-01<br>Epoch 1000, Loss: 4.828146e-02<br>Epoch 1500, Loss: 3.233620e-02<br>Epoch 2000, Loss: 3.518355e-04<br>Epoch 2500, Loss: 2.392017e-04<br>Epoch 3000, Loss: 1.745588e-04<br>Epoch 3500, Loss: 1.332138e-04<br>Epoch 4000, Loss: 1.039377e-04<br>Epoch 4500, Loss: 3.754102e-03<br>Epoch 5000, Loss: 7.414911e-05<br>Epoch 5500, Loss: 5.272599e-05<br>Epoch 6000, Loss: 4.189969e-05<br>Epoch 6500, Loss: 1.759992e-03<br>Epoch 7000, Loss: 1.593289e-04<br>Epoch 7500, Loss: 2.400937e-05<br>Epoch 8000, Loss: 8.885263e-03<br>Epoch 8500, Loss: 6.434955e-05<br>Epoch 9000, Loss: 1.761451e-05<br>Epoch 9500, Loss: 1.477061e-05</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*_h6wvDgqft87-fVAVC5EeA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LQU2EonXBV6Zmb6gMS8SHg.png" /><figcaption>Some Mountains for Beautiful Cover Image :)</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d55dab47cd7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pricing European Options using COS Method in Python under GBM]]></title>
            <link>https://finardfr.medium.com/pricing-european-options-using-cos-method-in-python-under-gbm-34d798c23d43?source=rss-dc313bcc2ae3------2</link>
            <guid isPermaLink="false">https://medium.com/p/34d798c23d43</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[fourier-series]]></category>
            <category><![CDATA[cos-method]]></category>
            <category><![CDATA[pricing-strategy]]></category>
            <category><![CDATA[options]]></category>
            <dc:creator><![CDATA[Bremphis]]></dc:creator>
            <pubDate>Mon, 09 Oct 2023 14:26:28 GMT</pubDate>
            <atom:updated>2025-03-28T14:36:44.704Z</atom:updated>
            <content:encoded><![CDATA[<p>Today, I’m going to propose an alternative method to price a European Option based on the famous COS Method proposed for the first time by Fang and Oosterlee in 2008.</p><p>The basic idea besides this method is to replace the risk-neutral probability density (RND) function with its Fourier-cosine series expansion since the coefficients can be derived in an analytical way and depend on the so-called characteristic function (CF).</p><p>The COS method is very useful as it is able to price a vector of strike prices at a relatively low computational cost.</p><pre>import numpy as np<br>from scipy.stats import norm<br>from scipy.special import erf<br>import matplotlib.pylab as plt</pre><p>Let us suppose we want to price European Call Options with the following characteristics:</p><ol><li>Spot Price = 100 and the log-price S_t follows a Geometric Brownian motion, i.e., the asset dynamic is described by the following process S_t = mu*S_t*dt + sigma*S_t*dW_t (where W_t is Wiener Process). Moreover, mu and sigma are set as constants as in B&amp;S framework.</li><li>Strike Prices K= [50,80,100,120,150]. We want to directly price a Deep-OTM, OTM, ATM, ITM and Deep-ITM options.</li><li>We set the other options’ parameters as follow: the risk free r=0.1, the dividend yield q=0, the maturity of the options tau=0.1, and the realised volatility sigma=0.25</li><li>The evaluation of the options’ values is done on a truncated interval [a,b] of the log(Price/K). The value of a and b are defined by a combination of a certain constant L (in the paper set as L=10) and the first two cumulants of log-Price distribution. Since the log-Price is normally distributed the first and second cumulants coincide with the first and the second moment, i.e., Cum1 = (mu-0.5*sigma²)dt and Cum2=sigma²*dt. For other models different from the GBM, also the fourth cumulant is take into account, for our purpose it is 0 (Cum4 = 0)</li><li>Since COS method is based on a numerical approximation we need a suitable N. We will see how the option’s value converges to its reference value as N. Now, set N=32</li></ol><p>Since we are dealing with risk-neutral evaluation, we need to transform the mu such that the process is a martingale under the risk neutral measure, i.e., mu = (r-q) — 0.5*sigma².</p><pre># Option Parameters<br>S0 = 100<br>r = 0.1<br>q = 0.0<br>dt = 0.1<br>sigma = 0.25<br>K = [50.0,80.0, 100.0, 120.0,150.0]<br><br>mu = (r-q) - 0.5*sigma**2<br><br>cum1 = (mu - 0.5*sigma**2)*dt<br>cum2 = sigma**2 * dt<br>cum4 = 0<br><br>L = 10<br>a = cum1 - L * (np.sqrt(cum2 + np.sqrt(cum4)))<br>b = cum1 + L * (np.sqrt(cum2 + np.sqrt(cum4)))<br>N = 32</pre><p>As I already mentioned, the model is the same one on which Black and Scholes have elaborated the closed formula for the European Option. Thus, we will use the Black and Scholes values as the references.</p><pre>def StdNormCdf(z):<br>    phi = 0.5 * (1 + erf(z/np.sqrt(2)))<br>    return phi<br><br># Black Scholes Model Vectorised<br>def BlackScholes_Vec(S, K, r, q, dt, sigma, type):<br>    S = S * np.exp(-q * dt)<br>    d1 = np.divide((np.log(np.divide(S, K)) + (r + 1/2 * np.power(sigma, 2)) * dt), (sigma * np.sqrt(dt)))<br>    d2 = d1 - sigma * np.sqrt(dt)<br>    call  = np.multiply(S, StdNormCdf(d1)) - np.multiply(np.multiply(K, np.exp(-r * dt)), StdNormCdf(d2))<br>    put  = call + np.multiply(K, np.exp(-r * dt)) - S<br>    if type == &#39;call&#39;:<br>        return call<br>    elif type == &#39;put&#39;: <br>        return put<br><br>BlackScholes_Vec(S0, K, r, q, dt, sigma, &#39;call&#39;)</pre><pre>OUTPUT: [5.04975083e+01 2.07992263e+01 3.65996845e+00 4.45778141e-02<br> 5.08421755e-07]</pre><p>The COS method for European Option Pricing is based on tons of analytical formula. For their derivation, I suggest you refer to Fang (2008). The formula needed to obtain the value of the option is the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qUMP_SQkeKuH6W-FM2OAZg.png" /></figure><ol><li>U_k is the cosine-series expansion. It is defined as follow:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*crvPpr1fQGtqF5bIzts3Ww.png" /></figure><p>where chi_k and psi_k are closed formula developed in various terms in sine and cosine.</p><p>2. phi of levy is the characteristic function (CF). It depends on the underlying model assumption, in our case the GBM. It is defined as follow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*EsS7Ttoae-HALgGCHXj35g.png" /></figure><p>The following sections report the code for the evaluation of European Option using the COS method:</p><pre># Definition of Chi(c,d) [Equation 22 Fang(2008)]<br>def CHI(k, a, b, c, d):<br>    bma = b-a<br>    uu  = k * np.pi/bma<br>    chi = np.multiply(np.divide(1, (1 + np.power(uu,2))), (np.cos(uu * (d-a)) * np.exp(d) - np.cos(uu * (c-a)) * np.exp(c) + np.multiply(uu,np.sin(uu * (d-a))) * np.exp(d)-np.multiply(uu,np.sin(uu * (c-a))) * np.exp(c)))<br>    return chi<br><br># Defintion of Psi (c,d) [Equation 23 Fang(2008)]<br>def PSI(k, a, b, c, d):<br>    bma    = b-a<br>    uu     = k * np.pi/bma<br>    uu[0]  = 1<br>    psi    = np.divide(1,uu) * ( np.sin(uu * (d-a)) - np.sin(uu * (c-a)) )<br>    psi[0] = d-c<br>    return psi<br><br># Defintion of U_k [Equation 29 Fang(2008)]<br>def UK(k,a,b,type):<br>    bma = b-a<br>    if type == &#39;put&#39;: <br>        UK  = 2 / bma * (-CHI(k,a,b,a,0) + PSI(k,a,b,a,0) )<br>    elif type == &#39;call&#39;:<br>        Uk = 2 / bma * (CHI(k,a,b,0,b) - PSI(k,a,b,0,b))<br>    return Uk </pre><pre># CF for a GBM<br>def charFuncBSM(s,r,q,sigma,T):<br>    phi = np.exp(((r-q) - 0.5 * np.power(sigma,2)) * 1j * np.multiply(T,s) - 0.5 * np.power(sigma,2) * T * np.power(s,2))<br>    return phi</pre><pre># Definition of Option Value [Equation 30 Fang(2008)]<br>def OptionValueCOS1_Vec(S0,K,r,q,dt,sigma,N,a,b,type): <br>    bma = b-a<br>    k  = np.arange(N+1)<br>    u  = k * np.pi/(b-a)<br>    V_COS = np.zeros((np.size(K)))<br>    CFBS = charFuncBSM(u,r,q,sigma,dt)<br>    for m in range(0,np.size(K)):<br>        x  = np.log(S0/K[m])<br>        Term = np.exp(1j * k * np.pi * (x-a)/bma)<br>        Fk = np.real(np.multiply(CFBS, Term))<br>        Fk[0]=0.5 * Fk[0] <br>        V_COS[m] = K[m] * np.sum(np.multiply(Fk,UK(k,a,b,type))) * np.exp(-r*dt)<br>    return V_COS</pre><p>Now, we are ready to test our code and compare the results with the reference value obtained by Black and Scholes closed formula.</p><pre>print(&#39;The values of the option with strike &#39;,K, &#39;are&#39;, OptionValueCOS1_Vec(S0,K,r,q,dt,sigma,N,a,b,&#39;call&#39;), <br>      &#39;\nThe Reference Values of BS are: &#39;, BlackScholes_Vec(S0, K, r, q, dt, sigma, &#39;call&#39;), <br>      &#39;\nThe abs errors are: &#39;, abs(OptionValueCOS1_Vec(S0,K,r,q,dt,sigma,N,a,b,&#39;call&#39;) - BlackScholes_Vec(S0, K, r, q, dt, sigma, &#39;call&#39;)))</pre><pre>OUTPUT: The values of the option with strike  [50.0, 80.0, 100.0, 120.0, 150.0] <br>are [4.95102782e+01 2.07992263e+01 3.65996845e+00 4.45778141e-02 5.08421767e-07] <br>The Reference Values of BS are:  [5.04975083e+01 2.07992263e+01 3.65996845e+00 4.45778141e-02<br> 5.08421755e-07] <br>The abs errors are:  [9.87230107e-01 1.78701498e-12 2.39808173e-14 5.16531262e-14<br> 1.21246325e-14]</pre><p>As you can observe, N=32 is sufficiently large in order to obtain precise results for our options’ values. However, I decided to simply conduct an analysis of the convergence as N increases for a fixed strike price (K=100). The orange line represents the BS value whereas the blue line is the value using COS method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*gmhNmXW5nl-UEyj4B3OQ4g.png" /><figcaption>Analysis of convergence</figcaption></figure><p>Finally, if we want to recovery the risk-neutral density, the following formula is recovered by Fang(2008):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*nZzC5KM9mAkXHklNwavZSQ.png" /></figure><p>with F_ks equal to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*P6I5kgDbHUIHEj0iSkNsPg.png" /></figure><p>The following code implements and displays the risk-neutral density for the log-price, changing maturity to 0.1 and keeping K=100:</p><pre>def FK(k,a,b,r,q,sigma,T): <br>    bma = b-a <br>    FK = 2/bma * np.real(charFuncBSM(k*np.pi/bma,r,q,sigma,T) * np.exp(-1j * k * a * np.pi / bma ))<br>    return FK<br><br>def Density(S0,K,a,b,r,q,sigma,T,N): <br>    x = np.log(S0/K)<br>    bma = b-a<br>    sum = 0.5 * np.cos(0) * FK(0,a,b,r,q,sigma,T)<br>    for k in range(1,N):<br>        sum += np.cos(k * np.pi * (x-a)/bma) * FK(k,a,b,r,q,sigma,T)<br>    return sum</pre><pre>dt = 0.1<br>mu = (r-q)-0.5*sigma**2<br>S0 = np.arange(40,200,1)<br>K = 100<br>Dens = np.zeros(np.size(S0))<br>target = np.zeros(np.size(S0))<br>for i in range(0,len(S0)):<br>    Dens[i] = Density(S0[i],K,a,b,r,q,sigma,dt,256)<br>    target[i] = norm.pdf(np.log(S0[i]/K), loc=mu*dt, scale=sigma*np.sqrt(dt))<br><br>axis = np.log(S0/K)<br><br>plt.plot(axis,Dens, color=&#39;blue&#39;, linewidth=3  )<br>plt.plot(axis,target, color=&#39;red&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*7auzm4S3DduVmxBWVWfUVQ.png" /><figcaption>RND for the log-Price</figcaption></figure><p>This concludes our article. More difficult models can be involved, e.g. Variance Gamma or CGMY. The only thing to care about is the Characteristic Function that changes among different models Finally, a new alternative approach using COS method will be proposed, without using any underlying model assumption: the so-called iCOS or Implied COS Method, proposed by Evgenii in 2023. But this is another story.</p><p>Have a good day, Francesco.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bEhTKFtZDn-M9BEUiZoDBA.png" /><figcaption>Some Mountains for Beautiful Image Cover</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34d798c23d43" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>