spd_trading package

Submodules

spd_trading.historical_density module

class spd_trading.historical_density.Calculator(data, tau_day, date, S0, garch_data_folder, n_fits, cutoff=0.5, overwrite_model=True, overwrite_simulations=True, target='price', window_length=365, h=0.15, simulations=5000)[source]

Bases: spd_trading.historical_density.GARCH

The Calculator Class for the Historical Density.

The Historical Density is estimated via a Monte Carlo simulation, where the sample paths are simulated by a GARCH(1,1) model.

Parameters
  • data (np.array) – Timeseries of the underlying.

  • tau_day (int) – Time to maturity in days, also: horizon.

  • date (str) – Evaluation date, the last day of timeseries.

  • S0 (float) – Price of underlying at \(t=0\), which is on evaluation date

  • garch_data_folder (str) – Path to folder where to save/load GARCH model.

  • n_fits (int) – How many sliding windows the data is devided into.

  • overwrite_model (bool, optional) – Whether to overwrite the GARCH model. Defaults to True.

  • overwrite_simulations (bool, optional) – Whether to overwrite the simulations. Defaults to True.

  • target (str, optional) – Column name of the timeseries. Defaults to “price”.

  • window_length (int, optional) – Length of each sliding window in GARCH fit. Defaults to 365.

  • h (float, optional) – Bandwidth for Kernel Density Estimation. Defaults to 0.15.

  • simulations (int, optional) – How many paths to simulate. Defaults to 5000.

log_returns

The daily log returns of the price index timeseries. Timeseries for GARCH model.

Type

np.array

GARCH

Instance of class.

Type

spd_trading.historical_density.GARCH

ST

Simulated prices of underlying, according to GARCH model.

Type

np.array

q_M

Density in Moneyness domain M=S0/ST.

Type

np.array

get_hd(variate_GARCH_parameters=True)[source]

Estimates the Historical Density via a GARCH(1,1) model and Monte Carlo simulation.

Parameters

variate_GARCH_parameters (bool, optional) – Whether the GARCH parameters should be variated slightly during the Monte Carlo Simulation. Defaults to True.

class spd_trading.historical_density.GARCH(data, data_name, n_fits, garch_data_folder, overwrite_model=True, window_length=365, z_h=0.1)[source]

Bases: object

The GARCH model class, which fits a model to the historical data and simulates sample paths based on that model

Parameters
  • data (np.array) – The timeseries that should be fitted (usually log returns)

  • data_name (str) – Name of the dataset, will be used in filename.

  • n_fits (int) – How many sliding windows the data is devided into.

  • garch_data_folder (str) – Path to folder where to save/load GARCH model.

  • overwrite_model (bool, optional) – Whether to overwrite the GARCH model. Defaults to True.

  • window_length (int, optional) – Length of each sliding window. Defaults to 365.

  • z_h (float, optional) – Bandwidth factor for Kernel Density Estimation. Defaults to 0.1.

parameters

The parameters \(\Theta = (\omega, \alpha, \beta)\) of GARCH model.

Type

np.array

z_dens

The distribution of innovations \(\mathcal{Z} = \left\{z_0, z_1, ...., z_T \right\}\)

Type

np.array

simulated_log_returns

simulated log returns at horizon (also: maturity) \(\tau\)

Type

np.array

simulated_tau_mu

product of \(\tau \cdot \mu\) for each simulation

Type

np.array

fit()[source]

Fits a GARCH(1,1) model to the data. This

For n_fits sliding windows, the parameters \(\Theta = (\omega, \alpha, \beta)\) and the distribution of innovations \(\mathcal{Z} = \left\{z_0, z_1, ...., z_T \right\}\) are estimated. The results are saved in self.

simulate_paths(horizon, simulations, variate_GARCH_parameters=True)[source]

Monte Carlo Simulation - Simulate paths using the fitted GARCH(1,1) model.

Parameters
  • horizon (int) – How many steps of paths to simulate

  • variate (bool, optional) – Whether GARCH parameters should be variated. Defaults to True.

Returns

simulated_log_returns, simulated_tau_mu

Return type

tuple

class spd_trading.historical_density.Plot(x=0.5)[source]

Bases: object

The Plotting class for Historical Density.

Parameters

