The RISC-V softcore Rocket runs on smaller FPGA development board like the NEXYS A7 and supports instruction set version RV64GC. Even though these are 64 bit cores they are only running at 25MHz. Hence we are better off cross compiling QuantLib on the host system. As expected quantlib-benchmark results are really low, around 2.4 MFlops.

# Category: QuantLib

# Almost exact SABR Interpolation using Neural Networks and Gradient Boosted Trees

**Update 03-11-2019**: Added arbitrage free SABR calibration based on neural networks.

Very efficient approximations exist for the SABR model

like the original Hagan et. al. formula [1] or variants of it [2] but these analytic formulas are in general not arbitrage free. Solving the corresponding partial differential equation leads to an arbitrage free solution

but is computationally demanding. The basic idea here is to use a neural network or gradient boosted trees to interpolate (predict) the difference between the analytic approximation and the exact result from the partial differential equation for a large variate of model parameters.

First step is to reduce the number of dimensions of the parameter space by utilizing the scaling symmetry of the SABR model [3]

so that we can focus on the case without lose of generality

.

This in turns also limits the “natural” parameter space for which will be set to

.

Next on the list is to set-up an efficient PDE solver to prepare the training data. The QuantLib solver supports already the two standard error reduction techniques, namely adaptive grid refinement around important points and cell averaging around special points of the payoff. The latter one ensure a smooth second order convergence in spatial direction [4]. The Hundsdorfer-Viewer ADI scheme is also of second order in the time direction and additional Rannacher smoothing steps at the beginning will ensure a smooth convergence in the time direction as well [5]. Hence the Richardson extrapolation can be used to improve the convergence order of the overall algorithm. An example pricing for

is shown in the diagram below to demonstrate the efficiency of the Richardson extrapolation. The original grid size for scaling factor 1.0 is .

The training data was generated by a five dimensional quasi Monte-Carlo Sobol sequence for the parameter ranges

.

The strikes are equally distributed between the and quantile of the risk neutral density distribution w.r.t to the ATM volatility of the SABR model. The PDE solver will not only calculate the fair value for but for a range of spot values around . Using the scaling symmetry of the SABR model this can be utilized to calculate more prices with new and values for .

The training set includes 617K samples values. The network is trained to fit the difference between the correct SABR volatility from the solution of the partial differential equation and the Floc’h-Kennedy approximation. It does not need a large neural network to interpolate the parameter space, e.g. the following Tensorflow/Keras model definition with 46K parameters has been used in the examples below

model = Sequential() model.add(Dense(20, activation='linear', input_shape=(7, ))) model.add(Dense(100, activation='linear')) model.add(Dense(400, activation='sigmoid')) model.add(Dense(10, activation='tanh')) model.add(Dense(1, activation='sigmoid')) model.compile(loss='mae', optimizer='adam')

As always it is important for the predictive power of the neural network to normalize the input data e.g. by using sklearn.preprocessing.MinMaxScaler. The out-of-sample mean absolute error of the neural network is around 0.00025 in annualized volatility, far better than the Kennedy-Floc’h or Hagan et al approximation.

The diagram below shows the difference between the correct volatility and the different approximations using the parameter example from the previous post. One could also used gradient tree boosting algorithms like XGBoost or LightGBM. For example the models

xgb_model = xgb.XGBRegressor(nthread=-1, max_depth=50, n_estimators=100, eval_metric ="mae") gbm_model = lgb.train({'objective': 'mae', 'num_leaves': 500 } lgb.Dataset(train_X, train_Y), num_boost_round=2000, valid_sets=lgb_eval, early_stopping_rounds=20)

result in similar out-of-sample mean absolute errors of 0.00030 for XGBoost and 0.00035 for LightGBM. On the first glance the interpolation looks smooth as can be seen in the diagram below using the same SABR model parameters, but zooming into it exposes non differentiable points, which defeats the object of stable greeks.

The average run time for the different approximations is shown in the tabular below.

With this highly efficient pricing routines calibration of the full SABR model can be done in a fraction of a second. To test this approach several Heston parameter configurations have been used to calculated the implied volatility of 15 benchmark options for a single expiry. The full SABR model has been calibrated against these volatility sets with help of a standard Levenberg-Marquardt optimizer by either using the PDE pricer or the neural network pricer. As expected the neural network calibration routine has only taken 0.2 seconds but the PDE calibration has taken over half an hour on average.

[1] P. Hagan, D. Kumar, A. Lesnieski, D. Woodward: Managing Smile Risk.

