QuantLib 之外,衍生品定价还能怎么选?DolphinDB Monte Carlo + PDE 工具实测 – DolphinDB

QuantLib 之外,衍生品定价还能怎么选?DolphinDB Monte Carlo + PDE 工具实测 – DolphinDB


It is not difficult to calculate a standard European option, but the difficulty lies in the “non-standard” products: Asian options require observing the day and historical fixing (Fixing), obstacles require judging whether the price has been touched, and stochastic volatility and multi-asset will also add state variables.

For common financial products, DolphinDB has provided dedicated pricing functions covering different asset classes, which can be valued by calling them. When it comes to non-standard derivatives, ready-made functions are often not enough. Developers need universal solving tools that can flexibly define models, adjust calculation conditions, and verify numerical results. For this purpose, DolphinDB Brand new onlineTwo types of universal pricing tools eliminate the need to write solvers from the ground up:

  1. Monte Carlo: simulates random paths, makes statistical valuations based on product return rules, and provides standard errors and confidence intervals;
  2. pdeSolver series of functions: solve one-dimensional and two-dimensional linear parabolic PDE, obtain the price curve or price surface on the grid, and output Greeks at the same time.

This article will combine typical derivatives cases to introduce the core interfaces and usage of the two types of tools, and demonstrate their calculation performance in different pricing scenarios through performance tests to help developers understand how to use DolphinDB to build flexible pricing models.

1. Monte Carlo: Flexible construction of path-dependent pricing models

For path-dependent derivatives such as Asian options and barrier options, option returns not only depend on the underlying price at expiration, but also on price changes during the duration. To complete pricing, developers need to simulate the random evolution path of the underlying asset, then calculate the income based on the product terms, and finally estimate the option price.

If the complete process is handwritten from the bottom every time, links such as random number generation, correlation conversion, batch calculation and statistical summary will need to be implemented repeatedly. In fact, the differences between different products often focus on two aspects:How the status of the underlying evolves, and how much is paid for the product under what conditions. The random path simulation and statistical estimation processes can be reused.

DolphinDB’s universal Monte Carlo tool is designed around this idea. Developers define state evolution and revenue logic through custom functions, and the simulation and statistical processes are unified and organized by tools.

core competencies

Monte Carlo pricing mainly involves three functions:

  • mcSimulate: simulates random processes and generates corresponding simulation paths.
  • monteCarlo: Combine custom state evolution functions, revenue functions and simulation configurations to complete the Monte Carlo pricing process.
  • mcEstimate: Statistical estimation of simulation results.

Depending on the purpose of use, two typical workflows can be adopted.

  • During the research and debugging phase, you can use mcSimulate to generate paths, and then complete the estimation through custom processing and mcEstimate. This method is convenient for checking simulation paths and intermediate results, but saving the complete path may take up more memory.
  • In business pricing scenarios, you can directly call monteCarlo, and the function will advance the simulation by batch and summarize the results, which is suitable for batch numerical estimation of fixed Payoff.

QuantLib 之外,衍生品定价还能怎么选?DolphinDB Monte Carlo + PDE 工具实测 – DolphinDB

All types of products can be expressed using the evolve and payoff functions. In this way, products such as European options, Asian options, barrier options, lookback options, and multi-asset options can all define their own model logic based on a reused simulation framework. For stochastic volatility models, state variables such as underlying price and volatility can also be included in the simulation.

Take Asian options as an example

Taking Asian options as an example, it is assumed that the price of the underlying asset follows geometric Brownian motion (GBM). Developers first pass evolve Functions define how asset prices change over time:

def gbmEvolve(t, state, dt, noise, p) {
    drift = (p["r"] - p["q"] - 0.5 * p["sigma"] * p["sigma"]) * dt
    return state * exp(drift + p["sigma"] * sqrt(dt) * noise)
}

Next, pass payoff Function defines how option returns are calculated based on simulated paths. The following example calculates the returns corresponding to both the arithmetic mean price and the geometric mean price:

def asianPayoff(paths, timeGrid, p) {
    n = rows(paths[0])
    m = size(paths) - 1
    prices = matrix(DOUBLE, n, m)
    for (i in 1..m) {
        prices[, i - 1] = paths[i][, 0]
    }
    arithmeticAverage = rowAvg(prices)
    geometricAverage = exp(rowAvg(log(prices)))
    T = timeGrid[size(timeGrid) - 1] - timeGrid[0]
    df = exp(-p["r"] * T)
    return df * matrix(max(arithmeticAverage - p["K"], 0.0),
                       max(geometricAverage - p["K"], 0.0))
}

After defining the state evolution function and revenue function, you can call monteCarlocombining the initial asset price, time grid, number of simulation paths and model parameters to complete the valuation:

res = monteCarlo(gbmEvolve, asianPayoff, 100.0,
    0..12 / 12.0, 100000, 1, p, opt)

In this example,gbmEvolve and asianPayoff It carries the developer’s customized model logic; the remaining parameters are used to specify the initial state, simulation time range, simulation scale and related configurations. The general Monte Carlo process organizes simulations and estimates and returns results such as price estimates and standard errors.

It can be seen that when product terms change, developers only need to adjust the evolve and payoff functions, and the path simulation and statistical estimation processes do not need to be rewritten.

2. pdeSolver: Get the entire price surface in one solution

For products such as European options, prices can be calculated directly through analytical formulas. However, for products with early exercise characteristics such as American options, the pricing problem will be more complicated: in addition to solving the pricing equation related to the underlying price and time, it is also necessary to consider the possibility of early exercise during the holding period.

The partial differential equation (PDE) method converts the pricing problem into a numerical solution: divide the underlying price and time into a grid, start from the income on the maturity date, and gradually work backwards to the current moment to calculate the theoretical price under different states. its advantage isWhat you get in one solution is not a single price, but a whole price surface.it can also handle early exercise, boundary conditions, time-varying parameters and complex income structures under the same framework.

core competencies

DolphinDB provides a complete PDE numerical solution framework:

DolphinDB’s pdeSolver series of functions supports one-dimensional and two-dimensional linear parabolic PDEs. The core capabilities include:

  • Equation configuration: Diffusion, convection, reaction, and source term coefficients can all be configured, supporting constants or functions that change with price and time (such as local volatility).
  • Grid and boundary: Supports uniform grid and sinh/tanh/log non-uniform grid (can be encrypted near the execution price and obstacles), supports Dirichlet, Neumann, and Robin boundaries.
  • Time advancement: Explicit, implicit Euler, Crank–Nicolson and Theta formats are optional; Rannacher smoothing can be used to suppress oscillations for discontinuous returns.
  • Early exercise constraints: American options are expressed through obstacle configuration and support two solution paths: PSOR and Penalty.
  • Two-dimensional problems: supports ADI methods (Douglas, CS, MCS, HV), and can handle Heston, Basket, Exchange and other models containing cross-derivatives.
  • Complete output: In addition to prices, it can also return interpolated prices, Delta, Gamma and other Greeks for specified state points, as well as convergence and iteration diagnostic information.

Developers can build pricing models by configuring pricing equations, terminal value conditions, boundary conditions and numerical solution parameters. They only need to express the financial model without having to implement the PDE solution algorithm from the bottom up.

Take American put options as an example

Taking the American put option as an example, assume that the underlying asset price is 100, the strike price is 100, the risk-free interest rate is 5%, the volatility is 20%, and the term is one year. You can first define the equation coefficients, return-to-maturity function and boundary conditions:

coeff = pdeCoeff1D(
    diff={S,tau -> 0.5 * volatility * volatility * S * S}, //扩散项
    conv={S,tau -> rate * S},                              //对流项
    react=-rate                                            //反应项
)
payoff = {S -> max(strike-S, 0.0)}                         //到期收益
boundary = [strike, 0.0]                                   //计算区域两端的边界值