x (float, optional) – The Moneyness interval for the plots. \(M = [1-x, 1+x]\). Defaults to 0.5.

density(HD)[source]

Visualization of the Historical Density.

Parameters

HD (spd_trading.historical_density.Calculator) – Instance of class spd_trading.historical_density.Calculator.

Returns

Matplotlib figure.

Return type

Figure

spd_trading.kernel module

class spd_trading.kernel.Calculator(tau_day, date, RND, HD, similarity_threshold=0, cut_tail_percent=0.02)[source]

Bases: object

The Calculator Class for the Pricing Kernel.

Stores all relevant parameters for traceability and reproducability. \(K=\frac{rnd}{hd}\)

Parameters
  • tau_day (int) – Time to maturity in days (tau * 365)

  • date (str) – Date of the option table.

  • RND (spd_trading.risk_neutral_density.Calculator) – Trained instance of class spd_trading.risk_neutral_density.Calculator.

  • HD (spd_trading.historical_density.Calculator) – Trained instance of class spd_trading.historical_density.Calculator.

  • similarity_threshold (float, optional) – Creates similarity area around 1. If densities are too similar, the Kernel is K=1. Defaults to 0.15.

  • cut_tail_percent (float, optional) – Percent threshold of when to cut off tails. Defaults to 0.02.

rnd_curve

Risk Neutral Density

Type

np.array

hd_curve

Historical Density

Type

np.array

kernel

Kernel

Type

np.array

trading_intervals

M-intervals for which to buy and sell options according to kernel

Type

dict of list of tuples

calc_kernel()[source]

Calculates the Kernel.

First, interpolates rnd and hd to the same M-values. Then removes tiny tails.
Finally calculates the Kernel: \(K = \frac{rnd}{hd}\).
calc_trading_intervals()[source]

Determines the Moneyness intervalls for which to buy and sell options according to the kernel.

class spd_trading.kernel.Plot(x=0.5)[source]

Bases: object

The Plotting class for Kernel.

Parameters

x (float, optional) – The Moneyness interval for the plots. \(M = [1-x, 1+x]\). Defaults to 0.5.

kernelplot(Kernel)[source]

Visualization of computation of the Kernel and its derived trading intervals.

Left: Risk Neutral Density (red line) and Historical Density (blue line) on evaluation day, option data is represented as dots (red: calls, blue: puts).
Middle: Construction of Trading Strategy based on the Pricing Kernel. The Pricing Kernel (black line) indicates whether options should be bought (red interval) or sold (blue interval). In grey the similarity area around \(K=1\).
Parameters

Kernel (spd_trading.kernel.Calculator) – Instance of class spd_trading.kernel.Calculator.

Returns

Matplotlib figure.

Return type

Figure

spd_trading.risk_neutral_density module

class spd_trading.risk_neutral_density.Calculator(data, tau_day, date, sampling='random', n_sections=15, loss='MSE', kernel='gaussian', h_m=None, h_m2=None, h_k=None, r=0)[source]

Bases: object

The Calculator Class for the Risk Neutral Density.

Stores all relevant parameters for traceability and reproducability. - Rookleys method - Local polynomial estimation - Density transformation

Parameters
  • data (pd.DataFrame) – The option table as a pd.DataFrame. Must include columns ["M", "iv", "S", "P", "K", "option", "tau"]

  • tau_day (int) – Time to maturity in days (tau * 365)

  • date (str) – Date of the option table.

  • sampling (str, optional) – Whether the dataset should be partitioned “random” or as “slicing”. Defaults to “random”.

  • n_sections (int, optional) – Amount of sections to devide the dataset in cross validation (k-folds) for bandwidth selection localpoly.LocalPolynomialRegressionCV.bandwdith_cv. Defaults to 15.

  • loss (str, optional) – Loss function for optimization. Defaults to “MSE”.

  • kernel (str, optional) – Name of the kernel. Defaults to “gaussian”.

  • h_m (float) – bandwidth for local polynomial estimation for iv-smile-fit. Defaults to None.

  • h_m2 (float, optional) – bandwidth for local polynomial estimation for q_M fit. Defaults to None.

  • h_k (float, optional) – bandwidth for local polynomial estimation for q_K fit. Defaults to None.

  • r (float, optional) – risk free interest rate. Defaults to 0.