[2] F. Le Floc’h, G. Kennedy: Explicit SABR Calibration through Simple Expansions.

[3] H. Park: Efficient valuation method for the SABR model.

[4] K. in’t Hout: Numerical Partial Differential Equations in Finance explained.

[5] K. in’t Hout, M. Wyns: Convergence of the Hundsdorfer–Verwer scheme for two-dimensional convection-diffusion equations with mixed derivative term

# Finite-Difference Solver for the SABR Model

Despite being based on a fairly simple stochastic differential equation

the corresponding partial differential equation

for the SABR model – derived using the variable transformation together with Ito’s lemma and the Feynman-Kac formula – is quite difficult to solve numerically. Part of the problem is the process of the underlying, which corresponds to a constant elasticity of variance (CEV) model if is zero. This model exhibits a variety of different behaviours depending on the value of and on the boundary conditions. The authors in [1] give a comprehensive overview on this topic. To limit the possible model zoo let’s define

and assume absorbing boundary conditions at if . First step for an implementation of a finite difference scheme is to find efficient limits for the discretization grid. These limits can e.g. be derived from the cumulative distribution function of the underlying process.

.

Please notice that the underlying in the first case appears in the non centrality parameter of the non central chi-squared distribution , hence the calculation of the inverse can only be carried out by a numerical root-finding algorithm. Sankaran’s approximation of the non central chi-squared distribution can be used to speed-up this method [2]. In the second case the inverse of the equation is

which can be computed using the boost library. In addition adaptive grid refinement around important points and cell averaging around special points of the payoff at maturity [3] improve the accuracy of the CEV finite difference scheme. is only a local martingale when or equivalent . In this case the call-put parity reads [1]

and acts as a litmus test for the implementation of the boundary conditions and the finite difference scheme.

The variance direction matches a Brownian motion, hence the discretization is straight forward. Operator splitting schemes like Craig-Sneyd or Hundsdorfer-Verwer [4] are tailor made to solve the two dimensional partial differential equation.

The finite difference solver can now be used to compare different approximations with the correct model behaviour and also to compare it with high accurate Monte-Carlo simulations [2]. The model configuration [5]

should act as a test bed. As can be seen in the diagram below the Monte-Carlo results are in line with the results from finite difference methods within very small error bars. The standard Hagan et al. formula as well as the Le Floc’h-Kennedy [6] log-normal formula deviate significantly from the correct implied volatilities.

The approximations are not arbitrage free. The probability densities for small strikes turn negative. Hagan’s formula exhibits this behaviour already for larger strikes than the Le Floc’h-Kennedy formula as can be seen in the following diagram. As expected the finite difference solution does not produce negative probabilities.

A note on the Floc’h-Kennedy approximation, the formula becomes numerically unstable around ATM strike levels, hence a second order Taylor expansion is used for moneyness

.

The following diagram shows the difference between second order Taylor expansion and the formula evaluated using IEEE-754 double precision.

The source code is part of the PR #589 and available here.

[1] D.R. Brecher, A.E. Lindsay: Results on the CEV Process, Past and Present.

[2] B. Chen, C.W. Oosterlee, H. Weide, Efficient unbiased simulation scheme for the SABR stochastic volatility model.

[3] K. in’t Hout: Numerical Partial Differential Equations in Finance explained.

[4] K. in’t Hout, S. Foulon: ADI Finite Difference Schemes for Option Pricing in the Heston Model with Correlation.

[5] P. Hagan, D. Kumar, A. Lesnieski, D. Woodward: Arbitrage free SABR.

[6] F. Le Floc’h, G. Kennedy: Explicit SABR Calibration through Simple Expansions.

# Compile QuantLib on an Android Mobile

Termux is an Android terminal emulator and Linux environment app which can be installed directly w/o rooting. It comes with a minimal Linux base system and additional packages can be installed afterwards. The following script compiles and runs QuantLib in a Termux session

pkg install clang autoconf automake libtool boost-dev nano git git clone https://github.com/lballabio/quantlib.git cd quantlib ./autogen.sh ./configure --disable-static CXXFLAGS='-O2' CXX='clang++' make ./test-suite/quantlib-test-suite

# Arbitrary Number of Stencil Points

The standard finite difference implementations of derivative pricing algorithms based on partial differential equations have a spatial order of convergence of two. Reason is that these implementations are using a three point central stencil for the first and second order derivatives. The three point stencil leads to a tridiagonal matrix. Such linear systems can be solved efficiently with help of the Thomas algorithm.