The early exercise constraint of American options is expressed by solving the obstacle in the configuration. The PSOR method is used here:

method = dict(STRING, ANY)
method["obstacle"] = payoff
method["obstacleSolver"] = "PSOR"
method["psorOmega"] = 1.2
method["psorTolerance"] = 1e-10
method["psorMaxIterations"] = 20000

Finally, construct the space grid and time grid, and pass in the equations, boundary conditions and solution configuration pdeSolver:

spotGrid = pdeGrid1D(0.0, 300.0, 401, "sinh", strike, 3.0)
tGrid = (0..400) / 400.0
setting = dict(STRING, ANY)
setting["interpAt"] = 100.0
result = pdeSolver(
    coeff, payoff, pdeDomain1D(spotGrid), tGrid,
    boundary, method, setting
)
result["interpValue"]

In the above case, the equation coefficients, terminal value conditions and boundary conditions constitute the pricing model of the American put option, and the early exercise constraints are configured separately through obstacle.

The differences between products ultimately come down to these configurations: European options can omit early exercise constraints, the terms of barrier options are reflected in the solution area and boundary values, and the local volatility model only changes the way the diff coefficient is valued, and the equation structure itself remains unchanged. The mesh construction and solution processes do not need to be rewritten in these cases.

3. Performance test

The performance of pricing tools not only affects the time taken for a single valuation, but also affects the computational efficiency of batch pricing, parameter sensitivity analysis, and complex product research. In order to evaluate the performance of DolphinDB’s general numerical pricing tool, Monte Carlo simulated pricing and PDE numerical solution are tested below and compared with other implementations.

Each library has differences in model expression, algorithm and execution optimization. The test compares the end-to-end efficiency under specific scenarios and configurations, rather than the absolute ranking without conditions; scenarios with inconsistent algorithm or accuracy settings will separately explain their comparability limitations.

Monte Carlo performance test

In a set of uniformly configured tests, each implementation computed 100,000 simulation paths, 126 time steps, using single worker and dual variable methods. The test was preheated once and officially run seven times, with the median end-to-end time taken as the result (DolphinDB’s timing includes SDK round-trip overhead).

The test results are as follows, the time-consuming units are all in milliseconds:

scene DolphinDB Standard DolphinDB log NumPy standard NumPy log QuantLib Standard QuantLib log PriceLib Standard PriceLib log
European Call 98.0 38.0 144.9 86.1 2447.2 571.2 209.5 152.6
GeometryAsian 241.0 80.4 223.4 94.3 10845.0 9438.8 249.2 142.4
ArithmeticAsian 139.1 208.0 154.4 183.1 10704.0 11320.1 199.1 202.8
Heston Call 344.8 283.2 316.3 256.4 2859.3† N/A 420.8 362.3
Discrete Up-and-Out 124.4 71.5 155.4 123.9 9762.1 10380.7 198.0 147.6
Two assets Basket 315.9 180.6 310.4 192.1 5655.3 1429.5 N/A N/A

Note: standard / log are two ways of expressing the status of the same engine. QuantLib’s Heston uses native FullTruncation variance discretization, and unlike other implementations, it does not participate in comparison. N/A means the interface is not supported.

Four database timing median comparison chart

From the test results, DolphinDB shows significant computing efficiency advantages in multiple pricing scenarios. Compared with QuantLib, in the five comparable scenarios of this test, the end-to-end time consumption of DolphinDB’s standard writing method is about 1/18 to 1/77, and the log writing method is about 1/8 to 1/145 of it. Among them, the log writing methods of geometric Asian and discrete Up-and-Out are respectively approximately 117 timesand 145 times. Compared with NumPy, DolphinDB also achieves lower time consumption in European Call, geometric Asian and discrete Up-and-Out scenarios.

However, the performance advantage does not hold true in all scenarios. In Heston Call, both DolphinDB writing methods are slightly more time-consuming than NumPy; in Arithmetic Asian, the standard writing method is also significantly faster than the log writing method. This shows that the actual execution efficiency not only depends on the pricing model itself, but is also affected by state representation, calculation expressions and specific implementation methods. It cannot be assumed that a certain writing method is faster in all models.

