I am trying to create a script to be able to fit Kumaraswamy-Laplace distribution, As defined in this paper, 1 Inspiring from these posts, 2 3 4 To replicate market returns fitting like in this study 5 The fitting always end up with NaN error somewhere. With the following attempt: import numpy as np import pandas as pd import scipy.stats as st from scipy.special import beta class kl(st.rv_continuous): def _pdf(self, x, mu, sigma, p, q): v = ( x - mu ) / sigma #I tried two ways of defining of the function #y = .5 + .5 * np.sign( v ) * ( 1 - np.exp( - np.abs( v ) ) ) #fx = p * q *.5 / sigma * np.exp( - np.abs( v ) ) * y ** ( p - 1 ) * ( 1 - y ** p ) ** ( q - 1 ) fx = np.where( v < 0 , p * q * 2. **(-p) * np.exp( p * v ) * (1. - 2. ** ( - p ) * np.exp( p * v)) **(q - 1.), .5 * p * q * np.exp (-v) * (1.-.5*np.exp(-v))**(p-1.) * (1.-(1.-.5*np.exp(-v))**p)**(q-1.) ) return fx def _argcheck(self, mu, sigma, p, q): s = sigma > 0 p_bool = p > 0 q_bool = q > 0 all_bool = s & p_bool & q_bool return all_bool It seems that I always end up with the error ValueError: The function value at x=nan is NaN; solver cannot continue. when attempting to fit the distribution. Even though, plotting it on given parameters looks correct. I suppose it comes from an overflow, but I am not sure, and I don't know how to solve it! Could someone please provide some understanding of the fitting and numerical analysis requirements I am missing? Note: Fitting a Laplace works for the same dataset since it is already defined in the library of scipy. The code to fit: initial_guess = [np.mean(sample_data), np.std(sample_data), 1.0, 1.0] # [mu, sigma, p, q] estimated_params = my_sgt_distribution.fit(sample_data, *initial_guess) And to plot: import matplotlib.pyplot as plt import numpy as np # Explicitly given parameters (replace with your desired values) mu = 0 sigma = 1 p = 0.6 q = 0.7 # Create an instance of custom distribution my_kl_distribution = kl() # Generate x values for plotting x_values = np.linspace(-5, 5, 1000) # Calculate PDF and CDF values pdf_values = my_kl_distribution.pdf(x_values, mu, sigma, p, q) cdf_values = my_kl_distribution.cdf(x_values, mu, sigma, p, q) # Plot the PDF plt.figure(figsize=(10, 5)) plt.plot(x_values, pdf_values, label='PDF') plt.title('Probability Density Function (PDF) of Kumaraswamy Laplace Distribution') plt.xlabel('x') plt.ylabel('Density') plt.legend() plt.grid(True) plt.show() # Plot the CDF plt.figure(figsize=(10, 5)) plt.plot(x_values, cdf_values, label='CDF', color='orange') plt.title('Cumulative Distribution Function (CDF) of Kumaraswamy Laplace Distribution') plt.xlabel('x') plt.ylabel('Probability') plt.legend() plt.grid(True) plt.show() Continue reading...