tau

Time to maturity in years.

Type

float

q_M

Risk Neutral Density in Moneyness domain. Transformed result of Rookley’s Method.

Type

np.array

q_K

Risk Neutral Density in Strike Price domain. Standard result of Rookley’s Method.

Type

np.array

smile

Implied volatility fit “iv-smile”.

Type

np.array

first

First derivative of iv-smile.

Type

np.array

second

Second derivative of iv-smile.

Type

np.array

curve_fit(X, y, h=None)[source]

Uses Local Polynomial Estimation to create a fit and estimate its first and second derivative.

Requires package localpoly for the fit. If no bandwidth h is given, first a Cross Validation for a range of bandwidths is performed. The final fit is performed with the optimal bandwidth (by MSE).

Parameters
  • X (np.array) – X-values of data that is to be fitted (explanatory variable)

  • y (np.array) – y-values of data that is to be fitted (observations)

  • h ([type], optional) – Bandwidth for local polynomial estimation. If not specified, h will be determined by Cross Validation. Defaults to None.

Returns

Results of fit:

{
    "parameters" : {
        "h": optimal bandwidth
        "bandwidths": list_of_bandwidths
        "MSE": means squared error for bandwidths
    },
    "fit" : {
        "X": prediction interval of fit
        "fit": fit
        "first": first derivative of fit
        "second": second derivative of fit
    }
}

Return type

dict

get_rnd()[source]

Pipeline that calculates the Risk Neutral Density using Rookley’s Method.

Tools used: Local Polynomial Smoothing and Density Transformation. The final result is saved in self.M, self.q_M

step 0 : fit iv-smile to iv-over-M option values
step 1 : calculate spd for every option-point “Rookley’s method”
step 2 : Rookley results (points in K-domain) - fit density curve
step 3 : transform density POINTS from K- to M-domain
step 4 : density points in M-domain - fit density curve
(All fits are obtained by local polynomial estimation)
class spd_trading.risk_neutral_density.Plot(x=0.5)[source]

Bases: object

The Plotting class for Risk Neutral Density.

Parameters

x (float, optional) – The Moneyness interval for the plots. \(M = [1-x, 1+x]\). Defaults to 0.5.

rookleyMethod(RND)[source]

Visualization of computation of RND.

Left: Option Data. Use Local Polynomial Estimation to fit \(V(M):=\sigma(M)\) curve to the implied volatility.
Middle left: fitted implied volatility and its derivatives (blue: \(V(M)\), orange: \(V'(M)\) and green: \(V''(M)\)), necessary for Rookley’s Method.
Middle right: RND from Rookley’s Method in strike price domain.
Right: RND from Rookley’s Method in moneyness domain (after Density Transformation from K- to M-domain).
Parameters

RND (spd_trading.risk_neutral_density.Calculator) – Instance of class spd_trading.risk_neutral_density.Calculator.

Returns

Matplotlib figure.

Return type

Figure

spd_trading.risk_neutral_density.create_bandwidth_range(X, num=10)[source]

Creates a range of bandwidths around the Silverman Bandwidth. Is used as a parameter grid for bandwidth optimization for smoothing algorithms.

Parameters
  • X (np.array) – X position of values

  • num (int, optional) – Length of grid. Defaults to 10.

Returns

Equal grid of bandwidths around Silverman bandwidth.

Return type

np.array

spd_trading.risk_neutral_density.rookley_method(M, S, K, o, o1, o2, r, tau)[source]

Uses Rookleys Method to calculate the Risk Neutral Density from an option table. The method can be found in the original paper. It calculates the second derivative of the option price by strike price (analytical solution) where some dimentionality reduction is used, that has to be resolved in the last step.

Parameters
  • M (float) – Moneyness = S / K

  • S (float) – Price of underlying

  • K (float) – Strike Price of option

  • o (float) – implied volatility (iv, might be value of smoothed iv surface at M)

  • o1 (float) – value of first derivative of iv surface at M

  • o2 (float) – value of second derivative of iv surface at M

  • r (float) – risk free interest rate

  • tau (float) – time until maturity (in years)

Returns

value of Risk Neutral Density at Strike Price K. (usually the result is projected to M, use Density Transformation)

Return type

float

Module contents