For practical applications, a comprehensive evaluation should also be conducted based on numerical accuracy, algorithm consistency, and target workload.

pdeSolver performance test

The test is based on the DolphinDB Server V3.00.6.4 Linux version and is conducted under single-core CPU and Release configuration. Each scene uses different spatial grids, time intervals and numerical algorithms; the time consumption is the median after preheating, in milliseconds.

scene Space node × time interval Pure C++ QuantLib Python DolphinDB QuantLib/ DolphinDB Python/ DolphinDB
BS European Bullish 401 × 400 1.473 3.534 12.590 4.584 0.77× 2.75×
Heston Stochastic Volatility 121 × 61 × 120 48.812 80.162 509.309 98.908 0.81× 5.15×
BS American Put (PSOR) 401 × 200 9.990 2.848 1092.076 25.533 Algorithms are different 42.78×
Cash or worthless numbers are bullish 401 × 200 0.804 3.150 7.474 2.370 1.33× 3.15×
Asset or worthless numbers are bullish 801 × 400 3.115 10.821 18.906 9.794 1.11× 1.93×
Knocking out single barrier is bullish 601 × 400 2.323 8.172 16.800 7.267 1.12× 2.31×
Bullish on knocking out single barrier 601 × 400 2.367 8.181 16.434 7.314 1.12× 2.25×
Space-time local volatility (Local Vol) 301 × 150 1.491 7.835 8.401 4.181 1.87× 2.01×
Quanto Fixed Rate Bullish 401 × 200 0.807 3.040 7.536 2.386 1.27× 3.16×

From the test results, the DolphinDB PDE solver shows good computational efficiency in a variety of pricing scenarios.

Compared with the Python implementation, DolphinDB is less time-consuming in all nine test scenarios, with a maximum acceleration ratio of 42.78 times. It also has obvious performance advantages in scenarios such as Heston random volatility, digital options, and barrier options.

Compared to QuantLib, the performance of DolphinDB varies depending on the pricing scenario. In scenarios such as digital options, barrier options, Local Vol and Quanto, DolphinDB takes less time to run; while in BS European call and Heston stochastic volatility scenarios, QuantLib takes less time. For the BS American bearish scenario, due to the different numerical algorithms used by both parties, the test results should not be directly used to compare performance.

4. How to select and verify pricing methods in practical applications

The previous cases and performance tests show that Monte Carlo and PDE each have applicable scenarios, and the execution efficiency will also change with the model and implementation method. In actual projects, method selection should not be based solely on product name or single run time, but should be based onModel suitability, numerical reliability and computational costThe three aspects are judged in turn.

Step One: Product Characteristics Determination Tool

First consider whether there is already a dedicated pricing function that meets your business needs. If not, then judge whether general Monte Carlo or PDE is applicable based on the model status, income structure and required output results.

Pricing requirements Tools to consider Main basis
Path dependent returns, complex payoff or multiple random factors Monte Carlo Describe product terms by simulating state evolution and custom revenue logic
It is necessary to obtain theoretical prices under different underlying prices, and the model is suitable for PDE PDE Solve price curves or price surfaces through space and time grids
It has early exercise characteristics and can be expressed with supported PDE constraints. PDE Handle early exercise constraints through obstacle and other configurations
There is a mature standard product pricing interface Specialized pricing functions Directly reuse existing models and calculation processes

The above choices are not absolute. The specific method used still depends on the model assumptions, solver support range, accuracy requirements and computing resources.

Step 2: Combined with numerical diagnosis verification results

Prices output by pricing tools need to be verified before they can be used for actual business. Different numerical methods have different sources of error, so the verification methods should also be different.

