Get startedGet started for free

KDE of a loss distribution

Kernel density estimation (KDE) can fit distributions with 'fat tails', i.e. distributions with occasionally large deviations from the mean (such as the distribution of portfolio losses).

In Chapter 2 you learned about the Student's T distribution, which for low degrees of freedom can also capture this feature of portfolio losses.

You'll compare a Gaussian KDE with a T distribution, each fitted to provided portfolio losses from 2008 - 2009. You'll visualize the relative fits of each using a histogram. (Recall the T distribution uses fitted parameters params, while the gaussian_kde, being non-parametric, returns a function.)

The function gaussian_kde() is available, as is the t distribution, both from scipy.stats. Plots may be added to the provided axis object.

This exercise is part of the course

Quantitative Risk Management in Python

View Course

Exercise instructions

  • Fit a t distribution to portfolio losses.
  • Fit a Gaussian KDE to losses by using gaussian_kde().
  • Plot the probability density functions (PDFs) of both estimates against losses, using the axis object.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Generate a fitted T distribution over losses
params = t.____(losses)

# Generate a Gaussian kernal density estimate over losses
kde = ____(____)

# Add the PDFs of both estimates to a histogram, and display
loss_range = np.linspace(np.min(losses), np.max(losses), 1000)
axis.plot(loss_range, t.____(loss_range, *params), label = 'T distribution')
axis.____(loss_range, kde.pdf(____), label = 'Gaussian KDE')
plt.legend(); plt.show()
Edit and Run Code