Higher order of spatial accuracy relies on stencils with more points. The corresponding linear systems can no longer be solved by the Thomas algorithm but by the BiCGStab iterative solver with the classical three point stencil as a very efficient preconditioner. The calculation algorithm for the coefficients of larger stencils on arbitrary grids is outlined in [1].

Before using higher order stencils one should first make sure, that the two standard error reduction techniques are in place, namely adaptive grid refinement around important points [2] and cell averaging around special points of the payoff at maturity or – equally effective for vanilla options – put the strike in the middle between two grid points. Let’s focus on the Black-Scholes-Merton PDE

after transforming it to the heat equation

to demonstrate the convergence improvements. The spatial pricing error is defined as the RMSE for a set of benchmark options. In this example the benchmark portfolio consists of OTM call or put options with strikes

.

The other parameters in this example are

.

The Crank-Nicolson scheme with “more than enough” time steps was used to integrate the PDE in time direction such that only the spatial error remains.

As can be seen in the diagram above the spatial order of convergence increases from second order to fourth order when moving from the standard three point to the five point stencil. On the other hand solving the resulting linear systems takes longer now. All in all only if the target RMSE is below , the five point stencil will be faster than the standard three point discretization.

The diagram below shoes the effective combination of a five point stencil and the Richardson extrapolation.

Diagrams are based on the test cases testHigerOrderBSOptionPricing and

testHigerOrderAndRichardsonExtrapolationg in the PR #483.

[1] B. Fornberg, [1988], Generation of Finite Difference Formulas on Arbitrarily Spaced Grids.

[2] Tavella, D. and C.Randall [2000], Pricing Financial Instruments The Finite Dierence Method, Wiley Series In Financial Engineering, John Wiley & Sons, New York

# Andreasen-Huge Volatility Interpolation

A few years ago Andreasen and Huge have introduced an efficient and arbitrage free volatility interpolation method [1] based on a one step finite difference implicit Euler scheme applied to a local volatility parametrization. Probably the most notable use case is the generation of a local volatility surface from a set of option quotes.

Starting point is Dupire’s forward equation for the prices of European call options at time with strike and maturity is given by

Define the normalized call price in terms of the discount factor , the forward price and the moneyness as

.

The Dupire forward equation for the normalized prices is then given by

.

Rewriting this equation in terms of amd yields

The normalized put prices are fulfilling the same equation, which can easily been shown by inserting the call-put parity into the equation above

.

The numerical stability of the original algorithm [1] can be enhanced for deep ITM options by calibrating to calls and puts instantaneously. Also the interpolation scheme has a significant impact on the stability. This topic has been discussed in [2][3]. Using concentrated meshes along the current spot level for the finite difference scheme is of advantage for the stability and accuracy of the algorithm.

In order to stabilize the calculation of the local volatility function

one should evaluate the first order derivative of w.r.t. time using the fact that the derivative of the inverse of the matrix is given by

As an example, the diagram below shows different calibrations of the Andreasen-Huge volatility interpolation to a SABR volatility skew at discrete strike sets

for the SABR parameter

The QuantLib implementation is part of the release 1.12.

[1] J. Andreasen, B. Huge, Volatility Interpolation

[2] F. Le Floc’h, Andreasen-Huge interpolation – Don’t stay flat

[3] J. Healy, A spline to fill the gaps with Andreasen-Huge one-step method

# Adaptive SOR Method for Implied Volatility Calculation

In a recent blog contribution Fabien Le Floc’h [1] suggests to combine the adaptive successive over-relexation method [2] with an improved explicit approximate implied volatility formula [3] to calculate the initial guess. The implementation of both algorithms is straight forward.

A large set of OTM and ITM options together with different displacement factors has been identified to serve as a benchmark portfolio to compare the performance with the original QuantLib implementation. As can be seen in the diagram below the new method is – depending on the accuracy – two to three times faster than the current QuantLib implementation.

The implementation is available here, the diagram above is derived from the test case testImpliedVolAdaptiveSuccessiveOverRelaxation in the class BlackFormulaTest.

[1] Le Floc_h, F (2017) Implied Volatility from Black Scholes Price

[2] Li, M. (2008) An Adaptive Successive Over-relaxation Method for Computing the Black-Scholes Implied Volatility

[3] J. Gatheral, I. Matic, R. Radoicic, D. Stefanica (2017), Tighter Bounds for Implied Volatility