For Monte Carlo, the standard error, confidence interval, and valuation results at different simulation scales can be combined to determine whether the statistical error meets the requirements; for PDE, the stability of the numerical results can be evaluated by encrypting the grid, adjusting the solution tolerance, and checking the convergence of prices and Greeks.

When conditions permit, analytical solutions or independent reference implementations can also be used for cross-validation. For complex products that lack analytical solutions, a verification scheme can be established that combines statistical error, grid convergence, and independent implementation results.

Step 3: Evaluate performance after meeting accuracy requirements

Performance optimization should be based on correct models and reliable results. Monte Carlo can evaluate computational efficiency in combination with the number of simulation paths, time steps, and batch configurations; PDE can test grid size, solution algorithms, and execution paths.

The test results in Chapter 3 show that the specific performance varies with the model and implementation. Therefore, before actual deployment, representative product and parameter combinations should be selected for testing, and try to ensure that the model definition, accuracy requirements, and test scale are comparable.

In general, in practical applications, the applicable pricing method should be determined first, then the numerical results should be verified, and finally the computational efficiency should be evaluated. The general Monte Carlo and PDE tools provided by DolphinDB provide a reusable calculation framework for this process, so developers can focus more on the financial model and product terms themselves.

5. Solution value and future evolution

DolphinDB’s Monte Carlo and PDE tools not only provide numerical solving capabilities, but also provide a reusable calculation basis for the development, optimization and integration of financial derivatives pricing models, which are mainly reflected in the following aspects:

  • Flexible pricing model construction capabilities: Standard financial products can directly call dedicated pricing functions; when faced with non-standard derivatives, path-dependent products or customized income structures, developers can build pricing models by customizing state evolution, income logic, or configuring PDE coefficients, boundary conditions, grids and solution methods, without the need to build a complete calculation framework from scratch for each new product.
  • Combining model development with high-performance computing: supports optimization of execution efficiency through batch calculation, vectorization, JIT, etc. Monte Carlo can adjust the calculation strategy based on the number of paths, time steps, batch divisions, and memory constraints; PDE can optimize around the grid size, precomputation strategy, and solution method. Actual performance depends on model, algorithm, hardware and parameter configuration, and needs to be verified through comparable testing.
  • Connect pricing calculations and business data processes: Combined with DolphinDB’s data processing and analysis capabilities, it reduces the need to transfer market data, model parameters and calculation results between different systems and components. On this basis, standardized calculation processes can be established around specific businesses, and product parameters, model configurations, numerical methods and result verification logic can be managed uniformly, providing a basis for batch valuation, scenario analysis and subsequent risk analysis, and reducing repeated development and maintenance costs.
  • Continuous expansion to meet the needs of complex financial engineering: Based on the existing capabilities, in the future we can further explore numerical methods such as three-dimensional PDE, finite volume method (FVM), finite element method (FEM), as well as Sobol sequence and quasi-Monte Carlo method (QMC), control variable method, Brownian bridge continuous obstacle correction, optimal stopping algorithm of American and Bermuda options, model parameter calibration and Greeks automatic differentiation. The above contents are potential evolution directions, and the specific implementation and support scope are subject to actual product progress.

No matter which numerical method is used, the core value of pricing tools is to reuse mature calculation processes, allowing developers to focus more on financial models, product terms and business logic, rather than repeatedly implementing the underlying solution algorithm.


To learn more about specific function interfaces, code implementation and performance testing, you can read the following tutorials through the Document Center:

  • “Monte Carlo Numerical Calculation and Option Pricing Practice”: explains the GBM stochastic process, European options, Asian options, barrier options, lookback options, two-asset options, Heston stochastic volatility and snowball examples, and discusses historical fixing, valuation errors, dual variables and performance testing.
  • “pdeSolver Financial Derivatives Pricing Tutorial”: How to use the DolphinDB pdeSolver series of functions to solve one-dimensional and two-dimensional linear parabolic PDEs and apply it to financial derivatives pricing. The content covers model and interface mapping, typical pricing cases, and is suitable for quantitative research, derivatives pricing R&D and other personnel.



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *